@sssb/kit 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +3 -1
  3. package/src/adapters/edge-headers.ts +171 -0
  4. package/src/adapters/fake/simulator-admin.ts +7 -3
  5. package/src/adapters/fake/storage.ts +60 -8
  6. package/src/adapters/origin-form.ts +24 -0
  7. package/src/adapters/real/auth.ts +3 -2
  8. package/src/adapters/real/clerk-authorized-parties.ts +3 -14
  9. package/src/adapters/real/index.ts +8 -0
  10. package/src/adapters/real/optional-ports.ts +3 -2
  11. package/src/adapters/real/s3-storage.ts +66 -5
  12. package/src/adapters/real/storage-settings.ts +7 -4
  13. package/src/adapters/real/storage.ts +9 -7
  14. package/src/authz/route-policy.ts +7 -4
  15. package/src/components/simulator/actors-app.tsx +1 -1
  16. package/src/components/simulator/errors-app.tsx +4 -1
  17. package/src/components/simulator/inbound-app.tsx +1 -1
  18. package/src/components/simulator/jobs-app.tsx +3 -3
  19. package/src/components/simulator/mail-app.tsx +1 -1
  20. package/src/components/simulator/mail-link.ts +27 -0
  21. package/src/components/simulator/simulator-host.tsx +556 -82
  22. package/src/components/simulator/simulator-panel.tsx +1 -1
  23. package/src/db/inbound-email.ts +7 -5
  24. package/src/db/migrations/0018_organizations_write.ts +87 -0
  25. package/src/db/migrations/index.ts +2 -0
  26. package/src/db/org-lookup.ts +4 -4
  27. package/src/db/rls-coverage.ts +140 -24
  28. package/src/db/rls-proofs.ts +147 -0
  29. package/src/demo-static/world.ts +2 -2
  30. package/src/guide.md +6 -0
  31. package/src/ports/storage.ts +50 -9
  32. package/src/server-lib/invite.ts +5 -1
  33. package/src/server-lib/simulator-api.ts +320 -3
  34. package/src/service-auth/secret-env.ts +19 -0
  35. package/src/service-auth/standard-webhooks.ts +358 -0
  36. package/src/service-auth/webhook.ts +39 -12
@@ -140,7 +140,7 @@ export interface HooksAppProps {
140
140
  * layout shift); expanded = a right-docked column with its own dark skin so it reads as "not the
141
141
  * product". The column is sticky so it stays docked while long pages scroll. Router-agnostic —
142
142
  * navigation happens via `onSelect`/mail's `onOpenLink`, data arrives as props; the host owns fetching and polling
