Files
archie/modules/governance/internal/store/accounts.go
T
sam 35688b449a fix(governance): invite a member by email without an identity provider (#2110)
Adding a member by email refused with a 409 whenever no OIDC issuer was set,
so an install with local accounts only could not invite anyone by address.

An address now reserves the identity under a local issuer instead, and a local
account made with that address adopts it: the invitation's roles carry over and
the organisation shows one member, not two. A provider subject still needs the
provider that asserts it, and the refusal says so.
2026-11-27 19:08:08 +11:00

378 lines
13 KiB
Go

package store
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"github.com/jmoiron/sqlx"
)
const setupAdvisoryLock = 484726231
// AccountRow is a local password account in governance.accounts.
type AccountRow struct {
IdentityID string `db:"identity_id"`
Email string `db:"email"`
PasswordHash string `db:"password_hash"`
RecoveryHash sql.NullString `db:"recovery_hash"`
FailedAttempts int `db:"failed_attempts"`
LockedUntil sql.NullTime `db:"locked_until"`
}
// AuthSettingsRow stores instance public URL and OIDC configuration.
type AuthSettingsRow struct {
PublicURL string `db:"public_url"`
OIDCIssuer string `db:"oidc_issuer"`
OIDCAudience string `db:"oidc_audience"`
OIDCClientID string `db:"oidc_client_id"`
// TrustedProxies is a JSON array of addresses and CIDR ranges.
TrustedProxies []byte `db:"trusted_proxies"`
}
// RegisterAccountParams carries the validated inputs to create a user account.
type RegisterAccountParams struct {
IdentityID string
Email string
DisplayName string
PasswordHash string
OrgID string
PublicURL string
Role string
ActorID string
RequestID string
Bootstrap bool
Now time.Time
}
// AccountSetupRequired reports whether no local accounts exist yet.
func (s *Store) AccountSetupRequired(ctx context.Context) (bool, error) {
var required bool
err := s.db.GetContext(ctx, &required, `SELECT NOT EXISTS (SELECT 1 FROM governance.accounts)`)
return required, err
}
// RegisterAccount creates a local user account and its organisation membership.
func (s *Store) RegisterAccount(ctx context.Context, p RegisterAccountParams) (IdentityRow, error) {
var out IdentityRow
err := s.withTx(ctx, func(tx *sqlx.Tx) error {
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`, setupAdvisoryLock); err != nil {
return err
}
var anyAccounts bool
if err := tx.GetContext(ctx, &anyAccounts, `SELECT EXISTS (SELECT 1 FROM governance.accounts)`); err != nil {
return err
}
if p.Bootstrap && anyAccounts {
return ErrSetupComplete
}
if !p.Bootstrap && !anyAccounts {
return ErrCredentialRejected
}
if p.Bootstrap {
if err := saveBootstrapOrigin(ctx, tx, p.PublicURL); err != nil {
return err
}
}
return writeAccountTx(ctx, tx, p, &out)
})
return out, err
}
func saveBootstrapOrigin(ctx context.Context, tx *sqlx.Tx, origin string) error {
_, err := tx.ExecContext(ctx, `
INSERT INTO governance.authentication_settings (singleton, public_url) VALUES (true, $1)
ON CONFLICT (singleton) DO UPDATE SET public_url = EXCLUDED.public_url`, origin)
return err
}
func writeAccountTx(ctx context.Context, tx *sqlx.Tx, p RegisterAccountParams, out *IdentityRow) error {
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.identities (id, kind, display_name, lifecycle, version, created_at, updated_at)
VALUES ($1, 'user', $2, 'active', 1, $3, $3)
ON CONFLICT (id) DO UPDATE
SET display_name = EXCLUDED.display_name, lifecycle = 'active',
version = governance.identities.version + 1, updated_at = EXCLUDED.updated_at`,
p.IdentityID, p.DisplayName, p.Now); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.identity_aliases (alias, identity_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
p.DisplayName, p.IdentityID); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.accounts (identity_id, email, password_hash) VALUES ($1, $2, $3)`,
p.IdentityID, p.Email, p.PasswordHash); err != nil {
if isUniqueViolation(err) {
return ErrAlreadyExists
}
return err
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.memberships (identity_id, org_id, role) VALUES ($1, $2, $3)
ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING`,
p.IdentityID, p.OrgID, p.Role); err != nil {
return err
}
if err := insertIdentityEvent(ctx, tx, IdentityEventRow{
IdentityID: p.IdentityID, EventType: "create", ToLifecycle: "active",
DisplayName: p.DisplayName, ActorID: p.ActorID, Source: "accounts",
RequestID: p.RequestID, At: p.Now, OrgID: sql.NullString{String: p.OrgID, Valid: true},
}); err != nil {
return err
}
return tx.GetContext(ctx, out, `SELECT `+identityCols+` FROM governance.identities WHERE id = $1`, p.IdentityID)
}
// SignInAccount authenticates email with verify, applies lockout rules, and opens a session.
func (s *Store) SignInAccount(
ctx context.Context,
email, tokenHash string,
expires time.Time,
verify func(passwordHash string) bool,
) (IdentityRow, error) {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return IdentityRow{}, err
}
defer func() { _ = tx.Rollback() }()
var acc AccountRow
err = tx.GetContext(ctx, &acc, `
SELECT identity_id, email, password_hash, recovery_hash, failed_attempts, locked_until
FROM governance.accounts WHERE email = $1 FOR UPDATE`,
strings.ToLower(strings.TrimSpace(email)))
if errors.Is(err, sql.ErrNoRows) {
_ = verify("")
return IdentityRow{}, ErrCredentialRejected
}
if err != nil {
return IdentityRow{}, err
}
valid := verify(acc.PasswordHash)
if acc.LockedUntil.Valid && time.Now().Before(acc.LockedUntil.Time) {
return IdentityRow{}, ErrCredentialRejected
}
if !valid {
return IdentityRow{}, recordFailedLogin(ctx, tx, acc)
}
var id IdentityRow
if err := tx.GetContext(ctx, &id, `SELECT `+identityCols+` FROM governance.identities WHERE id = $1`, acc.IdentityID); err != nil {
return IdentityRow{}, err
}
if id.Lifecycle != "active" {
return IdentityRow{}, ErrCredentialRejected
}
if err := openSignInSessionTx(ctx, tx, acc.IdentityID, tokenHash, expires); err != nil {
return IdentityRow{}, err
}
return id, tx.Commit()
}
func recordFailedLogin(ctx context.Context, tx *sqlx.Tx, acc AccountRow) error {
attempts := acc.FailedAttempts
if acc.LockedUntil.Valid {
attempts = 0
}
if _, err := tx.ExecContext(ctx, `
UPDATE governance.accounts
SET failed_attempts = $2,
locked_until = CASE WHEN $2 >= 5 THEN now() + interval '15 minutes' ELSE NULL END
WHERE identity_id = $1`, acc.IdentityID, attempts+1); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return err
}
return ErrCredentialRejected
}
func openSignInSessionTx(ctx context.Context, tx *sqlx.Tx, identityID, tokenHash string, expires time.Time) error {
if _, err := tx.ExecContext(ctx, `
UPDATE governance.accounts SET failed_attempts = 0, locked_until = NULL, last_sign_in_at = now()
WHERE identity_id = $1`,
identityID); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `DELETE FROM governance.account_sessions WHERE expires_at <= now()`); err != nil {
return err
}
_, err := tx.ExecContext(ctx, `
INSERT INTO governance.account_sessions (token_hash, identity_id, expires_at) VALUES ($1, $2, $3)`,
tokenHash, identityID, expires)
return err
}
// ResolveAccountSession resolves a session token hash to its active identity.
func (s *Store) ResolveAccountSession(ctx context.Context, tokenHash string) (IdentityRow, error) {
var out IdentityRow
err := s.db.GetContext(ctx, &out, `
SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at
FROM governance.account_sessions s
JOIN governance.identities i ON i.id = s.identity_id
WHERE s.token_hash = $1 AND s.expires_at > now() AND i.lifecycle = 'active'`, tokenHash)
if errors.Is(err, sql.ErrNoRows) {
return IdentityRow{}, ErrCredentialRejected
}
return out, err
}
// DeleteAccountSession removes a session token.
func (s *Store) DeleteAccountSession(ctx context.Context, tokenHash string) error {
_, err := s.db.ExecContext(ctx, `DELETE FROM governance.account_sessions WHERE token_hash = $1`, tokenHash)
return err
}
// ChangeAccountPassword verifies the current password, updates the hash, and ends sessions.
func (s *Store) ChangeAccountPassword(ctx context.Context, identityID string, verify func(oldHash string) bool, newHash string) error {
return s.withTx(ctx, func(tx *sqlx.Tx) error {
var oldHash string
err := tx.GetContext(ctx, &oldHash, `
SELECT password_hash FROM governance.accounts WHERE identity_id = $1 FOR UPDATE`, identityID)
if errors.Is(err, sql.ErrNoRows) {
return ErrCredentialRejected
}
if err != nil {
return err
}
if !verify(oldHash) {
return ErrCredentialRejected
}
if _, err := tx.ExecContext(ctx, `
UPDATE governance.accounts SET password_hash = $2, failed_attempts = 0, locked_until = NULL
WHERE identity_id = $1`, identityID, newHash); err != nil {
return err
}
_, err = tx.ExecContext(ctx, `DELETE FROM governance.account_sessions WHERE identity_id = $1`, identityID)
return err
})
}
// OpenAccountSession opens an account session for an active user identity.
func (s *Store) OpenAccountSession(ctx context.Context, identityID, tokenHash string, expires time.Time) (IdentityRow, error) {
row, err := s.GetIdentity(ctx, identityID)
if err != nil {
return IdentityRow{}, err
}
if row.Kind != "user" || row.Lifecycle != "active" {
return IdentityRow{}, ErrCredentialRejected
}
if _, err := s.db.ExecContext(ctx, `
INSERT INTO governance.account_sessions (token_hash, identity_id, expires_at) VALUES ($1, $2, $3)`,
tokenHash, identityID, expires); err != nil {
return IdentityRow{}, err
}
if _, err := s.db.ExecContext(ctx, `
UPDATE governance.accounts SET last_sign_in_at = now() WHERE identity_id = $1`, identityID); err != nil {
return IdentityRow{}, err
}
return row, nil
}
// IsFreshAccountSession reports whether tokenHash belongs to identityID and was issued within 10 minutes.
func (s *Store) IsFreshAccountSession(ctx context.Context, identityID, tokenHash string) (bool, error) {
var fresh bool
err := s.db.GetContext(ctx, &fresh, `
SELECT EXISTS(
SELECT 1 FROM governance.account_sessions
WHERE token_hash = $1 AND identity_id = $2
AND expires_at > now() AND issued_at > now() - interval '10 minutes'
)`, tokenHash, identityID)
return fresh, err
}
// SetAccountRecoveryHash stores a single-use recovery secret hash on identityID's account.
func (s *Store) SetAccountRecoveryHash(ctx context.Context, identityID, recoveryHash string) error {
res, err := s.db.ExecContext(ctx, `
UPDATE governance.accounts SET recovery_hash = $2 WHERE identity_id = $1`, identityID, recoveryHash)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return ErrNotFound
}
return nil
}
// RecoverAccount consumes a recovery secret, sets newPasswordHash, and revokes sessions.
func (s *Store) RecoverAccount(ctx context.Context, email, recoveryHash, newPasswordHash string) error {
return s.withTx(ctx, func(tx *sqlx.Tx) error {
var id string
err := tx.GetContext(ctx, &id, `
UPDATE governance.accounts a
SET password_hash = $3, recovery_hash = NULL, failed_attempts = 0, locked_until = NULL
FROM governance.identities i
WHERE a.identity_id = i.id AND i.lifecycle = 'active'
AND a.email = $1 AND a.recovery_hash = $2
RETURNING a.identity_id`,
strings.ToLower(strings.TrimSpace(email)), recoveryHash, newPasswordHash)
if errors.Is(err, sql.ErrNoRows) {
return ErrCredentialRejected
}
if err != nil {
return err
}
_, err = tx.ExecContext(ctx, `DELETE FROM governance.account_sessions WHERE identity_id = $1`, id)
return err
})
}
// AuthenticationSettings returns the singleton authentication settings row.
func (s *Store) AuthenticationSettings(ctx context.Context) (AuthSettingsRow, error) {
var out AuthSettingsRow
err := s.db.GetContext(ctx, &out, `
SELECT public_url, oidc_issuer, oidc_audience, oidc_client_id, trusted_proxies
FROM governance.authentication_settings WHERE singleton`)
if errors.Is(err, sql.ErrNoRows) {
return AuthSettingsRow{}, nil
}
if err != nil {
return AuthSettingsRow{}, fmt.Errorf("read authentication settings: %w", err)
}
return out, nil
}
// SaveAuthenticationSettings updates authentication settings, refusing origin changes when passkeys exist.
func (s *Store) SaveAuthenticationSettings(ctx context.Context, row AuthSettingsRow) (updated bool, err error) {
res, err := s.db.ExecContext(ctx, `
UPDATE governance.authentication_settings
SET public_url = $1, oidc_issuer = $2, oidc_audience = $3, oidc_client_id = $4, trusted_proxies = $5
WHERE singleton AND (public_url = $1 OR NOT EXISTS (SELECT 1 FROM governance.passkeys))`,
row.PublicURL, row.OIDCIssuer, row.OIDCAudience, row.OIDCClientID, string(row.TrustedProxies))
if err != nil {
return false, fmt.Errorf("save authentication settings: %w", err)
}
n, err := res.RowsAffected()
return n == 1, err
}
// InvitedIdentity returns the identity an invitation to subject reserved, when
// the address is still waiting for an account: the placeholder binding holds an
// identity with none of its own.
func (s *Store) InvitedIdentity(ctx context.Context, subject string) (IdentityRow, bool, error) {
var row IdentityRow
err := s.db.GetContext(ctx, &row, `
SELECT `+identityCols+`
FROM governance.identities i
JOIN governance.identity_subjects s ON s.identity_id = i.id
WHERE s.subject = $1
AND NOT EXISTS (SELECT 1 FROM governance.accounts a WHERE a.identity_id = i.id)
ORDER BY s.bound_at
LIMIT 1`, subject)
if errors.Is(err, sql.ErrNoRows) {
return IdentityRow{}, false, nil
}
if err != nil {
return IdentityRow{}, false, err
}
return row, true, nil
}