@fabrika/check 0.9.0-dev.2 → 0.9.0-dev.21

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 (61) hide show
  1. package/package.json +7 -7
  2. package/src/ast.ts +69 -6
  3. package/src/check.ts +148 -44
  4. package/src/cli.ts +34 -8
  5. package/src/contract.ts +42 -6
  6. package/src/dialect.ts +29 -0
  7. package/src/finding.ts +14 -7
  8. package/src/index.ts +4 -12
  9. package/src/inputs.ts +4 -2
  10. package/src/layout.ts +41 -12
  11. package/src/limits.ts +13 -3
  12. package/src/migration-base.ts +85 -0
  13. package/src/reader/schema.ts +42 -512
  14. package/src/reader/surface.ts +43 -5
  15. package/src/reader/value.ts +18 -6
  16. package/src/resolution.ts +2 -2
  17. package/src/rules/cloudflare.ts +59 -0
  18. package/src/rules/compile.ts +32 -0
  19. package/src/rules/framework.ts +2 -2
  20. package/src/rules/literal.ts +3 -1
  21. package/src/rules/migration-history.ts +70 -0
  22. package/src/rules/migrations.ts +248 -9
  23. package/src/rules/modules.ts +9 -3
  24. package/src/rules/platform-migrations.ts +100 -0
  25. package/src/rules/runtime.ts +45 -14
  26. package/src/rules/structure.ts +38 -18
  27. package/src/rules/tests.ts +9 -60
  28. package/src/rules/types.ts +17 -16
  29. package/src/source-maps.ts +2 -0
  30. package/src/trust.ts +8 -4
  31. package/types/src/ast.d.ts +6 -0
  32. package/types/src/check.d.ts +3 -0
  33. package/types/src/contract.d.ts +1 -0
  34. package/types/src/dialect.d.ts +8 -0
  35. package/types/src/finding.d.ts +6 -5
  36. package/types/src/index.d.ts +4 -3
  37. package/types/src/layout.d.ts +25 -10
  38. package/types/src/limits.d.ts +12 -2
  39. package/types/src/migration-base.d.ts +9 -0
  40. package/types/src/reader/schema.d.ts +5 -2
  41. package/types/src/reader/value.d.ts +2 -2
  42. package/types/src/rules/cloudflare.d.ts +9 -0
  43. package/types/src/rules/compile.d.ts +7 -0
  44. package/types/src/rules/framework.d.ts +1 -1
  45. package/types/src/rules/migration-history.d.ts +12 -0
  46. package/types/src/rules/migrations.d.ts +28 -0
  47. package/types/src/rules/platform-migrations.d.ts +15 -0
  48. package/types/src/rules/runtime.d.ts +7 -2
  49. package/types/src/rules/structure.d.ts +11 -4
  50. package/types/src/rules/tests.d.ts +6 -14
  51. package/types/src/rules/types.d.ts +2 -0
  52. package/src/endpoint-fixtures.ts +0 -221
  53. package/src/rules/crontab.ts +0 -147
  54. package/src/rules/isolation.ts +0 -79
  55. package/src/scaffold-sample.ts +0 -111
  56. package/src/scaffold.ts +0 -650
  57. package/types/src/endpoint-fixtures.d.ts +0 -36
  58. package/types/src/rules/crontab.d.ts +0 -15
  59. package/types/src/rules/isolation.d.ts +0 -18
  60. package/types/src/scaffold-sample.d.ts +0 -8
  61. package/types/src/scaffold.d.ts +0 -28