143
- * (the kit's own server host, ./simulator-host, an app's own glue, or the static demo's shell). Tab strip:
143
+ * (the kit's own server host, ./simulator-host, or the static demo's shell). Tab strip:
144
144
  * People / Mail / Messages / Events / Jobs / Hooks / …host `extraTabs`… / Errors / Snapshots / Tours —
145
145
  * `data-testid="simulator-tab-<id>"`, each tab but People present only when the host passes its props. App tabs are
146
146
  * registered on the seam (@sssb/app-config/simulator) and composed by the host into `extraTabs`, slotted in between
@@ -3,7 +3,7 @@ import type { DbPort } from '../ports/db'
3
3
  /**
4
4
  * DB access for inbound email: the row writes intake performs (insert 'received', update the
5
5
  * final status) all go through withTenant, and the global org resolution + the Simulator world list are
6
- * raw reads of the RLS-free infra tables (the org-lookup / listSchedulesForWorld precedents).
6
+ * raw reads of the infra tables, readable across tenants (the org-lookup / listSchedulesForWorld precedents).
7
7
  */
8
8
 
9
9
  /** timestamptz reads back a Date on real pg, a string on pglite — normalise (the webhooks.ts iso). */
@@ -20,12 +20,14 @@ export interface ResolvedInboundOrg {
20
20
 
21
21
  /**
22
22
  * Resolve an org slug to its (tenant, org) GLOBALLY — the recipient address (`<org-slug>+<handler>@…`)
23
- * names only the org, not the tenant. Org slugs are unique across the seed, so a single match yields the
24
- * tenant too. ZERO matches (unknown slug) OR more than one (the same slug reused in two tenants — the
25
- * schema permits it, though the seed never does) both return null: an address alone can't disambiguate
23
+ * names only the org, not the tenant. Org slugs are unique across the seed, and a request cannot create one another
24
+ * tenant holds (0018_organizations_write), so a single match yields the tenant too; the gaps are
25
+ * safeinsights/sssb#211. ZERO matches (unknown slug) OR more than one (the same slug reused in two tenants — no
26
+ * constraint forbids it, and the table owner, a concurrent insert or a later grant can still make one; the seed never
27
+ * does) both return null: an address alone can't disambiguate
26
28
  * a collision, so it's treated as unresolved rather than filed under an arbitrary tenant. A real
27
29
  * MULTI-domain instance resolves the tenant from the recipient DOMAIN first (see the decision log).
28
- * Reads the RLS-free `organizations`/`tenants` infra tables — the orgIdForSlug precedent.
30
+ * Reads the `organizations`/`tenants` infra tables, readable across tenants — the orgIdForSlug precedent.
29
31
  */
30
32
  export async function resolveOrgBySlugGlobally(db: DbPort, orgSlug: string): Promise<ResolvedInboundOrg | null> {
31
33
  await db.ready()
@@ -0,0 +1,87 @@
1
+ import { Kysely, sql } from 'kysely'
2
+
3
+ /**
4
+ * Lets a request WRITE `organizations` (create, rename, delete a team) inside its own tenant, and lets another table
5
+ * pin its org to its own tenant in Postgres (safeinsights/sssb#124).
6
+ *
7
+ * Until now `app_user` held SELECT only (0003), so a route that created or renamed a team at request time failed with
8
+ * `permission denied`. This grants INSERT, UPDATE (of the name) and DELETE, and puts the WRITES behind row-level
9
+ * security:
10
+ *
11
+ * - READS stay cross-tenant, as before. `organizations` is read while resolving who is calling, before any tenant
12
+ * context exists (../org-lookup.ts), and a request may join another team of its own tenant (an app's cross-team
13
+ * request, say),
14
+ * so the SELECT policy is `USING (true)`. That is what keeps it on the coverage check's exempt list
15
+ * (../rls-coverage.ts), whose entry for it now declares the three writes.
16
+ * - WRITES are tenant-scoped, one policy per command: an INSERT or an UPDATE may only leave a row in the tenant the
17
+ * request runs in (`WITH CHECK`), and an UPDATE or a DELETE only reaches rows of that tenant (`USING`). With no tenant
18
+ * context the setting is NULL, every comparison is NULL, and no write lands: fail closed, as every tenant table.
19
+ * (The column grants below already keep `tenant_id` out of an UPDATE; the policy holds even if a later grant
20
+ * widens them.) WHICH person may write which team of their own tenant
21
+ * is an authorization decision (`authorize(...)`), not a grant one: a team is a collaboration boundary inside a
22
+ * tenant, the tenant the hostile-isolation boundary.
23
+ * - ENABLE, not FORCE. FORCE would put the table's OWNER under these policies too, and the owner is the privileged
24
+ * path that seeds teams with no tenant context (../seed.ts). Its access is exactly what it was. An app's routes do
25
+ * not write as the owner: `getDb()` is banned in an app's `src` (`sssb/no-raw-db-handle`) bar the exceptions it
26
+ * names, and every `withTenant` switches to `app_user`. The kit's only writer of teams is that seed.
27
+ * - A new team's slug may not be one another tenant's team holds. The inbound mail address names a team by its slug
28
+ * alone (`<org-slug>+<handler>@`, ../inbound-email.ts), resolved across every tenant and refused when two match, so
29
+ * a tenant that could take another's slug could silence that team's mail. Two tenants creating the same NEW slug at
30
+ * the same moment can both pass this check (it is not a constraint); their mail is then refused, never misfiled.
31
+ * A slug a team gives up by being deleted is free for any tenant to take, with whatever mail still comes to it.
32
+ * - TRUNCATE is NOT granted: it ignores row-level security, so it would empty every tenant's teams.
33
+ * - A DELETE succeeds only for a team nothing references: every table that names an org holds a plain foreign key
34
+ * to it, and the audit trail is append-only, so a request cannot delete a team with history.
35
+ *
36
+ * `organizations_tenant_id_id_unique` over `(tenant_id, id)` is what a COMPOSITE foreign key needs: an app table
37
+ * can then declare `FOREIGN KEY (tenant_id, org_id) REFERENCES organizations (tenant_id, id)`, and Postgres refuses a
38
+ * row whose org belongs to another tenant. The id alone is the primary key, so the constraint never rejects a row
39
+ * that the key accepts.
40
+ *
41
+ * It names the one table it touches (the order-independence rule in ./index.ts).
42
+ */
43
+ export async function up(db: Kysely<any>): Promise<void> {
44
+ await sql`ALTER TABLE organizations ADD CONSTRAINT organizations_tenant_id_id_unique UNIQUE (tenant_id, id)`.execute(
45
+ db,
46
+ )
47
+
48
+ // Column grants: a request names a new team's tenant, slug and name (its id is the default), and renames it by
49
+ // its name alone. The slug is how the auth provider and the inbound mail address name a team, and the id is what
50
+ // every other table holds, so neither is a request's to change.
51
+ await sql`GRANT INSERT (tenant_id, slug, name), UPDATE (name), DELETE ON organizations TO app_user`.execute(db)
52
+ await sql`ALTER TABLE organizations ENABLE ROW LEVEL SECURITY`.execute(db)
53
+ // NULLIF: unset tenant context must mean zero rows, never a cast error (the 1001_items pattern).
54
+ await sql`CREATE POLICY organizations_read ON organizations FOR SELECT USING (true)`.execute(db)
55
+ await sql`
56
+ CREATE POLICY organizations_tenant_insert ON organizations
57
+ FOR INSERT
58
+ WITH CHECK (
59
+ tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid
60
+ AND NOT EXISTS (
61
+ SELECT 1 FROM organizations other
62
+ WHERE other.slug = organizations.slug AND other.tenant_id <> organizations.tenant_id
63
+ )
64
+ )
65
+ `.execute(db)
66
+ await sql`
67
+ CREATE POLICY organizations_tenant_update ON organizations
68
+ FOR UPDATE
69
+ USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
70
+ WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
71
+ `.execute(db)
72
+ await sql`
73
+ CREATE POLICY organizations_tenant_delete ON organizations
74
+ FOR DELETE
75
+ USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
76
+ `.execute(db)
77
+ }
78
+
79
+ export async function down(db: Kysely<any>): Promise<void> {
80
+ await sql`DROP POLICY organizations_tenant_delete ON organizations`.execute(db)
81
+ await sql`DROP POLICY organizations_tenant_update ON organizations`.execute(db)
82
+ await sql`DROP POLICY organizations_tenant_insert ON organizations`.execute(db)
83
+ await sql`DROP POLICY organizations_read ON organizations`.execute(db)
84
+ await sql`REVOKE INSERT, UPDATE, DELETE ON organizations FROM app_user`.execute(db)
85
+ await sql`ALTER TABLE organizations DISABLE ROW LEVEL SECURITY`.execute(db)
86
+ await sql`ALTER TABLE organizations DROP CONSTRAINT organizations_tenant_id_id_unique`.execute(db)
87
+ }
@@ -14,6 +14,7 @@ import * as m0014 from './0014_audit_credential'
14
14
  import * as m0015 from './0015_app_user_grant'
15
15
  import * as m0016 from './0016_audit_detail'
16
16
  import * as m0017 from './0017_job_requester'
17
+ import * as m0018 from './0018_organizations_write'
17
18
 
18
19
  /**
19
20
  * Static migration registry (no filesystem scanning — bundles cleanly into the Lambda migrator and
@@ -46,6 +47,7 @@ export const frameworkMigrations: Record<string, Migration> = {
46
47
  '0015_app_user_grant': m0015,
47
48
  '0016_audit_detail': m0016,
48
49
  '0017_job_requester': m0017,
50
+ '0018_organizations_write': m0018,
49
51
  }
50
52
 
51
53
  export const migrations: Record<string, Migration> = { ...frameworkMigrations, ...appMigrations }
@@ -2,7 +2,7 @@ import type { DbPort } from '../ports/db'
2
2
 
3
3
  /**
4
4
  * Resolves an org slug (what sessions carry) to its uuid, scoped to the tenant it belongs to. Reads
5
- * the RLS-free `organizations` infra table — the same legitimate raw read as tenant-lookup. Org slugs
5
+ * the `organizations` infra table, readable across tenants: the same legitimate raw read as tenant-lookup. Org slugs
6
6
  * are unique per tenant, so the tenant scope keeps the lookup unambiguous even if two tenants ever
7
7
  * reuse a slug.
8
8
  */
@@ -50,7 +50,7 @@ export async function orgIdentityForSlug(db: DbPort, tenantId: string, orgSlug:
50
50
  }
51
51
 
52
52
  /**
53
- * Resolves an org uuid back to its slug + name — the reverse of orgIdForSlug, same RLS-free raw read.
53
+ * Resolves an org uuid back to its slug + name — the reverse of orgIdForSlug, same cross-tenant raw read.
54
54
  * Used by the scheduled digest handler, which knows its job's org_id but needs the slug to
55
55
  * list the org's members (`auth.listMembers`) and the name for the digest copy. Null when the org is gone.
56
56
  */
@@ -84,7 +84,7 @@ export async function listOrgsForWorld(db: DbPort): Promise<{ slug: string; name
84
84
  }
85
85
 
86
86
  /**
87
- * All orgs (teams) in one tenant, for the cross-org request target picker. Reads the RLS-free
87
+ * All orgs (teams) in one tenant, for the cross-org request target picker. Reads the cross-tenant-readable
88
88
  * `organizations` infra table — the same legitimate raw read as orgIdForSlug — so it lists every team
89
89
  * in the caller's tenant regardless of which one they're acting in. The route strips the active org
90
90
  * from the result (you don't request from yourself); the table CHECK is the backstop.
@@ -104,7 +104,7 @@ export async function listOrgsInTenant(
104
104
  }
105
105
 
106
106
  /**
107
- * An org's display name, by its tenant's slug and its own: the same RLS-free raw read of the `organizations` infra
107
+ * An org's display name, by its tenant's slug and its own: the same cross-tenant raw read of the `organizations` infra
108
108
  * table as the lookups above. The auth port's fixed org source names its home org with it (`listMyOrgs`), since the
109
109
  * port knows the org only by slug. Null when the tenant has no such org.
110
110
  */
@@ -50,27 +50,56 @@ import type { DB } from './schema'
50
50
  * Schema-qualified, so a table in another schema can never be exempted by a bare name.
51
51
  *
52
52
  * These are INFRA tables read while resolving who is calling — before any tenant context exists — so
53
- * `app_user` holds a cross-tenant `SELECT` on them and no policy applies.
53
+ * `app_user` holds a cross-tenant `SELECT` on them that no policy narrows.
54
54
  *
55
- * Adding a name here removes a relation from the guarantee `SECURITY.md` makes, so it is a security
56
- * decision and belongs in that file too — which `EXPECTED_EXEMPTIONS` below makes a two-file edit
57
- * rather than something that can be slipped in. A stale entry is a hazard rather than dead weight: it
58
- * would silently exempt a FUTURE relation reusing the name, so an entry naming nothing also fails.
55
+ * An exempt relation is SELECT-only unless its entry declares `writes`. A declared write is held to
56
+ * row-level security that reads the tenant setting, as a tenant table's is, though not to FORCE
57
+ * (`provenWrite` below says why), so the exemption stays one of READING across tenants. TRUNCATE is not declarable, because it
58
+ * ignores row-level security altogether.
59
+ *
60
+ * Adding a name here, or a write to a name, removes something from the guarantee `SECURITY.md` makes, so
61
+ * it is a security decision and belongs in that file too — which `EXPECTED_EXEMPTIONS` below makes a
62
+ * two-file edit rather than something that can be slipped in. A stale entry is a hazard rather than dead
63
+ * weight: it would silently exempt a FUTURE relation reusing the name, so an entry naming nothing fails,
64
+ * and so does a declared write `app_user` does not hold.
59
65
  */
60
- const RLS_EXEMPT: Record<string, string> = {
61
- 'public.tenants': 'the tenant registry itself, read to resolve a tenant before any tenant context exists',
62
- 'public.organizations':
63
- 'read to resolve a caller org before a tenant context exists; holds a team slug and display name only',
64
- 'public.service_keys':
65
- 'read to verify a service token before a tenant context exists; holds PUBLIC key material only, so its boundary is cryptographic',
66
+ const RLS_EXEMPT: Record<string, Exemption> = {
67
+ 'public.tenants': {
68
+ reason: 'the tenant registry itself, read to resolve a tenant before any tenant context exists',
69
+ },
70
+ 'public.organizations': {
71
+ reason: 'read to resolve a caller org before a tenant context exists; holds a team slug and display name only',
72
+ // A request creates, renames and deletes its own tenant's teams (0018_organizations_write).
73
+ writes: ['INSERT', 'UPDATE', 'DELETE'],
74
+ },
75
+ 'public.service_keys': {
76
+ reason: 'read to verify a service token before a tenant context exists; holds PUBLIC key material only, so its boundary is cryptographic',
77
+ },
66
78
  }
67
79
 
68
80
  /**
69
- * The exemption list, pinned. Changing `RLS_EXEMPT` without changing this fails, and the assertion
70
- * message says to update `SECURITY.md` in the same commit — because that file enumerates these three
71
- * to the public and was already caught once promising more than the code delivered.
81
+ * The exemption list, pinned, each name with the writes it declares. Changing `RLS_EXEMPT` without
82
+ * changing this fails, and the assertion message says to update `SECURITY.md` in the same commit —
83
+ * because that file enumerates these three to the public and was already caught once promising more
84
+ * than the code delivered.
72
85
  */
73
- const EXPECTED_EXEMPTIONS = ['public.organizations', 'public.service_keys', 'public.tenants']
86
+ const EXPECTED_EXEMPTIONS = ['public.organizations (DELETE, INSERT, UPDATE)', 'public.service_keys', 'public.tenants']
87
+
88
+ /** The privileges an exempt relation may declare, and the policy command (`pg_policy.polcmd`) each runs under. */
89
+ const WRITE_COMMANDS = { INSERT: 'a', UPDATE: 'w', DELETE: 'd' } as const
90
+ type ExemptWrite = keyof typeof WRITE_COMMANDS
91
+
92
+ interface Exemption {
93
+ /** Why `app_user` may read it across tenants. */
94
+ reason: string
95
+ /** The writes `app_user` may hold on it, each held to tenant-scoped row-level security. Absent: SELECT only. */
96
+ writes?: readonly ExemptWrite[]
97
+ }
98
+
99
+ function pinnedName(name: string, exemption: Exemption): string {
100
+ const writes = [...(exemption.writes ?? [])].sort()
101
+ return writes.length === 0 ? name : `${name} (${writes.join(', ')})`
102
+ }
74
103
 
75
104
  /**
76
105
  * Framework tables the framework's own migrations always create. Used as a SHAPE floor rather than a
@@ -112,6 +141,8 @@ interface RelationRow {
112
141
  enabled: boolean
113
142
  forced: boolean
114
143
  is_partition: boolean
144
+ /** `app_user` has its OWNER's privileges (a member of the owning role), so ENABLE-only RLS does not hold it. */
145
+ app_user_owns: boolean
115
146
  }
116
147
 
117
148
  interface PolicyRow {
@@ -119,6 +150,8 @@ interface PolicyRow {
119
150
  table_name: string
120
151
  policy_name: string
121
152
  permissive: boolean
153
+ /** `pg_policy.polcmd`: r SELECT, a INSERT, w UPDATE, d DELETE, * ALL. */
154
+ command: string
122
155
  using_src: string | null
123
156
  check_src: string | null
124
157
  }
@@ -132,8 +165,9 @@ interface PrivilegeRow {
132
165
 
133
166
  /**
134
167
  * Fails if anything `app_user` can reach is unprotected, if an exemption is stale or unexpected, if
135
- * the catalog query has stopped seeing the schema, or if an exempt relation has grown a write grant
136
- * at table OR column level.
168
+ * the catalog query has stopped seeing the schema, if an exempt relation has grown a write grant
169
+ * at table OR column level that its entry does not declare, or if a declared write is not held or not
170
+ * confined to the request's tenant by row-level security.
137
171
  */
138
172
  export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown) => ProofExpectation): Promise<void> {
139
173
  // Every relation on which app_user — or PUBLIC, which app_user is a member of — holds any
@@ -160,7 +194,8 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
160
194
  c.relkind::text AS kind,
161
195
  c.relrowsecurity AS enabled,
162
196
  c.relforcerowsecurity AS forced,
163
- c.relispartition AS is_partition
197
+ c.relispartition AS is_partition,
198
+ pg_has_role('app_user', c.relowner, 'USAGE') AS app_user_owns
164
199
  FROM reachable r
165
200
  JOIN pg_class c ON c.oid = r.oid
166
201
  JOIN pg_namespace n ON n.oid = c.relnamespace
@@ -175,6 +210,7 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
175
210
  c.relname AS table_name,
176
211
  p.polname AS policy_name,
177
212
  p.polpermissive AS permissive,
213
+ p.polcmd::text AS command,
178
214
  pg_get_expr(p.polqual, p.polrelid) AS using_src,
179
215
  pg_get_expr(p.polwithcheck, p.polrelid) AS check_src
180
216
  FROM pg_policy p
@@ -200,11 +236,13 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
200
236
  }
201
237
  }
202
238
 
203
- const exemptions = Object.keys(RLS_EXEMPT).sort()
239
+ const exemptions = Object.entries(RLS_EXEMPT)
240
+ .map(([exempt, exemption]) => pinnedName(exempt, exemption))
241
+ .sort()
204
242
  if (exemptions.join(',') !== [...EXPECTED_EXEMPTIONS].sort().join(',')) {
205
243
  failures.push(
206
244
  `RLS_EXEMPT changed to [${exemptions.join(', ')}] — update EXPECTED_EXEMPTIONS and SECURITY.md's ` +
207
- `list of deliberately exempt tables in the same commit`,
245
+ `list of deliberately exempt tables, and the writes each may hold, in the same commit`,
208
246
  )
209
247
  }
210
248
  for (const exempt of Object.keys(RLS_EXEMPT)) {
@@ -261,8 +299,9 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
261
299
  }
262
300
  }
263
301
 
264
- // Makes SECURITY.md's "the grants are SELECT-only" a proof rather than a promise — including the
265
- // column-level and TRUNCATE/REFERENCES forms that has_table_privilege does not report.
302
+ // Makes SECURITY.md's "the grants are SELECT-only, but for the writes declared" a proof rather than a
303
+ // promise — including the column-level and TRUNCATE/REFERENCES forms that has_table_privilege does not
304
+ // report.
266
305
  const { rows: privileges } = await sql<PrivilegeRow>`
267
306
  SELECT n.nspname AS schema_name, c.relname AS table_name, a.privilege_type AS privilege_type, 'table' AS scope
268
307
  FROM pg_class c
@@ -280,14 +319,91 @@ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown)
280
319
  AND a.privilege_type <> 'SELECT'
281
320
  `.execute(db)
282
321
 
322
+ const held = new Set<string>()
283
323
  for (const privilege of privileges) {
284
324
  const key = `${privilege.schema_name}.${privilege.table_name}`
285
- if (RLS_EXEMPT[key] === undefined) continue
325
+ const exemption = RLS_EXEMPT[key]
326
+ if (exemption === undefined) continue
327
+ held.add(`${key} ${privilege.privilege_type}`)
328
+ if (declares(exemption, privilege.privilege_type)) continue
286
329
  failures.push(
287
330
  `app_user holds ${privilege.privilege_type} (${privilege.scope}-level) on the exempt relation ${key}, ` +
288
- `which SECURITY.md promises is SELECT-only`,
331
+ `which SECURITY.md promises is SELECT-only unless RLS_EXEMPT declares the write`,
289
332
  )
290
333
  }
291
334
 
335
+ // A declared write is the one thing an exempt relation may hold beyond SELECT, so it is proved here
336
+ // rather than trusted: held (a declaration app_user no longer needs is a stale hole), and scoped to the
337
+ // tenant by row-level security.
338
+ for (const [key, exemption] of Object.entries(RLS_EXEMPT)) {
339
+ const relation = rows.find((row) => name(row) === key)
340
+ if (relation === undefined) continue // reported above as a stale exemption
341
+ for (const write of exemption.writes ?? []) {
342
+ if (!Object.hasOwn(WRITE_COMMANDS, write)) {
343
+ failures.push(`RLS_EXEMPT declares ${write} on ${key}; only INSERT, UPDATE and DELETE can be declared`)
344
+ continue
345
+ }
346
+ if (!held.has(`${key} ${write}`)) {
347
+ failures.push(
348
+ `RLS_EXEMPT declares ${write} on ${key}, which app_user does not hold — stale declaration`,
349
+ )
350
+ continue
351
+ }
352
+ failures.push(...provenWrite(key, relation, write, policiesOf.get(key) ?? []))
353
+ }
354
+ }
355
+
292
356
  expect(failures.join('\n')).toBe('')
293
357
  }
