Repository Public
1package identity23import (4 "context"5 "crypto/rand"6 "errors"7 "time"89 "github.com/go-webauthn/webauthn/protocol"10 "github.com/google/uuid"11 "github.com/jackc/pgx/v5"1213 "clustr.spboucher.ai/mcc/internal/audit"14 "clustr.spboucher.ai/mcc/internal/authz"15 "clustr.spboucher.ai/mcc/internal/httpx"16 "clustr.spboucher.ai/mcc/internal/ids"17 "clustr.spboucher.ai/mcc/internal/secret"18)1920// InvitationParams describes an invitation to create.21type InvitationParams struct {22 Purpose string // new_account (default) | link | recovery23 Role authz.Role24 Handle string25 DisplayName string26 TargetUserID *uuid.UUID27 TTL time.Duration28 Note string29}3031const invCols = `i.id, i.purpose, i.role::text, coalesce(i.handle::text,''), coalesce(i.display_name,''), i.target_user_id, i.note, i.created_by,32 coalesce((select display_name from users where id=i.created_by),''), i.created_at, i.expires_at, i.consumed_at, i.revoked_at,33 i.completed_at, i.failed_attempts, i.resulting_user_id`3435func scanInvitation(r pgx.Row, extra ...any) (Invitation, error) {36 var i Invitation37 var role string38 dst := append([]any{&i.ID, &i.Purpose, &role, &i.Handle, &i.DisplayName, &i.TargetUserID, &i.Note, &i.CreatedBy, &i.CreatedByName,39 &i.CreatedAt, &i.ExpiresAt, &i.ConsumedAt, &i.RevokedAt, &i.CompletedAt, &i.FailedAttempts, &i.ResultingUserID}, extra...)40 err := r.Scan(dst...)41 i.Role = authz.Role(role)42 return i, err43}4445// CreateInvitation issues a single-use invitation and returns its clear46// token, shown once. actor is nil only for the out-of-band CLI.47//48// Rules: the actor must be allowed to assign the role; an invitation never49// silently targets an existing account by handle; "recovery" (register a new50// passkey without signing in) can only be created out of band.51func (s *Service) CreateInvitation(ctx context.Context, actor *Session, p InvitationParams, meta ReqMeta) (Invitation, string, error) {52 if p.Purpose == "" {53 p.Purpose = "new_account"54 }55 if !p.Role.Valid() {56 return Invitation{}, "", httpx.Validation("Unknown role.")57 }58 if p.TTL == 0 {59 p.TTL = defaultInvitationTTL60 }61 if p.TTL < time.Minute || p.TTL > maxInvitationTTL {62 return Invitation{}, "", httpx.Validation("ttl_minutes must be between 1 and 1440.")63 }64 if len(p.Note) > 500 {65 return Invitation{}, "", httpx.Validation("Note is too long.")66 }67 var handle, name *string68 switch p.Purpose {69 case "new_account":70 if p.TargetUserID != nil {71 return Invitation{}, "", httpx.Validation("target_user_id is not allowed for a new account.")72 }73 if actor != nil && !authz.CanAssignRole(actor.User.Role, "", p.Role) {74 s.audit(ctx, s.pool, actor, meta, "invitation.create", "", "", audit.Denied, "role not assignable by actor", map[string]any{"role": string(p.Role)})75 return Invitation{}, "", httpx.ErrForbidden76 }77 if p.Handle != "" {78 h, err := normalizeHandle(p.Handle)79 if err != nil {80 return Invitation{}, "", err81 }82 var exists bool83 if err := s.pool.QueryRow(ctx, `select exists(select 1 from users where handle=$1)`, h).Scan(&exists); err != nil {84 return Invitation{}, "", err85 }86 if exists {87 return Invitation{}, "", ErrHandleTaken88 }89 handle = &h90 }91 if p.DisplayName != "" {92 n, err := normalizeName(p.DisplayName)93 if err != nil {94 return Invitation{}, "", err95 }96 name = &n97 }98 case "link", "recovery":99 if p.TargetUserID == nil {100 return Invitation{}, "", httpx.Validation("target_user_id is required.")101 }102 target, err := s.UserByID(ctx, *p.TargetUserID)103 if err != nil {104 return Invitation{}, "", err105 }106 if p.Purpose == "recovery" {107 if actor != nil {108 return Invitation{}, "", httpx.ErrForbidden // out of band only109 }110 p.Role = target.Role // recovery never changes the role111 } else if actor == nil || !authz.CanAssignRole(actor.User.Role, target.Role, p.Role) {112 s.audit(ctx, s.pool, actor, meta, "invitation.create", "user", target.ID.String(), audit.Denied, "role not assignable by actor", map[string]any{"role": string(p.Role)})113 return Invitation{}, "", httpx.ErrForbidden114 }115 default:116 return Invitation{}, "", httpx.Validation("Unknown purpose.")117 }118119 token, hash := secret.NewToken()120 now := s.now()121 inv := Invitation{ID: ids.New(), Purpose: p.Purpose, Role: p.Role, TargetUserID: p.TargetUserID, Note: p.Note, CreatedAt: now, ExpiresAt: now.Add(p.TTL)}122 if handle != nil {123 inv.Handle = *handle124 }125 if name != nil {126 inv.DisplayName = *name127 }128 var createdBy *uuid.UUID129 if actor != nil {130 createdBy = &actor.User.ID131 inv.CreatedBy, inv.CreatedByName = createdBy, actor.User.DisplayName132 }133 tx, err := s.pool.Begin(ctx)134 if err != nil {135 return Invitation{}, "", err136 }137 defer tx.Rollback(ctx)138 _, err = tx.Exec(ctx, `insert into invitations(id,token_hash,role,handle,display_name,target_user_id,note,created_by,created_at,expires_at,purpose)139 values ($1,$2,$3::user_role,$4,$5,$6,$7,$8,$9,$10,$11)`, inv.ID, hash, string(p.Role), handle, name, p.TargetUserID, p.Note, createdBy, now, inv.ExpiresAt, p.Purpose)140 if isUniqueViolation(err) {141 return Invitation{}, "", httpx.Conflict("recovery_pending", "A recovery invitation is already open for this account.")142 } else if err != nil {143 return Invitation{}, "", err144 }145 e := audit.Entry{ActorKind: "cli", ActorLabel: "mccctl", Action: "invitation.create", TargetKind: "invitation", TargetID: inv.ID.String(),146 Outcome: audit.Success, CorrelationID: meta.Correlation, IP: meta.IP,147 Params: map[string]any{"purpose": p.Purpose, "role": string(p.Role), "ttl_s": int(p.TTL.Seconds()), "handle": inv.Handle}}148 if actor != nil {149 e.ActorKind, e.ActorID, e.ActorLabel, e.SessionID, e.DeviceID = "user", &actor.User.ID, actor.User.Handle, &actor.ID, &actor.DeviceID150 }151 if p.TargetUserID != nil {152 e.Params["target_user_id"] = p.TargetUserID.String()153 }154 if _, err := audit.Append(ctx, tx, e); err != nil {155 return Invitation{}, "", err156 }157 return inv, token, tx.Commit(ctx)158}159160func (s *Service) ListInvitations(ctx context.Context) ([]Invitation, error) {161 rows, err := s.pool.Query(ctx, `select `+invCols+` from invitations i order by i.created_at desc limit 200`)162 if err != nil {163 return nil, err164 }165 return pgx.CollectRows(rows, func(r pgx.CollectableRow) (Invitation, error) { return scanInvitation(r) })166}167168// RevokeInvitation invalidates a pending or in-progress invitation.169func (s *Service) RevokeInvitation(ctx context.Context, actor *Session, id uuid.UUID, meta ReqMeta) error {170 tx, err := s.pool.Begin(ctx)171 if err != nil {172 return err173 }174 defer tx.Rollback(ctx)175 tag, err := tx.Exec(ctx, `update invitations set revoked_at=$2 where id=$1 and revoked_at is null and completed_at is null`, id, s.now())176 if err != nil {177 return err178 }179 if tag.RowsAffected() == 0 {180 return httpx.ErrNotFound181 }182 if err := s.audit(ctx, tx, actor, meta, "invitation.revoke", "invitation", id.String(), audit.Success, "", nil); err != nil {183 return err184 }185 return tx.Commit(ctx)186}187188// ExchangeInvitation atomically consumes an invitation token and opens a189// short setup transaction. The token can never be exchanged twice: the190// single UPDATE below is the only place consumed_at is set. All failures191// return the same error so the endpoint is not an oracle.192func (s *Service) ExchangeInvitation(ctx context.Context, token string, meta ReqMeta) (*SetupTx, string, error) {193 hash, err := secret.Parse(token)194 if err != nil {195 return nil, "", ErrInvitation196 }197 now := s.now()198 tx, err := s.pool.Begin(ctx)199 if err != nil {200 return nil, "", err201 }202 defer tx.Rollback(ctx)203 var invID uuid.UUID204 err = tx.QueryRow(ctx, `update invitations set consumed_at=$2205 where token_hash=$1 and consumed_at is null and revoked_at is null and expires_at > $2 returning id`, hash, now).Scan(&invID)206 if errors.Is(err, pgx.ErrNoRows) {207 tx.Rollback(ctx)208 // Record the refusal when the token matches a known (dead) invitation; unknown tokens are just noise.209 var id uuid.UUID210 if s.pool.QueryRow(ctx, `select id from invitations where token_hash=$1`, hash).Scan(&id) == nil {211 s.audit(ctx, s.pool, nil, meta, "invitation.exchange", "invitation", id.String(), audit.Denied, "expired, revoked or already used", nil)212 }213 return nil, "", ErrInvitation214 } else if err != nil {215 return nil, "", err216 }217 txToken, txHash := secret.NewToken()218 stx := &SetupTx{ID: ids.New(), ExpiresAt: now.Add(setupTxTTL)}219 var ip *string220 if meta.IP != nil {221 v := meta.IP.String()222 ip = &v223 }224 if _, err := tx.Exec(ctx, `insert into invitation_transactions(id,invitation_id,tx_hash,created_at,expires_at,ip) values ($1,$2,$3,$4,$5,$6::inet)`,225 stx.ID, invID, txHash, now, stx.ExpiresAt, ip); err != nil {226 return nil, "", err227 }228 if stx.Invitation, err = scanInvitation(tx.QueryRow(ctx, `select `+invCols+` from invitations i where i.id=$1`, invID)); err != nil {229 return nil, "", err230 }231 if err := s.audit(ctx, tx, nil, meta, "invitation.exchange", "invitation", invID.String(), audit.Success, "", nil); err != nil {232 return nil, "", err233 }234 return stx, txToken, tx.Commit(ctx)235}236237// SetupTransaction resolves a live setup transaction from its token.238func (s *Service) SetupTransaction(ctx context.Context, txToken string) (*SetupTx, error) {239 hash, err := secret.Parse(txToken)240 if err != nil {241 return nil, ErrSetupTx242 }243 return s.loadSetupTx(ctx, s.pool, `t.tx_hash=$1`, hash, false)244}245246func (s *Service) loadSetupTx(ctx context.Context, q rowQuerier, where string, arg any, lock bool) (*SetupTx, error) {247 sql := `select ` + invCols + `, t.id, t.expires_at, t.completed_at from invitation_transactions t join invitations i on i.id=t.invitation_id where ` + where248 if lock {249 sql += ` for update of i, t`250 }251 var stx SetupTx252 var completed *time.Time253 inv, err := scanInvitation(q.QueryRow(ctx, sql, arg), &stx.ID, &stx.ExpiresAt, &completed)254 if errors.Is(err, pgx.ErrNoRows) {255 return nil, ErrSetupTx256 } else if err != nil {257 return nil, err258 }259 if completed != nil || inv.CompletedAt != nil || inv.RevokedAt != nil || !s.now().Before(stx.ExpiresAt) {260 return nil, ErrSetupTx261 }262 stx.Invitation = inv263 return &stx, nil264}265266// SetSetupProfile records the handle and display name chosen by the invitee267// when the inviter left them open.268func (s *Service) SetSetupProfile(ctx context.Context, txToken, handle, displayName string) (*SetupTx, error) {269 stx, err := s.SetupTransaction(ctx, txToken)270 if err != nil {271 return nil, err272 }273 if stx.Invitation.Purpose != "new_account" {274 return nil, httpx.Conflict("profile_fixed", "This invitation is bound to an existing account.")275 }276 h, n := stx.Invitation.Handle, stx.Invitation.DisplayName277 // Values fixed by the inviter cannot be overridden by the invitee.278 if h == "" {279 if h, err = normalizeHandle(handle); err != nil {280 return nil, err281 }282 }283 if n == "" {284 if n, err = normalizeName(displayName); err != nil {285 return nil, err286 }287 }288 var taken bool289 if err := s.pool.QueryRow(ctx, `select exists(select 1 from users where handle=$1)`, h).Scan(&taken); err != nil {290 return nil, err291 }292 if taken {293 return nil, ErrHandleTaken294 }295 if _, err := s.pool.Exec(ctx, `update invitations set handle=$2, display_name=$3 where id=$1`, stx.Invitation.ID, h, n); err != nil {296 return nil, err297 }298 stx.Invitation.Handle, stx.Invitation.DisplayName = h, n299 return stx, nil300}301302// AbandonSetup ends a setup transaction; the invitation stays consumed.303func (s *Service) AbandonSetup(ctx context.Context, txToken string, meta ReqMeta) error {304 stx, err := s.SetupTransaction(ctx, txToken)305 if err != nil {306 return err307 }308 if _, err := s.pool.Exec(ctx, `update invitations set revoked_at=$2 where id=$1 and completed_at is null`, stx.Invitation.ID, s.now()); err != nil {309 return err310 }311 return s.audit(ctx, s.pool, nil, meta, "invitation.abandon", "invitation", stx.Invitation.ID.String(), audit.Success, "", nil)312}313314// BeginSetupRegistration starts the passkey ceremony of a setup transaction315// (new account, or recovery of an existing one).316func (s *Service) BeginSetupRegistration(ctx context.Context, txToken string) (uuid.UUID, *protocol.CredentialCreation, error) {317 stx, err := s.SetupTransaction(ctx, txToken)318 if err != nil {319 return uuid.Nil, nil, err320 }321 inv := stx.Invitation322 var u waUser323 data := challengeData{}324 switch inv.Purpose {325 case "new_account":326 if inv.Handle == "" || inv.DisplayName == "" {327 return uuid.Nil, nil, ErrProfileRequired328 }329 wh := make([]byte, 32)330 if _, err := rand.Read(wh); err != nil {331 return uuid.Nil, nil, err332 }333 u = waUser{User: User{Handle: inv.Handle, DisplayName: inv.DisplayName, WebAuthnHandle: wh}}334 data.NewHandle, data.NewDisplayName, data.NewUserHandle = inv.Handle, inv.DisplayName, wh335 case "recovery":336 target, err := s.UserByID(ctx, *inv.TargetUserID)337 if err != nil || target.DisabledAt != nil {338 return uuid.Nil, nil, ErrSetupTx339 }340 u = waUser{User: target} // no exclusions: the old authenticators are presumed lost341 default:342 return uuid.Nil, nil, httpx.Conflict("link_required", "Sign in to the existing account to accept this invitation.")343 }344 opts, sd, err := s.wa.BeginRegistration(u, registrationOptions(nil))345 if err != nil {346 return uuid.Nil, nil, err347 }348 data.Session = *sd349 id, err := s.storeChallenge(ctx, "registration", inv.TargetUserID, nil, &stx.ID, data)350 return id, opts, err351}352353// FinishSetupRegistration verifies the new passkey and, in one database354// transaction, creates the account (or recovers it), stores the passkey,355// completes the invitation and opens the first session.356func (s *Service) FinishSetupRegistration(ctx context.Context, txToken string, challengeID uuid.UUID, credential []byte, client ClientInfo, label string, meta ReqMeta) (*AuthResult, error) {357 if !client.valid() {358 return nil, httpx.Validation("client.kind must be web, macos or ios.")359 }360 stx, err := s.SetupTransaction(ctx, txToken)361 if err != nil {362 return nil, err363 }364 ch, err := s.consumeChallenge(ctx, challengeID, "registration")365 if err != nil {366 return nil, err367 }368 if ch.TxID == nil || *ch.TxID != stx.ID {369 return nil, ErrChallenge370 }371 inv := stx.Invitation372 var u waUser373 if inv.Purpose == "recovery" {374 target, err := s.UserByID(ctx, *inv.TargetUserID)375 if err != nil {376 return nil, ErrSetupTx377 }378 u = waUser{User: target}379 } else {380 u = waUser{User: User{Handle: ch.Data.NewHandle, DisplayName: ch.Data.NewDisplayName, WebAuthnHandle: ch.Data.NewUserHandle}}381 }382 cred, err := s.verifyCreation(u, ch, credential)383 if err != nil {384 return nil, s.setupFailure(ctx, inv.ID, meta, "attestation verification failed")385 }386387 tx, err := s.pool.Begin(ctx)388 if err != nil {389 return nil, err390 }391 defer tx.Rollback(ctx)392 // Re-check under lock: only one finisher can complete the invitation.393 locked, err := s.loadSetupTx(ctx, tx, `t.id=$1`, stx.ID, true)394 if err != nil {395 return nil, err396 }397 now := s.now()398 user := u.User399 params := map[string]any{"purpose": inv.Purpose, "role": string(locked.Invitation.Role), "client": client.Kind}400 switch inv.Purpose {401 case "new_account":402 user.ID, user.Role, user.Locale, user.CreatedAt = ids.New(), locked.Invitation.Role, "fr", now403 _, err = tx.Exec(ctx, `insert into users(id,handle,display_name,role,webauthn_handle,created_at) values ($1,$2,$3,$4::user_role,$5,$6)`,404 user.ID, user.Handle, user.DisplayName, string(user.Role), user.WebAuthnHandle, now)405 if isUniqueViolation(err) {406 return nil, ErrHandleTaken407 } else if err != nil {408 return nil, err409 }410 case "recovery":411 // The previous authenticators are presumed lost or compromised: revoke them and every session.412 if _, err := tx.Exec(ctx, `update passkeys set revoked_at=$2 where user_id=$1 and revoked_at is null`, user.ID, now); err != nil {413 return nil, err414 }415 if _, err := tx.Exec(ctx, `update sessions set revoked_at=$2, revoked_reason='account_recovery' where user_id=$1 and revoked_at is null`, user.ID, now); err != nil {416 return nil, err417 }418 default:419 return nil, ErrSetupTx420 }421 pk, err := s.insertPasskey(ctx, tx, user.ID, cred, label)422 if err != nil {423 return nil, err424 }425 if _, err := tx.Exec(ctx, `update invitations set completed_at=$2, resulting_user_id=$3 where id=$1`, inv.ID, now, user.ID); err != nil {426 return nil, err427 }428 if _, err := tx.Exec(ctx, `update invitation_transactions set completed_at=$2 where id=$1`, stx.ID, now); err != nil {429 return nil, err430 }431 res, err := s.issueSession(ctx, tx, user, &pk.ID, client, meta)432 if err != nil {433 return nil, err434 }435 action := "invitation.complete"436 if inv.Purpose == "recovery" {437 action = "account.recovered"438 }439 if err := s.audit(ctx, tx, &res.Session, meta, action, "user", user.ID.String(), audit.Success, "", params); err != nil {440 return nil, err441 }442 return res, tx.Commit(ctx)443}444445// setupFailure counts a failed attempt; after maxSetupFailures the invitation is revoked.446func (s *Service) setupFailure(ctx context.Context, invID uuid.UUID, meta ReqMeta, reason string) error {447 var n int448 if err := s.pool.QueryRow(ctx, `update invitations set failed_attempts=failed_attempts+1,449 revoked_at=case when failed_attempts+1 >= $2 then $3 else revoked_at end where id=$1 returning failed_attempts`,450 invID, maxSetupFailures, s.now()).Scan(&n); err != nil {451 return err452 }453 s.audit(ctx, s.pool, nil, meta, "invitation.attempt_failed", "invitation", invID.String(), audit.Denied, reason, map[string]any{"failed_attempts": n})454 return ErrCredential455}456457// LinkSetup applies a "link" invitation to the existing account it targets.458// The caller must be signed in AS THAT ACCOUNT with a fresh step-up (enforced459// here, not only in the handler) and must send an explicit confirmation.460func (s *Service) LinkSetup(ctx context.Context, txToken string, sess *Session, confirm bool, meta ReqMeta) (User, error) {461 stx, err := s.SetupTransaction(ctx, txToken)462 if err != nil {463 return User{}, err464 }465 inv := stx.Invitation466 if inv.Purpose != "link" {467 return User{}, httpx.Conflict("not_a_link_invitation", "This invitation creates a new account.")468 }469 if sess == nil {470 return User{}, httpx.ErrUnauthenticated471 }472 if inv.TargetUserID == nil || *inv.TargetUserID != sess.User.ID {473 s.audit(ctx, s.pool, sess, meta, "invitation.link", "invitation", inv.ID.String(), audit.Denied, "signed-in account is not the invitation target", nil)474 return User{}, ErrWrongAccount475 }476 if !s.StepUpFresh(sess) {477 return User{}, httpx.ErrStepUp478 }479 if !confirm {480 return User{}, httpx.Validation("Explicit confirmation is required.")481 }482 tx, err := s.pool.Begin(ctx)483 if err != nil {484 return User{}, err485 }486 defer tx.Rollback(ctx)487 if _, err := tx.Exec(ctx, `select pg_advisory_xact_lock(7305001)`); err != nil {488 return User{}, err489 }490 locked, err := s.loadSetupTx(ctx, tx, `t.id=$1`, stx.ID, true)491 if err != nil {492 return User{}, err493 }494 // A link that would demote the last owner is refused like any other demotion.495 if sess.User.Role == authz.Owner && locked.Invitation.Role != authz.Owner {496 if n, err := activeOwners(ctx, tx); err != nil {497 return User{}, err498 } else if n <= 1 {499 return User{}, ErrLastOwner500 }501 }502 now := s.now()503 if _, err := tx.Exec(ctx, `update users set role=$2::user_role where id=$1`, sess.User.ID, string(locked.Invitation.Role)); err != nil {504 return User{}, err505 }506 if _, err := tx.Exec(ctx, `update invitations set completed_at=$2, resulting_user_id=$3 where id=$1`, inv.ID, now, sess.User.ID); err != nil {507 return User{}, err508 }509 if _, err := tx.Exec(ctx, `update invitation_transactions set completed_at=$2 where id=$1`, stx.ID, now); err != nil {510 return User{}, err511 }512 if err := s.audit(ctx, tx, sess, meta, "invitation.link", "user", sess.User.ID.String(), audit.Success, "",513 map[string]any{"role_from": string(sess.User.Role), "role_to": string(locked.Invitation.Role)}); err != nil {514 return User{}, err515 }516 if err := tx.Commit(ctx); err != nil {517 return User{}, err518 }519 return s.UserByID(ctx, sess.User.ID)520}521522// ── Out-of-band operations (mccctl, run on the host) ───────────────────────523524// BootstrapOwner issues the first owner invitation. It refuses when an owner525// who can sign in already exists.526func (s *Service) BootstrapOwner(ctx context.Context, handle, displayName string, ttl time.Duration) (Invitation, string, error) {527 n, err := activeOwners(ctx, s.pool)528 if err != nil {529 return Invitation{}, "", err530 }531 if n > 0 {532 return Invitation{}, "", httpx.Conflict("owner_exists", "An owner already exists; use a normal invitation or a recovery invitation.")533 }534 return s.CreateInvitation(ctx, nil, InvitationParams{Role: authz.Owner, Handle: handle, DisplayName: displayName, TTL: ttl, Note: "bootstrap"}, ReqMeta{Correlation: uuid.New()})535}536537// RecoveryInvitation issues an out-of-band recovery invitation for an existing account.538func (s *Service) RecoveryInvitation(ctx context.Context, handle string, ttl time.Duration) (Invitation, string, error) {539 h, err := normalizeHandle(handle)540 if err != nil {541 return Invitation{}, "", err542 }543 var id uuid.UUID544 if err := s.pool.QueryRow(ctx, `select id from users where handle=$1 and disabled_at is null`, h).Scan(&id); errors.Is(err, pgx.ErrNoRows) {545 return Invitation{}, "", httpx.ErrNotFound546 } else if err != nil {547 return Invitation{}, "", err548 }549 return s.CreateInvitation(ctx, nil, InvitationParams{Purpose: "recovery", Role: authz.Viewer, TargetUserID: &id, TTL: ttl, Note: "recovery"}, ReqMeta{Correlation: uuid.New()})550}551