feat: sign up and sign in with platform identity providers
ci / build (pull_request) Successful in 5m13s
ci / lint (pull_request) Successful in 5m45s
ci / image (pull_request) Successful in 6m20s
ci / test (pull_request) Successful in 11m46s

Platform admins register identity providers for the whole installation:
any OpenID Connect provider, checked by discovery, and GitHub or GitHub
Enterprise through OAuth, which reads the primary email GitHub verified.
Sign-in pages offer them; the sign-up page offers those open to sign-up,
also where email sign-up is closed for lack of a mail server.

Accounts are reached only through identities stored by subject. A new
identity signs up only with an email the provider confirmed, within the
per-address limit and sign-up mode, and never takes over an existing
account, including through an alias of its address: its owner links
the provider in the security settings. The account's TOTP still applies
after the provider. Unlinking refuses to remove the last way to sign in,
and removing a provider refuses while accounts depend on it.

The test browser takes the CSRF token from pages, as the console does.

Closes #114

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-23 01:26:14 +01:00
1 parent 1ad68e2e87
commit fe5c4fb24c
26 files changed
+2710 -351

No files matched your search

+12
View File
@@ -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.",
+4
View File
@@ -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",
+8 -1
View File
@@ -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(`<meta name="csrf-token" content="([^"]+)"`)
// page fetches path and returns the final status, path and body. Like the
// console's script, it takes the CSRF token from the page.
func (b *browser) page(path string) (int, string, string) {
b.t.Helper()
resp, err := b.hc.Get(b.base + path)
@@ -19,6 +23,9 @@ func (b *browser) page(path string) (int, string, string) {
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
if m := csrfMeta.FindSubmatch(body); m != nil {
b.csrf = string(m[1])
}
return resp.StatusCode, resp.Request.URL.Path, string(body)
}
+46 -7
View File
@@ -56,6 +56,7 @@ var flashErrors = map[ssoError]bool{
"sso_unavailable": true, "sso_provider_error": true, "sso_expired": true,
"sso_denied": true, "sso_not_member": true, "sso_not_provisioned": true,
"sso_link_required": true, "sso_identity_taken": true, "invalid_credentials": true,
"sso_email_unverified": true, "signup_limit": true,
"totp_required_by_org": true, "sso_required_by_org": true, "account_suspended": true,
}
@@ -88,25 +89,41 @@ func (s *Server) loginPage(c *gin.Context) {
c.Redirect(http.StatusSeeOther, next)
return
}
allowed, err := s.signupAllowed(c.Request.Context())
email, signupProviders, err := s.signupOptions(c.Request.Context())
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.Login(s.pageFor(c, "auth.login.title"), allowed, next))
allowed := email || len(signupProviders) > 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) {
+574
View File
@@ -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
}
+201
View File
@@ -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)
}
}
+6
View File
@@ -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)
+7
View File
@@ -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 {