358
+
359
+ function declares(exemption: Exemption, privilege: string): boolean {
360
+ return (exemption.writes as readonly string[] | undefined)?.includes(privilege) ?? false
361
+ }
362
+
363
+ /**
364
+ * Why a declared write on an exempt relation is NOT confined to the request's tenant, as failure lines; none
365
+ * when it is. The relation must have row-level security ENABLED (an exempt relation is not held to FORCE: its
366
+ * owner is the privileged path that seeds rows with no tenant context, and `withTenant` writes as `app_user`), an
367
+ * owner whose privileges `app_user` does not hold (they skip every policy that is not forced), and some
368
+ * PERMISSIVE policy must admit the command, or the grant reaches nothing. Every permissive policy that
369
+ * applies to the command (its own, or ALL) is then read the way the tenant tables' policies are, but only in
370
+ * the expressions that command evaluates: an INSERT its WITH CHECK, an UPDATE both, a DELETE its USING, an
371
+ * absent WITH CHECK falling back to USING. An absent expression the command evaluates admits every row. A
372
+ * SELECT policy is the exemption itself and is not read; RESTRICTIVE policies only narrow.
373
+ */
374
+ function provenWrite(key: string, relation: RelationRow, write: ExemptWrite, policies: PolicyRow[]): string[] {
375
+ if (!relation.enabled) {
376
+ return [`RLS_EXEMPT declares ${write} on ${key}, which has no ROW LEVEL SECURITY to confine it to a tenant`]
377
+ }
378
+ // Without FORCE the owner skips every policy, and so does any role with the owner's privileges: a member of the
379
+ // owning role. A tenant table's FORCE holds such a role; an exempt one's ENABLE does not.
380
+ if (relation.app_user_owns && !relation.forced) {
381
+ return [
382
+ `RLS_EXEMPT declares ${write} on ${key}, whose owner's privileges app_user holds, so no policy applies to it`,
383
+ ]
384
+ }
385
+ const command = WRITE_COMMANDS[write]
386
+ const applying = policies.filter(
387
+ (policy) => policy.permissive && (policy.command === command || policy.command === '*'),
388
+ )
389
+ if (applying.length === 0) {
390
+ return [
391
+ `RLS_EXEMPT declares ${write} on ${key}, but no permissive policy admits ${write}: the grant reaches nothing`,
392
+ ]
393
+ }
394
+ const failures: string[] = []
395
+ for (const policy of applying) {
396
+ const check = policy.check_src ?? policy.using_src
397
+ const evaluated =
398
+ write === 'INSERT' ? [check] : write === 'UPDATE' ? [policy.using_src, check] : [policy.using_src]
399
+ const blind = evaluated.filter((expression) => expression === null || !expression.includes(TENANT_SETTING))
400
+ if (blind.length > 0) {
401
+ failures.push(
402
+ `${key} declares ${write}, and its permissive policy \`${policy.policy_name}\` admits ${write} ` +
403
+ `without reading ${TENANT_SETTING}, so the write is not confined to a tenant: ` +
404
+ blind.map((expression) => expression ?? '(no expression: every row)').join(' / '),
405
+ )
406
+ }
407
+ }
408
+ return failures
409
+ }
@@ -233,6 +233,153 @@ export const frameworkRlsProofs: RlsProofSuite = async ({
233
233
  }
234
234
  expect(keyDeleteRejected).toBe(true)
235
235
 
236
+ // ---- organizations: cross-tenant READ, tenant-scoped WRITES (0018_organizations_write) ----
237
+ //
238
+ // An infra table like service_keys for reading: a request reads any tenant's teams (callers are resolved
239
+ // before a tenant context exists). But app_user also holds INSERT, UPDATE and DELETE, so a request can
240
+ // create, rename and delete teams, and row-level security confines each of those to the request's own tenant.
241
+ // Every write below is the shape a route would send; each cross-tenant one must land nowhere.
242
+ const orgStamp = Date.now()
243
+ // Every write through orgWriteFails ROLLS BACK, whatever it does, so a regression shows as a red proof and never leaves a
244
+ // stray or rewritten team behind in a contract database that is reused.
245
+ const rolledBack = new Error('rolled back')
246
+ const orgWriteFails = async (tenantId: string | null, write: (trx: Kysely<DB>) => Promise<unknown>) => {
247
+ try {
248
+ await appDb.transaction().execute(async (trx) => {
249
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
250
+ if (tenantId !== null) {
251
+ await sql`SELECT set_config('app.current_tenant', ${tenantId}, true)`.execute(trx)
252
+ }
253
+ await write(trx)
254
+ throw rolledBack
255
+ })
256
+ } catch (error) {
257
+ return error === rolledBack ? 'no error' : String(error)
258
+ }
259
+ return 'no error'
260
+ }
261
+ const demoOrgName = async () =>
262
+ (await db.selectFrom('organizations').select('name').where('id', '=', demoOrgId).executeTakeFirstOrThrow()).name
263
+
264
+ // the read stays cross-tenant: alpha's request sees demo's team (the exemption, unchanged)
265
+ const orgsSeenByAlpha = await runWithTenant(appDb, alphaTenantId, (trx) =>
266
+ trx.selectFrom('organizations').select('id').where('id', 'in', [alphaOrgId, demoOrgId]).execute(),
267
+ )
268
+ expect(orgsSeenByAlpha.length).toBe(2)
269
+
270
+ // a request creates, renames and deletes a team of its OWN tenant
271
+ const [ownOrg] = await runWithTenant(appDb, alphaTenantId, (trx) =>
272
+ trx
273
+ .insertInto('organizations')
274
+ .values({ tenant_id: alphaTenantId, slug: `alpha-own-${orgStamp}`, name: 'Alpha Own' })
275
+ .returning('id')
276
+ .execute(),
277
+ )
278
+ const renamed = await runWithTenant(appDb, alphaTenantId, (trx) =>
279
+ trx.updateTable('organizations').set({ name: 'Alpha Renamed' }).where('id', '=', ownOrg!.id).executeTakeFirst(),
280
+ )
281
+ expect(Number(renamed.numUpdatedRows)).toBe(1)
282
+
283
+ // INSERT carrying the other tenant's id is rejected by WITH CHECK
284
+ const foreignInsert = await orgWriteFails(alphaTenantId, (trx) =>
285
+ trx
286
+ .insertInto('organizations')
287
+ .values({ tenant_id: demoTenantId, slug: `smuggled-${orgStamp}`, name: 'Smuggled' })
288
+ .execute(),
289
+ )
290
+ expect(/row-level security/.test(foreignInsert)).toBe(true)
291
+
292
+ // UPDATE and DELETE never reach the other tenant's team: zero rows, and the row is untouched
293
+ const foreignRename = await runWithTenant(appDb, alphaTenantId, (trx) =>
294
+ trx.updateTable('organizations').set({ name: 'Hijacked' }).where('id', '=', demoOrgId).executeTakeFirst(),
295
+ )
296
+ expect(Number(foreignRename.numUpdatedRows)).toBe(0)
297
+ const foreignDelete = await runWithTenant(appDb, alphaTenantId, (trx) =>
298
+ trx.deleteFrom('organizations').where('id', '=', demoOrgId).executeTakeFirst(),
299
+ )
300
+ expect(Number(foreignDelete.numDeletedRows)).toBe(0)
301
+ expect(await demoOrgName()).toBe('Demo Proof Org')
302
+
303
+ // only a team's name is a request's to change: its tenant, its slug and its id are not, and a new team's id is the
304
+ // default (the grants are column grants)
305
+ for (const change of [
306
+ { tenant_id: demoTenantId },
307
+ { slug: `alpha-moved-${orgStamp}` },
308
+ { id: '00000000-0000-4000-8000-000000000018' },
309
+ ]) {
310
+ const refused = await orgWriteFails(alphaTenantId, (trx) =>
311
+ trx.updateTable('organizations').set(change).where('id', '=', ownOrg!.id).execute(),
312
+ )
313
+ expect(/permission denied/.test(refused)).toBe(true)
314
+ }
315
+ const mintedId = await orgWriteFails(alphaTenantId, (trx) =>
316
+ trx
317
+ .insertInto('organizations')
318
+ .values({
319
+ id: '00000000-0000-4000-8000-000000000018',
320
+ tenant_id: alphaTenantId,
321
+ slug: `minted-${orgStamp}`,
322
+ name: 'Minted',
323
+ })
324
+ .execute(),
325
+ )
326
+ expect(/permission denied/.test(mintedId)).toBe(true)
327
+
328
+ // a new team cannot take a slug another tenant's team holds: the inbound mail address names a team by its slug
329
+ // alone, and two matches leave that team's mail unresolved
330
+ const { slug: demoOrgSlug } = await db
331
+ .selectFrom('organizations')
332
+ .select('slug')
333
+ .where('id', '=', demoOrgId)
334
+ .executeTakeFirstOrThrow()
335
+ const squat = await orgWriteFails(alphaTenantId, (trx) =>
336
+ trx
337
+ .insertInto('organizations')
338
+ .values({ tenant_id: alphaTenantId, slug: demoOrgSlug, name: 'Squat' })
339
+ .execute(),
340
+ )
341
+ expect(/row-level security/.test(squat)).toBe(true)
342
+
343
+ // fail-closed: role set, no tenant context -> no write lands anywhere
344
+ const contextlessInsert = await orgWriteFails(null, (trx) =>
345
+ trx
346
+ .insertInto('organizations')
347
+ .values({ tenant_id: alphaTenantId, slug: `contextless-${orgStamp}`, name: 'Contextless' })
348
+ .execute(),
349
+ )
350
+ expect(/row-level security/.test(contextlessInsert)).toBe(true)
351
+ let contextlessWrites = -1
352
+ const contextless = await orgWriteFails(null, async (trx) => {
353
+ const update = await trx.updateTable('organizations').set({ name: 'Contextless' }).executeTakeFirst()
354
+ const remove = await trx.deleteFrom('organizations').executeTakeFirst()
355
+ contextlessWrites = Number(update.numUpdatedRows) + Number(remove.numDeletedRows)
356
+ })
357
+ expect(contextless).toBe('no error')
358
+ expect(contextlessWrites).toBe(0)
359
+
360
+ // TRUNCATE ignores row-level security, so it is not granted
361
+ const truncate = await orgWriteFails(alphaTenantId, (trx) => sql`TRUNCATE organizations`.execute(trx))
362
+ expect(/permission denied/.test(truncate)).toBe(true)
363
+
364
+ // the composite key lets a table pin its org to its own tenant: a row naming demo's team under alpha is refused.
365
+ // The probe table is a plain one (a temporary table may not reference a permanent one), created as the owner
366
+ // inside a transaction that always rolls back, so it never outlives the proof.
367
+ const compositeRefused = await orgWriteFails(alphaTenantId, async (trx) => {
368
+ await sql`RESET ROLE`.execute(trx)
369
+ await sql`CREATE TABLE org_pinned_probe (tenant_id uuid, org_id uuid,
370
+ FOREIGN KEY (tenant_id, org_id) REFERENCES organizations (tenant_id, id))`.execute(trx)
371
+ await sql`INSERT INTO org_pinned_probe VALUES (${alphaTenantId}, ${alphaOrgId})`.execute(trx)
372
+ await sql`INSERT INTO org_pinned_probe VALUES (${alphaTenantId}, ${demoOrgId})`.execute(trx)
373
+ throw new Error("the composite key accepted another tenant's org")
374
+ })
375
+ expect(/foreign key/.test(compositeRefused)).toBe(true)
376
+
377
+ // and the request deletes the team it made, which nothing references
378
+ const ownDelete = await runWithTenant(appDb, alphaTenantId, (trx) =>
379
+ trx.deleteFrom('organizations').where('id', '=', ownOrg!.id).executeTakeFirst(),
380
+ )
381
+ expect(Number(ownDelete.numDeletedRows)).toBe(1)
382
+
236
383
  // ---- audit_events: tenant-only RLS, org_id NOT NULL, APPEND-ONLY (SELECT/INSERT, no UPDATE/DELETE) ----
237
384
  //
238
385
  // The compliance-grade product record. Same tenant-only RLS shape as jobs. Two extra guarantees:
@@ -1127,8 +1127,8 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
1127
1127
  }),