package/src/scaffold.ts DELETED
@@ -1,650 +0,0 @@
1
- // The tests `fabrika db test-scaffold` writes. Policy isolation tests, one file per table a store reaches, from the
2
- // table policies alone: they prove the data layer enforces each policy, on a layer of their own. Endpoint access tests,
3
- // one file per application, from the contract: they run the application's own `serve(…)` and handlers. The checker
4
- // regenerates both to find a missing, edited, stale or orphaned file. Browser-safe: no file API.
5
-
6
- import { GENERATED_INVITATION, GENERATED_LINK, GENERATED_MEMBER, GENERATED_ROW_PREFIX } from '@fabrika/app/contract'
7
- import {
8
- type ContractArtifact,
9
- endpointDirectory,
10
- endpointMembers,
11
- type EndpointRow,
12
- type SchemaShape,
13
- tableActions,
14
- type TablePolicyArtifact,
15
- } from '@fabrika/auth-core'
16
- import { tablePolicies } from '@fabrika/db/tables'
17
- import { ContractSourceError, readContractSource, readTablesDefinition } from './contract'
18
- import { type EndpointFixtures, isSampleObject, NO_FIXTURES, readEndpointFixtures } from './endpoint-fixtures'
19
- import type { Finding } from './finding'
20
- import { CONTRACT_FILE, ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR } from './layout'
21
-
22
- export { ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR } from './layout'
23
- import { generatedTestHeader } from './rules/tests'
24
- import { renderSample, type Sample, sample } from './scaffold-sample'
25
-
26
- export const policyTestPath = (table: string): string => `${POLICY_TESTS_DIR}${table}${POLICY_TEST_SUFFIX}`
27
-
28
- /** One generated test file: its full text, header included, and the name of every test case it registers. */
29
- export interface GeneratedTest {
30
- readonly text: string
31
- readonly cases: readonly string[]
32
- }
33
-
34
- type Policies = Readonly<Record<string, TablePolicyArtifact>>
35
-
36
- interface Case {
37
- readonly name: string
38
- readonly lines: readonly string[]
39
- }
40
-
41
- const testCase = (name: string, ...lines: readonly string[]): Case => ({ name, lines })
42
-
43
- const quote = (text: string): string => `'${text.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`
44
-
45
- const renderCase = (item: Case): string =>
46
- [`\t\ttest(${quote(item.name)}, async () => {`, ...item.lines.map((line) => `\t\t\t${line}`), '\t\t})'].join('\n')
47
-
48
- /** The dimension a caller's grants are scoped by: the container of a dimension table, or its own; a child's parent's. */
49
- const grantDimension = (policies: Policies, policy: TablePolicyArtifact): string | undefined => {
50
- const scope = policy.scope
51
- if (scope.mode === 'dimension') return scope.container?.dimension ?? scope.dimension
52
- if (scope.mode !== 'child') return undefined
53
- const parent = policies[scope.parent]?.scope
54
- return parent?.mode === 'dimension' ? (parent.container?.dimension ?? parent.dimension) : undefined
55
- }
56
-
57
- /**
58
- * The actions the generated cases probe: the first of each operation, whose kit endpoint holds it. A refusal case runs
59
- * only where the probed read action is not also an action of the operation it is refused.
60
- */
61
- interface ProbedActions {
62
- readonly read: string
63
- readonly insert: string | null
64
- readonly update: string | null
65
- readonly delete: string | null
66
- readonly updateRefusesRead: boolean
67
- readonly deleteRefusesRead: boolean
68
- readonly appRead?: readonly string[]
69
- readonly appCount?: readonly string[]
70
- }
71
-
72
- const probedActions = (actions: TablePolicyArtifact['actions']): ProbedActions => {
73
- const read = tableActions(actions.read)[0] ?? ''
74
- return {
75
- read,
76
- insert: tableActions(actions.insert)[0] ?? null,
77
- update: tableActions(actions.update)[0] ?? null,
78
- delete: tableActions(actions.delete)[0] ?? null,
79
- updateRefusesRead: !tableActions(actions.update).includes(read),
80
- deleteRefusesRead: !tableActions(actions.delete).includes(read),
81
- ...(actions.appRead === undefined ? {} : { appRead: actions.appRead }),
82
- ...(actions.appCount === undefined ? {} : { appCount: actions.appCount }),
83
- }
84
- }
85
-
86
- const isolationCases = (policy: TablePolicyArtifact, dimension: string): readonly Case[] => {
87
- const { scope } = policy
88
- const actions = probedActions(policy.actions)
89
- const child = scope.mode === 'child'
90
- const contained = scope.mode === 'child' || (scope.mode === 'dimension' && scope.container !== null)
91
- const other = `another ${dimension}`
92
- const writes = policy.update.length > 0 || policy.version !== null
93
- const cases: Case[] = [
94
- testCase('get answers its own row', "expect((await kit.get('own')).status).toBe(200)"),
95
- testCase(`get of a row in ${other} is 404`, "expect((await kit.get('other')).status).toBe(404)"),
96
- ]
97
- if (child) {
98
- cases.push(testCase(`get of a key in ${other} through its own parent is 404`, "expect((await kit.get('crossed')).status).toBe(404)"))
99
- cases.push(
100
- testCase('a list by its own parent reaches only its own row', "expect(await kit.listByParent('own')).toEqual({ status: 200, rows: ['own'] })"),
101
- )
102
- cases.push(testCase(`a list by a parent in ${other} is 404`, "expect((await kit.listByParent('other')).status).toBe(404)"))
103
- }
104
- cases.push(testCase('a list reaches only its own row', "expect(await kit.list()).toEqual({ status: 200, rows: ['own'] })"))
105
- cases.push(testCase('a count counts only its own row', "expect(await kit.count()).toEqual({ status: 200, count: '1' })"))
106
- if (actions.insert !== null) {
107
- if (contained) cases.push(testCase(`insert into its own ${dimension} succeeds`, "expect((await kit.insert('own')).status).toBe(200)"))
108
- cases.push(testCase(`insert into ${other} is 403`, "expect((await kit.insert('other')).status).toBe(403)"))
109
- }
110
- if (actions.update !== null) {
111
- if (writes) cases.push(testCase('update of its own row succeeds', "expect((await kit.update('own')).status).toBe(200)"))
112
- cases.push(testCase(`update of a row in ${other} is 404`, "expect((await kit.update('other')).status).toBe(404)"))
113
- if (child) {
114
- cases.push(testCase(`update of a key in ${other} through its own parent is 404`, "expect((await kit.update('crossed')).status).toBe(404)"))
115
- }
116
- if (actions.updateRefusesRead) {
117
- cases.push(testCase(`update refuses a Ref for ${actions.read}`, 'expect(await kit.updateWithRead()).toEqual({ status: 200, refused: true })'))
118
- }
119
- }
120
- if (actions.delete !== null) {
121
- cases.push(testCase('remove of its own row succeeds', "expect((await kit.remove('own')).status).toBe(200)"))
122
- cases.push(testCase(`remove of a row in ${other} is 404`, "expect((await kit.remove('other')).status).toBe(404)"))
123
- if (child) {
124
- cases.push(testCase(`remove of a key in ${other} through its own parent is 404`, "expect((await kit.remove('crossed')).status).toBe(404)"))
125
- }
126
- if (actions.deleteRefusesRead) {
127
- cases.push(testCase(`remove refuses a Ref for ${actions.read}`, 'expect(await kit.removeWithRead()).toEqual({ status: 200, refused: true })'))
128
- }
129
- }
130
- for (const action of actions.appRead ?? []) {
131
- cases.push(
132
- testCase(
133
- `an app endpoint of ${action} lists every row`,
134
- `expect(await kit.appList(${quote(action)})).toEqual({ status: 200, rows: ['own', 'other'] })`,
135
- ),
136
- testCase(
137
- `an app endpoint of ${action} reads the columns of its own action`,
138
- `expect(await kit.appColumns(${quote(action)})).toEqual({ status: 200, leaked: [], missing: [] })`,
139
- ),
140
- )
141
- }
142
- for (const action of actions.appCount ?? []) {
143
- cases.push(
144
- testCase(`an app endpoint of ${action} counts every row`, `expect(await kit.appCount(${quote(action)})).toEqual({ status: 200, counted: 2 })`),
145
- testCase(
146
- `an app endpoint of ${action} lists no row`,
147
- `expect(await kit.appListWithCount(${quote(action)})).toEqual({ status: 200, refused: true })`,
148
- ),
149
- testCase(
150
- `an app endpoint of ${action} groups no row`,
151
- `expect(await kit.appGroupWithCount(${quote(action)})).toEqual({ status: 200, refused: true })`,
152
- ),
153
- )
154
- }
155
- return cases
156
- }
157
-
158
- /**
159
- * An application table's cases: its rows lie in no scope, so the boundary is the grant. A holder of the table's actions
160
- * as global grants reaches each operation; a holder of the same actions in one scope only is refused by the proxy. Where
161
- * the vocabulary has a dimension, a scoped site of the read action reads every row, and one of another action none.
162
- */
163
- const appIsolationCases = (policy: TablePolicyArtifact, scopedSites: boolean): readonly Case[] => {
164
- const actions = probedActions(policy.actions)
165
- const writes = policy.update.length > 0 || policy.version !== null
166
- const pair = (operation: string, call: string, done: string): Case[] => [
167
- testCase(`${operation} by a global holder succeeds`, `expect(${call.replace('CALLER', "'global'")}).${done}`),
168
- testCase(`${operation} by a holder in one scope only is 403`, `expect((${call.replace('CALLER', "'scoped'")}).status).toBe(403)`),
169
- ]
170
- const cases: Case[] = [
171
- ...pair('get', 'await kit.get(CALLER)', 'toMatchObject({ status: 200 })'),
172
- ...pair('a list', 'await kit.list(CALLER)', "toEqual({ status: 200, rows: ['own'] })"),
173
- ]
174
- if (actions.insert !== null) cases.push(...pair('insert', 'await kit.insert(CALLER)', 'toEqual({ status: 200 })'))
175
- if (actions.update !== null) {
176
- if (writes) cases.push(...pair('update', 'await kit.update(CALLER)', 'toEqual({ status: 200 })'))
177
- if (actions.updateRefusesRead) {
178
- cases.push(
179
- testCase(`update refuses a capability of ${actions.read}`, 'expect(await kit.updateWithRead()).toEqual({ status: 200, refused: true })'),
180
- )
181
- }
182
- }
183
- if (actions.delete !== null) {
184
- cases.push(...pair('remove', 'await kit.remove(CALLER)', 'toEqual({ status: 200 })'))
185
- if (actions.deleteRefusesRead) {
186
- cases.push(
187
- testCase(`remove refuses a capability of ${actions.read}`, 'expect(await kit.removeWithRead()).toEqual({ status: 200, refused: true })'),
188
- )
189
- }
190
- }
191
- if (scopedSites) {
192
- cases.push(testCase(`a scoped site of ${actions.read} reads every row`, "expect(await kit.scopedList()).toEqual({ status: 200, rows: ['own'] })"))
193
- const reads = tableActions(policy.actions.read)
194
- const other = [actions.insert, actions.update, actions.delete].find((action) => action !== null && !reads.includes(action))
195
- if (other !== undefined) {
196
- cases.push(
197
- testCase(`a scoped site of ${other} reads no row`, 'expect(await kit.scopedListWithOther()).toEqual({ status: 200, refused: true })'),
198
- )
199
- }
200
- }
201
- return cases
202
- }
203
-
204
- const describeBlock = (title: string, cases: readonly Case[]): string =>
205
- [`\tdescribe(${quote(title)}, () => {`, cases.map(renderCase).join('\n\n'), '\t})'].join('\n')
206
-
207
- /** `table`'s policy isolation test (everything after the header), or `undefined` for a table no store reaches. */
208
- const policyTestBody = (
209
- policies: Policies,
210
- table: string,
211
- scopedSites: boolean,
212
- ): { readonly body: string; readonly cases: readonly string[] } | undefined => {
213
- const policy = policies[table]
214
- if (policy === undefined) return undefined
215
- const app = policy.scope.mode === 'app'
216
- const dimension = grantDimension(policies, policy)
217
- if (dimension === undefined && !app) return undefined
218
- const isolation = dimension === undefined ? appIsolationCases(policy, scopedSites) : isolationCases(policy, dimension)
219
- const own = app ? "'global'" : "'own'"
220
- // A column with only its own write action is read by the table's read action, so it is returned like any other.
221
- const hidden = Object.keys(policy.columns).filter((column) => policy.columns[column]?.read !== undefined).sort().map((column) =>
222
- testCase(`get leaves out ${column}, which has its own read action`, `expect((await kit.get(${own})).columns).not.toContain(${quote(column)})`)
223
- )
224
- const title = dimension === undefined
225
- ? `policy of ${table}: only a global holder of its actions reaches a row`
226
- : `policy of ${table}: a caller of one ${dimension} reaches no row of another`
227
- const kitOf = app ? 'appPolicyIsolationKit' : 'policyIsolationKit'
228
- const blocks = [describeBlock(title, isolation)]
229
- if (hidden.length > 0) blocks.push(describeBlock(`policy of ${table}: a column with its own read action is never returned`, hidden))
230
- const body = [
231
- `// The policy isolation tests of ${table}, written by fabrika db test-scaffold from src/db/tables.ts. They prove that`,
232
- "// the data layer enforces the policy, through a probe of their own: the application's handlers and stores do not run.",
233
- '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a policy change.',
234
- '',
235
- `import { ${['afterAll', 'describe', 'expect', kitOf, 'test'].sort().join(', ')} } from '@fabrika/app/testing/isolation'`,
236
- "import { testDatabase } from '@fabrika/db/testing'",
237
- "import { contract } from '../../../fabrika.contract'",
238
- "import { tables } from '../tables'",
239
- '',
240
- `const label = ${quote(`${table}${POLICY_TEST_SUFFIX}`)}`,
241
- "const postgres = await testDatabase({ migrations: new URL('../../../db/migrations/', import.meta.url), label })",
242
- '',
243
- 'if (postgres !== null) {',
244
- '\tafterAll(() => postgres.close())',
245
- `\tconst kit = ${kitOf}(contract, tables, ${quote(table)}, postgres)`,
246
- '',
247
- blocks.join('\n\n'),
248
- '}',
249
- '',
250
- ].join('\n')
251
- return { body, cases: [...isolation, ...hidden].map((item) => item.name) }
252
- }
253
-
254
- /** Whether an endpoint gets endpoint access cases: a procedure with an access form or several, for a person or a machine. */
255
- const isAccessTested = (row: EndpointRow): boolean => {
256
- if ((row.kind !== 'query' && row.kind !== 'mutation') || row.requirement === null || row.requirement.kind === 'member') return false
257
- return row.callers.some((caller) => caller === 'human' || caller === 'machine')
258
- }
259
-
260
- /** Whether an endpoint is a procedure of a link mount: its link holder reaches the object the key is bound to. */
261
- const isLinkProcedure = (row: EndpointRow): boolean =>
262
- (row.kind === 'query' || row.kind === 'mutation') && row.requirement?.kind === 'action' && row.callers.some((caller) => caller === 'link')
263
-
264
- /**
265
- * The input an endpoint's cases send: the author's fixture, else a sample of its schema; `undefined` when neither
266
- * exists. Each field its `members`, `invitations` or `links` name holds `GENERATED_MEMBER`, `GENERATED_INVITATION` or
267
- * `GENERATED_LINK`, which the kit replaces with a real member, an open invitation or a link it issued; each field its
268
- * `rows` name holds `GENERATED_ROW_PREFIX` and the table, which the kit replaces with the key of a row it seeded.
269
- */
270
- const inputOf = (row: EndpointRow, fixtures: EndpointFixtures): Readonly<Record<string, Sample>> | undefined => {
271
- const fixture = fixtures.inputs[row.id]
272
- const input = fixture ?? (row.input === null ? {} : sample(row.input))
273
- if (input === undefined || !isSampleObject(input)) return undefined
274
- const generated = (fields: readonly string[] | undefined, marker: string) => (fields ?? []).map((field) => [field, marker])
275
- return {
276
- ...input,
277
- ...Object.fromEntries([
278
- ...generated(fixtures.members[row.id], GENERATED_MEMBER),
279
- ...generated(fixtures.invitations[row.id], GENERATED_INVITATION),
280
- ...generated(fixtures.links[row.id], GENERATED_LINK),
281
- ...Object.entries(fixtures.rows[row.id] ?? {}).map(([field, table]) => [field, `${GENERATED_ROW_PREFIX}${table}`]),
282
- ]),
283
- }
284
- }
285
-
286
- /** Whether the endpoint's handler gets `ctx.links`: on or in a dimension a link mount's `issuedBy` names its action for. */
287
- const issuesLinks = (artifact: ContractArtifact, row: EndpointRow): boolean => {
288
- if (row.requirement?.kind !== 'action') return false
289
- const { action, access } = row.requirement
290
- return (access.form === 'on' || access.form === 'in')
291
- && Object.values(artifact.mounts).some((mount) => mount.kind === 'link' && mount.dimension === access.dimension && mount.issuedBy === action)
292
- }
293
-
294
- /** Whether `shape` admits a principal id: a string, optional or nullable. */
295
- const admitsString = (shape: SchemaShape | undefined): boolean =>
296
- shape?.type === 'string' || ((shape?.type === 'optional' || shape?.type === 'nullable') && admitsString(shape.inner))
297
-
298
- /**
299
- * Whether a row of `table` lies directly in an object of `dimension`, the only rows the kit seeds there: a dimension
300
- * table whose container is `dimension`, or a child table of the table that owns it. A row further down needs a
301
- * container between, which the kit does not seed.
302
- */
303
- const liesDirectlyIn = (policies: Policies, table: string, dimension: string): boolean => {
304
- const scope = policies[table]?.scope
305
- if (scope?.mode === 'dimension') return scope.container?.dimension === dimension
306
- const parent = scope?.mode === 'child' ? policies[scope.parent]?.scope : undefined
307
- return parent?.mode === 'dimension' && parent.dimension === dimension
308
- }
309
-
310
- /** The read action of the table that owns `dimension`, or `undefined` when no table owns it. */
311
- const ownerRead = (policies: Policies, dimension: string): string | undefined =>
312
- tableActions(
313
- Object.values(policies).find((policy) => policy.scope.mode === 'dimension' && policy.scope.dimension === dimension)?.actions.read ?? null,
314
- )[0]
315
-
316
- /**
317
- * What the `own` case's caller holds: the endpoint's action, plus what IAM requires of a link's issuer (the actions the
318
- * link grants) and of a member manager (an assigning role and the assigned role's actions).
319
- */
320
- const ownGrants = (row: EndpointRow, artifact: ContractArtifact, action: string, dimension: string): string => {
321
- const issues = artifact.declared?.[row.id]?.issues
322
- const granted = Object.entries(artifact.mounts).flatMap(([name, mount]) =>
323
- mount.kind === 'link' && mount.dimension === dimension && mount.issuedBy === action && (issues === undefined || issues === name)
324
- ? mount.grants
325
- : []
326
- )
327
- const held = [action, ...new Set(granted)].join(', ')
328
- return endpointMembers(artifact, row) === 'manage' ? `${held}, an assigning role and the assigned role's actions` : held
329
- }
330
-
331
- /**
332
- * One endpoint's cases: an object or a value of another scope is refused; no answer holds another scope's rows unless
333
- * the endpoint declares `unscoped` (it reaches across scopes by design); a write action reads its own target.
334
- */
335
- const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: Policies, fixtures: EndpointFixtures): readonly Case[] => {
336
- const linked = isLinkProcedure(row)
337
- if ((!isAccessTested(row) && !linked) || row.requirement === null || row.requirement.kind !== 'action') return []
338
- const { access, action } = row.requirement
339
- const input = inputOf(row, fixtures)
340
- if (input === undefined) return []
341
- const seed = fixtures.seeds[row.id]
342
- const args = `${quote(row.id)}, ${renderSample(input)}`
343
- const seeded = seed === undefined ? args : `${args}, ${renderSample(seed)}`
344
- const declared = artifact.declared?.[row.id]
345
- const unscoped = declared !== undefined && Object.keys(declared.unscoped).length > 0
346
- const read = access.form === 'on' ? ownerRead(policies, access.dimension) : undefined
347
- const own = read !== undefined && (linked || read !== action)
348
- const cases: Case[] = []
349
- // The unseeded probe always runs: a seed meets a precondition, and must not also set aside the state that leaks.
350
- const leaked = (): Case[] => [
351
- testCase(
352
- `${row.id}: the answer to one scope holds nothing of the scope answered before it`,
353
- `expect(await kit.leaked(${args})).toEqual({ answered: true, leaked: [] })`,
354
- ),
355
- ...(seed === undefined ? [] : [
356
- testCase(
357
- `${row.id}: with its seed, the answer to one scope holds nothing of the scope answered before it`,
358
- `expect(await kit.leaked(${seeded})).toEqual({ answered: true, leaked: [] })`,
359
- ),
360
- ]),
361
- ]
362
- if (access.form === 'creates') {
363
- return [
364
- testCase(
365
- `${row.id}: a caller with ${action} in one ${access.dimension} only creates none (403)`,
366
- `expect(await kit.scoped(${args})).toEqual({ status: 403 })`,
367
- ),
368
- testCase(
369
- `${row.id}: a caller with ${action} held globally creates one`,
370
- `expect(await kit.global(${args})).toEqual({ answered: true })`,
371
- ),
372
- ]
373
- }
374
- if (access.form === 'app') {
375
- return [
376
- testCase(`${row.id}: a caller with ${action} in one scope only is 403`, `expect(await kit.scoped(${args})).toEqual({ status: 403 })`),
377
- testCase(`${row.id}: a caller with ${action} held globally reaches it`, `expect(await kit.global(${args})).toEqual({ answered: true })`),
378
- ]
379
- }
380
- if (linked) {
381
- if (own) {
382
- cases.push(
383
- testCase(`${row.id}: the holder of a link to a ${access.dimension} reaches it`, `expect(await kit.own(${seeded})).toEqual({ status: 200 })`),
384
- )
385
- }
386
- return cases
387
- }
388
- if (access.form === 'on') {
389
- cases.push(testCase(`${row.id}: the ${access.dimension} of another scope is 404`, `expect(await kit.denied(${args})).toEqual({ status: 404 })`))
390
- if (!unscoped) cases.push(...leaked())
391
- if (own) {
392
- cases.push(
393
- testCase(
394
- `${row.id}: a caller with only ${ownGrants(row, artifact, action, access.dimension)} reaches its own ${access.dimension}`,
395
- `expect(await kit.own(${seeded})).toEqual({ status: 200 })`,
396
- ),
397
- )
398
- }
399
- }
400
- if (access.form === 'in') {
401
- cases.push(testCase(`${row.id}: the ${access.dimension} of another scope is 403`, `expect(await kit.denied(${args})).toEqual({ status: 403 })`))
402
- if (declared !== undefined && declared.sql !== null && !unscoped) cases.push(...leaked())
403
- }
404
- if (access.form === 'over' && !unscoped) cases.push(...leaked())
405
- return cases
406
- }
407
-
408
- /**
409
- * An endpoint of several capabilities: one denied case per capability, each refused while every other one passes. An
410
- * object of another scope is 404 (`on`), a value of another scope 403 (`in`), and a caller without the action 403 (`over`).
411
- */
412
- const capabilityCases = (row: EndpointRow, fixtures: EndpointFixtures): readonly Case[] => {
413
- if (row.requirement?.kind !== 'capabilities' || !row.callers.some((caller) => caller === 'human' || caller === 'machine')) return []
414
- const input = inputOf(row, fixtures)
415
- if (input === undefined) return []
416
- const seed = fixtures.seeds[row.id]
417
- return Object.entries(row.requirement.capabilities).map(([name, { action, access }]) => {
418
- const args = `${quote(row.id)}, ${quote(name)}, ${renderSample(input)}${seed === undefined ? '' : `, ${renderSample(seed)}`}`
419
- const call = `await kit.capability(${args})`
420
- if (access.form === 'over') {
421
- return testCase(`${row.id}: a caller without ${action} (capability ${name}) is 403`, `expect(${call}).toEqual({ status: 403 })`)
422
- }
423
- const status = access.form === 'on' ? 404 : 403
424
- return testCase(
425
- `${row.id}: the ${access.dimension} of another scope as capability ${name} is ${status}`,
426
- `expect(${call}).toEqual({ status: ${status} })`,
427
- )
428
- })
429
- }
430
-
431
- /**
432
- * A public procedure's case: anyone reaches it with no credential, or, behind a challenge, is refused without a solved
433
- * one. Its name carries the workload's actions, so a change of them makes the committed test stale.
434
- */
435
- const publicCases = (row: EndpointRow, artifact: ContractArtifact, fixtures: EndpointFixtures): readonly Case[] => {
436
- // A `challenge` row is the framework's own issuer of a procedure's ALTCHA challenge: it runs no handler to test.
437
- if (row.kind !== 'public' || row.source.kind !== 'mount') return []
438
- const input = inputOf(row, fixtures)
439
- if (input === undefined) return []
440
- const call = `await kit.anyone(${quote(row.id)}, ${renderSample(input)})`
441
- const actions = artifact.declared?.[row.id]?.actions ?? []
442
- if (artifact.procedures?.[row.id]?.challenge != null) {
443
- return [testCase(`${row.id}: anyone without a solved challenge is 400`, `expect(${call}).toEqual({ answered: false, status: 400 })`)]
444
- }
445
- return [
446
- testCase(`${row.id}: anyone reaches it with no credential, running with ${actions.join(', ')}`, `expect(${call}).toEqual({ answered: true })`),
447
- ]
448
- }
449
-
450
- /** The endpoint access test of the application, or `undefined` when no endpoint has an access form to test. */
451
- const endpointTestBody = (
452
- artifact: ContractArtifact,
453
- policies: Policies,
454
- fixtures: EndpointFixtures,
455
- ): { readonly body: string; readonly cases: readonly string[] } | undefined => {
456
- const cases = [...artifact.endpoints].sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).flatMap((
457
- row,
458
- ) => [
459
- ...endpointCases(row, artifact, policies, fixtures),
460
- ...capabilityCases(row, fixtures),
461
- ...publicCases(row, artifact, fixtures),
462
- ])
463
- if (cases.length === 0) return undefined
464
- const body = [
465
- '// The endpoint access tests of this application, written by fabrika db test-scaffold from fabrika.contract.ts and',
466
- '// src/db/tables.ts. They run src/app.ts itself: callers of two scopes that share no value ask every endpoint with an',
467
- "// access form, and a caller with only the endpoint's action, plus what IAM requires of a member manager or a link's",
468
- '// issuer, asks for its own object. A handler bug that needs other data or another order is beyond them; the state a',
469
- '// precondition needs is a seed in endpoint-access.fixtures.ts.',
470
- '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a contract change.',
471
- '',
472
- "import { afterAll, describe, endpointAccessKit, expect, test } from '@fabrika/app/testing/isolation'",
473
- "import { testDatabase } from '@fabrika/db/testing'",
474
- "import app from '../app'",
475
- "import { tables } from '../db/tables'",
476
- '',
477
- "const label = 'endpoint-access.test.ts'",
478
- "const postgres = await testDatabase({ migrations: new URL('../../db/migrations/', import.meta.url), label })",
479
- '',
480
- 'if (postgres !== null) {',
481
- '\tafterAll(() => postgres.close())',
482
- '\tconst kit = endpointAccessKit(app, tables, postgres)',
483
- '',
484
- describeBlock('endpoints: a caller of one scope reaches nothing of another', cases),
485
- '}',
486
- '',
487
- ].join('\n')
488
- return { body, cases: cases.map((item) => item.name) }
489
- }
490
-
491
- const generated = async ({ body, cases }: { readonly body: string; readonly cases: readonly string[] }): Promise<GeneratedTest> => ({
492
- text: `${await generatedTestHeader(body)}\n${body}`,
493
- cases,
494
- })
495
-
496
- /**
497
- * Every test the scaffold writes for these policies and, when the application has a contract, its artifact; by path.
498
- * Endpoint access tests exist only for an application on `@fabrika/db`, which has policies to seed rows from.
499
- */
500
- export const generatedTests = async (
501
- policies: Policies,
502
- artifact: ContractArtifact | null,
503
- fixtures: EndpointFixtures = NO_FIXTURES,
504
- ): Promise<ReadonlyMap<string, GeneratedTest>> => {
505
- const files = new Map<string, GeneratedTest>()
506
- // The kit's scoped sites are `over` the vocabulary's first dimension: without one, no scoped site exists.
507
- const scopedSites = artifact !== null && Object.keys(artifact.dimensions).length > 0
508
- for (const table of Object.keys(policies).sort()) {
509
- const test = policyTestBody(policies, table, scopedSites)
510
- if (test !== undefined) files.set(policyTestPath(table), await generated(test))
511
- }
512
- const endpoints = artifact === null || files.size === 0 ? undefined : endpointTestBody(artifact, policies, fixtures)
513
- if (endpoints !== undefined) files.set(ENDPOINT_ACCESS_TEST, await generated(endpoints))
514
- return files
515
- }
516
-
517
- export interface ScaffoldInputs {
518
- readonly policies: Policies
519
- readonly artifact: ContractArtifact | null
520
- readonly fixtures: EndpointFixtures
521
- }
522
-
523
- /** What the scaffold reads from an application's files; throws `ContractSourceError` or `ContractError` as the reader does. */
524
- export const scaffoldInputs = (files: ReadonlyMap<string, string>): ScaffoldInputs => {
525
- const tables = readTablesDefinition(files)
526
- const policies = tables === null ? {} : tablePolicies(tables)
527
- const fixtures = readEndpointFixtures(files)
528
- if (!fixtures.ok) throw new ContractSourceError(fixtures.findings)
529
- // Endpoint tests seed rows from the policies, so without src/db/tables.ts there is nothing to compile them against.
530
- const artifact = files.has(CONTRACT_FILE) && tables !== null ? readContractSource(files, tables) : null
531
- return { policies, artifact, fixtures: fixtures.fixtures }
532
- }
533
-
534
- /**
535
- * What stops the endpoint access tests from covering every endpoint: one whose input the scaffold cannot sample and
536
- * the author gave no fixture, and a fixture of no tested endpoint. Each is an `endpoint-fixture` finding.
537
- */
538
- export const missingEndpointFixtures = ({ policies, artifact, fixtures }: ScaffoldInputs): readonly Finding[] => {
539
- if (artifact === null || Object.keys(policies).length === 0) return []
540
- const at = (message: string, allowed: string): Finding => ({
541
- file: ENDPOINT_FIXTURES_FILE,
542
- line: 1,
543
- column: 1,
544
- severity: 'refusal',
545
- rule: 'endpoint-fixture',
546
- message,
547
- allowed,
548
- })
549
- const tested = artifact.endpoints.filter((row) => isAccessTested(row) || isLinkProcedure(row))
550
- const findings = tested.filter((row) => inputOf(row, fixtures) === undefined).map((row) =>
551
- at(
552
- `${row.id}: the scaffold cannot write an input its schema admits, so its endpoint access cases need one here`,
553
- `export const fixtures = { '${row.id}': { … } }, an input the endpoint's schema admits`,
554
- )
555
- )
556
- for (const id of Object.keys(fixtures.inputs).sort()) {
557
- if (!tested.some((row) => row.id === id)) {
558
- findings.push(
559
- at(`${id} is no endpoint with an on, in, over, app or creates access form, or several capabilities`, 'a fixture of a tested endpoint, or none'),
560
- )
561
- }
562
- }
563
- for (const [id, fields] of Object.entries(fixtures.members).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
564
- const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate))
565
- const directory = row === undefined ? null : endpointDirectory(artifact, row)
566
- if (row === undefined || directory === null) {
567
- findings.push(
568
- at(
569
- `${id} is no tested endpoint below a dimension with members, whose handler could look one up`,
570
- "export const members = { '<endpoint id>': ['<input field>'] }, for an endpoint on or in a dimension with members or below one",
571
- ),
572
- )
573
- continue
574
- }
575
- const input = row.input
576
- for (const field of fields) {
577
- if (input?.type !== 'object' || !admitsString(input.fields[field])) {
578
- findings.push(at(`${id}: ${field} is no string field of its input, so it cannot name a member`, 'a top-level string field of the input'))
579
- }
580
- }
581
- }
582
- const sortedById = (fields: Readonly<Record<string, readonly string[]>>) =>
583
- Object.entries(fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
584
- const holders = [
585
- {
586
- fields: fixtures.invitations,
587
- names: 'an invitation',
588
- admits: (row: EndpointRow) => endpointMembers(artifact, row) === 'manage',
589
- refusal: (id: string) => `${id} is no tested endpoint that manages a dimension's members, whose handler could cancel an invitation`,
590
- allowed: "export const invitations = { '<endpoint id>': ['<input field>'] }, for an endpoint with its dimension's members.manage",
591
- },
592
- {
593
- fields: fixtures.links,
594
- names: 'a share link',
595
- admits: (row: EndpointRow) => issuesLinks(artifact, row),
596
- refusal: (id: string) => `${id} is no tested endpoint that issues a share link, whose handler could revoke one`,
597
- allowed: "export const links = { '<endpoint id>': ['<input field>'] }, for an endpoint whose action a link mount's issuedBy names",
598
- },
599
- ]
600
- for (const holder of holders) {
601
- for (const [id, fields] of sortedById(holder.fields)) {
602
- const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate) && holder.admits(candidate))
603
- if (row === undefined) {
604
- findings.push(at(holder.refusal(id), holder.allowed))
605
- continue
606
- }
607
- for (const field of fields) {
608
- if (row.input?.type !== 'object' || !admitsString(row.input.fields[field])) {
609
- findings.push(at(`${id}: ${field} is no string field of its input, so it cannot name ${holder.names}`, 'a top-level string field of the input'))
610
- }
611
- }
612
- }
613
- }
614
- for (const [id, fields] of Object.entries(fixtures.rows).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
615
- const row = tested.find((candidate) => candidate.id === id)
616
- const access = row?.requirement?.kind === 'action' ? row.requirement.access : undefined
617
- const owned = access?.form === 'on' && ownerRead(policies, access.dimension) !== undefined
618
- if (row === undefined || access?.form !== 'on' || !owned) {
619
- findings.push(
620
- at(
621
- `${id} is no tested endpoint on an object a table owns, in which the kit could seed a row`,
622
- "export const rows = { '<endpoint id>': { <input field>: '<table>' } }, for an endpoint on a dimension a table owns",
623
- ),
624
- )
625
- continue
626
- }
627
- for (const [field, table] of Object.entries(fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
628
- if (row.input?.type !== 'object' || !admitsString(row.input.fields[field])) {
629
- findings.push(at(`${id}: ${field} is no string field of its input, so it cannot name a row`, 'a top-level string field of the input'))
630
- } else if (!liesDirectlyIn(policies, table, access.dimension)) {
631
- findings.push(
632
- at(
633
- `${id}: ${table} is no dimension or child table that lies directly in a ${access.dimension}, so the kit seeds none in the endpoint's object (it seeds no container between)`,
634
- `a child table of the table that owns ${access.dimension}, or a dimension table whose container is ${access.dimension}`,
635
- ),
636
- )
637
- }
638
- }
639
- }
640
- const seeded = (row: EndpointRow): boolean =>
641
- row.requirement?.kind === 'action' && (row.requirement.access.form === 'on' || row.requirement.access.form === 'in')
642
- for (const id of Object.keys(fixtures.seeds).sort()) {
643
- if (!tested.some((row) => row.id === id && seeded(row))) {
644
- findings.push(
645
- at(`${id} is no endpoint with an on or in access form, whose row a seed sets`, "export const seeds = { '<endpoint id>': { <column>: <value> } }"),
646
- )
647
- }
648
- }
649
- return findings
650
- }