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
+203 -31

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;
+7 -5
View File
@@ -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
+15 -13
View File
@@ -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
}
+11 -6
View File
@@ -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
}
+5
View File
@@ -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)
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+15
View File
@@ -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;
+69 -3
View File
@@ -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
}
+5
View File
@@ -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} }
+49 -2
View File
@@ -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")
}
}