1128
1128
  ]
1129
1129
  const viewpoint = person ? `person:${person.id}` : invitedViewpoint
1130
- // Mirrors the real glue's derivation (simulator-glue.tsx): resolve the viewpoint's email from
1131
- // the same people list the People tab renders, rather than re-deriving it a second way.
1130
+ // Mirrors the server host's derivation (../components/simulator/simulator-host.tsx): resolve the viewpoint's email
1131
+ // from the same people list the People tab renders, rather than re-deriving it a second way.
1132
1132
  const personEmail = peopleRows.find((p) => p.key === viewpoint)?.email ?? null
1133
1133
  const scopedEmails =
1134
1134
  mailScope === 'all' || !personEmail ? emails : emails.filter((email) => email.to === personEmail)
package/src/guide.md CHANGED
@@ -32,6 +32,12 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
32
32
  tests and in the app-root tool configs (Playwright, Vite). Every other module imports the resolved value: deployment
33
33
  parameters from `config/params.ts`, the run mode from `isSimulated`.
34
34
  - Deployment and service parameters exist only in `config/params.ts`. Secret values never enter the repository.
35
+ - Build an absolute URL a visitor follows (a link in an email, a URL you store) on `publicOrigin(request)` from
36
+ `@sssb/kit/adapters/edge-headers`, never on `request.url` or `nextUrl`: behind `SssbApp` their origin is the server's
37
+ own bind address and port, never the visitor's host. Outside a request, in a job, it needs the server's `PUBLIC_ORIGIN`. Key what depends on
38
+ the visitor's address (a rate limit, a lockout, an audit record's "from") on `clientAddress(request)`, and treat its
39
+ `undefined` as unknown; never on `X-Forwarded-For`'s first entry, `X-Real-IP` or `CF-Connecting-IP`, which the visitor
40
+ writes. `sssb/no-raw-request-origin` flags a direct read.
35
41
  - Declare which of SSSB's optional ports the app uses in `config/params.ts`'s `ports` (`llm`, `email`, `inboundEmail`,
36
42
  `jobs`, `storage`). A port the app does not use is `none`, never configured with placeholder values.
37
43
  - A job handler never reads the seed (`@sssb/app-config/seed`), which a deployment does not have: it finds people with