@sssb/kit 0.0.0-stage → 0.2.0

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 (214) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +209 -3
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +312 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +270 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +94 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +115 -0
  28. package/src/adapters/real/accept-invite-form.tsx +77 -0
  29. package/src/adapters/real/analytics.ts +28 -0
  30. package/src/adapters/real/auth.ts +216 -0
  31. package/src/adapters/real/contract-data-api.ts +104 -0
  32. package/src/adapters/real/contract-postgres.ts +167 -0
  33. package/src/adapters/real/database-transport.ts +34 -0
  34. package/src/adapters/real/db-data-api.ts +61 -0
  35. package/src/adapters/real/db.ts +88 -0
  36. package/src/adapters/real/email.ts +22 -0
  37. package/src/adapters/real/index.ts +89 -0
  38. package/src/adapters/real/jobs.ts +32 -0
  39. package/src/adapters/real/llm.ts +108 -0
  40. package/src/adapters/real/migrate-handler.ts +66 -0
  41. package/src/adapters/real/providers.tsx +12 -0
  42. package/src/adapters/real/rds-data-codec.ts +508 -0
  43. package/src/adapters/real/rds-data-dialect.ts +470 -0
  44. package/src/adapters/real/rds-data-emulator.ts +351 -0
  45. package/src/adapters/real/s3-storage.ts +233 -0
  46. package/src/adapters/real/sign-in-form.tsx +59 -0
  47. package/src/adapters/real/storage.ts +10 -0
  48. package/src/adapters/sentry/baseline.ts +90 -0
  49. package/src/adapters/sentry/client.ts +17 -0
  50. package/src/adapters/sentry/init.ts +17 -0
  51. package/src/authz/app-exemptions.ts +226 -0
  52. package/src/authz/authorize.ts +214 -0
  53. package/src/authz/route-policy.ts +153 -0
  54. package/src/authz/route-scan.ts +1516 -0
  55. package/src/components/agreements/acceptances-section.tsx +55 -0
  56. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  57. package/src/components/agreements/agreement-body.tsx +34 -0
  58. package/src/components/agreements/agreement-gate.tsx +45 -0
  59. package/src/components/app-header.tsx +45 -0
  60. package/src/components/auth/accept-invite-screen.tsx +126 -0
  61. package/src/components/auth/auth-icons.tsx +68 -0
  62. package/src/components/auth/org-switcher.tsx +76 -0
  63. package/src/components/auth/people-picker.tsx +50 -0
  64. package/src/components/auth/preview-row.tsx +64 -0
  65. package/src/components/auth/sign-in-screen.tsx +24 -0
  66. package/src/components/auth/user-menu.tsx +64 -0
  67. package/src/components/demo-badge.tsx +20 -0
  68. package/src/components/demo-banner.tsx +14 -0
  69. package/src/components/gates/gate-interstitial.tsx +23 -0
  70. package/src/components/job-timeline.tsx +64 -0
  71. package/src/components/notifications/notification-bell.tsx +120 -0
  72. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  73. package/src/components/org-screen.tsx +197 -0
  74. package/src/components/profile-screen.tsx +100 -0
  75. package/src/components/simulator/actor-runtime.ts +180 -0
  76. package/src/components/simulator/actor-shell.tsx +275 -0
  77. package/src/components/simulator/actors-app.tsx +119 -0
  78. package/src/components/simulator/errors-app.tsx +84 -0
  79. package/src/components/simulator/events-app.tsx +210 -0
  80. package/src/components/simulator/format-when.ts +20 -0
  81. package/src/components/simulator/hooks-app.tsx +319 -0
  82. package/src/components/simulator/inbound-app.tsx +210 -0
  83. package/src/components/simulator/jobs-app.tsx +471 -0
  84. package/src/components/simulator/mail-app.tsx +290 -0
  85. package/src/components/simulator/messages-app.tsx +64 -0
  86. package/src/components/simulator/people-app.tsx +140 -0
  87. package/src/components/simulator/people-dimensions.ts +16 -0
  88. package/src/components/simulator/simulator-panel.tsx +716 -0
  89. package/src/components/simulator/snapshots-app.tsx +398 -0
  90. package/src/components/simulator/tab-mount.ts +25 -0
  91. package/src/components/simulator/tours-app.tsx +105 -0
  92. package/src/components/webhook-endpoints-card.tsx +172 -0
  93. package/src/core/abilities.ts +459 -0
  94. package/src/core/agreements.ts +139 -0
  95. package/src/core/gates.ts +157 -0
  96. package/src/core/greeting.ts +11 -0
  97. package/src/core/inbound-email.ts +129 -0
  98. package/src/core/jobs.ts +51 -0
  99. package/src/core/keyset.ts +227 -0
  100. package/src/core/llm-models.ts +10 -0
  101. package/src/core/locale.ts +3 -0
  102. package/src/core/notifications.ts +182 -0
  103. package/src/core/presets.ts +456 -0
  104. package/src/core/roles.ts +47 -0
  105. package/src/core/schedules.ts +147 -0
  106. package/src/core/standard-schema.ts +56 -0
  107. package/src/core/state-machine.ts +43 -0
  108. package/src/core/webhook-events.ts +86 -0
  109. package/src/core/webhook-hmac.ts +248 -0
  110. package/src/core/webhook-signing.ts +27 -0
  111. package/src/cutover/rows.json +101 -0
  112. package/src/db/agreements.ts +176 -0
  113. package/src/db/app-roles.ts +197 -0
  114. package/src/db/audit.ts +356 -0
  115. package/src/db/inbound-email.ts +145 -0
  116. package/src/db/jobs.ts +300 -0
  117. package/src/db/jsonb.ts +18 -0
  118. package/src/db/keyset.ts +179 -0
  119. package/src/db/migrate.ts +73 -0
  120. package/src/db/migrations/0001_tenants.ts +25 -0
  121. package/src/db/migrations/0003_organizations.ts +27 -0
  122. package/src/db/migrations/0004_jobs.ts +64 -0
  123. package/src/db/migrations/0005_service_keys.ts +33 -0
  124. package/src/db/migrations/0008_audit_events.ts +51 -0
  125. package/src/db/migrations/0009_job_schedules.ts +52 -0
  126. package/src/db/migrations/0010_webhooks.ts +100 -0
  127. package/src/db/migrations/0011_notifications.ts +98 -0
  128. package/src/db/migrations/0012_inbound_email.ts +74 -0
  129. package/src/db/migrations/0013_agreements.ts +98 -0
  130. package/src/db/migrations/0014_audit_credential.ts +29 -0
  131. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  132. package/src/db/migrations/0016_audit_detail.ts +26 -0
  133. package/src/db/migrations/index.ts +49 -0
  134. package/src/db/notifications.ts +185 -0
  135. package/src/db/org-lookup.ts +104 -0
  136. package/src/db/owner-pass.ts +252 -0
  137. package/src/db/rls-coverage.ts +259 -0
  138. package/src/db/rls-proof-runner.ts +94 -0
  139. package/src/db/rls-proofs.ts +1176 -0
  140. package/src/db/schedules.ts +187 -0
  141. package/src/db/schema.ts +235 -0
  142. package/src/db/seed.ts +176 -0
  143. package/src/db/service-keys.ts +50 -0
  144. package/src/db/tenant-lookup.ts +13 -0
  145. package/src/db/webhooks.ts +483 -0
  146. package/src/db/with-tenant.ts +26 -0
  147. package/src/demo-static/actor-drivers.ts +161 -0
  148. package/src/demo-static/assistant-replay.ts +61 -0
  149. package/src/demo-static/contracts.ts +282 -0
  150. package/src/demo-static/email-html.ts +58 -0
  151. package/src/demo-static/hash-route.ts +24 -0
  152. package/src/demo-static/rows.ts +105 -0
  153. package/src/demo-static/shell.tsx +440 -0
  154. package/src/demo-static/tour/contracts.ts +97 -0
  155. package/src/demo-static/tour/driver.ts +320 -0
  156. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  157. package/src/demo-static/tour/use-tours.tsx +394 -0
  158. package/src/demo-static/world.ts +1479 -0
  159. package/src/email/send.ts +12 -0
  160. package/src/email/templates/digest-email.tsx +61 -0
  161. package/src/email/templates/invite-email.tsx +57 -0
  162. package/src/email/templates/notification-email.tsx +39 -0
  163. package/src/guide.md +118 -0
  164. package/src/i18n/messages/en.json +373 -0
  165. package/src/i18n/messages/es.json +373 -0
  166. package/src/i18n/messages.ts +34 -0
  167. package/src/i18n/namespaces.ts +32 -0
  168. package/src/i18n/request.ts +34 -0
  169. package/src/i18n/routing.ts +7 -0
  170. package/src/inbound-email/handlers.ts +67 -0
  171. package/src/inbound-email/intake.ts +180 -0
  172. package/src/jobs/digest-email.ts +97 -0
  173. package/src/observability/scrub.ts +42 -0
  174. package/src/ports/README.md +8 -0
  175. package/src/ports/analytics.ts +8 -0
  176. package/src/ports/auth.ts +87 -0
  177. package/src/ports/db.ts +27 -0
  178. package/src/ports/email.ts +14 -0
  179. package/src/ports/errors.ts +46 -0
  180. package/src/ports/jobs.ts +48 -0
  181. package/src/ports/llm.ts +85 -0
  182. package/src/ports/storage.ts +132 -0
  183. package/src/seed/contracts.ts +129 -0
  184. package/src/server-lib/assistant.ts +45 -0
  185. package/src/server-lib/defer.ts +53 -0
  186. package/src/server-lib/demo-presets.ts +85 -0
  187. package/src/server-lib/invite.ts +92 -0
  188. package/src/server-lib/notify-deps.ts +15 -0
  189. package/src/server-lib/notify.ts +252 -0
  190. package/src/server-lib/preset-operations.ts +121 -0
  191. package/src/server-lib/scheduled-tick.ts +38 -0
  192. package/src/server-lib/sms.ts +43 -0
  193. package/src/server-lib/webhook-dispatch.ts +75 -0
  194. package/src/service-auth/mailgun.ts +70 -0
  195. package/src/service-auth/verify.ts +73 -0
  196. package/src/service-auth/webhook.ts +60 -0
  197. package/src/testing/checks.json +103 -0
  198. package/src/testing/conformance/authz.ts +46 -0
  199. package/src/testing/conformance/db.ts +258 -0
  200. package/src/testing/conformance/demo-presets.ts +295 -0
  201. package/src/testing/conformance/i18n.ts +80 -0
  202. package/src/testing/conformance/register.ts +200 -0
  203. package/src/testing/conformance/seam-map.ts +205 -0
  204. package/src/testing/conformance/suite.ts +59 -0
  205. package/src/testing/conformance/types.ts +18 -0
  206. package/src/testing/contract.ts +200 -0
  207. package/src/testing/e2e.ts +15 -0
  208. package/src/testing/index.ts +6 -0
  209. package/src/testing/seam-specifiers.json +22 -0
  210. package/src/testing/tmp-dir-marker.d.mts +4 -0
  211. package/src/testing/tmp-dir-marker.mjs +5 -0
  212. package/src/testing/tmp-dir.ts +182 -0
  213. package/src/theme.ts +28 -0
  214. package/README.md +0 -3
