diff --git a/README.md b/README.md index cfba226..1dff68c 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ It is built for teams and hosting providers: organizations with members, roles a - **Alerting:** incidents with webhooks (signed), email and over 100 services: chat and messengers (Slack, Discord, Microsoft Teams, Telegram, Matrix, WhatsApp gateways, Nostr, …), push (ntfy, Gotify, Pushover, …), SMS and calls (Twilio, Plivo, …), email APIs (SendGrid, Microsoft 365, …) and incident management (PagerDuty, Opsgenie, Grafana OnCall, Jira Service Management, …), plus Apprise; customers bring their own credentials. Confirmations, maintenance windows (one-off or recurring). - **History:** charts and SLA from one hour to a year, per region; see what the checker saw (redirect chain, timing, certificate, response body). - **Status pages:** unlimited, custom domains with automatic TLS, themes, Markdown, legal notice; served from cache during outages. -- **Organizations:** members, custom roles scoped to monitor groups or status pages, API tokens, OpenID Connect SSO per organization, enforced 2FA, audit log. +- **Organizations:** members, custom roles scoped to monitor groups or status pages, API tokens, OpenID Connect SSO per organization, sign-up and sign-in with providers such as Google, Microsoft or GitHub, enforced 2FA, audit log. - **Privacy:** GDPR data export (JSON, PDF) and deletion, configurable retention, no telemetry. - **Operations:** three stateless binaries, horizontally scalable; TimescaleDB and Redis (Sentinel supported); OpenAPI documentation. diff --git a/internal/api/apidocs.go b/internal/api/apidocs.go index b264f32..7513f81 100644 --- a/internal/api/apidocs.go +++ b/internal/api/apidocs.go @@ -41,6 +41,8 @@ var endpoints = []endpoint{ req: secondFactorRequest{}, resp: sessionStarted}, {method: "POST", path: "/api/v1/auth/logout", tag: "Account", summary: "Sign out", sessionOnly: true, status: http.StatusNoContent}, {method: "GET", path: "/api/v1/me", tag: "Account", summary: "The signed-in user and their organizations", resp: meView{}}, + {method: "DELETE", path: "/api/v1/me/identities/:provider", tag: "Account", summary: "Unlink a platform identity provider from the account", sessionOnly: true, + description: "Refused with `409 last_sign_in` when it is the account's only way to sign in.", status: http.StatusNoContent}, {method: "POST", path: "/api/v1/me/org", tag: "Account", summary: "Switch the active organization", sessionOnly: true, req: switchOrgRequest{}, status: http.StatusNoContent}, {method: "POST", path: "/api/v1/locale", tag: "Account", summary: "Set the interface language", public: true, @@ -260,6 +262,16 @@ var endpoints = []endpoint{ {method: "PUT", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Let platform checkers check private addresses or not", description: "Unset, they may on self-hosted installations and may not in the cloud edition. Applies from each checker's next poll.", perm: "platform admin", req: checkerNetwork{}, status: http.StatusNoContent}, + {method: "GET", path: "/api/v1/admin/identity-providers", tag: "Platform", summary: "Identity providers for signing up and in", + description: "With the callback URL to register at each provider. Secrets are never returned.", perm: "platform admin", + resp: obj{"providers": []idpView{}, "callback_url": ""}}, + {method: "POST", path: "/api/v1/admin/identity-providers", tag: "Platform", summary: "Add an identity provider", + description: "`kind` oidc takes the issuer, which is checked by discovery; github takes the GitHub server (empty for github.com). Accounts are linked by subject, never by email: an existing account with the provider's email is not taken over.", + perm: "platform admin", req: idpRequest{}, status: http.StatusCreated, resp: idpView{}}, + {method: "PUT", path: "/api/v1/admin/identity-providers/:id", tag: "Platform", summary: "Change an identity provider", + description: "An empty client secret keeps the stored one; the kind cannot change.", perm: "platform admin", req: idpRequest{}, resp: idpView{}}, + {method: "DELETE", path: "/api/v1/admin/identity-providers/:id", tag: "Platform", summary: "Remove an identity provider", + description: "Refused with `409 idp_in_use` while accounts can sign in only through it; disable it instead.", perm: "platform admin", status: http.StatusNoContent}, {method: "GET", path: "/api/v1/admin/limits", tag: "Platform", summary: "Default limits of organizations and accounts", perm: "platform admin", resp: Limits{}}, {method: "PUT", path: "/api/v1/admin/limits", tag: "Platform", summary: "Set the default limits", description: "0 means unlimited. Defaults apply at once to every organization and account without an override of its own. Lowering a limit below current usage keeps everything; only new monitors, status pages, regions or organizations are refused.", diff --git a/internal/api/audit.go b/internal/api/audit.go index 4e0549a..bd1d888 100644 --- a/internal/api/audit.go +++ b/internal/api/audit.go @@ -96,6 +96,10 @@ var auditActions = map[string]string{ "PUT /api/v1/admin/check-types": "platform.check_types_update", "PUT /api/v1/admin/checker-network": "platform.checker_network_update", "PUT /api/v1/admin/limits": "platform.limits_update", + "POST /api/v1/admin/identity-providers": "platform.idp_create", + "PUT /api/v1/admin/identity-providers/:id": "platform.idp_update", + "DELETE /api/v1/admin/identity-providers/:id": "platform.idp_delete", + "DELETE /api/v1/me/identities/:provider": "account.identity_unlink", "PUT /api/v1/admin/orgs/:id/limits": "platform.org_limits_update", "PUT /api/v1/admin/users/:id/limits": "platform.user_limits_update", "PUT /api/v1/admin/status-pages/:id/suspension": "platform.status_page_suspension", diff --git a/internal/api/console_test.go b/internal/api/console_test.go index ad743ee..cb68150 100644 --- a/internal/api/console_test.go +++ b/internal/api/console_test.go @@ -5,12 +5,16 @@ import ( "io" "net/http" "net/http/httptest" + "regexp" "strings" "testing" "time" ) -// page fetches path and returns the final status, path and body. +var csrfMeta = regexp.MustCompile(` 0 + providers := s.platformButtons(c.Request.Context(), false) + web.Render(c, http.StatusOK, web.Login(s.pageFor(c, "auth.login.title"), allowed, next, providers, c.Query("mfa") == "1")) +} + +// signupOptions tells whether people may sign up with email, and which +// providers they may sign up through. +func (s *Server) signupOptions(ctx context.Context) (bool, []web.IDPButton, error) { + email, err := s.signupAllowed(ctx) + if err != nil { + return false, nil, err + } + mode, err := s.signupModeAllows(ctx) + if err != nil || !mode { + return email, nil, err + } + return email, s.platformButtons(ctx, true), nil } func (s *Server) signupPage(c *gin.Context) { - allowed, err := s.signupAllowed(c.Request.Context()) + email, providers, err := s.signupOptions(c.Request.Context()) if err != nil { internalError(c, err) return } - if !allowed { + if !email && len(providers) == 0 { c.Redirect(http.StatusSeeOther, "/login") return } - web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title"))) + web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title"), providers, email)) } func (s *Server) signupSentPage(c *gin.Context) { @@ -259,7 +276,29 @@ func (s *Server) securityPage(c *gin.Context) { internalError(c, err) return } - web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), me, identities, canLink, auditEntries(c, rows))) + var platform web.PlatformIdentities + var linked []store.ListUserPlatformIdentitiesRow + err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error { + var err error + linked, err = q.ListUserPlatformIdentities(ctx, sess.UserID) + return err + }) + if err != nil { + internalError(c, err) + return + } + isLinked := map[string]bool{} + for _, l := range linked { + platform.Linked = append(platform.Linked, web.LinkedIdentity{ProviderID: l.ProviderID.String(), Name: l.ProviderName, Email: deref(l.Email)}) + isLinked["/login/sso/"+l.ProviderID.String()] = true + } + for _, b := range s.platformButtons(ctx, false) { + if !isLinked[b.URL] { + b.URL += "?link=1" + platform.Available = append(platform.Available, b) + } + } + web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), me, identities, canLink, auditEntries(c, rows), platform)) } func toWebRoles(rows []store.Role) []web.Role { @@ -551,7 +590,7 @@ func (s *Server) adminPage(c *gin.Context) { for _, t := range check.Types { types = append(types, web.CheckTypeOption{Type: string(t), Enabled: !off[string(t)]}) } - web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), webLimits(s.platformLimits(ctx)))) + web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), webLimits(s.platformLimits(ctx)), s.idpAdminView(ctx))) } func (s *Server) adminStatusPagesPage(c *gin.Context) { diff --git a/internal/api/platform_sso.go b/internal/api/platform_sso.go new file mode 100644 index 0000000..57ecf4e --- /dev/null +++ b/internal/api/platform_sso.go @@ -0,0 +1,574 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + "git.zb-server.de/ZB-Server/uptimesebi/internal/sso" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" + "git.zb-server.de/ZB-Server/uptimesebi/internal/web" +) + +// Platform identity providers, such as Google or GitHub, let people sign +// up and sign in without a password. Accounts are reached only through +// identities stored by subject: an existing account with the provider's +// email is never taken over, its owner links the provider while signed in. + +const githubServer = "https://github.com" + +func (s *Server) platformIDP(row store.PlatformIdentityProvider) (sso.Provider, error) { + p := sso.Provider{Issuer: row.Issuer, ClientID: row.ClientID, Scopes: []string{"openid", "email", "profile"}} + if row.Kind == sso.GitHub { + p.Kind = sso.GitHub + } + if row.ClientSecret != nil { + secret, err := s.keys.Open(row.ClientSecret, row.ID[:]) + if err != nil { + return p, err + } + p.ClientSecret = string(secret) + } + return p, nil +} + +func (s *Server) loadPlatformIDP(ctx context.Context, id uuid.UUID) (store.PlatformIdentityProvider, error) { + var row store.PlatformIdentityProvider + err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + var err error + row, err = q.GetPlatformIDP(ctx, id) + return err + }) + return row, err +} + +// platformButtons lists the enabled providers for sign-in pages, only +// those open to sign-up if signup is set. +func (s *Server) platformButtons(ctx context.Context, signup bool) []web.IDPButton { + var rows []store.PlatformIdentityProvider + err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + var err error + rows, err = q.ListPlatformIDPs(ctx) + return err + }) + if err != nil { + s.log.WarnContext(ctx, "listing identity providers failed", "error", err) + return nil + } + var out []web.IDPButton + for _, r := range rows { + if r.Enabled && (!signup || r.AllowSignup) { + out = append(out, web.IDPButton{URL: "/login/sso/" + r.ID.String(), Name: r.Name, Kind: r.Kind}) + } + } + return out +} + +// platformSSOStart sends the browser to a platform provider, to sign in or, +// with ?link=1, to link it to the signed-in account. +func (s *Server) platformSSOStart(c *gin.Context) { + ctx := c.Request.Context() + if !s.limitPage(c, "sso:ip:"+c.ClientIP(), 30, time.Minute) { + return + } + var linkUser uuid.UUID + if c.Query("link") == "1" { + sess := auth.Current(c) + if sess == nil { + c.Redirect(http.StatusSeeOther, "/login") + return + } + linkUser = sess.UserID + } + id, err := uuid.Parse(c.Param("provider")) + if err != nil { + s.ssoAbort(c, linkUser, "sso_unavailable") + return + } + row, err := s.loadPlatformIDP(ctx, id) + if errors.Is(err, pgx.ErrNoRows) || (err == nil && !row.Enabled) { + s.ssoAbort(c, linkUser, "sso_unavailable") + return + } + if err != nil { + internalError(c, err) + return + } + p, err := s.platformIDP(row) + if err != nil { + internalError(c, err) + return + } + flow := sso.NewFlow(auth.RandomToken) + authURL, err := s.sso.AuthURL(ctx, p, flow) + if err != nil { + s.log.WarnContext(ctx, "sso discovery failed", "provider", row.ID, "error", err) + s.ssoAbort(c, linkUser, "sso_provider_error") + return + } + state, _ := json.Marshal(ssoFlow{Provider: row.ID, Platform: true, Nonce: flow.Nonce, Verifier: flow.Verifier, LinkUser: linkUser}) + if err := s.rdb.Set(ctx, ssoFlowKey(flow.State), state, ssoFlowTTL).Err(); err != nil { + internalError(c, err) + return + } + setCookie(c, ssoCookie, flow.State, int(ssoFlowTTL.Seconds())) + c.Redirect(http.StatusFound, authURL) +} + +// platformCallback finishes a platform provider's flow: linking, signing +// in through a stored identity, or signing up. +func (s *Server) platformCallback(c *gin.Context, f ssoFlow, state string) { + ctx := c.Request.Context() + row, err := s.loadPlatformIDP(ctx, f.Provider) + if errors.Is(err, pgx.ErrNoRows) || (err == nil && !row.Enabled) { + s.ssoAbort(c, f.LinkUser, "sso_unavailable") + return + } + if err != nil { + internalError(c, err) + return + } + p, err := s.platformIDP(row) + if err != nil { + internalError(c, err) + return + } + claims, err := s.sso.Exchange(ctx, p, sso.Flow{State: state, Nonce: f.Nonce, Verifier: f.Verifier}, c.Query("code")) + if err != nil { + s.log.WarnContext(ctx, "sso exchange failed", "provider", row.ID, "error", err) + s.ssoAbort(c, f.LinkUser, "sso_provider_error") + return + } + if f.LinkUser != uuid.Nil { + s.platformLink(c, row, f.LinkUser, claims) + return + } + userID, code, err := s.platformResolve(c, row, claims) + if err != nil { + internalError(c, err) + return + } + if code != "" { + s.ssoAbort(c, uuid.Nil, code) + return + } + user, err := s.loadUser(ctx, userID) + if err != nil { + internalError(c, err) + return + } + if user.DisabledAt != nil { + s.ssoAbort(c, uuid.Nil, "account_suspended") + return + } + // The account's second factor still applies; the provider replaces + // only the password. + if user.TotpSecret != nil { + token := auth.RandomToken() + if err := s.rdb.Set(ctx, mfaKey(token), user.ID.String(), mfaTTL).Err(); err != nil { + internalError(c, err) + return + } + setCookie(c, mfaCookie, token, int(mfaTTL.Seconds())) + c.Redirect(http.StatusSeeOther, "/login?mfa=1") + return + } + var orgs []store.ListUserOrgsRow + err = s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error { + var err error + orgs, err = q.ListUserOrgs(ctx, userID) + return err + }) + if err != nil { + internalError(c, err) + return + } + var org uuid.UUID + if len(orgs) > 0 { + org = orgs[0].ID + } + if old := auth.Current(c); old != nil { + _ = s.sessions.Delete(ctx, old) + } + sess, err := s.sessions.Create(ctx, auth.NewSession{UserID: userID, OrgID: org, Locale: cmpOr(deref(user.Locale), i18n.Lang(ctx)), Method: auth.MethodSSO}) + if err != nil { + internalError(c, err) + return + } + auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds())) + s.writeAudit(c, store.InsertAuditEventParams{ + Kind: "user", ActorUserID: &userID, Action: "auth.login_sso", TargetID: &row.ID, Status: http.StatusSeeOther, + }, map[string]any{"name": row.Name}) + c.Redirect(http.StatusSeeOther, "/") +} + +func cmpOr(a, b string) string { + if a != "" { + return a + } + return b +} + +// signupModeAllows reports whether the sign-up mode lets a new account in, +// regardless of mail: providers confirm addresses themselves. +func (s *Server) signupModeAllows(ctx context.Context) (bool, error) { + switch s.cfg.Signup { + case config.SignupOpen: + return true, nil + case config.SignupFirstUser: + var exists bool + err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + var err error + exists, err = q.AnyUserExists(ctx) + return err + }) + return !exists, err + } + return false, nil +} + +// platformResolve finds the account behind an identity or signs one up. +func (s *Server) platformResolve(c *gin.Context, row store.PlatformIdentityProvider, cl sso.Claims) (uuid.UUID, ssoError, error) { + ctx := c.Request.Context() + email := normalizeEmail(cl.Email) + var ( + userID uuid.UUID + code ssoError + created bool + ) + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + ident, err := q.GetPlatformIdentity(ctx, store.GetPlatformIdentityParams{ProviderID: row.ID, Subject: cl.Subject}) + if err == nil { + userID = ident.UserID + return q.TouchPlatformIdentity(ctx, store.TouchPlatformIdentityParams{ProviderID: row.ID, Subject: cl.Subject, Email: nonEmpty(email)}) + } + if !errors.Is(err, pgx.ErrNoRows) { + return err + } + allowed, err := s.signupModeAllows(ctx) + switch { + case err != nil: + return err + case !row.AllowSignup || !allowed: + code = "sso_not_provisioned" + return nil + case email == "" || !cl.EmailVerified: + code = "sso_email_unverified" + return nil + } + if _, err := q.GetUserByEmail(ctx, email); err == nil { + code = "sso_link_required" + return nil + } else if !errors.Is(err, pgx.ErrNoRows) { + return err + } + if taken, err := q.EmailKeyTaken(ctx, ptr(emailKey(email))); err != nil || taken { + code = "sso_link_required" + return err + } + if left, err := s.signupsLeft(c); err != nil || !left { + code = "signup_limit" + return err + } + u, err := q.CreateUser(ctx, store.CreateUserParams{ + Email: email, DisplayName: truncate(strings.TrimSpace(cl.Name), 200), Locale: ptr(i18n.Lang(ctx)), + EmailKey: ptr(emailKey(email)), EmailVerifiedAt: ptr(time.Now()), + }) + if err != nil { + return err + } + if s.cfg.Signup == config.SignupFirstUser && s.cfg.Edition == config.EditionSelfHosted { + if err := q.MakeAdmin(ctx, u.ID); err != nil { + return err + } + } + userID, created = u.ID, true + return q.CreatePlatformIdentity(ctx, store.CreatePlatformIdentityParams{ProviderID: row.ID, Subject: cl.Subject, UserID: u.ID, Email: nonEmpty(email)}) + }) + if err == nil && created { + s.countSignup(c) + s.writeAudit(c, store.InsertAuditEventParams{Kind: "user", ActorUserID: &userID, Action: "account.signup", TargetID: &row.ID, Status: http.StatusOK}, + map[string]any{"via": row.Name}) + } + return userID, code, err +} + +func (s *Server) platformLink(c *gin.Context, row store.PlatformIdentityProvider, userID uuid.UUID, cl sso.Claims) { + ctx := c.Request.Context() + sess := auth.Current(c) + if sess == nil || sess.UserID != userID { + s.ssoAbort(c, uuid.Nil, "sso_expired") + return + } + var code ssoError + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + ident, err := q.GetPlatformIdentity(ctx, store.GetPlatformIdentityParams{ProviderID: row.ID, Subject: cl.Subject}) + switch { + case err == nil && ident.UserID == userID: + return nil + case err == nil: + code = "sso_identity_taken" + return nil + case !errors.Is(err, pgx.ErrNoRows): + return err + } + return q.CreatePlatformIdentity(ctx, store.CreatePlatformIdentityParams{ + ProviderID: row.ID, Subject: cl.Subject, UserID: userID, Email: nonEmpty(normalizeEmail(cl.Email)), + }) + }) + if err != nil { + internalError(c, err) + return + } + if code != "" { + s.ssoAbort(c, userID, code) + return + } + s.writeAudit(c, store.InsertAuditEventParams{Kind: "user", ActorUserID: &userID, Action: "account.identity_link", TargetID: &row.ID, Status: http.StatusSeeOther}, + map[string]any{"name": row.Name}) + c.Redirect(http.StatusSeeOther, "/settings/security?sso=linked") +} + +// unlinkIdentity removes a platform provider from the account, unless it +// is the last way to sign in. +func (s *Server) unlinkIdentity(c *gin.Context) { + id, err := uuid.Parse(c.Param("provider")) + if err != nil { + fail(c, http.StatusNotFound, "not_found") + return + } + sess := auth.Current(c) + ctx := c.Request.Context() + var n int64 + err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error { + ways, err := q.CountUserSignIns(ctx, sess.UserID) + if err != nil { + return err + } + if ways <= 1 { + return errLastSignIn + } + n, err = q.DeletePlatformIdentity(ctx, store.DeletePlatformIdentityParams{UserID: sess.UserID, ProviderID: id}) + return err + }) + switch { + case errors.Is(err, errLastSignIn): + fail(c, http.StatusConflict, "last_sign_in") + case err != nil: + internalError(c, err) + case n == 0: + fail(c, http.StatusNotFound, "not_found") + default: + c.Status(http.StatusNoContent) + } +} + +var errLastSignIn = errors.New("api: last way to sign in") + +// idpView is a platform identity provider; the secret is never returned. +type idpView struct { + ID uuid.UUID `json:"id"` + Kind string `json:"kind"` + Name string `json:"name"` + Issuer string `json:"issuer"` + ClientID string `json:"client_id"` + SecretSet bool `json:"client_secret_set"` + AllowSignup bool `json:"allow_signup"` + Enabled bool `json:"enabled"` +} + +func viewIDP(r store.PlatformIdentityProvider) idpView { + return idpView{r.ID, r.Kind, r.Name, r.Issuer, r.ClientID, r.ClientSecret != nil, r.AllowSignup, r.Enabled} +} + +func (s *Server) adminListIDPs(c *gin.Context) { + ctx := c.Request.Context() + var rows []store.PlatformIdentityProvider + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + rows, err = q.ListPlatformIDPs(ctx) + return err + }) + if err != nil { + internalError(c, err) + return + } + out := make([]idpView, len(rows)) + for i, r := range rows { + out[i] = viewIDP(r) + } + c.JSON(http.StatusOK, gin.H{"providers": out, "callback_url": s.sso.RedirectURL()}) +} + +// idpRequest registers a platform provider. Issuer is the OIDC issuer, or +// the GitHub server (default https://github.com). An empty secret on +// update keeps the stored one. +type idpRequest struct { + Kind string `json:"kind" binding:"required,oneof=oidc github"` + Name string `json:"name" binding:"required,max=100"` + Issuer string `json:"issuer" binding:"max=500"` + ClientID string `json:"client_id" binding:"required,max=500"` + ClientSecret string `json:"client_secret" binding:"max=2000"` + AllowSignup bool `json:"allow_signup"` + Enabled bool `json:"enabled"` +} + +// checkIDP normalizes req and validates its server, contacting OIDC +// issuers so mistakes show when saving. +func (s *Server) checkIDP(c *gin.Context, req *idpRequest) bool { + req.Name, req.Issuer, req.ClientID = strings.TrimSpace(req.Name), strings.TrimSuffix(strings.TrimSpace(req.Issuer), "/"), strings.TrimSpace(req.ClientID) + if req.Kind == sso.GitHub && req.Issuer == "" { + req.Issuer = githubServer + } + var err error + if req.Kind == sso.GitHub { + err = s.sso.CheckURL(req.Issuer) + } else { + err = s.sso.ValidateIssuer(c.Request.Context(), req.Issuer) + } + if err != nil { + code := "sso_discovery_failed" + switch { + case errors.Is(err, sso.ErrInvalidIssuer): + code = "sso_invalid_issuer" + case errors.Is(err, sso.ErrForbiddenAddress): + code = "sso_forbidden_address" + } + fail(c, http.StatusUnprocessableEntity, code) + return false + } + return true +} + +func (s *Server) adminCreateIDP(c *gin.Context) { + var req idpRequest + if !bind(c, &req) || !s.checkIDP(c, &req) { + return + } + ctx := c.Request.Context() + id := uuid.New() + var secret []byte + if req.ClientSecret != "" { + secret = s.keys.Seal([]byte(req.ClientSecret), id[:]) + } + auditDetail(c, "name", req.Name) + var row store.PlatformIdentityProvider + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + row, err = q.CreatePlatformIDP(ctx, store.CreatePlatformIDPParams{ + ID: id, Kind: req.Kind, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID, + ClientSecret: secret, AllowSignup: req.AllowSignup, Enabled: req.Enabled, + }) + return err + }) + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusCreated, viewIDP(row)) +} + +func (s *Server) adminUpdateIDP(c *gin.Context) { + id, err := uuid.Parse(c.Param("id")) + if err != nil { + fail(c, http.StatusNotFound, "not_found") + return + } + var req idpRequest + if !bind(c, &req) || !s.checkIDP(c, &req) { + return + } + ctx := c.Request.Context() + var secret []byte + if req.ClientSecret != "" { + secret = s.keys.Seal([]byte(req.ClientSecret), id[:]) + } + auditDetail(c, "name", req.Name) + var row store.PlatformIdentityProvider + err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + old, err := q.GetPlatformIDP(ctx, id) + if err != nil { + return err + } + if old.Kind != req.Kind { + return errKindChange + } + row, err = q.UpdatePlatformIDP(ctx, store.UpdatePlatformIDPParams{ + ID: id, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID, + ClientSecret: secret, AllowSignup: req.AllowSignup, Enabled: req.Enabled, + }) + return err + }) + switch { + case errors.Is(err, errKindChange): + fail(c, http.StatusUnprocessableEntity, "invalid_input") + case errors.Is(err, pgx.ErrNoRows): + fail(c, http.StatusNotFound, "not_found") + case err != nil: + internalError(c, err) + default: + c.JSON(http.StatusOK, viewIDP(row)) + } +} + +var errKindChange = errors.New("api: provider kind cannot change") + +func (s *Server) adminDeleteIDP(c *gin.Context) { + id, err := uuid.Parse(c.Param("id")) + if err != nil { + fail(c, http.StatusNotFound, "not_found") + return + } + ctx := c.Request.Context() + var n, sole int64 + err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + // Deleting would lock out accounts that sign in only this way; + // disabling can be undone. + if sole, err = q.SoleSignInUsers(ctx, id); err != nil || sole > 0 { + return err + } + n, err = q.DeletePlatformIDP(ctx, id) + return err + }) + switch { + case err == nil && sole > 0: + fail(c, http.StatusConflict, "idp_in_use", "Count", sole) + case err != nil: + internalError(c, err) + case n == 0: + fail(c, http.StatusNotFound, "not_found") + default: + c.Status(http.StatusNoContent) + } +} + +func (s *Server) idpAdminView(ctx context.Context) web.IDPAdminView { + v := web.IDPAdminView{CallbackURL: s.sso.RedirectURL()} + var rows []store.PlatformIdentityProvider + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + rows, err = q.ListPlatformIDPs(ctx) + return err + }) + if err != nil { + s.log.WarnContext(ctx, "listing identity providers failed", "error", err) + } + for _, r := range rows { + v.Providers = append(v.Providers, web.IDPRow{ + ID: r.ID.String(), Kind: r.Kind, Name: r.Name, Issuer: r.Issuer, ClientID: r.ClientID, + SecretSet: r.ClientSecret != nil, AllowSignup: r.AllowSignup, Enabled: r.Enabled, + }) + } + return v +} diff --git a/internal/api/platform_sso_test.go b/internal/api/platform_sso_test.go new file mode 100644 index 0000000..0c93fd9 --- /dev/null +++ b/internal/api/platform_sso_test.go @@ -0,0 +1,201 @@ +package api_test + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/jackc/pgx/v5" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +// fakeGitHub answers like GitHub's OAuth and REST API for one user. +func fakeGitHub(t *testing.T, id int64, email string, verified bool) *httptest.Server { + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/login/oauth/authorize": + back, _ := url.Parse(r.URL.Query().Get("redirect_uri")) + q := back.Query() + q.Set("code", "gh-code") + q.Set("state", r.URL.Query().Get("state")) + back.RawQuery = q.Encode() + http.Redirect(w, r, back.String(), http.StatusFound) + case "/login/oauth/access_token": + if r.FormValue("code") != "gh-code" || r.FormValue("code_verifier") == "" { + w.WriteHeader(http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"access_token":"gh-token","token_type":"bearer"}`)) + case "/api/v3/user": + if r.Header.Get("Authorization") != "Bearer gh-token" { + w.WriteHeader(http.StatusUnauthorized) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"id": id, "login": "octo", "name": ""}) + case "/api/v3/user/emails": + _ = json.NewEncoder(w).Encode([]map[string]any{ + {"email": "other@" + uniq("x") + ".test", "primary": false, "verified": true}, + {"email": email, "primary": true, "verified": verified}, + }) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + return srv +} + +func TestPlatformSSO(t *testing.T) { + e := newEnv(t) + ctx := context.Background() + idp := ssotest.New(t) + admin := e.browser(t) + admin.signup("admin@"+uniq("psso")+".test", uniq("psso-")) + if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error { + return q.MakeAdmin(ctx, admin.userIDSelf()) + }); err != nil { + t.Fatal(err) + } + st, google := admin.do("POST", "/api/v1/admin/identity-providers", map[string]any{ + "kind": "oidc", "name": "Google", "issuer": idp.Issuer(), "client_id": idp.ClientID, "client_secret": idp.Secret, + "allow_signup": true, "enabled": true, + }) + if st != http.StatusCreated || google["client_secret_set"] != true || strings.Contains(mustJSON(google), idp.Secret) { + t.Fatalf("create provider = %d %v", st, google) + } + start := "/login/sso/" + google["id"].(string) + t.Cleanup(func() { + _ = e.asSystem(t, func(tx pgx.Tx) error { + _, err := tx.Exec(ctx, `DELETE FROM platform_identity_providers`) + return err + }) + }) + if _, _, html := e.browser(t).page("/login"); !strings.Contains(html, "Continue with Google") || !strings.Contains(html, start) { + t.Error("the login page lacks the provider") + } + + // Sign up, then sign in again with the same identity. + newEmail := uniq("new") + "@example.test" + subject := uniq("sub") + idp.SetUser(ssotest.User{Subject: subject, Email: newEmail, EmailVerified: true, Name: "New Person"}) + u := e.browser(t) + if got := u.visit(start); got.Path != "/orgs/new" { + t.Fatalf("sign-up landed on %s, want /orgs/new", got) + } + if _, me := u.do("GET", "/api/v1/me", nil); me["email"] != newEmail { + t.Errorf("me = %v", me) + } + if got := e.browser(t).visit(start); got.Path != "/orgs/new" || got.Query().Get("sso_error") != "" { + t.Errorf("second sign-in landed on %s", got) + } + + // Existing accounts are never taken over, also not through an alias. + owner := e.browser(t) + ownerBox := uniq("owner") + owner.signup(ownerBox+"@example.test", uniq("psso-o-")) + for _, email := range []string{ownerBox + "@example.test", ownerBox + "+x@example.test"} { + idp.SetUser(ssotest.User{Subject: uniq("sub"), Email: email, EmailVerified: true}) + if got := e.browser(t).visit(start); got.Query().Get("sso_error") != "sso_link_required" { + t.Errorf("%s: landed on %s, want sso_link_required", email, got) + } + } + idp.SetUser(ssotest.User{Subject: uniq("sub"), Email: uniq("u") + "@example.test", EmailVerified: false}) + if got := e.browser(t).visit(start); got.Query().Get("sso_error") != "sso_email_unverified" { + t.Errorf("unverified email landed on %s", got) + } + + // The owner links the provider while signed in and then signs in with it. + linked := uniq("sub") + idp.SetUser(ssotest.User{Subject: linked, Email: "whatever@" + uniq("x") + ".test", EmailVerified: true}) + if got := owner.visit(start + "?link=1"); got.Path != "/settings/security" || got.Query().Get("sso") != "linked" { + t.Fatalf("linking landed on %s", got) + } + if _, _, html := owner.page("/settings/security"); !strings.Contains(html, "Disconnect") { + t.Error("the security page lacks the linked provider") + } + via := e.browser(t) + if got := via.visit(start); got.Path != "/" { + t.Errorf("sign-in through the linked identity landed on %s", got) + } + if _, me := via.do("GET", "/api/v1/me", nil); me["email"] != ownerBox+"@example.test" { + t.Errorf("signed in as %v", me["email"]) + } + + // The account's second factor still applies after the provider. + _, codes := owner.enableTOTP() + mfa := e.browser(t) + if got := mfa.visit(start); got.Path != "/login" || got.Query().Get("mfa") != "1" { + t.Fatalf("sign-in with TOTP landed on %s", got) + } + if st, _ := mfa.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized { + t.Error("signed in before the second factor") + } + if st, body := mfa.do("POST", "/api/v1/auth/login/totp", map[string]any{"code": codes[0]}); st != http.StatusOK { + t.Fatalf("second factor = %d %v", st, body) + } + + // Unlinking: never the last way to sign in. + u.page("/orgs/new") + st, body := u.do("DELETE", "/api/v1/me/identities/"+google["id"].(string), nil) + expect(t, "unlink the only sign-in", st, body, http.StatusConflict, "last_sign_in") + if st, _ := owner.do("DELETE", "/api/v1/me/identities/"+google["id"].(string), nil); st != http.StatusNoContent { + t.Errorf("unlink = %d", st) + } + + // Removing a provider some accounts depend on is refused. + st, body = admin.do("DELETE", "/api/v1/admin/identity-providers/"+google["id"].(string), nil) + expect(t, "delete a provider in use", st, body, http.StatusConflict, "idp_in_use") + + // Sign-up closed for this provider. + google["allow_signup"], google["client_secret"] = false, "" + if st, body := admin.do("PUT", "/api/v1/admin/identity-providers/"+google["id"].(string), google); st != http.StatusOK || body["client_secret_set"] != true { + t.Fatalf("update = %d %v", st, body) + } + idp.SetUser(ssotest.User{Subject: uniq("sub"), Email: uniq("late") + "@example.test", EmailVerified: true}) + if got := e.browser(t).visit(start); got.Query().Get("sso_error") != "sso_not_provisioned" { + t.Errorf("sign-up through a closed provider landed on %s", got) + } + + // GitHub, here a GitHub Enterprise server. + ghEmail := uniq("octo") + "@example.test" + gh := fakeGitHub(t, 4242, ghEmail, true) + st, github := admin.do("POST", "/api/v1/admin/identity-providers", map[string]any{ + "kind": "github", "name": "GitHub", "issuer": gh.URL, "client_id": "gh-client", "client_secret": "gh-secret", + "allow_signup": true, "enabled": true, + }) + if st != http.StatusCreated { + t.Fatalf("create github = %d %v", st, github) + } + g := e.browser(t) + if got := g.visit("/login/sso/" + github["id"].(string)); got.Path != "/orgs/new" { + t.Fatalf("GitHub sign-up landed on %s", got) + } + if _, me := g.do("GET", "/api/v1/me", nil); me["email"] != ghEmail || me["display_name"] != "octo" { + t.Errorf("GitHub account = %v", me) + } + unverified := fakeGitHub(t, 777, uniq("u")+"@example.test", false) + _, gh2 := admin.do("POST", "/api/v1/admin/identity-providers", map[string]any{ + "kind": "github", "name": "GHE", "issuer": unverified.URL, "client_id": "c", "client_secret": "s", "allow_signup": true, "enabled": true, + }) + if got := e.browser(t).visit("/login/sso/" + gh2["id"].(string)); got.Query().Get("sso_error") != "sso_email_unverified" { + t.Errorf("GitHub with an unverified primary email landed on %s", got) + } + + // Admins only, secrets never listed. + if st, _ := u.do("GET", "/api/v1/admin/identity-providers", nil); st != http.StatusForbidden { + t.Errorf("non-admin listing = %d", st) + } + _, list := admin.do("GET", "/api/v1/admin/identity-providers", nil) + if raw := mustJSON(list); strings.Contains(raw, "gh-secret") || strings.Contains(raw, idp.Secret) || !strings.Contains(raw, "/sso/callback") { + t.Errorf("provider list = %s", raw) + } +} diff --git a/internal/api/server.go b/internal/api/server.go index be0b89a..95380ae 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -118,6 +118,7 @@ func (s *Server) Mount(r gin.IRouter) { me := v1.Group("/me", auth.Require()) me.GET("", s.me) me.POST("/org", s.switchOrg) + me.DELETE("/identities/:provider", s.unlinkIdentity) me.POST("/totp/setup", s.totpSetup) me.POST("/totp/enable", s.totpEnable) me.POST("/totp/disable", s.totpDisable) @@ -175,6 +176,10 @@ func (s *Server) Mount(r gin.IRouter) { admin.GET("/check-types", s.adminListCheckTypes) admin.PUT("/check-types", s.adminSetCheckTypes) admin.GET("/checker-network", s.adminGetCheckerNetwork) + admin.GET("/identity-providers", s.adminListIDPs) + admin.POST("/identity-providers", s.adminCreateIDP) + admin.PUT("/identity-providers/:id", s.adminUpdateIDP) + admin.DELETE("/identity-providers/:id", s.adminDeleteIDP) admin.GET("/limits", s.adminGetLimits) admin.PUT("/limits", s.adminSetLimits) admin.GET("/orgs", s.adminListOrgs) @@ -252,6 +257,7 @@ func (s *Server) Mount(r gin.IRouter) { g.GET("/sso", s.ssoLookup) g.GET("/sso/callback", s.ssoCallback) + g.GET("/login/sso/:provider", s.platformSSOStart) g.GET("/sso/:slug", s.ssoChoose) g.GET("/sso/:slug/:provider", s.ssoStartProvider) diff --git a/internal/api/sso.go b/internal/api/sso.go index 7371ecb..8b027fc 100644 --- a/internal/api/sso.go +++ b/internal/api/sso.go @@ -40,6 +40,9 @@ type ssoFlow struct { // LinkUser is set when a signed-in user connects this IdP to their // existing account instead of signing in. LinkUser uuid.UUID `json:"link_user,omitempty"` + // Platform marks a platform identity provider rather than an + // organization's. + Platform bool `json:"platform,omitempty"` } // ssoError aborts a browser flow by redirecting with a code the target page @@ -206,6 +209,10 @@ func (s *Server) ssoCallback(c *gin.Context) { s.ssoAbort(c, f.LinkUser, "sso_denied") return } + if f.Platform { + s.platformCallback(c, f, state) + return + } var row store.SsoProvider err = s.db.Tx(ctx, tenant.Org(f.Org, uuid.Nil), func(q *store.Queries) error { diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index 2bcd14f..9045bbb 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -52,6 +52,8 @@ "app.network_error": "Verbindung fehlgeschlagen.", "audit.action.account.delete": "Konto gelöscht", "audit.action.account.export": "Persönliche Daten exportiert", + "audit.action.account.identity_link": "Anmelde-Anbieter verbunden", + "audit.action.account.identity_unlink": "Anmelde-Anbieter getrennt", "audit.action.account.recovery_codes": "Wiederherstellungscodes neu erzeugt", "audit.action.account.signup": "Konto erstellt", "audit.action.account.totp_disable": "Zwei-Faktor-Authentifizierung deaktiviert", @@ -98,6 +100,9 @@ "audit.action.platform.agent_delete": "Plattform-Agent widerrufen", "audit.action.platform.check_types_update": "Check-Typen geändert", "audit.action.platform.checker_network_update": "Checker-Netzwerk geändert", + "audit.action.platform.idp_create": "Anmelde-Anbieter hinzugefügt", + "audit.action.platform.idp_delete": "Anmelde-Anbieter entfernt", + "audit.action.platform.idp_update": "Anmelde-Anbieter geändert", "audit.action.platform.legal_update": "Rechtstext der Plattform geändert", "audit.action.platform.limits_update": "Standard-Limits geändert", "audit.action.platform.org_delete": "Organisation durch Admin gelöscht", @@ -149,11 +154,14 @@ "auth.login.title": "Anmelden", "auth.login.to_signup": "Registrieren", "auth.login.totp_hint": "Code aus der Authenticator-App oder einen Wiederherstellungscode eingeben.", + "auth.or": "oder", "auth.signup.submit": "Anlegen", "auth.signup.title": "Konto anlegen", "auth.signup.to_login": "Zur Anmeldung", + "auth.sso.continue_with": "Weiter mit {{.Name}}", "auth.sso.heading": "Single Sign-on", "auth.sso.org_placeholder": "Kurzname der Organisation", + "auth.sso.signup_with": "Registrieren mit {{.Name}}", "auth.sso.submit": "Weiter", "auth.verify.intro": "Drücke den Knopf, um deine E-Mail-Adresse zu bestätigen und dich anzumelden.", "auth.verify.resend_intro": "Wenn ein unbestätigtes Konto diese Adresse nutzt, schicken wir ihm einen neuen Link.", @@ -498,6 +506,7 @@ "error.forbidden": "Dafür fehlt dir die Berechtigung.", "error.group_cycle": "Eine Gruppe kann nicht in sich selbst oder eine ihrer Untergruppen verschoben werden.", "error.group_too_deep": "Gruppen lassen sich höchstens acht Ebenen tief verschachteln.", + "error.idp_in_use": "{{.Count}} Konten melden sich nur über diesen Anbieter an. Deaktiviere ihn stattdessen.", "error.internal": "Interner Fehler.", "error.invalid_alert_group": "Eine Alertgruppe existiert nicht in dieser Organisation.", "error.invalid_assertion_op": "Unbekannter Operator.", @@ -544,6 +553,7 @@ "error.invitation_email_mismatch": "Diese Einladung ging an eine andere E-Mail-Adresse als die, mit der du angemeldet bist.", "error.invitation_invalid": "Diese Einladung ist ungültig, abgelaufen oder wurde bereits verwendet.", "error.keyword_needs_get": "Keyword-Checks brauchen GET-Anfragen.", + "error.last_sign_in": "Das ist der einzige Anmeldeweg des Kontos. Setze zuerst ein Passwort oder verbinde einen anderen Anbieter.", "error.locked": "Die Ressource ist von einem anderen Prozess gesperrt.", "error.maintenance_overlaps": "Die Wartung würde länger dauern als der Abstand bis zur Wiederholung.", "error.maintenance_without_targets": "Wähle mindestens einen Monitor oder eine Gruppe.", @@ -576,6 +586,7 @@ "error.slug_taken": "Dieser Kurzname ist bereits vergeben.", "error.sso_denied": "Die Anmeldung wurde beim Identity Provider abgebrochen.", "error.sso_discovery_failed": "Der Identity Provider ist nicht erreichbar oder lieferte keine gültige Konfiguration.", + "error.sso_email_unverified": "Der Anbieter hat für dieses Konto keine bestätigte E-Mail-Adresse, darum ist keine Registrierung möglich.", "error.sso_expired": "Der Anmeldeversuch ist abgelaufen, bitte neu starten.", "error.sso_forbidden_address": "Der Issuer zeigt auf eine nicht öffentliche Adresse.", "error.sso_identity_taken": "Diese SSO-Anmeldung ist bereits mit einem anderen Konto verknüpft.", @@ -751,6 +762,20 @@ "groups.none": "– oberste Ebene –", "groups.parent": "In Gruppe", "groups.title": "Monitor-Gruppen", + "idp.add": "Anbieter hinzufügen", + "idp.allow_signup": "Neue Leute dürfen sich damit registrieren", + "idp.callback": "Callback-URL, die beim Anbieter einzutragen ist:", + "idp.client_id": "Client-ID", + "idp.client_secret": "Client-Secret", + "idp.delete_confirm": "{{.Name}} entfernen? Konten verlieren diesen Anmeldeweg.", + "idp.enabled": "Aktiv", + "idp.intro": "Damit können sich Leute registrieren und anmelden. Ein bestehendes Konto mit derselben E-Mail wird nie übernommen: Sein Inhaber verbindet den Anbieter in den Sicherheitseinstellungen.", + "idp.issuer": "Issuer oder Server", + "idp.issuer_hint": "Bei OpenID Connect der Issuer, z. B. https://accounts.google.com oder https://login.microsoftonline.com//v2.0. Bei GitHub leer lassen oder den GitHub-Enterprise-Server angeben.", + "idp.kind": "Art", + "idp.kind_oidc": "OpenID Connect (Google, Microsoft, GitLab, Keycloak, …)", + "idp.signup_open": "Registrierung offen", + "idp.title": "Anmelde-Anbieter", "incidents.all": "Alle Vorfälle", "incidents.all_of_monitor": "Alle Vorfälle dieses Monitors", "incidents.none": "Bisher keine Incidents.", @@ -1184,6 +1209,10 @@ "scope.status_page": "Statuspage", "security.activity": "Kontoaktivität", "security.activity_intro": "Letzte Anmeldungen und Sicherheitsänderungen an deinem Konto. Wende dich an einen Administrator, wenn du einen Eintrag nicht erkennst.", + "security.platform_sso.heading": "Anmelden mit anderen Konten", + "security.platform_sso.link": "{{.Name}} verbinden", + "security.platform_sso.unlink": "Trennen", + "security.platform_sso.unlink_confirm": "Nicht mehr mit {{.Name}} anmelden?", "security.recovery.left": { "one": "{{.Count}} Wiederherstellungscode übrig", "other": "{{.Count}} Wiederherstellungscodes übrig" diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 5ac35ea..c1683c7 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -52,6 +52,8 @@ "app.network_error": "Connection failed.", "audit.action.account.delete": "Account deleted", "audit.action.account.export": "Personal data exported", + "audit.action.account.identity_link": "Sign-in provider connected", + "audit.action.account.identity_unlink": "Sign-in provider disconnected", "audit.action.account.recovery_codes": "Recovery codes regenerated", "audit.action.account.signup": "Account created", "audit.action.account.totp_disable": "Two-factor authentication disabled", @@ -98,6 +100,9 @@ "audit.action.platform.agent_delete": "Platform agent revoked", "audit.action.platform.check_types_update": "Check types changed", "audit.action.platform.checker_network_update": "Checker network changed", + "audit.action.platform.idp_create": "Sign-in provider added", + "audit.action.platform.idp_delete": "Sign-in provider removed", + "audit.action.platform.idp_update": "Sign-in provider changed", "audit.action.platform.legal_update": "Platform legal document changed", "audit.action.platform.limits_update": "Default limits changed", "audit.action.platform.org_delete": "Organization deleted by admin", @@ -149,11 +154,14 @@ "auth.login.title": "Sign in", "auth.login.to_signup": "Sign up", "auth.login.totp_hint": "Enter the code from your authenticator app or one of your recovery codes.", + "auth.or": "or", "auth.signup.submit": "Create", "auth.signup.title": "Create account", "auth.signup.to_login": "Back to sign in", + "auth.sso.continue_with": "Continue with {{.Name}}", "auth.sso.heading": "Single sign-on", "auth.sso.org_placeholder": "Organization short name", + "auth.sso.signup_with": "Sign up with {{.Name}}", "auth.sso.submit": "Continue", "auth.verify.intro": "Press the button to confirm your email address and sign in.", "auth.verify.resend_intro": "If an unconfirmed account uses this address, we send it a new link.", @@ -498,6 +506,7 @@ "error.forbidden": "You are not allowed to do this.", "error.group_cycle": "A group cannot be placed inside itself or one of its subgroups.", "error.group_too_deep": "Groups can be nested at most eight levels deep.", + "error.idp_in_use": "{{.Count}} accounts sign in only through this provider. Disable it instead.", "error.internal": "Internal error.", "error.invalid_alert_group": "An alert group does not exist in this organization.", "error.invalid_assertion_op": "Unknown condition operator.", @@ -544,6 +553,7 @@ "error.invitation_email_mismatch": "This invitation was sent to a different email address than the one you are signed in with.", "error.invitation_invalid": "This invitation is invalid, expired or was already used.", "error.keyword_needs_get": "Keyword checks need GET requests.", + "error.last_sign_in": "This is the account's only way to sign in. Set a password or connect another provider first.", "error.locked": "The resource is locked by another process.", "error.maintenance_overlaps": "The maintenance would last longer than the time until it repeats.", "error.maintenance_without_targets": "Choose at least one monitor or group.", @@ -576,6 +586,7 @@ "error.slug_taken": "This short name is already taken.", "error.sso_denied": "Sign-in was cancelled at the identity provider.", "error.sso_discovery_failed": "The identity provider could not be reached or returned no valid configuration.", + "error.sso_email_unverified": "The provider did not confirm an email address for this account, so it cannot sign up here.", "error.sso_expired": "The sign-in attempt expired, please start again.", "error.sso_forbidden_address": "The issuer points to a non-public address.", "error.sso_identity_taken": "This SSO sign-in is already linked to another account.", @@ -751,6 +762,20 @@ "groups.none": "– top level –", "groups.parent": "Inside group", "groups.title": "Monitor groups", + "idp.add": "Add provider", + "idp.allow_signup": "New people may sign up with it", + "idp.callback": "Callback URL to register at the provider:", + "idp.client_id": "Client ID", + "idp.client_secret": "Client secret", + "idp.delete_confirm": "Remove {{.Name}}? Accounts lose this way to sign in.", + "idp.enabled": "Enabled", + "idp.intro": "People can sign up and sign in with these accounts. An existing account with the same email is never taken over: its owner connects the provider in the security settings.", + "idp.issuer": "Issuer or server", + "idp.issuer_hint": "For OpenID Connect the issuer, e.g. https://accounts.google.com or https://login.microsoftonline.com//v2.0. For GitHub leave it empty, or give your GitHub Enterprise server.", + "idp.kind": "Kind", + "idp.kind_oidc": "OpenID Connect (Google, Microsoft, GitLab, Keycloak, …)", + "idp.signup_open": "sign-up open", + "idp.title": "Sign-in providers", "incidents.all": "All incidents", "incidents.all_of_monitor": "All incidents of this monitor", "incidents.none": "No incidents so far.", @@ -1184,6 +1209,10 @@ "scope.status_page": "status page", "security.activity": "Account activity", "security.activity_intro": "Recent sign-ins and security changes on your account. Contact an administrator if you do not recognize an entry.", + "security.platform_sso.heading": "Sign in with other accounts", + "security.platform_sso.link": "Connect {{.Name}}", + "security.platform_sso.unlink": "Disconnect", + "security.platform_sso.unlink_confirm": "Stop signing in with {{.Name}}?", "security.recovery.left": { "one": "{{.Count}} recovery code left", "other": "{{.Count}} recovery codes left" diff --git a/internal/migrations/sql/00045_platform_sso.sql b/internal/migrations/sql/00045_platform_sso.sql new file mode 100644 index 0000000..02278b1 --- /dev/null +++ b/internal/migrations/sql/00045_platform_sso.sql @@ -0,0 +1,49 @@ +-- +goose Up +-- Identity providers of the whole installation, such as Google or GitHub, +-- for signing up and signing in; organizations' own IdPs stay in +-- sso_providers. +CREATE TABLE platform_identity_providers ( + id uuid PRIMARY KEY, + kind text NOT NULL CHECK (kind IN ('oidc', 'github')), + name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100), + -- The OIDC issuer, or the GitHub server (https://github.com or a GitHub + -- Enterprise host). + issuer text NOT NULL CHECK (issuer ~ '^https?://[^\s]+$' AND length(issuer) <= 500), + client_id text NOT NULL CHECK (length(client_id) BETWEEN 1 AND 500), + -- Sealed with the application keyring, bound to the provider id. + client_secret bytea, + -- Whether people without an account may sign up through it. + allow_signup boolean NOT NULL DEFAULT true, + enabled boolean NOT NULL DEFAULT true, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +-- Accounts are linked by subject, never by email. +CREATE TABLE platform_identities ( + provider_id uuid NOT NULL REFERENCES platform_identity_providers (id) ON DELETE CASCADE, + subject text NOT NULL CHECK (length(subject) BETWEEN 1 AND 255), + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + email citext, + created_at timestamptz NOT NULL DEFAULT now(), + last_login_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (provider_id, subject) +); +CREATE INDEX platform_identities_user_idx ON platform_identities (user_id); + +ALTER TABLE platform_identity_providers ENABLE ROW LEVEL SECURITY; +ALTER TABLE platform_identity_providers FORCE ROW LEVEL SECURITY; +-- Sign-in pages list them to everyone; only the system scope changes them. +CREATE POLICY platform_identity_providers_read ON platform_identity_providers FOR SELECT USING (true); +CREATE POLICY platform_identity_providers_write ON platform_identity_providers FOR ALL + USING (app_scope_system()) WITH CHECK (app_scope_system()); + +ALTER TABLE platform_identities ENABLE ROW LEVEL SECURITY; +ALTER TABLE platform_identities FORCE ROW LEVEL SECURITY; +CREATE POLICY platform_identities_own ON platform_identities FOR ALL + USING (app_scope_system() OR user_id = app_user_id()) + WITH CHECK (app_scope_system() OR user_id = app_user_id()); + +-- +goose Down +DROP TABLE platform_identities; +DROP TABLE platform_identity_providers; diff --git a/internal/sso/github.go b/internal/sso/github.go new file mode 100644 index 0000000..8ca9119 --- /dev/null +++ b/internal/sso/github.go @@ -0,0 +1,93 @@ +package sso + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "strings" + + "golang.org/x/oauth2" +) + +// GitHub signs users in with OAuth instead of OpenID Connect. A Provider +// with Kind GitHub names the GitHub server as Issuer: https://github.com or +// a GitHub Enterprise host. +const GitHub = "github" + +func (c *Client) githubOAuth(p Provider) *oauth2.Config { + web := strings.TrimSuffix(p.Issuer, "/") + return &oauth2.Config{ + ClientID: p.ClientID, + ClientSecret: p.ClientSecret, + Endpoint: oauth2.Endpoint{ + AuthURL: web + "/login/oauth/authorize", TokenURL: web + "/login/oauth/access_token", + AuthStyle: oauth2.AuthStyleInParams, + }, + RedirectURL: c.redirectURL, + Scopes: []string{"read:user", "user:email"}, + } +} + +// githubAPI is the REST API of a GitHub server. +func githubAPI(issuer string) string { + web := strings.TrimSuffix(issuer, "/") + if web == "https://github.com" { + return "https://api.github.com" + } + return web + "/api/v3" +} + +// githubClaims reads the user behind tok. Only the primary email counts, +// and only if GitHub verified it. +func (c *Client) githubClaims(ctx context.Context, p Provider, tok *oauth2.Token) (Claims, error) { + get := func(path string, v any) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, githubAPI(p.Issuer)+path, nil) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+tok.AccessToken) + req.Header.Set("Accept", "application/vnd.github+json") + resp, err := c.http.Do(req) + if err != nil { + return err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("sso: github %s answered %d", path, resp.StatusCode) + } + return json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(v) + } + var user struct { + ID int64 `json:"id"` + Login string `json:"login"` + Name string `json:"name"` + } + if err := get("/user", &user); err != nil { + return Claims{}, err + } + if user.ID == 0 { + return Claims{}, errors.New("sso: github user without id") + } + var emails []struct { + Email string `json:"email"` + Primary bool `json:"primary"` + Verified bool `json:"verified"` + } + if err := get("/user/emails", &emails); err != nil { + return Claims{}, err + } + cl := Claims{Subject: strconv.FormatInt(user.ID, 10), Name: user.Name} + if cl.Name == "" { + cl.Name = user.Login + } + for _, e := range emails { + if e.Primary { + cl.Email, cl.EmailVerified = e.Email, e.Verified + } + } + return cl, nil +} diff --git a/internal/sso/sso.go b/internal/sso/sso.go index c46bb03..f40a778 100644 --- a/internal/sso/sso.go +++ b/internal/sso/sso.go @@ -16,8 +16,10 @@ import ( "golang.org/x/oauth2" ) -// Provider is one organization's IdP registration. +// Provider is an IdP registration, of an organization or the platform. type Provider struct { + // Kind is empty for OpenID Connect or GitHub. + Kind string Issuer string ClientID string ClientSecret string @@ -91,6 +93,9 @@ func (c *Client) ValidateIssuer(ctx context.Context, issuer string) error { return err } +// CheckURL checks that a server URL may be used, without contacting it. +func (c *Client) CheckURL(issuer string) error { return c.checkIssuer(issuer) } + func (c *Client) checkIssuer(issuer string) error { u, err := url.Parse(issuer) if err != nil || u.Host == "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil { @@ -144,6 +149,9 @@ func (c *Client) AuthURL(ctx context.Context, p Provider, f Flow) (string, error if err := c.checkIssuer(p.Issuer); err != nil { return "", err } + if p.Kind == GitHub { + return c.githubOAuth(p).AuthCodeURL(f.State, oauth2.S256ChallengeOption(f.Verifier)), nil + } op, err := c.discover(ctx, p.Issuer) if err != nil { return "", err @@ -157,6 +165,13 @@ func (c *Client) AuthURL(ctx context.Context, p Provider, f Flow) (string, error // Exchange redeems the authorization code and verifies the ID token's // signature, issuer, audience, expiry and nonce. func (c *Client) Exchange(ctx context.Context, p Provider, f Flow, code string) (Claims, error) { + if p.Kind == GitHub { + tok, err := c.githubOAuth(p).Exchange(oidc.ClientContext(ctx, c.http), code, oauth2.VerifierOption(f.Verifier)) + if err != nil { + return Claims{}, fmt.Errorf("sso: code exchange: %w", err) + } + return c.githubClaims(ctx, p, tok) + } op, err := c.discover(ctx, p.Issuer) if err != nil { return Claims{}, err diff --git a/internal/store/models.go b/internal/store/models.go index b8d697c..bae04a9 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -292,6 +292,28 @@ type Org struct { LimitOwnRegionsCount *bool } +type PlatformIdentity struct { + ProviderID uuid.UUID + Subject string + UserID uuid.UUID + Email *string + CreatedAt time.Time + LastLoginAt time.Time +} + +type PlatformIdentityProvider struct { + ID uuid.UUID + Kind string + Name string + Issuer string + ClientID string + ClientSecret []byte + AllowSignup bool + Enabled bool + CreatedAt time.Time + UpdatedAt time.Time +} + type PlatformSetting struct { Key string Value []byte diff --git a/internal/store/platform_sso.sql.go b/internal/store/platform_sso.sql.go new file mode 100644 index 0000000..34f35c0 --- /dev/null +++ b/internal/store/platform_sso.sql.go @@ -0,0 +1,318 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: platform_sso.sql + +package store + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const countUserSignIns = `-- name: CountUserSignIns :one +SELECT (password_hash IS NOT NULL)::integer + + (SELECT count(*) FROM user_identities ui WHERE ui.user_id = users.id)::integer + + (SELECT count(*) FROM platform_identities pi WHERE pi.user_id = users.id)::integer AS ways +FROM users WHERE id = $1 +` + +// Ways the account can sign in besides platform identities. +func (q *Queries) CountUserSignIns(ctx context.Context, id uuid.UUID) (int32, error) { + row := q.db.QueryRow(ctx, countUserSignIns, id) + var ways int32 + err := row.Scan(&ways) + return ways, err +} + +const createPlatformIDP = `-- name: CreatePlatformIDP :one +INSERT INTO platform_identity_providers (id, kind, name, issuer, client_id, client_secret, allow_signup, enabled) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8) +RETURNING id, kind, name, issuer, client_id, client_secret, allow_signup, enabled, created_at, updated_at +` + +type CreatePlatformIDPParams struct { + ID uuid.UUID + Kind string + Name string + Issuer string + ClientID string + ClientSecret []byte + AllowSignup bool + Enabled bool +} + +func (q *Queries) CreatePlatformIDP(ctx context.Context, arg CreatePlatformIDPParams) (PlatformIdentityProvider, error) { + row := q.db.QueryRow(ctx, createPlatformIDP, + arg.ID, + arg.Kind, + arg.Name, + arg.Issuer, + arg.ClientID, + arg.ClientSecret, + arg.AllowSignup, + arg.Enabled, + ) + var i PlatformIdentityProvider + err := row.Scan( + &i.ID, + &i.Kind, + &i.Name, + &i.Issuer, + &i.ClientID, + &i.ClientSecret, + &i.AllowSignup, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const createPlatformIdentity = `-- name: CreatePlatformIdentity :exec +INSERT INTO platform_identities (provider_id, subject, user_id, email) VALUES ($1, $2, $3, $4) +` + +type CreatePlatformIdentityParams struct { + ProviderID uuid.UUID + Subject string + UserID uuid.UUID + Email *string +} + +func (q *Queries) CreatePlatformIdentity(ctx context.Context, arg CreatePlatformIdentityParams) error { + _, err := q.db.Exec(ctx, createPlatformIdentity, + arg.ProviderID, + arg.Subject, + arg.UserID, + arg.Email, + ) + return err +} + +const deletePlatformIDP = `-- name: DeletePlatformIDP :execrows +DELETE FROM platform_identity_providers WHERE id = $1 +` + +func (q *Queries) DeletePlatformIDP(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deletePlatformIDP, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const deletePlatformIdentity = `-- name: DeletePlatformIdentity :execrows +DELETE FROM platform_identities WHERE user_id = $1 AND provider_id = $2 +` + +type DeletePlatformIdentityParams struct { + UserID uuid.UUID + ProviderID uuid.UUID +} + +func (q *Queries) DeletePlatformIdentity(ctx context.Context, arg DeletePlatformIdentityParams) (int64, error) { + result, err := q.db.Exec(ctx, deletePlatformIdentity, arg.UserID, arg.ProviderID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getPlatformIDP = `-- name: GetPlatformIDP :one +SELECT id, kind, name, issuer, client_id, client_secret, allow_signup, enabled, created_at, updated_at FROM platform_identity_providers WHERE id = $1 +` + +func (q *Queries) GetPlatformIDP(ctx context.Context, id uuid.UUID) (PlatformIdentityProvider, error) { + row := q.db.QueryRow(ctx, getPlatformIDP, id) + var i PlatformIdentityProvider + err := row.Scan( + &i.ID, + &i.Kind, + &i.Name, + &i.Issuer, + &i.ClientID, + &i.ClientSecret, + &i.AllowSignup, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const getPlatformIdentity = `-- name: GetPlatformIdentity :one +SELECT provider_id, subject, user_id, email, created_at, last_login_at FROM platform_identities WHERE provider_id = $1 AND subject = $2 +` + +type GetPlatformIdentityParams struct { + ProviderID uuid.UUID + Subject string +} + +func (q *Queries) GetPlatformIdentity(ctx context.Context, arg GetPlatformIdentityParams) (PlatformIdentity, error) { + row := q.db.QueryRow(ctx, getPlatformIdentity, arg.ProviderID, arg.Subject) + var i PlatformIdentity + err := row.Scan( + &i.ProviderID, + &i.Subject, + &i.UserID, + &i.Email, + &i.CreatedAt, + &i.LastLoginAt, + ) + return i, err +} + +const listPlatformIDPs = `-- name: ListPlatformIDPs :many +SELECT id, kind, name, issuer, client_id, client_secret, allow_signup, enabled, created_at, updated_at FROM platform_identity_providers ORDER BY name +` + +func (q *Queries) ListPlatformIDPs(ctx context.Context) ([]PlatformIdentityProvider, error) { + rows, err := q.db.Query(ctx, listPlatformIDPs) + if err != nil { + return nil, err + } + defer rows.Close() + items := []PlatformIdentityProvider{} + for rows.Next() { + var i PlatformIdentityProvider + if err := rows.Scan( + &i.ID, + &i.Kind, + &i.Name, + &i.Issuer, + &i.ClientID, + &i.ClientSecret, + &i.AllowSignup, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listUserPlatformIdentities = `-- name: ListUserPlatformIdentities :many +SELECT i.provider_id, i.email, i.created_at, p.name AS provider_name, p.kind +FROM platform_identities i JOIN platform_identity_providers p ON p.id = i.provider_id +WHERE i.user_id = $1 +ORDER BY p.name +` + +type ListUserPlatformIdentitiesRow struct { + ProviderID uuid.UUID + Email *string + CreatedAt time.Time + ProviderName string + Kind string +} + +func (q *Queries) ListUserPlatformIdentities(ctx context.Context, userID uuid.UUID) ([]ListUserPlatformIdentitiesRow, error) { + rows, err := q.db.Query(ctx, listUserPlatformIdentities, userID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListUserPlatformIdentitiesRow{} + for rows.Next() { + var i ListUserPlatformIdentitiesRow + if err := rows.Scan( + &i.ProviderID, + &i.Email, + &i.CreatedAt, + &i.ProviderName, + &i.Kind, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const soleSignInUsers = `-- name: SoleSignInUsers :one +SELECT count(*) FROM platform_identities pi JOIN users u ON u.id = pi.user_id +WHERE pi.provider_id = $1 AND u.password_hash IS NULL + AND NOT EXISTS (SELECT 1 FROM user_identities ui WHERE ui.user_id = u.id) + AND NOT EXISTS (SELECT 1 FROM platform_identities o WHERE o.user_id = u.id AND o.provider_id <> pi.provider_id) +` + +// Accounts that can sign in only through this provider. +func (q *Queries) SoleSignInUsers(ctx context.Context, providerID uuid.UUID) (int64, error) { + row := q.db.QueryRow(ctx, soleSignInUsers, providerID) + var count int64 + err := row.Scan(&count) + return count, err +} + +const touchPlatformIdentity = `-- name: TouchPlatformIdentity :exec +UPDATE platform_identities SET last_login_at = now(), email = coalesce($3, email) +WHERE provider_id = $1 AND subject = $2 +` + +type TouchPlatformIdentityParams struct { + ProviderID uuid.UUID + Subject string + Email *string +} + +func (q *Queries) TouchPlatformIdentity(ctx context.Context, arg TouchPlatformIdentityParams) error { + _, err := q.db.Exec(ctx, touchPlatformIdentity, arg.ProviderID, arg.Subject, arg.Email) + return err +} + +const updatePlatformIDP = `-- name: UpdatePlatformIDP :one +UPDATE platform_identity_providers +SET name = $2, issuer = $3, client_id = $4, client_secret = coalesce($7, client_secret), + allow_signup = $5, enabled = $6, updated_at = now() +WHERE id = $1 +RETURNING id, kind, name, issuer, client_id, client_secret, allow_signup, enabled, created_at, updated_at +` + +type UpdatePlatformIDPParams struct { + ID uuid.UUID + Name string + Issuer string + ClientID string + AllowSignup bool + Enabled bool + ClientSecret []byte +} + +func (q *Queries) UpdatePlatformIDP(ctx context.Context, arg UpdatePlatformIDPParams) (PlatformIdentityProvider, error) { + row := q.db.QueryRow(ctx, updatePlatformIDP, + arg.ID, + arg.Name, + arg.Issuer, + arg.ClientID, + arg.AllowSignup, + arg.Enabled, + arg.ClientSecret, + ) + var i PlatformIdentityProvider + err := row.Scan( + &i.ID, + &i.Kind, + &i.Name, + &i.Issuer, + &i.ClientID, + &i.ClientSecret, + &i.AllowSignup, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} diff --git a/internal/store/querier.go b/internal/store/querier.go index 03da4b0..8acbae8 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -51,6 +51,8 @@ type Querier interface { CountRoleAssignments(ctx context.Context, roleID uuid.UUID) (int64, error) CountStatusPages(ctx context.Context, orgID uuid.UUID) (int64, error) CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error) + // Ways the account can sign in besides platform identities. + CountUserSignIns(ctx context.Context, id uuid.UUID) (int32, error) CreateAPIToken(ctx context.Context, arg CreateAPITokenParams) (ApiToken, error) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error) CreateAlertGroup(ctx context.Context, arg CreateAlertGroupParams) (AlertGroup, error) @@ -63,6 +65,8 @@ type Querier interface { CreateMaintenance(ctx context.Context, arg CreateMaintenanceParams) (MaintenanceWindow, error) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) + CreatePlatformIDP(ctx context.Context, arg CreatePlatformIDPParams) (PlatformIdentityProvider, error) + CreatePlatformIdentity(ctx context.Context, arg CreatePlatformIdentityParams) error CreateRegion(ctx context.Context, arg CreateRegionParams) (Region, error) CreateRole(ctx context.Context, arg CreateRoleParams) (Role, error) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error) @@ -90,6 +94,8 @@ type Querier interface { DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) DeleteOrgStorage(ctx context.Context, orgID uuid.UUID) error + DeletePlatformIDP(ctx context.Context, id uuid.UUID) (int64, error) + DeletePlatformIdentity(ctx context.Context, arg DeletePlatformIdentityParams) (int64, error) DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error DeleteRegion(ctx context.Context, id uuid.UUID) (int64, error) DeleteRole(ctx context.Context, id uuid.UUID) (int64, error) @@ -139,6 +145,8 @@ type Querier interface { GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) GetOrgBySlug(ctx context.Context, slug string) (Org, error) + GetPlatformIDP(ctx context.Context, id uuid.UUID) (PlatformIdentityProvider, error) + GetPlatformIdentity(ctx context.Context, arg GetPlatformIdentityParams) (PlatformIdentity, error) GetPlatformSetting(ctx context.Context, key string) ([]byte, error) GetRegion(ctx context.Context, id uuid.UUID) (Region, error) GetRole(ctx context.Context, id uuid.UUID) (Role, error) @@ -205,6 +213,7 @@ type Querier interface { ListOrgMembersPage(ctx context.Context, arg ListOrgMembersPageParams) ([]ListOrgMembersPageRow, error) ListOrgs(ctx context.Context) ([]Org, error) ListPendingInvitations(ctx context.Context) ([]ListPendingInvitationsRow, error) + ListPlatformIDPs(ctx context.Context) ([]PlatformIdentityProvider, error) ListPlatformRegions(ctx context.Context) ([]Region, error) // A monitor's results newest first, a page from a keyset cursor (see // paging.go) whose string key is region and checker. @@ -215,6 +224,7 @@ type Querier interface { ListStatusPages(ctx context.Context) ([]StatusPage, error) ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) + ListUserPlatformIdentities(ctx context.Context, userID uuid.UUID) ([]ListUserPlatformIdentitiesRow, error) // Row-level security limits this to platform regions and the scope's org; // the org's own regions come first. ListVisibleRegions(ctx context.Context) ([]Region, error) @@ -304,6 +314,8 @@ type Querier interface { SetUserOrgLimit(ctx context.Context, arg SetUserOrgLimitParams) (SetUserOrgLimitRow, error) // Other instances of the same agent seen in the last day. SiblingInstances(ctx context.Context, agentID uuid.UUID) ([]SiblingInstancesRow, error) + // Accounts that can sign in only through this provider. + SoleSignInUsers(ctx context.Context, providerID uuid.UUID) (int64, error) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]StatusPageMonitorsRow, error) // Deletes key and, as certmagic expects, everything below it. StorageDelete(ctx context.Context, arg StorageDeleteParams) (int64, error) @@ -318,12 +330,14 @@ type Querier interface { // Writes at most once a minute per instance; agents poll far more often. TouchAgentInstance(ctx context.Context, arg TouchAgentInstanceParams) error TouchIdentity(ctx context.Context, arg TouchIdentityParams) error + TouchPlatformIdentity(ctx context.Context, arg TouchPlatformIdentityParams) error UpdateAlertGroup(ctx context.Context, arg UpdateAlertGroupParams) (AlertGroup, error) UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error) UpdateGroup(ctx context.Context, arg UpdateGroupParams) (MonitorGroup, error) UpdateMaintenance(ctx context.Context, arg UpdateMaintenanceParams) (MaintenanceWindow, error) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error) UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error) + UpdatePlatformIDP(ctx context.Context, arg UpdatePlatformIDPParams) (PlatformIdentityProvider, error) UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error) UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error) UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error) diff --git a/internal/store/queries/platform_sso.sql b/internal/store/queries/platform_sso.sql new file mode 100644 index 0000000..13dbb1a --- /dev/null +++ b/internal/store/queries/platform_sso.sql @@ -0,0 +1,53 @@ +-- name: CreatePlatformIDP :one +INSERT INTO platform_identity_providers (id, kind, name, issuer, client_id, client_secret, allow_signup, enabled) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8) +RETURNING *; + +-- name: UpdatePlatformIDP :one +UPDATE platform_identity_providers +SET name = $2, issuer = $3, client_id = $4, client_secret = coalesce(sqlc.narg(client_secret), client_secret), + allow_signup = $5, enabled = $6, updated_at = now() +WHERE id = $1 +RETURNING *; + +-- name: GetPlatformIDP :one +SELECT * FROM platform_identity_providers WHERE id = $1; + +-- name: ListPlatformIDPs :many +SELECT * FROM platform_identity_providers ORDER BY name; + +-- name: DeletePlatformIDP :execrows +DELETE FROM platform_identity_providers WHERE id = $1; + +-- name: GetPlatformIdentity :one +SELECT * FROM platform_identities WHERE provider_id = $1 AND subject = $2; + +-- name: CreatePlatformIdentity :exec +INSERT INTO platform_identities (provider_id, subject, user_id, email) VALUES ($1, $2, $3, $4); + +-- name: TouchPlatformIdentity :exec +UPDATE platform_identities SET last_login_at = now(), email = coalesce(sqlc.narg(email), email) +WHERE provider_id = $1 AND subject = $2; + +-- name: ListUserPlatformIdentities :many +SELECT i.provider_id, i.email, i.created_at, p.name AS provider_name, p.kind +FROM platform_identities i JOIN platform_identity_providers p ON p.id = i.provider_id +WHERE i.user_id = $1 +ORDER BY p.name; + +-- name: DeletePlatformIdentity :execrows +DELETE FROM platform_identities WHERE user_id = $1 AND provider_id = $2; + +-- name: CountUserSignIns :one +-- Ways the account can sign in besides platform identities. +SELECT (password_hash IS NOT NULL)::integer + + (SELECT count(*) FROM user_identities ui WHERE ui.user_id = users.id)::integer + + (SELECT count(*) FROM platform_identities pi WHERE pi.user_id = users.id)::integer AS ways +FROM users WHERE id = $1; + +-- name: SoleSignInUsers :one +-- Accounts that can sign in only through this provider. +SELECT count(*) FROM platform_identities pi JOIN users u ON u.id = pi.user_id +WHERE pi.provider_id = $1 AND u.password_hash IS NULL + AND NOT EXISTS (SELECT 1 FROM user_identities ui WHERE ui.user_id = u.id) + AND NOT EXISTS (SELECT 1 FROM platform_identities o WHERE o.user_id = u.id AND o.provider_id <> pi.provider_id); diff --git a/internal/web/auth.templ b/internal/web/auth.templ index a81be86..37d106b 100644 --- a/internal/web/auth.templ +++ b/internal/web/auth.templ @@ -5,15 +5,36 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" ) -templ Login(p Page, signupAllowed bool, next string) { +// IDPButton is a platform identity provider to sign in with. +type IDPButton struct { + URL, Name, Kind string +} + +templ idpButtons(providers []IDPButton, labelID string) { + if len(providers) > 0 { +
+ for _, pr := range providers { + { i18n.T(ctx, labelID, "Name", pr.Name) } + } +
+

{ i18n.T(ctx, "auth.or") }

+ } +} + +// Login signs in; mfa starts at the second factor, after a provider +// confirmed who it is. +templ Login(p Page, signupAllowed bool, next string, providers []IDPButton, mfa bool) { @authShell(p) { + if !mfa { + @idpButtons(providers, "auth.sso.continue_with") + }
@formError() -
+
@field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true) @field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true)
-