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 <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-21 23:55:23 +01:00
1 parent caff396264
commit 99e9b1e57d
12 files changed
+188 -16

No files matched your search

+14
View File
@@ -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;
+3 -1
View File
@@ -70,7 +70,7 @@ func (q *Queries) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOr
} }
const listUserOrgs = `-- name: ListUserOrgs :many 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 FROM memberships m
JOIN orgs o ON o.id = m.org_id JOIN orgs o ON o.id = m.org_id
WHERE m.user_id = $1 WHERE m.user_id = $1
@@ -81,6 +81,7 @@ type ListUserOrgsRow struct {
ID uuid.UUID ID uuid.UUID
Slug string Slug string
Name string Name string
RequireTotp bool
IsOwner bool IsOwner bool
} }
@@ -97,6 +98,7 @@ func (q *Queries) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUse
&i.ID, &i.ID,
&i.Slug, &i.Slug,
&i.Name, &i.Name,
&i.RequireTotp,
&i.IsOwner, &i.IsOwner,
); err != nil { ); err != nil {
return nil, err return nil, err
+4 -2
View File
@@ -8,7 +8,6 @@ import (
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
) )
type Membership struct { type Membership struct {
@@ -24,6 +23,7 @@ type Org struct {
Name string Name string
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
RequireTotp bool
} }
type User struct { type User struct {
@@ -31,7 +31,9 @@ type User struct {
Email string Email string
DisplayName string DisplayName string
PasswordHash *string PasswordHash *string
DisabledAt pgtype.Timestamptz DisabledAt *time.Time
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
TotpSecret []byte
TotpEnabledAt *time.Time
} }
+11 -6
View File
@@ -12,17 +12,18 @@ import (
) )
const createOrg = `-- name: CreateOrg :one const createOrg = `-- name: CreateOrg :one
INSERT INTO orgs (slug, name) VALUES ($1, $2) INSERT INTO orgs (id, slug, name) VALUES ($1, $2, $3)
RETURNING id, slug, name, created_at, updated_at RETURNING id, slug, name, created_at, updated_at, require_totp
` `
type CreateOrgParams struct { type CreateOrgParams struct {
ID uuid.UUID
Slug string Slug string
Name string Name string
} }
func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) { 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 var i Org
err := row.Scan( err := row.Scan(
&i.ID, &i.ID,
@@ -30,6 +31,7 @@ func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, erro
&i.Name, &i.Name,
&i.CreatedAt, &i.CreatedAt,
&i.UpdatedAt, &i.UpdatedAt,
&i.RequireTotp,
) )
return i, err return i, err
} }
@@ -47,7 +49,7 @@ func (q *Queries) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) {
} }
const getOrg = `-- name: GetOrg :one 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) { 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.Name,
&i.CreatedAt, &i.CreatedAt,
&i.UpdatedAt, &i.UpdatedAt,
&i.RequireTotp,
) )
return i, err return i, err
} }
const getOrgBySlug = `-- name: GetOrgBySlug :one 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) { 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.Name,
&i.CreatedAt, &i.CreatedAt,
&i.UpdatedAt, &i.UpdatedAt,
&i.RequireTotp,
) )
return i, err return i, err
} }
const listOrgs = `-- name: ListOrgs :many 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) { 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.Name,
&i.CreatedAt, &i.CreatedAt,
&i.UpdatedAt, &i.UpdatedAt,
&i.RequireTotp,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
+5
View File
@@ -12,9 +12,13 @@ import (
type Querier interface { type Querier interface {
AddMembership(ctx context.Context, arg AddMembershipParams) error AddMembership(ctx context.Context, arg AddMembershipParams) error
AnyUserExists(ctx context.Context) (bool, error)
CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error)
CreateUser(ctx context.Context, arg CreateUserParams) (User, error) CreateUser(ctx context.Context, arg CreateUserParams) (User, error)
DeleteOrg(ctx context.Context, id uuid.UUID) (int64, 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) GetOrg(ctx context.Context, id uuid.UUID) (Org, error)
GetOrgBySlug(ctx context.Context, slug string) (Org, error) GetOrgBySlug(ctx context.Context, slug string) (Org, error)
GetUser(ctx context.Context, id uuid.UUID) (User, error) GetUser(ctx context.Context, id uuid.UUID) (User, error)
@@ -23,6 +27,7 @@ type Querier interface {
ListOrgs(ctx context.Context) ([]Org, error) ListOrgs(ctx context.Context) ([]Org, error)
ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error)
RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error)
SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error
} }
var _ Querier = (*Queries)(nil) var _ Querier = (*Queries)(nil)
+1 -1
View File
@@ -12,7 +12,7 @@ WHERE m.org_id = $1
ORDER BY u.email; ORDER BY u.email;
-- name: ListUserOrgs :many -- 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 FROM memberships m
JOIN orgs o ON o.id = m.org_id JOIN orgs o ON o.id = m.org_id
WHERE m.user_id = $1 WHERE m.user_id = $1
+1 -1
View File
@@ -1,5 +1,5 @@
-- name: CreateOrg :one -- name: CreateOrg :one
INSERT INTO orgs (slug, name) VALUES ($1, $2) INSERT INTO orgs (id, slug, name) VALUES ($1, $2, $3)
RETURNING *; RETURNING *;
-- name: GetOrg :one -- name: GetOrg :one
+15
View File
@@ -7,3 +7,18 @@ SELECT * FROM users WHERE id = $1;
-- name: GetUserByEmail :one -- name: GetUserByEmail :one
SELECT * FROM users WHERE email = $1; 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;
+69 -3
View File
@@ -11,9 +11,20 @@ import (
"github.com/google/uuid" "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 const createUser = `-- name: CreateUser :one
INSERT INTO users (email, display_name, password_hash) VALUES ($1, $2, $3) 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 { type CreateUserParams struct {
@@ -33,12 +44,49 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e
&i.DisabledAt, &i.DisabledAt,
&i.CreatedAt, &i.CreatedAt,
&i.UpdatedAt, &i.UpdatedAt,
&i.TotpSecret,
&i.TotpEnabledAt,
) )
return i, err 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 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) { 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.DisabledAt,
&i.CreatedAt, &i.CreatedAt,
&i.UpdatedAt, &i.UpdatedAt,
&i.TotpSecret,
&i.TotpEnabledAt,
) )
return i, err return i, err
} }
const getUserByEmail = `-- name: GetUserByEmail :one 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) { 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.DisabledAt,
&i.CreatedAt, &i.CreatedAt,
&i.UpdatedAt, &i.UpdatedAt,
&i.TotpSecret,
&i.TotpEnabledAt,
) )
return i, err 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
}
+5
View File
@@ -18,6 +18,7 @@ type Scope struct {
OrgID uuid.UUID OrgID uuid.UUID
UserID uuid.UUID UserID uuid.UUID
system bool system bool
global bool
} }
func Org(org, user uuid.UUID) Scope { return Scope{OrgID: org, UserID: user} } 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. // which is what login and the org switcher need before an org is chosen.
func User(user uuid.UUID) Scope { return Scope{UserID: user} } 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 // System bypasses tenant isolation. Reserve it for work that is inherently
// cross-tenant, never for request handling. // cross-tenant, never for request handling.
func System() Scope { return Scope{system: true} } func System() Scope { return Scope{system: true} }
+49 -2
View File
@@ -52,10 +52,10 @@ func seed(t *testing.T, db *tenant.DB) fixture {
suffix := uuid.NewString()[:8] suffix := uuid.NewString()[:8]
err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error { err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err 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 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 return err
} }
if f.alice, err = q.CreateUser(ctx, store.CreateUserParams{Email: "alice-" + suffix + "@example.test"}); err != nil { 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 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 return nil
}) })
}) })
@@ -186,3 +191,45 @@ func TestSingleOwnerPerOrg(t *testing.T) {
t.Fatal("second owner accepted") 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")
}
}
+11
View File
@@ -18,3 +18,14 @@ sql:
go_type: string go_type: string
- db_type: timestamptz - db_type: timestamptz
go_type: time.Time 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