From 99e9b1e57dcb7b16cec218e20ad372eb75d5e1bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sat, 21 Nov 2026 23:55:23 +0100 Subject: [PATCH] feat(store): add totp columns, org totp policy and global scope Orgs are created inside their own tenant scope, so signup needs no system scope. Refs #3 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/migrations/sql/00005_totp.sql | 14 +++++ internal/store/memberships.sql.go | 12 +++-- internal/store/models.go | 28 +++++----- internal/store/orgs.sql.go | 17 +++--- internal/store/querier.go | 5 ++ internal/store/queries/memberships.sql | 2 +- internal/store/queries/orgs.sql | 2 +- internal/store/queries/users.sql | 15 ++++++ internal/store/users.sql.go | 72 ++++++++++++++++++++++++-- internal/tenant/tenant.go | 5 ++ internal/tenant/tenant_test.go | 51 +++++++++++++++++- sqlc.yaml | 11 ++++ 12 files changed, 203 insertions(+), 31 deletions(-) create mode 100644 internal/migrations/sql/00005_totp.sql diff --git a/internal/migrations/sql/00005_totp.sql b/internal/migrations/sql/00005_totp.sql new file mode 100644 index 0000000..544c962 --- /dev/null +++ b/internal/migrations/sql/00005_totp.sql @@ -0,0 +1,14 @@ +-- +goose Up +ALTER TABLE users + ADD COLUMN totp_secret bytea, + ADD COLUMN totp_enabled_at timestamptz, + ADD CONSTRAINT users_totp_consistent CHECK ((totp_secret IS NULL) = (totp_enabled_at IS NULL)); + +ALTER TABLE orgs ADD COLUMN require_totp boolean NOT NULL DEFAULT false; + +-- +goose Down +ALTER TABLE orgs DROP COLUMN require_totp; +ALTER TABLE users + DROP CONSTRAINT users_totp_consistent, + DROP COLUMN totp_enabled_at, + DROP COLUMN totp_secret; diff --git a/internal/store/memberships.sql.go b/internal/store/memberships.sql.go index 8c62aa0..ee9eee7 100644 --- a/internal/store/memberships.sql.go +++ b/internal/store/memberships.sql.go @@ -70,7 +70,7 @@ func (q *Queries) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOr } const listUserOrgs = `-- name: ListUserOrgs :many -SELECT o.id, o.slug, o.name, m.is_owner +SELECT o.id, o.slug, o.name, o.require_totp, m.is_owner FROM memberships m JOIN orgs o ON o.id = m.org_id WHERE m.user_id = $1 @@ -78,10 +78,11 @@ ORDER BY o.name ` type ListUserOrgsRow struct { - ID uuid.UUID - Slug string - Name string - IsOwner bool + ID uuid.UUID + Slug string + Name string + RequireTotp bool + IsOwner bool } func (q *Queries) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) { @@ -97,6 +98,7 @@ func (q *Queries) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUse &i.ID, &i.Slug, &i.Name, + &i.RequireTotp, &i.IsOwner, ); err != nil { return nil, err diff --git a/internal/store/models.go b/internal/store/models.go index 584bf5a..ccccfaa 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -8,7 +8,6 @@ import ( "time" "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" ) type Membership struct { @@ -19,19 +18,22 @@ type Membership struct { } type Org struct { - ID uuid.UUID - Slug string - Name string - CreatedAt time.Time - UpdatedAt time.Time + ID uuid.UUID + Slug string + Name string + CreatedAt time.Time + UpdatedAt time.Time + RequireTotp bool } type User struct { - ID uuid.UUID - Email string - DisplayName string - PasswordHash *string - DisabledAt pgtype.Timestamptz - CreatedAt time.Time - UpdatedAt time.Time + ID uuid.UUID + Email string + DisplayName string + PasswordHash *string + DisabledAt *time.Time + CreatedAt time.Time + UpdatedAt time.Time + TotpSecret []byte + TotpEnabledAt *time.Time } diff --git a/internal/store/orgs.sql.go b/internal/store/orgs.sql.go index 445598d..168fef1 100644 --- a/internal/store/orgs.sql.go +++ b/internal/store/orgs.sql.go @@ -12,17 +12,18 @@ import ( ) const createOrg = `-- name: CreateOrg :one -INSERT INTO orgs (slug, name) VALUES ($1, $2) -RETURNING id, slug, name, created_at, updated_at +INSERT INTO orgs (id, slug, name) VALUES ($1, $2, $3) +RETURNING id, slug, name, created_at, updated_at, require_totp ` type CreateOrgParams struct { + ID uuid.UUID Slug string Name string } func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) { - row := q.db.QueryRow(ctx, createOrg, arg.Slug, arg.Name) + row := q.db.QueryRow(ctx, createOrg, arg.ID, arg.Slug, arg.Name) var i Org err := row.Scan( &i.ID, @@ -30,6 +31,7 @@ func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, erro &i.Name, &i.CreatedAt, &i.UpdatedAt, + &i.RequireTotp, ) return i, err } @@ -47,7 +49,7 @@ func (q *Queries) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) { } const getOrg = `-- name: GetOrg :one -SELECT id, slug, name, created_at, updated_at FROM orgs WHERE id = $1 +SELECT id, slug, name, created_at, updated_at, require_totp FROM orgs WHERE id = $1 ` func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) { @@ -59,12 +61,13 @@ func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) { &i.Name, &i.CreatedAt, &i.UpdatedAt, + &i.RequireTotp, ) return i, err } const getOrgBySlug = `-- name: GetOrgBySlug :one -SELECT id, slug, name, created_at, updated_at FROM orgs WHERE slug = $1 +SELECT id, slug, name, created_at, updated_at, require_totp FROM orgs WHERE slug = $1 ` func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) { @@ -76,12 +79,13 @@ func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) { &i.Name, &i.CreatedAt, &i.UpdatedAt, + &i.RequireTotp, ) return i, err } const listOrgs = `-- name: ListOrgs :many -SELECT id, slug, name, created_at, updated_at FROM orgs ORDER BY name +SELECT id, slug, name, created_at, updated_at, require_totp FROM orgs ORDER BY name ` func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) { @@ -99,6 +103,7 @@ func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) { &i.Name, &i.CreatedAt, &i.UpdatedAt, + &i.RequireTotp, ); err != nil { return nil, err } diff --git a/internal/store/querier.go b/internal/store/querier.go index f785781..6f20f1c 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -12,9 +12,13 @@ import ( type Querier interface { AddMembership(ctx context.Context, arg AddMembershipParams) error + AnyUserExists(ctx context.Context) (bool, error) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) + DeleteUser(ctx context.Context, id uuid.UUID) (int64, error) + DisableTOTP(ctx context.Context, id uuid.UUID) error + EnableTOTP(ctx context.Context, arg EnableTOTPParams) error GetOrg(ctx context.Context, id uuid.UUID) (Org, error) GetOrgBySlug(ctx context.Context, slug string) (Org, error) GetUser(ctx context.Context, id uuid.UUID) (User, error) @@ -23,6 +27,7 @@ type Querier interface { ListOrgs(ctx context.Context) ([]Org, error) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) + SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error } var _ Querier = (*Queries)(nil) diff --git a/internal/store/queries/memberships.sql b/internal/store/queries/memberships.sql index ef2bd0e..443a104 100644 --- a/internal/store/queries/memberships.sql +++ b/internal/store/queries/memberships.sql @@ -12,7 +12,7 @@ WHERE m.org_id = $1 ORDER BY u.email; -- name: ListUserOrgs :many -SELECT o.id, o.slug, o.name, m.is_owner +SELECT o.id, o.slug, o.name, o.require_totp, m.is_owner FROM memberships m JOIN orgs o ON o.id = m.org_id WHERE m.user_id = $1 diff --git a/internal/store/queries/orgs.sql b/internal/store/queries/orgs.sql index 8fb19c6..98a20f3 100644 --- a/internal/store/queries/orgs.sql +++ b/internal/store/queries/orgs.sql @@ -1,5 +1,5 @@ -- name: CreateOrg :one -INSERT INTO orgs (slug, name) VALUES ($1, $2) +INSERT INTO orgs (id, slug, name) VALUES ($1, $2, $3) RETURNING *; -- name: GetOrg :one diff --git a/internal/store/queries/users.sql b/internal/store/queries/users.sql index b1af3dc..4c0420e 100644 --- a/internal/store/queries/users.sql +++ b/internal/store/queries/users.sql @@ -7,3 +7,18 @@ SELECT * FROM users WHERE id = $1; -- name: GetUserByEmail :one SELECT * FROM users WHERE email = $1; + +-- name: AnyUserExists :one +SELECT EXISTS (SELECT 1 FROM users); + +-- name: SetPasswordHash :exec +UPDATE users SET password_hash = $2, updated_at = now() WHERE id = $1; + +-- name: EnableTOTP :exec +UPDATE users SET totp_secret = $2, totp_enabled_at = now(), updated_at = now() WHERE id = $1; + +-- name: DisableTOTP :exec +UPDATE users SET totp_secret = NULL, totp_enabled_at = NULL, updated_at = now() WHERE id = $1; + +-- name: DeleteUser :execrows +DELETE FROM users WHERE id = $1; diff --git a/internal/store/users.sql.go b/internal/store/users.sql.go index db14ac3..5db19c4 100644 --- a/internal/store/users.sql.go +++ b/internal/store/users.sql.go @@ -11,9 +11,20 @@ import ( "github.com/google/uuid" ) +const anyUserExists = `-- name: AnyUserExists :one +SELECT EXISTS (SELECT 1 FROM users) +` + +func (q *Queries) AnyUserExists(ctx context.Context) (bool, error) { + row := q.db.QueryRow(ctx, anyUserExists) + var exists bool + err := row.Scan(&exists) + return exists, err +} + const createUser = `-- name: CreateUser :one INSERT INTO users (email, display_name, password_hash) VALUES ($1, $2, $3) -RETURNING id, email, display_name, password_hash, disabled_at, created_at, updated_at +RETURNING id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at ` type CreateUserParams struct { @@ -33,12 +44,49 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e &i.DisabledAt, &i.CreatedAt, &i.UpdatedAt, + &i.TotpSecret, + &i.TotpEnabledAt, ) return i, err } +const deleteUser = `-- name: DeleteUser :execrows +DELETE FROM users WHERE id = $1 +` + +func (q *Queries) DeleteUser(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteUser, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const disableTOTP = `-- name: DisableTOTP :exec +UPDATE users SET totp_secret = NULL, totp_enabled_at = NULL, updated_at = now() WHERE id = $1 +` + +func (q *Queries) DisableTOTP(ctx context.Context, id uuid.UUID) error { + _, err := q.db.Exec(ctx, disableTOTP, id) + return err +} + +const enableTOTP = `-- name: EnableTOTP :exec +UPDATE users SET totp_secret = $2, totp_enabled_at = now(), updated_at = now() WHERE id = $1 +` + +type EnableTOTPParams struct { + ID uuid.UUID + TotpSecret []byte +} + +func (q *Queries) EnableTOTP(ctx context.Context, arg EnableTOTPParams) error { + _, err := q.db.Exec(ctx, enableTOTP, arg.ID, arg.TotpSecret) + return err +} + const getUser = `-- name: GetUser :one -SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at FROM users WHERE id = $1 +SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at FROM users WHERE id = $1 ` func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) { @@ -52,12 +100,14 @@ func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) { &i.DisabledAt, &i.CreatedAt, &i.UpdatedAt, + &i.TotpSecret, + &i.TotpEnabledAt, ) return i, err } const getUserByEmail = `-- name: GetUserByEmail :one -SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at FROM users WHERE email = $1 +SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at FROM users WHERE email = $1 ` func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error) { @@ -71,6 +121,22 @@ func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error &i.DisabledAt, &i.CreatedAt, &i.UpdatedAt, + &i.TotpSecret, + &i.TotpEnabledAt, ) return i, err } + +const setPasswordHash = `-- name: SetPasswordHash :exec +UPDATE users SET password_hash = $2, updated_at = now() WHERE id = $1 +` + +type SetPasswordHashParams struct { + ID uuid.UUID + PasswordHash *string +} + +func (q *Queries) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error { + _, err := q.db.Exec(ctx, setPasswordHash, arg.ID, arg.PasswordHash) + return err +} diff --git a/internal/tenant/tenant.go b/internal/tenant/tenant.go index fb802ff..8a10fdc 100644 --- a/internal/tenant/tenant.go +++ b/internal/tenant/tenant.go @@ -18,6 +18,7 @@ type Scope struct { OrgID uuid.UUID UserID uuid.UUID system bool + global bool } func Org(org, user uuid.UUID) Scope { return Scope{OrgID: org, UserID: user} } @@ -26,6 +27,10 @@ func Org(org, user uuid.UUID) Scope { return Scope{OrgID: org, UserID: user} } // which is what login and the org switcher need before an org is chosen. func User(user uuid.UUID) Scope { return Scope{UserID: user} } +// Global carries no tenant context: only tables without row-level security, +// such as users, are usable. Login runs here before the user is known. +func Global() Scope { return Scope{global: true} } + // System bypasses tenant isolation. Reserve it for work that is inherently // cross-tenant, never for request handling. func System() Scope { return Scope{system: true} } diff --git a/internal/tenant/tenant_test.go b/internal/tenant/tenant_test.go index 910d541..421384a 100644 --- a/internal/tenant/tenant_test.go +++ b/internal/tenant/tenant_test.go @@ -52,10 +52,10 @@ func seed(t *testing.T, db *tenant.DB) fixture { suffix := uuid.NewString()[:8] err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error { var err error - if f.orgA, err = q.CreateOrg(ctx, store.CreateOrgParams{Slug: "a-" + suffix, Name: "A"}); err != nil { + if f.orgA, err = q.CreateOrg(ctx, store.CreateOrgParams{ID: uuid.New(), Slug: "a-" + suffix, Name: "A"}); err != nil { return err } - if f.orgB, err = q.CreateOrg(ctx, store.CreateOrgParams{Slug: "b-" + suffix, Name: "B"}); err != nil { + if f.orgB, err = q.CreateOrg(ctx, store.CreateOrgParams{ID: uuid.New(), Slug: "b-" + suffix, Name: "B"}); err != nil { return err } if f.alice, err = q.CreateUser(ctx, store.CreateUserParams{Email: "alice-" + suffix + "@example.test"}); err != nil { @@ -79,6 +79,11 @@ func seed(t *testing.T, db *tenant.DB) fixture { return err } } + for _, id := range []uuid.UUID{f.alice.ID, f.bob.ID} { + if _, err := q.DeleteUser(context.Background(), id); err != nil { + return err + } + } return nil }) }) @@ -186,3 +191,45 @@ func TestSingleOwnerPerOrg(t *testing.T) { t.Fatal("second owner accepted") } } + +func TestGlobalScopeSeesNoTenantRows(t *testing.T) { + db, _ := setup(t) + f := seed(t, db) + ctx := context.Background() + err := db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + if _, err := q.GetOrg(ctx, f.orgA.ID); !errors.Is(err, pgx.ErrNoRows) { + t.Errorf("org visible in global scope: %v", err) + } + if _, err := q.GetUser(ctx, f.alice.ID); err != nil { + t.Errorf("users must be readable in global scope: %v", err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +func TestNewOrgCanBeCreatedInItsOwnScope(t *testing.T) { + db, _ := setup(t) + ctx := context.Background() + id := uuid.New() + err := db.Tx(ctx, tenant.Org(id, uuid.Nil), func(q *store.Queries) error { + _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: id, Slug: "n-" + id.String()[:8], Name: "N"}) + return err + }) + if err != nil { + t.Fatal(err) + } + _ = db.Tx(ctx, tenant.Org(id, uuid.Nil), func(q *store.Queries) error { + _, err := q.DeleteOrg(ctx, id) + return err + }) + err = db.Tx(ctx, tenant.Org(uuid.New(), uuid.Nil), func(q *store.Queries) error { + _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: uuid.New(), Slug: "x-" + id.String()[:8], Name: "X"}) + return err + }) + if err == nil { + t.Fatal("org created outside its own scope") + } +} diff --git a/sqlc.yaml b/sqlc.yaml index 793ff72..2a12748 100644 --- a/sqlc.yaml +++ b/sqlc.yaml @@ -18,3 +18,14 @@ sql: go_type: string - db_type: timestamptz go_type: time.Time + - db_type: timestamptz + nullable: true + go_type: + type: time.Time + pointer: true + - db_type: uuid + nullable: true + go_type: + import: github.com/google/uuid + type: UUID + pointer: true