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 } // Suspended accounts sign in too, but only to export or delete their // data (accountGate). // 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 }