Files
uptimesebi/internal/api/sso.go
T
Sebastian UnterschützandClaude Opus 5.5 8d7c1f856c
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 9m21s
ci / test (pull_request) Successful in 13m53s
ci / build (pull_request) Successful in 11m22s
ci / image (pull_request) Successful in 4m36s
feat: terms of service and versioned consent; data rights for every account
Terms of service join the legal notice and privacy policy, for the
platform only. Every account accepts the platform's privacy policy and
terms: on sign-up (also through an invitation) by ticking a box for the
versions shown, and after a sign-in through a provider right away. When
an admin saves a material change with "everyone has to accept again",
the document gets a new version and each account is asked at its next
request; corrections ask nobody. Acceptances are kept per version with
their time, as proof, and are part of the data export.

Until an account accepted, and while it is suspended, it can read the
documents, export its data, delete itself and sign out, nothing else:
pages lead to /consent or /account/suspended, other API calls answer 403
consent_required or account_suspended. Suspended accounts therefore sign
in again, by password or provider; their API tokens stay blocked.

Deleting an account deletes the organizations it owns, monitors and all,
also when they have other members (each organization has one owner); it
no longer refuses. The account settings name those organizations first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 22:26:20 +01:00

464 lines
13 KiB
Go

package api
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"net/url"
"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/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"
)
// viewerRoleID is the built-in Viewer role seeded by migration 00009.
var viewerRoleID = uuid.MustParse("00000000-0000-0000-0000-00000000a003")
const (
ssoCookie = "__Host-sso"
ssoFlowTTL = 10 * time.Minute
)
// ssoFlow is kept in Redis between the redirect to the IdP and the callback.
type ssoFlow struct {
Provider uuid.UUID `json:"provider"`
Org uuid.UUID `json:"org"`
Nonce string `json:"nonce"`
Verifier string `json:"verifier"`
// 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
// translates. Unlike JSON errors, the user has navigated away from our page.
type ssoError string
func ssoFlowKey(state string) string {
sum := sha256.Sum256([]byte(state))
return "sso_flow:" + hex.EncodeToString(sum[:])
}
func (s *Server) ssoProvider(row store.SsoProvider) (sso.Provider, error) {
p := sso.Provider{Issuer: row.Issuer, ClientID: row.ClientID, Scopes: row.Scopes}
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
}
// ssoLookup redirects the login page's slug form to the org's SSO URL.
func (s *Server) ssoLookup(c *gin.Context) {
slug := strings.ToLower(strings.TrimSpace(c.Query("org")))
if slug == "" {
c.Redirect(http.StatusSeeOther, "/login")
return
}
c.Redirect(http.StatusSeeOther, "/sso/"+url.PathEscape(slug))
}
// ssoChoose starts the flow if the org has exactly one enabled provider and
// otherwise lets the user pick.
func (s *Server) ssoChoose(c *gin.Context) {
ctx := c.Request.Context()
if !s.limitPage(c, "sso:ip:"+c.ClientIP(), 30, time.Minute) {
return
}
org, err := s.orgIDBySlug(ctx, c.Param("slug"))
if err != nil {
internalError(c, err)
return
}
var providers []store.ListEnabledSSOProvidersRow
if org != uuid.Nil {
err = s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error {
providers, err = q.ListEnabledSSOProviders(ctx)
return err
})
if err != nil {
internalError(c, err)
return
}
}
switch len(providers) {
case 0:
s.ssoAbort(c, uuid.Nil, "sso_unavailable")
case 1:
s.ssoStart(c, org, providers[0].ID)
default:
opts := make([]web.SSOOption, len(providers))
for i, p := range providers {
opts[i] = web.SSOOption{Name: p.Name, URL: "/sso/" + url.PathEscape(c.Param("slug")) + "/" + p.ID.String() + linkSuffix(c)}
}
web.Render(c, http.StatusOK, web.SSOChooser(s.pageFor(c, "sso.choose.title"), opts))
}
}
func linkSuffix(c *gin.Context) string {
if c.Query("link") == "1" {
return "?link=1"
}
return ""
}
func (s *Server) ssoStartProvider(c *gin.Context) {
ctx := c.Request.Context()
if !s.limitPage(c, "sso:ip:"+c.ClientIP(), 30, time.Minute) {
return
}
org, err := s.orgIDBySlug(ctx, c.Param("slug"))
if err != nil {
internalError(c, err)
return
}
id, err := uuid.Parse(c.Param("provider"))
if err != nil || org == uuid.Nil {
s.ssoAbort(c, uuid.Nil, "sso_unavailable")
return
}
s.ssoStart(c, org, id)
}
func (s *Server) ssoStart(c *gin.Context, org, providerID uuid.UUID) {
ctx := c.Request.Context()
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
}
var row store.SsoProvider
err := s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error {
var err error
row, err = q.GetSSOProvider(ctx, providerID)
return err
})
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.ssoProvider(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", providerID, "error", err)
s.ssoAbort(c, linkUser, "sso_provider_error")
return
}
state, _ := json.Marshal(ssoFlow{Provider: row.ID, Org: org, 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
}
// Binding the state to this browser stops an attacker from completing
// their own flow in a victim's browser (login CSRF).
setCookie(c, ssoCookie, flow.State, int(ssoFlowTTL.Seconds()))
c.Redirect(http.StatusFound, authURL)
}
func (s *Server) ssoCallback(c *gin.Context) {
ctx := c.Request.Context()
state := c.Query("state")
cookie, _ := c.Cookie(ssoCookie)
setCookie(c, ssoCookie, "", -1)
if state == "" || cookie != state {
s.ssoAbort(c, uuid.Nil, "sso_expired")
return
}
raw, err := s.rdb.GetDel(ctx, ssoFlowKey(state)).Bytes()
if err != nil {
s.ssoAbort(c, uuid.Nil, "sso_expired")
return
}
var f ssoFlow
if err := json.Unmarshal(raw, &f); err != nil {
internalError(c, err)
return
}
if c.Query("error") != "" {
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 {
row, err = q.GetSSOProvider(ctx, f.Provider)
return err
})
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.ssoProvider(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.ssoLink(c, row, f.LinkUser, claims)
return
}
userID, code, err := s.ssoResolveUser(ctx, row, claims)
if err != nil {
internalError(c, err)
return
}
if code != "" {
s.ssoAbort(c, uuid.Nil, code)
return
}
var user store.User
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
user, err = q.GetUser(ctx, userID)
return err
})
if err != nil {
internalError(c, err)
return
}
// Suspended accounts sign in too, but only to export or delete their
// data (accountGate).
if old := auth.Current(c); old != nil {
_ = s.sessions.Delete(ctx, old)
}
locale := deref(user.Locale)
if locale == "" {
locale = i18n.Lang(ctx)
}
sess, err := s.sessions.Create(ctx, auth.NewSession{
UserID: userID, OrgID: row.OrgID, Locale: locale, Method: auth.MethodSSO, SSOOrg: row.OrgID,
})
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, "/")
}
// ssoResolveUser maps an IdP identity to a user. It returns a non-empty
// error code when sign-in must be refused.
//
// Existing accounts are only ever reached through a stored identity. A
// matching email is not enough: the org controls its IdP and could assert
// the address of a user who also belongs to other orgs.
func (s *Server) ssoResolveUser(ctx context.Context, row store.SsoProvider, cl sso.Claims) (uuid.UUID, ssoError, error) {
var (
userID uuid.UUID
code ssoError
)
email := normalizeEmail(cl.Email)
err := s.db.Tx(ctx, tenant.Org(row.OrgID, uuid.Nil), func(q *store.Queries) error {
ident, err := q.GetIdentity(ctx, store.GetIdentityParams{ProviderID: row.ID, Subject: cl.Subject})
switch {
case err == nil:
member, err := q.IsMember(ctx, store.IsMemberParams{OrgID: row.OrgID, UserID: ident.UserID})
if err != nil {
return err
}
if !member {
code = "sso_not_member"
return nil
}
userID = ident.UserID
return q.TouchIdentity(ctx, store.TouchIdentityParams{ProviderID: row.ID, Subject: cl.Subject, Email: nonEmpty(email)})
case !errors.Is(err, pgx.ErrNoRows):
return err
}
if !row.AutoProvision || email == "" || !cl.EmailVerified || !domainAllowed(email, row.AllowedDomains) {
code = "sso_not_provisioned"
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
}
// Another address of the same mailbox has an account.
if taken, err := q.EmailKeyTaken(ctx, ptr(emailKey(email))); err != nil || taken {
code = "sso_link_required"
return err
}
// The identity provider confirmed the address.
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 err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: row.OrgID, UserID: u.ID}); err != nil {
return err
}
role := viewerRoleID
if row.DefaultRoleID != nil {
role = *row.DefaultRoleID
}
if _, err := q.CreateAssignment(ctx, store.CreateAssignmentParams{OrgID: row.OrgID, UserID: u.ID, RoleID: role}); err != nil {
return err
}
userID = u.ID
return q.CreateIdentity(ctx, store.CreateIdentityParams{ProviderID: row.ID, Subject: cl.Subject, OrgID: row.OrgID, UserID: u.ID, Email: nonEmpty(email)})
})
return userID, code, err
}
func (s *Server) ssoLink(c *gin.Context, row store.SsoProvider, 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.Org(row.OrgID, userID), func(q *store.Queries) error {
member, err := q.IsMember(ctx, store.IsMemberParams{OrgID: row.OrgID, UserID: userID})
if err != nil {
return err
}
if !member {
code = "sso_not_member"
return nil
}
ident, err := q.GetIdentity(ctx, store.GetIdentityParams{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.CreateIdentity(ctx, store.CreateIdentityParams{
ProviderID: row.ID, Subject: cl.Subject, OrgID: row.OrgID, UserID: userID, Email: nonEmpty(normalizeEmail(cl.Email)),
})
})
if err != nil {
internalError(c, err)
return
}
if code != "" {
s.ssoAbort(c, userID, code)
return
}
c.Redirect(http.StatusSeeOther, "/settings/security?sso=linked")
}
// ssoAbort sends the browser back to where the flow started with an error
// code the page renders in the user's language.
func (s *Server) ssoAbort(c *gin.Context, linkUser uuid.UUID, code ssoError) {
target := "/login"
if linkUser != uuid.Nil {
target = "/settings/security"
}
c.Redirect(http.StatusSeeOther, target+"?sso_error="+url.QueryEscape(string(code)))
}
func (s *Server) orgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) {
var id uuid.UUID
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
var err error
id, err = q.OrgIDBySlug(ctx, strings.ToLower(slug))
return err
})
return id, err
}
func (s *Server) limitPage(c *gin.Context, key string, n int, window time.Duration) bool {
ok, err := s.limiter.Allow(c.Request.Context(), key, n, window)
if err != nil {
internalError(c, err)
return false
}
if !ok {
c.Header("Retry-After", "60")
c.AbortWithStatus(http.StatusTooManyRequests)
return false
}
return true
}
func domainAllowed(email string, allowed []string) bool {
if len(allowed) == 0 {
return true
}
at := strings.LastIndexByte(email, '@')
if at < 0 {
return false
}
domain := email[at+1:]
for _, d := range allowed {
if domain == d {
return true
}
}
return false
}
func nonEmpty(s string) *string {
if s == "" {
return nil
}
return &s
}
func truncate(s string, n int) string {
if r := []rune(s); len(r) > n {
return string(r[:n])
}
return s
}