@@ -0,0 +1,252 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { type Kysely, sql } from 'kysely'
3
+ import {
4
+ appRoles,
5
+ checkAppRoles,
6
+ FRAMEWORK_ROLE,
7
+ ORDINARY_APP_USER,
8
+ ORDINARY_NAMED,
9
+ refusedOf,
10
+ shownRefused,
11
+ } from './app-roles'
12
+ import { migrateToLatest } from './migrate'
13
+ import { runRlsProofs } from './rls-proof-runner'
14
+ import type { ProofExpectation } from './rls-proofs'
15
+ import type { DB } from './schema'
16
+ import { runWithTenant } from './with-tenant'
17
+
18
+ /**
19
+ * THE NON-SUPERUSER PASS of the contract suite: SSSB's migrations and its RLS proofs, run the way a
20
+ * real deployment runs them — as a database OWNER that is not a superuser (ADR-0004 addendum,
21
+ * 2026-11-16).
22
+ *
23
+ * Why it exists. Every other contract pass connects as `postgres`, a superuser, and a superuser may
24
+ * `SET ROLE` to any role. Aurora's master user is `NOSUPERUSER CREATEROLE`, and since Postgres 16 a
25
+ * non-superuser that creates a role is granted ADMIN on it, but not SET. So the owner that created
26
+ * `app_user` could not switch to it, and every `withTenant` failed closed with `permission denied to set
27
+ * role "app_user"`. No gate could see it, because every gate was a superuser.
28
+ *
29
+ * The app's own roles. `app_user` is not the only cluster-wide role a migration may create: an app's may create its
30
+ * own, which it names in `appRoles` (./app-roles.ts). Where an earlier pass created one, a later owner is granted the
31
+ * creator's membership in it too, as in `app_user` (`grantAppRoles`), and on no role the app does not name, nor on a
32
+ * named role, or an `app_user`, that is not ordinary; after the migrations, `app_user` and every named role must still
33
+ * be ordinary. Teardown leaves the roles themselves, as it leaves `app_user` (a role a migration creates is the
34
+ * cluster's, not the pass's), but not what the owner granted on them: `DROP OWNED BY` revokes a membership the owner's migration granted (`GRANT <role> TO
35
+ * app_user`), which would otherwise keep the owner from being dropped (`dropPassRole`). An owner the teardown cannot
36
+ * drop fails the pass.
37
+ *
38
+ * How it is built, so another transport can run it. The pass only ever reaches the server through
39
+ * `admin` and `connect`, and migrates through `migrate`. The `pg` contract run (../adapters/real/db.contract.test.ts)
40
+ * hands it pooled `pg` connections. The Data API run (../adapters/real/rds-data.contract.test.ts) hands it
41
+ * Data API connections through the emulator, and its own migrate: the Data API runs every migration in
42
+ * one transaction that takes a transaction-scoped lock first (ADR-0002, addendum 2026-11-16).
43
+ */
44
+
45
+ /** A login to one database. */
46
+ export interface Login {
47
+ database: string
48
+ user: string
49
+ password: string
50
+ }
51
+
52
+ export interface OwnerPassConnections {
53
+ /** A SUPERUSER connection to a database that already exists on the server: it creates the owner. */
54
+ admin: Kysely<DB>
55
+ /** The superuser's own login: the privileged handle the proofs seed and run the negative control with. */
56
+ superuser: { user: string; password: string }
57
+ /** A database that already exists, for the owner to connect to while it creates its own. */
58
+ maintenanceDatabase: string
59
+ /** Open a connection for a login, through whichever transport this pass is proving. */
60
+ connect: (login: Login) => Kysely<DB>
61
+ /** Run the migrations on a connection `connect` opened, the way that transport does; `migrateToLatest` when omitted. */
62
+ migrate?: (db: Kysely<DB>) => Promise<void>
63
+ }
64
+
65
+ /**
66
+ * Grants `owner` the creator's membership — ADMIN, and neither INHERIT nor SET — in each of the app's named roles
67
+ * (`appRoles`, ./app-roles.ts) that ALREADY exists on the server, as the pass does for `app_user`. A named role that
68
+ * does not exist yet is the owner's own migration's to create, and the owner gets that membership by creating it. A
69
+ * role that is not named is never touched.
70
+ *
71
+ * It refuses, before granting anything, a named role that is not ORDINARY (`refusedOf`, ./app-roles.ts): one that
72
+ * can log in, create databases or roles, is a superuser, bypasses RLS or replicates, holds a privilege on a server
73
+ * parameter, owns a database or tablespace, or is a member, at any depth, of any role but `app_user` and the other
74
+ * named roles. ADMIN lets its holder grant itself SET on the role and so act as the role and everything it is a member
75
+ * of, and, with CREATEROLE, reset a LOGIN role's password: on such a role it gives the owner more than
76
+ * an app's own role, and the names alone (validated again here by `checkAppRoles`, as a caller may pass any list)
77
+ * cannot rule that out on a server another hand set up. It refuses an existing `app_user` that is not ordinary the same
78
+ * way, though it does not grant it: `runOwnerPass` grants `app_user` only once this has passed.
79
+ */
80
+ export async function grantAppRoles(admin: Kysely<DB>, owner: string, named: readonly string[]): Promise<void> {
81
+ const found = await refusedOf(admin, checkAppRoles(named))
82
+ const privileged = shownRefused(found)
83
+ if (privileged !== '') {
84
+ throw new Error(
85
+ `owner pass: refusing to grant ADMIN on ${privileged}: a later owner is handed ADMIN on app_user and on ` +
86
+ 'every role appRoles names, so each must be an ordinary role, and ADMIN on this one would give the owner ' +
87
+ `more than that. Leave a named role ${ORDINARY_NAMED}, or stop naming it in appRoles; leave app_user ` +
88
+ `${ORDINARY_APP_USER}.`,
89
+ )
90
+ }
91
+ for (const { rolname } of found) {
92
+ if (rolname === FRAMEWORK_ROLE) continue
93
+ await sql`GRANT ${sql.id(rolname)} TO ${sql.id(owner)} WITH ADMIN TRUE, INHERIT FALSE, SET FALSE`.execute(admin)
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Drops a role the pass created, if it is there: `DROP OWNED BY` first, on `admin`'s database, which revokes what the
99
+ * role GRANTED as well as what it was granted, the role memberships it granted included (a migration's
100
+ * `GRANT <app role> TO app_user`, run as the owner, makes the owner that membership's grantor, a dependency `DROP ROLE`
101
+ * refuses to break), then `DROP ROLE`. Objects the role owns in another database still block it, so the caller drops
102
+ * that database first. Throws when the role is still there.
103
+ */
104
+ export async function dropPassRole(admin: Kysely<DB>, role: string): Promise<void> {
105
+ const { rows } = await sql<{ n: number }>`SELECT count(*)::int AS n FROM pg_roles WHERE rolname = ${role}`.execute(
106
+ admin,
107
+ )
108
+ if (rows[0]!.n === 0) return
109
+ await sql`DROP OWNED BY ${sql.id(role)}`.execute(admin)
110
+ await sql`DROP ROLE ${sql.id(role)}`.execute(admin)
111
+ }
112
+
113
+ export async function runOwnerPass(
114
+ connections: OwnerPassConnections,
115
+ expect: (actual: unknown) => ProofExpectation,
116
+ ): Promise<void> {
117
+ const { admin, connect } = connections
118
+ // Read before anything is created, so an invalid `appRoles` fails the pass with nothing to tear down.
119
+ const roles = await appRoles()
120
+ const stamp = Date.now()
121
+ const owner = `sssb_owner_${stamp}`
122
+ const probe = `${owner}_probe`
123
+ const database = `sssb_owner_db_${stamp}`
124
+ // Random, so a role a failed run left behind on a reused server cannot be logged into by its name.
125
+ const login = { user: owner, password: randomUUID() }
126
+
127
+ let ownerDb: Kysely<DB> | undefined
128
+ let superDb: Kysely<DB> | undefined
129
+ // ONE teardown for everything from CREATE ROLE on, run whatever happened: a failure at any step must not leave a
130
+ // LOGIN CREATEROLE role (which may hold ADMIN on app_user and the app's roles) on a server that outlives the run.
131
+ let failed: { error: unknown } | undefined
132
+ try {
133
+ // Aurora's master user, as a role: may log in, create roles and databases, and is no superuser.
134
+ await sql`CREATE ROLE ${sql.id(owner)} LOGIN CREATEROLE CREATEDB NOSUPERUSER PASSWORD ${sql.lit(login.password)}`.execute(
135
+ admin,
136
+ )
137
+
138
+ const bootstrap = connect({ ...login, database: connections.maintenanceDatabase })
139
+ try {
140
+ // What THIS server gives a non-superuser for a role it creates, measured rather than assumed:
141
+ // the owner creates a throwaway role, and its own membership in it is read back. On Postgres 16+
142
+ // with `createrole_self_grant` unset, that is ADMIN, and neither INHERIT nor SET.
143
+ await sql`CREATE ROLE ${sql.id(probe)} NOLOGIN`.execute(bootstrap)
144
+ const creator = await sql<{ admin_option: boolean; inherit_option: boolean; set_option: boolean }>`
145
+ SELECT m.admin_option, m.inherit_option, m.set_option
146
+ FROM pg_auth_members m
147
+ JOIN pg_roles r ON r.oid = m.roleid AND r.rolname = ${probe}
148
+ JOIN pg_roles me ON me.oid = m.member AND me.rolname = current_user`.execute(bootstrap)
149
+ expect(creator.rows.length).toBe(1)
150
+ expect(creator.rows[0]!.admin_option).toBe(true)
151
+ expect(creator.rows[0]!.inherit_option).toBe(false)
152
+ expect(creator.rows[0]!.set_option).toBe(false)
153
+
154
+ // Every cluster-wide role the APP's migrations create, which it names in `appRoles` (./app-roles.ts): a
155
+ // later owner's migration that alters one needs the ADMIN its creator holds. FIRST, because it refuses an
156
+ // existing app_user or named role that is not ordinary before anything at all is granted.
157
+ await grantAppRoles(admin, owner, roles)
158
+ // ...and `app_user`, which is cluster-wide too. Where it does not exist yet, the owner's own migration 0001
159
+ // creates it and the owner gets the creator's membership just measured. Where another pass
160
+ // already created it, the owner is granted EXACTLY that membership, so it stands where Aurora's
161
+ // master user stands after creating app_user either way.
162
+ const existing = await sql<{ n: number }>`
163
+ SELECT count(*)::int AS n FROM pg_roles WHERE rolname = 'app_user'`.execute(admin)
164
+ if (existing.rows[0]!.n > 0) {
165
+ await sql`GRANT app_user TO ${sql.id(owner)} WITH ADMIN TRUE, INHERIT FALSE, SET FALSE`.execute(admin)
166
+ }
167
+
168
+ await sql`CREATE DATABASE ${sql.id(database)}`.execute(bootstrap)
169
+ } finally {
170
+ await bootstrap.destroy()
171
+ }
172
+
173
+ ownerDb = connect({ ...login, database })
174
+ superDb = connect({ ...connections.superuser, database })
175
+
176
+ // The pass proves what it says only if the owner really is no superuser and cannot bypass RLS.
177
+ const self = await sql<{ rolsuper: boolean; rolbypassrls: boolean }>`
178
+ SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user`.execute(ownerDb)
179
+ expect(self.rows[0]!.rolsuper).toBe(false)
180
+ expect(self.rows[0]!.rolbypassrls).toBe(false)
181
+
182
+ await (connections.migrate ?? migrateToLatest)(ownerDb)
183
+
184
+ // Whichever branch each named role took, the owner now stands where its creator does: the role exists, and the
185
+ // owner holds ADMIN on it.
186
+ for (const role of roles) {
187
+ const held = await sql<{ admin: boolean | null }>`
188
+ SELECT bool_or(m.admin_option) AS admin FROM pg_auth_members m
189
+ JOIN pg_roles r ON r.oid = m.roleid AND r.rolname = ${role}
190
+ JOIN pg_roles me ON me.oid = m.member AND me.rolname = ${owner}`.execute(admin)
191
+ // As text, so a failure names the role.
192
+ expect(`ADMIN on ${role}: ${String(held.rows[0]?.admin ?? false)}`).toBe(`ADMIN on ${role}: true`)
193
+ }
194
+ // ...and app_user and every named role are still ordinary. The owner's migration ran with ADMIN and CREATEROLE
195
+ // on each, which let it make one LOGIN with a password it chose, CREATEDB or CREATEROLE, or (granting itself SET
196
+ // on it) the owner of the pass's own database, by `ALTER DATABASE … OWNER TO` (`CREATE DATABASE` cannot run in
197
+ // the migrations' transaction); never SUPERUSER, BYPASSRLS or REPLICATION, which the owner lacks, nor a
198
+ // holder of a parameter privilege or a tablespace, which need a superuser (all measured on Postgres 18.4): a role
199
+ // every later owner is handed ADMIN on must not be one.
200
+ const strayed = shownRefused(await refusedOf(admin, roles))
201
+ if (strayed !== '') {
202
+ throw new Error(
203
+ `owner pass: after the migrations, not an ordinary role: ${strayed}. Every later owner is handed ` +
204
+ `ADMIN on app_user and on every role appRoles names. Leave a named role ${ORDINARY_NAMED}; leave ` +
205
+ `app_user ${ORDINARY_APP_USER}.`,
206
+ )
207
+ }
208
+
209
+ // The failure itself, named: inside withTenant the owner IS app_user, in the tenant it asked for.
210
+ const [tenant] = await superDb
211
+ .insertInto('tenants')
212
+ .values({ slug: `owner-pass-${stamp}`, name: 'Owner Pass' })
213
+ .returning('id')
214
+ .execute()
215
+ const inside = await runWithTenant(ownerDb, tenant!.id, (trx) =>
216
+ sql<{ role: string; tenant: string }>`
217
+ SELECT current_user AS role, current_setting('app.current_tenant', true) AS tenant`.execute(trx),
218
+ )
219
+ expect(inside.rows[0]!.role).toBe('app_user')
220
+ expect(inside.rows[0]!.tenant).toBe(tenant!.id)
221
+
222
+ // ...and the whole composed proof suite, every role switch made by the owner.
223
+ await runRlsProofs(superDb, expect, { appDb: ownerDb })
224
+ } catch (error) {
225
+ failed = { error }
226
+ }
227
+ await ownerDb?.destroy().catch(() => undefined)
228
+ await superDb?.destroy().catch(() => undefined)
229
+ // Every step runs, each on its own. The database goes first (what the owner owns there would block its drop),
230
+ // best effort: a role it leaves behind is reported below.
231
+ await sql`DROP DATABASE IF EXISTS ${sql.id(database)} WITH (FORCE)`.execute(admin).catch(() => undefined)
232
+ const leaked: string[] = []
233
+ for (const role of [probe, owner]) {
234
+ await dropPassRole(admin, role).catch((error: unknown) => {
235
+ leaked.push(`"${role}" (${error instanceof Error ? error.message : String(error)})`)
236
+ })
237
+ }
238
+ // A role left behind is a failure of its own: the owner may log in, create roles, and holds ADMIN on app_user and
239
+ // the app's roles, on a server that outlives the run. It never hides the pass's own failure: both are reported, and
240
+ // Vitest (4.1) prints each error an AggregateError holds on its own, an assertion's expected/actual diff included.
241
+ if (leaked.length > 0) {
242
+ const teardown = new Error(`owner pass: teardown left ${leaked.join(', ')} on the server; drop it by hand`)
243
+ if (failed) {
244
+ throw new AggregateError(
245
+ [failed.error, teardown],
246
+ `${failed.error instanceof Error ? failed.error.message : String(failed.error)}\n...and ${teardown.message}`,
247
+ )
248
+ }
249
+ throw teardown
250
+ }
251
+ if (failed) throw failed.error
252
+ }
@@ -0,0 +1,259 @@
1
+ import { sql, type Kysely } from 'kysely'
2
+ import type { ProofExpectation } from './rls-proofs'
3
+ import type { DB } from './schema'
4
+
5
+ /**
6
+ * The COVERAGE half of the tenant-isolation proof (ADR-0004): not "do these tables isolate", but
7
+ * "is everything the app can reach actually protected at all".
8
+ *
9
+ * WHY THIS EXISTS. `SECURITY.md` promises that every tenant-scoped table is protected by row-level
10
+ * security. Nothing used to enforce the word "every" — the proof suite was a hand-written list of
11
+ * tables somebody remembered to extend, and a table left off it was invisible. That was demonstrated,
12
+ * not theorised: a tenant-scoped table added exactly the way `/sssb:new-entity` instructs, minus its
13
+ * six-line RLS block, passed typecheck, lint, knip and the whole unit suite while permitting a
14
+ * cross-tenant SELECT *and* a cross-tenant INSERT through the sanctioned `db.withTenant()` API.
15
+ *
16
+ * WHY IT ASKS ABOUT REACHABILITY RATHER THAN ABOUT `tenant_id`. The first version of this file asked
17
+ * "does the table have a column named `tenant_id`", and an adversarial round then walked through four
18
+ * doors that question does not cover: a table keyed on `org_id` instead (an org belongs to exactly one
19
+ * tenant, so it is tenant-scoped in fact and the convention says nothing about it in SQL), a table in
20
+ * a schema other than `public`, and a VIEW or MATERIALIZED VIEW over a protected table. Each one
21
+ * leaked, in the adopted artifact, with the gate green. A naming convention is not a mechanism —
22
+ * which was the whole lesson of the round that created this file, applied to the file itself.
23
+ *
24
+ * So the question is now the one that actually matters: **can `app_user` reach this relation?** That
25
+ * is the role every request runs as, it needs no convention to be true, and a relation the app cannot
26
+ * reach cannot leak through the app. Everything reachable must either be protected or be named as a
27
+ * deliberate exemption below.
28
+ *
29
+ * REACHABILITY MEANS INHERITED REACHABILITY, and getting that wrong was the same mistake a third
30
+ * time. The first version of this predicate matched a grant made to `PUBLIC` or written DIRECTLY to
31
+ * `app_user` — which is itself a convention, one level down. Postgres privileges pass through role
32
+ * MEMBERSHIP, so `GRANT SELECT ON t TO reporter; GRANT reporter TO app_user;` leaves `aclexplode`
33
+ * reporting the grantee as `reporter`, the relation invisible here, and a cross-tenant read available
34
+ * through `db.withTenant()` — demonstrated, with this check green. `pg_has_role` asks the transitive
35
+ * question instead. The `grantee = 0` arm stays beside it: that is `PUBLIC`, which `pg_has_role`
36
+ * does not cover.
37
+ *
38
+ * `FORCE` is checked because it cannot be caught behaviourally: every behavioural proof runs through
39
+ * `runWithTenant`, which does `SET LOCAL ROLE app_user`, and `app_user` is not the table owner — so
40
+ * `FORCE` makes no difference on that path. It protects the OWNER connection, which is what
41
+ * the SssbApp construct (packages/cdk) actually deploys, and measured on real Postgres with a non-superuser
42
+ * owner a table without it hands that connection every tenant's rows while a table with it hands over none.
43
+ *
44
+ * It runs inside `runRlsProofs`, so it runs on BOTH engines — pglite in the unit suite and real
45
+ * Postgres in `pnpm test:contract` — against whatever the registered migrations actually created.
46
+ */
47
+
48
+ /**
49
+ * Relations `app_user` can reach that deliberately have NO row-level security, each with the reason.
50
+ * Schema-qualified, so a table in another schema can never be exempted by a bare name.
51
+ *
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.
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.
59
+ */
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
+ }
67
+
68
+ /**
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.
72
+ */
73
+ const EXPECTED_EXEMPTIONS = ['public.organizations', 'public.service_keys', 'public.tenants']
74
+
75
+ /**
76
+ * Framework tables the framework's own migrations always create. Used as a SHAPE floor rather than a
77
+ * count floor: an earlier version asserted only "more rows than exemptions", and a deliberately
78
+ * broken catalog query that happened to retain the exemption names sailed past it while a shipped
79
+ * table had no RLS at all. A count is not a shape.
80
+ */
81
+ const MUST_APPEAR = [
82
+ 'public.agreements',
83
+ 'public.audit_events',
84
+ 'public.jobs',
85
+ 'public.job_schedules',
86
+ 'public.notifications',
87
+ 'public.organizations',
88
+ 'public.service_keys',
89
+ 'public.tenants',
90
+ 'public.webhook_deliveries',
91
+ 'public.webhook_endpoints',
92
+ ]
93
+
94
+ /** The transaction-scoped setting `runWithTenant` sets; a policy that ignores it is not isolating. */
95
+ const TENANT_SETTING = 'app.current_tenant'
96
+
97
+ /** Relation kinds that can carry RLS. Anything else reachable must be exempted explicitly. */
98
+ const CAN_CARRY_RLS = new Set(['r', 'p'])
99
+
100
+ const KIND_NAMES: Record<string, string> = {
101
+ r: 'table',
102
+ p: 'partitioned table',
103
+ v: 'view',
104
+ m: 'materialized view',
105
+ f: 'foreign table',
106
+ }
107
+
108
+ interface RelationRow {
109
+ schema_name: string
110
+ table_name: string
111
+ kind: string
112
+ enabled: boolean
113
+ forced: boolean
114
+ is_partition: boolean
115
+ policies: number
116
+ policy_src: string
117
+ }
118
+
119
+ interface PrivilegeRow {
120
+ schema_name: string
121
+ table_name: string
122
+ privilege_type: string
123
+ scope: string
124
+ }
125
+
126
+ /**
127
+ * Fails if anything `app_user` can reach is unprotected, if an exemption is stale or unexpected, if
128
+ * the catalog query has stopped seeing the schema, or if an exempt relation has grown a write grant
129
+ * at table OR column level.
130
+ */
131
+ export async function proveRlsCoverage(db: Kysely<DB>, expect: (actual: unknown) => ProofExpectation): Promise<void> {
132
+ // Every relation on which app_user — or PUBLIC, which app_user is a member of — holds any
133
+ // privilege, at table or column level. Column ACLs are included because a column-level grant is
134
+ // invisible to has_table_privilege, and one was demonstrated to allow UPDATEing every row of the
135
+ // tenant registry while the previous version of this check reported nothing.
136
+ const reachable = sql`
137
+ SELECT c.oid
138
+ FROM pg_class c
139
+ CROSS JOIN LATERAL aclexplode(c.relacl) a
140
+ WHERE a.grantee = 0 OR pg_has_role('app_user', a.grantee, 'USAGE')
141
+ UNION
142
+ SELECT c.oid
143
+ FROM pg_class c
144
+ JOIN pg_attribute att ON att.attrelid = c.oid AND att.attacl IS NOT NULL
145
+ CROSS JOIN LATERAL aclexplode(att.attacl) a
146
+ WHERE a.grantee = 0 OR pg_has_role('app_user', a.grantee, 'USAGE')
147
+ `
148
+
149
+ const { rows } = await sql<RelationRow>`
150
+ WITH reachable AS (${reachable})
151
+ SELECT n.nspname AS schema_name,
152
+ c.relname AS table_name,
153
+ c.relkind::text AS kind,
154
+ c.relrowsecurity AS enabled,
155
+ c.relforcerowsecurity AS forced,
156
+ c.relispartition AS is_partition,
157
+ (SELECT count(*) FROM pg_policy p WHERE p.polrelid = c.oid)::int AS policies,
158
+ COALESCE((
159
+ SELECT string_agg(
160
+ COALESCE(pg_get_expr(p.polqual, p.polrelid), '') || ' ' ||
161
+ COALESCE(pg_get_expr(p.polwithcheck, p.polrelid), ''), ' ')
162
+ FROM pg_policy p WHERE p.polrelid = c.oid
163
+ ), '') AS policy_src
164
+ FROM reachable r
165
+ JOIN pg_class c ON c.oid = r.oid
166
+ JOIN pg_namespace n ON n.oid = c.relnamespace
167
+ WHERE n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
168
+ ORDER BY n.nspname, c.relname
169
+ `.execute(db)
170
+
171
+ const failures: string[] = []
172
+ const name = (row: RelationRow) => `${row.schema_name}.${row.table_name}`
173
+ const present = new Set(rows.map(name))
174
+
175
+ // A catalog query that stopped seeing the schema would make every check below vacuously true —
176
+ // the "gate that has only ever passed" failure mode, which this file exists to refuse.
177
+ for (const required of MUST_APPEAR) {
178
+ if (!present.has(required)) {
179
+ failures.push(`the catalog query did not find \`${required}\`; it is not seeing the schema`)
180
+ }
181
+ }
182
+
183
+ const exemptions = Object.keys(RLS_EXEMPT).sort()
184
+ if (exemptions.join(',') !== [...EXPECTED_EXEMPTIONS].sort().join(',')) {
185
+ failures.push(
186
+ `RLS_EXEMPT changed to [${exemptions.join(', ')}] — update EXPECTED_EXEMPTIONS and SECURITY.md's ` +
187
+ `list of deliberately exempt tables in the same commit`,
188
+ )
189
+ }
190
+ for (const exempt of Object.keys(RLS_EXEMPT)) {
191
+ if (!present.has(exempt)) {
192
+ failures.push(`RLS_EXEMPT names \`${exempt}\`, which app_user cannot reach here — stale exemption`)
193
+ }
194
+ }
195
+
196
+ for (const row of rows) {
197
+ const key = name(row)
198
+ if (RLS_EXEMPT[key] !== undefined) continue
199
+
200
+ // A partition inherits its parent's policies and cannot usefully carry its own, so Postgres
201
+ // applies the parent's. Flagging partitions produced an unsatisfiable red gate whose only
202
+ // documented escape was adding them to the exemption list — a false positive that widens the
203
+ // hole. The parent is checked on its own row.
204
+ if (row.is_partition) continue
205
+
206
+ if (!CAN_CARRY_RLS.has(row.kind)) {
207
+ const kind = KIND_NAMES[row.kind] ?? row.kind
208
+ failures.push(
209
+ `${key} is a ${kind} reachable by app_user; it cannot carry RLS, so it must be listed in ` +
210
+ `RLS_EXEMPT with a reason (a view over a protected table bypasses that table's policy ` +
211
+ `whenever the view's owner is not itself subject to RLS)`,
212
+ )
213
+ continue
214
+ }
215
+
216
+ if (!row.enabled) failures.push(`${key} is reachable by app_user but has no ROW LEVEL SECURITY`)
217
+ else if (!row.forced) failures.push(`${key} has RLS but not FORCE ROW LEVEL SECURITY`)
218
+ else if (row.policies === 0) failures.push(`${key} has RLS enabled but no policy`)
219
+ else if (!row.policy_src.includes(TENANT_SETTING)) {
220
+ // Coverage used to accept any policy at all, so `USING (true)` — a policy that exists and
221
+ // isolates nothing — passed. Reading the expression is what distinguishes a policy from a
222
+ // policy that does something.
223
+ failures.push(
224
+ `${key} has a policy that never reads ${TENANT_SETTING}, so it does not isolate tenants: ` +
225
+ `${row.policy_src.trim()}`,
226
+ )
227
+ }
228
+ }
229
+
230
+ // Makes SECURITY.md's "the grants are SELECT-only" a proof rather than a promise — including the
231
+ // column-level and TRUNCATE/REFERENCES forms that has_table_privilege does not report.
232
+ const { rows: privileges } = await sql<PrivilegeRow>`
233
+ SELECT n.nspname AS schema_name, c.relname AS table_name, a.privilege_type AS privilege_type, 'table' AS scope
234
+ FROM pg_class c
235
+ JOIN pg_namespace n ON n.oid = c.relnamespace
236
+ CROSS JOIN LATERAL aclexplode(c.relacl) a
237
+ WHERE (a.grantee = 0 OR pg_has_role('app_user', a.grantee, 'USAGE'))
238
+ AND a.privilege_type <> 'SELECT'
239
+ UNION ALL
240
+ SELECT n.nspname, c.relname, a.privilege_type, 'column'
241
+ FROM pg_class c
242
+ JOIN pg_namespace n ON n.oid = c.relnamespace
243
+ JOIN pg_attribute att ON att.attrelid = c.oid AND att.attacl IS NOT NULL
244
+ CROSS JOIN LATERAL aclexplode(att.attacl) a
245
+ WHERE (a.grantee = 0 OR pg_has_role('app_user', a.grantee, 'USAGE'))
246
+ AND a.privilege_type <> 'SELECT'
247
+ `.execute(db)
248
+
249
+ for (const privilege of privileges) {
250
+ const key = `${privilege.schema_name}.${privilege.table_name}`
251
+ if (RLS_EXEMPT[key] === undefined) continue
252
+ failures.push(
253
+ `app_user holds ${privilege.privilege_type} (${privilege.scope}-level) on the exempt relation ${key}, ` +
254
+ `which SECURITY.md promises is SELECT-only`,
255
+ )
256
+ }
257
+
258
+ expect(failures.join('\n')).toBe('')
259
+ }
@@ -0,0 +1,94 @@
1
+ import { appRlsProofs } from '@sssb/app-config/db/rls-proofs'
2
+ import type { Kysely } from 'kysely'
3
+ import type { DbPort } from '../ports/db'
4
+ import { proveRlsCoverage } from './rls-coverage'
5
+ import { frameworkRlsProofs, type ProofExpectation } from './rls-proofs'
6
+ import type { DB } from './schema'
7
+ import { runWithTenant } from './with-tenant'
8
+
9
+ /**
10
+ * The composition root of THE tenant-isolation proof suite (ADR-0004): framework proofs ∪ app proofs,
11
+ * over one shared set of fixtures, as a single call both engines make.
12
+ *
13
+ * WHY IT LIVES IN THE PACKAGE. The suite has two consumers on opposite sides of the framework/app line —
14
+ * the conformance suite's `rls-pglite` check (packages/kit/src/testing/conformance/db.ts; unit, pglite) and the
15
+ * contract runner's `contract-rls` check (packages/kit/src/testing/contract.ts, `@sssb/kit/testing/contract`; real
16
+ * Postgres; every app's tests/contract file calls it) — and they must run the IDENTICAL assertions or
17
+ * the anti-drift guarantee is gone. A repo-root composition point would force the package's own test to escape its tree with a
18
+ * relative `../../../../` import, which is precisely the wart ADR-0012 recorded and this file closes.
19
+ * So the framework owns the composition and reads the app's half through the seam: `@sssb/app-config/db/
20
+ * rls-proofs` joins the short enumerated list of framework→seam VALUE imports (ability rules,
21
+ * migrations, the job/actor/flag registries, the inbound-email handlers, the seed re-export, the
22
+ * assistant config, identity, the message loader).
23
+ *
24
+ * Deleting the demo app therefore never breaks SSSB's own tenancy proof: `frameworkRlsProofs` names no
25
+ * app table, and an adopter with no tenant tables of its own registers an empty `appRlsProofs`.
26
+ */
27
+ export async function runRlsProofs(
28
+ db: Kysely<DB>,
29
+ expect: (actual: unknown) => ProofExpectation,
30
+ /**
31
+ * `appDb`: the connection that switches to `app_user` (see `RlsProofContext.appDb`). Omitted, it is
32
+ * `db`. The contract suite's non-superuser pass passes the database owner here, with a superuser as
33
+ * `db` for the seeding and the negative control.
34
+ */
35
+ { appDb = db }: { appDb?: Kysely<DB> } = {},
36
+ ): Promise<void> {
37
+ // The shared fixtures, seeded as the privileged migration user: two tenants to isolate against, and
38
+ // one organization inside each. Both halves need a valid org id on the right tenant AND one on the
39
+ // wrong tenant, so their cross-tenant WITH CHECK proofs fail on the tenant boundary rather than on a
40
+ // fabricated foreign key. Slugs carry a timestamp because a contract run may reuse a live database.
41
+ const stamp = Date.now()
42
+ const [alpha] = await db
43
+ .insertInto('tenants')
44
+ .values({ slug: `alpha-${stamp}`, name: 'Alpha Proof' })
45
+ .returning('id')
46
+ .execute()
47
+ const [demo] = await db
48
+ .insertInto('tenants')
49
+ .values({ slug: `demo-${stamp}`, name: 'Demo Proof' })
50
+ .returning('id')
51
+ .execute()
52
+ const [alphaOrg] = await db
53
+ .insertInto('organizations')
54
+ .values({ tenant_id: alpha!.id, slug: `alpha-org-${stamp}`, name: 'Alpha Proof Org' })
55
+ .returning('id')
56
+ .execute()
57
+ const [demoOrg] = await db
58
+ .insertInto('organizations')
59
+ .values({ tenant_id: demo!.id, slug: `demo-org-${stamp}`, name: 'Demo Proof Org' })
60
+ .returning('id')
61
+ .execute()
62
+
63
+ // The raw handle wearing the port's face, so both halves can drive REAL product code paths
64
+ // (`keysetPage`, which takes a DbPort and opens `withTenant` itself) rather than a re-implementation
65
+ // of them. Migration/ready are not this suite's business — it is handed an already-migrated engine.
66
+ const dbPort: DbPort = {
67
+ getDb: () => db,
68
+ withTenant: (tenantId, fn) => runWithTenant(appDb, tenantId, fn),
69
+ ready: () => Promise.resolve(),
70
+ migrateToLatest: () => Promise.resolve(),
71
+ }
72
+
73
+ const context = {
74
+ db,
75
+ appDb,
76
+ dbPort,
77
+ expect,
78
+ alphaTenantId: alpha!.id,
79
+ demoTenantId: demo!.id,
80
+ alphaOrgId: alphaOrg!.id,
81
+ demoOrgId: demoOrg!.id,
82
+ }
83
+
84
+ // Coverage BEFORE behaviour, and deliberately not part of either half: it asks whether every
85
+ // tenant_id table the registered migrations created is protected at all, which is a question
86
+ // neither half can answer about the other. Reading the catalog rather than a list is what makes
87
+ // an adopter's own new table covered without them registering anything — see ./rls-coverage.
88
+ await proveRlsCoverage(db, expect)
89
+
90
+ // Sequential, not concurrent: several proofs assert exact row COUNTS under RLS, so the two halves
91
+ // must not be interleaving inserts into the same tenants.
92
+ await frameworkRlsProofs(context)
93
+ await appRlsProofs(context)
94
+ }