@fabrika/check 0.9.0-dev.18 → 0.9.0-dev.19

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.
package/src/scaffold.ts DELETED
@@ -1,994 +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 {
7
- deniedCaseRuledOutBy,
8
- GENERATED_FILE_PREFIX,
9
- GENERATED_INVITATION,
10
- GENERATED_LINK,
11
- GENERATED_MEMBER,
12
- GENERATED_ROW_CAPABILITY,
13
- GENERATED_ROW_PREFIX,
14
- } from '@fabrika/app/contract'
15
- import {
16
- type AccessForm,
17
- type ContractArtifact,
18
- endpointDirectory,
19
- endpointMembers,
20
- type EndpointRow,
21
- type SchemaShape,
22
- tableActions,
23
- type TablePolicyArtifact,
24
- } from '@fabrika/auth-core'
25
- import { type ApplicationRowRefusal, applicationRowRefusalText, applicationRowsPlan, tablePolicies, type Tables } from '@fabrika/db/tables'
26
- import { ContractSourceError, readContractSource, readTablesDefinition } from './contract'
27
- import { type ApplicationDialect, applicationDialect } from './dialect'
28
- import { type EndpointFixtures, isFixtureFilePath, isSampleObject, NO_FIXTURES, readEndpointFixtures } from './endpoint-fixtures'
29
- import type { Finding } from './finding'
30
- import { CONTRACT_FILE, ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR } from './layout'
31
-
32
- export { ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR } from './layout'
33
- import { generatedTestHeader } from './rules/tests'
34
- import { renderSample, type Sample, sample } from './scaffold-sample'
35
-
36
- export const policyTestPath = (table: string): string => `${POLICY_TESTS_DIR}${table}${POLICY_TEST_SUFFIX}`
37
-
38
- /** One generated test file: its full text, header included, and the name of every test case it registers. */
39
- export interface GeneratedTest {
40
- readonly text: string
41
- readonly cases: readonly string[]
42
- /** What the test cannot check, one line each, which `fabrika db test-scaffold` prints: a ruled-out capability case. */
43
- readonly notes: readonly string[]
44
- }
45
-
46
- type Policies = Readonly<Record<string, TablePolicyArtifact>>
47
-
48
- /** The test database kit of each dialect, and the name a generated test gives the database it opens. */
49
- const TEST_KITS: Readonly<Record<ApplicationDialect, { readonly module: string; readonly name: string }>> = {
50
- postgres: { module: '@fabrika/db/testing', name: 'postgres' },
51
- sqlite: { module: '@fabrika/db/testing-sqlite', name: 'database' },
52
- }
53
-
54
- /** The lines of a generated test that open its database: the kit's import and the call, against `migrations`. */
55
- const testDatabaseLines = (
56
- dialect: ApplicationDialect,
57
- migrations: string,
58
- ): { readonly kit: string; readonly open: string; readonly name: string } => {
59
- const { module, name } = TEST_KITS[dialect]
60
- return {
61
- kit: `import { testDatabase } from '${module}'`,
62
- open: `const ${name} = await testDatabase({ migrations: new URL('${migrations}', import.meta.url), label })`,
63
- name,
64
- }
65
- }
66
-
67
- interface Case {
68
- readonly name: string
69
- readonly lines: readonly string[]
70
- /** A leak or an own case: it runs the handler for the caller's own scope, which application rows can serve. */
71
- readonly ownScope?: true
72
- }
73
-
74
- const testCase = (name: string, ...lines: readonly string[]): Case => ({ name, lines })
75
-
76
- /** A case that runs the handler for the caller's own scope: a leak or an own case. */
77
- const ownScopeCase = (name: string, line: string): Case => ({ name, lines: [line], ownScope: true })
78
-
79
- /** Orders entries by their key, as every fixture is reported and seeded. */
80
- const byKey = ([left]: readonly [string, unknown], [right]: readonly [string, unknown]): number => (left < right ? -1 : left > right ? 1 : 0)
81
-
82
- const quote = (text: string): string => `'${text.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`
83
-
84
- const renderCase = (item: Case): string =>
85
- [`\t\ttest(${quote(item.name)}, async () => {`, ...item.lines.map((line) => `\t\t\t${line}`), '\t\t})'].join('\n')
86
-
87
- /** The dimension a caller's grants are scoped by: the container of a dimension table, or its own; a child's parent's. */
88
- const grantDimension = (policies: Policies, policy: TablePolicyArtifact): string | undefined => {
89
- const scope = policy.scope
90
- if (scope.mode === 'dimension') return scope.container?.dimension ?? scope.dimension
91
- if (scope.mode !== 'child') return undefined
92
- const parent = policies[scope.parent]?.scope
93
- return parent?.mode === 'dimension' ? (parent.container?.dimension ?? parent.dimension) : undefined
94
- }
95
-
96
- /**
97
- * The actions the generated cases probe: the first of each operation, whose kit endpoint holds it. A refusal case runs
98
- * only where the probed read action is not also an action of the operation it is refused.
99
- */
100
- interface ProbedActions {
101
- readonly read: string
102
- readonly insert: string | null
103
- readonly update: string | null
104
- readonly delete: string | null
105
- readonly updateRefusesRead: boolean
106
- readonly deleteRefusesRead: boolean
107
- readonly appRead?: readonly string[]
108
- readonly appCount?: readonly string[]
109
- }
110
-
111
- const probedActions = (actions: TablePolicyArtifact['actions']): ProbedActions => {
112
- const read = tableActions(actions.read)[0] ?? ''
113
- return {
114
- read,
115
- insert: tableActions(actions.insert)[0] ?? null,
116
- update: tableActions(actions.update)[0] ?? null,
117
- delete: tableActions(actions.delete)[0] ?? null,
118
- updateRefusesRead: !tableActions(actions.update).includes(read),
119
- deleteRefusesRead: !tableActions(actions.delete).includes(read),
120
- ...(actions.appRead === undefined ? {} : { appRead: actions.appRead }),
121
- ...(actions.appCount === undefined ? {} : { appCount: actions.appCount }),
122
- }
123
- }
124
-
125
- const isolationCases = (policy: TablePolicyArtifact, dimension: string): readonly Case[] => {
126
- const { scope } = policy
127
- const actions = probedActions(policy.actions)
128
- const child = scope.mode === 'child'
129
- const contained = scope.mode === 'child' || (scope.mode === 'dimension' && scope.container !== null)
130
- const other = `another ${dimension}`
131
- const writes = policy.update.length > 0 || policy.version !== null
132
- const cases: Case[] = [
133
- testCase('get answers its own row', "expect((await kit.get('own')).status).toBe(200)"),
134
- testCase(`get of a row in ${other} is 404`, "expect((await kit.get('other')).status).toBe(404)"),
135
- ]
136
- if (child) {
137
- cases.push(testCase(`get of a key in ${other} through its own parent is 404`, "expect((await kit.get('crossed')).status).toBe(404)"))
138
- cases.push(
139
- testCase('a list by its own parent reaches only its own row', "expect(await kit.listByParent('own')).toEqual({ status: 200, rows: ['own'] })"),
140
- )
141
- cases.push(testCase(`a list by a parent in ${other} is 404`, "expect((await kit.listByParent('other')).status).toBe(404)"))
142
- }
143
- cases.push(testCase('a list reaches only its own row', "expect(await kit.list()).toEqual({ status: 200, rows: ['own'] })"))
144
- cases.push(testCase('a count counts only its own row', "expect(await kit.count()).toEqual({ status: 200, count: '1' })"))
145
- if (actions.insert !== null) {
146
- if (contained) cases.push(testCase(`insert into its own ${dimension} succeeds`, "expect((await kit.insert('own')).status).toBe(200)"))
147
- cases.push(testCase(`insert into ${other} is 403`, "expect((await kit.insert('other')).status).toBe(403)"))
148
- }
149
- if (actions.update !== null) {
150
- if (writes) cases.push(testCase('update of its own row succeeds', "expect((await kit.update('own')).status).toBe(200)"))
151
- cases.push(testCase(`update of a row in ${other} is 404`, "expect((await kit.update('other')).status).toBe(404)"))
152
- if (child) {
153
- cases.push(testCase(`update of a key in ${other} through its own parent is 404`, "expect((await kit.update('crossed')).status).toBe(404)"))
154
- }
155
- if (actions.updateRefusesRead) {
156
- cases.push(testCase(`update refuses a Ref for ${actions.read}`, 'expect(await kit.updateWithRead()).toEqual({ status: 200, refused: true })'))
157
- }
158
- }
159
- if (actions.delete !== null) {
160
- cases.push(testCase('remove of its own row succeeds', "expect((await kit.remove('own')).status).toBe(200)"))
161
- cases.push(testCase(`remove of a row in ${other} is 404`, "expect((await kit.remove('other')).status).toBe(404)"))
162
- if (child) {
163
- cases.push(testCase(`remove of a key in ${other} through its own parent is 404`, "expect((await kit.remove('crossed')).status).toBe(404)"))
164
- }
165
- if (actions.deleteRefusesRead) {
166
- cases.push(testCase(`remove refuses a Ref for ${actions.read}`, 'expect(await kit.removeWithRead()).toEqual({ status: 200, refused: true })'))
167
- }
168
- }
169
- for (const action of actions.appRead ?? []) {
170
- cases.push(
171
- testCase(
172
- `an app endpoint of ${action} lists every row`,
173
- `expect(await kit.appList(${quote(action)})).toEqual({ status: 200, rows: ['own', 'other'] })`,
174
- ),
175
- testCase(
176
- `an app endpoint of ${action} reads the columns of its own action`,
177
- `expect(await kit.appColumns(${quote(action)})).toEqual({ status: 200, leaked: [], missing: [] })`,
178
- ),
179
- )
180
- }
181
- for (const action of actions.appCount ?? []) {
182
- cases.push(
183
- testCase(`an app endpoint of ${action} counts every row`, `expect(await kit.appCount(${quote(action)})).toEqual({ status: 200, counted: 2 })`),
184
- testCase(
185
- `an app endpoint of ${action} lists no row`,
186
- `expect(await kit.appListWithCount(${quote(action)})).toEqual({ status: 200, refused: true })`,
187
- ),
188
- testCase(
189
- `an app endpoint of ${action} groups no row`,
190
- `expect(await kit.appGroupWithCount(${quote(action)})).toEqual({ status: 200, refused: true })`,
191
- ),
192
- )
193
- }
194
- return cases
195
- }
196
-
197
- /**
198
- * An application table's cases: its rows lie in no scope, so the boundary is the grant. A holder of the table's actions
199
- * as global grants reaches each operation; a holder of the same actions in one scope only is refused by the proxy. Where
200
- * the vocabulary has a dimension, a scoped site of the read action reads every row, and one of another action none.
201
- */
202
- const appIsolationCases = (policy: TablePolicyArtifact, scopedSites: boolean): readonly Case[] => {
203
- const actions = probedActions(policy.actions)
204
- const writes = policy.update.length > 0 || policy.version !== null
205
- const pair = (operation: string, call: string, done: string): Case[] => [
206
- testCase(`${operation} by a global holder succeeds`, `expect(${call.replace('CALLER', "'global'")}).${done}`),
207
- testCase(`${operation} by a holder in one scope only is 403`, `expect((${call.replace('CALLER', "'scoped'")}).status).toBe(403)`),
208
- ]
209
- const cases: Case[] = [
210
- ...pair('get', 'await kit.get(CALLER)', 'toMatchObject({ status: 200 })'),
211
- ...pair('a list', 'await kit.list(CALLER)', "toEqual({ status: 200, rows: ['own'] })"),
212
- ]
213
- if (actions.insert !== null) cases.push(...pair('insert', 'await kit.insert(CALLER)', 'toEqual({ status: 200 })'))
214
- if (actions.update !== null) {
215
- if (writes) cases.push(...pair('update', 'await kit.update(CALLER)', 'toEqual({ status: 200 })'))
216
- if (actions.updateRefusesRead) {
217
- cases.push(
218
- testCase(`update refuses a capability of ${actions.read}`, 'expect(await kit.updateWithRead()).toEqual({ status: 200, refused: true })'),
219
- )
220
- }
221
- }
222
- if (actions.delete !== null) {
223
- cases.push(...pair('remove', 'await kit.remove(CALLER)', 'toEqual({ status: 200 })'))
224
- if (actions.deleteRefusesRead) {
225
- cases.push(
226
- testCase(`remove refuses a capability of ${actions.read}`, 'expect(await kit.removeWithRead()).toEqual({ status: 200, refused: true })'),
227
- )
228
- }
229
- }
230
- if (scopedSites) {
231
- cases.push(testCase(`a scoped site of ${actions.read} reads every row`, "expect(await kit.scopedList()).toEqual({ status: 200, rows: ['own'] })"))
232
- const reads = tableActions(policy.actions.read)
233
- const other = [actions.insert, actions.update, actions.delete].find((action) => action !== null && !reads.includes(action))
234
- if (other !== undefined) {
235
- cases.push(
236
- testCase(`a scoped site of ${other} reads no row`, 'expect(await kit.scopedListWithOther()).toEqual({ status: 200, refused: true })'),
237
- )
238
- }
239
- }
240
- return cases
241
- }
242
-
243
- const describeBlock = (title: string, cases: readonly Case[]): string =>
244
- [`\tdescribe(${quote(title)}, () => {`, cases.map(renderCase).join('\n\n'), '\t})'].join('\n')
245
-
246
- /** `table`'s policy isolation test (everything after the header), or `undefined` for a table no store reaches. */
247
- const policyTestBody = (
248
- policies: Policies,
249
- table: string,
250
- scopedSites: boolean,
251
- dialect: ApplicationDialect,
252
- ): { readonly body: string; readonly cases: readonly string[] } | undefined => {
253
- const policy = policies[table]
254
- // A view's rows come from the tables it reads, so no probe seeds one; its parent's cases still run.
255
- if (policy === undefined || policy.view === true) return undefined
256
- const app = policy.scope.mode === 'app'
257
- const dimension = grantDimension(policies, policy)
258
- if (dimension === undefined && !app) return undefined
259
- const isolation = dimension === undefined ? appIsolationCases(policy, scopedSites) : isolationCases(policy, dimension)
260
- const own = app ? "'global'" : "'own'"
261
- // A column with only its own write action is read by the table's read action, so it is returned like any other.
262
- const hidden = Object.keys(policy.columns).filter((column) => policy.columns[column]?.read !== undefined).sort().map((column) =>
263
- testCase(`get leaves out ${column}, which has its own read action`, `expect((await kit.get(${own})).columns).not.toContain(${quote(column)})`)
264
- )
265
- const title = dimension === undefined
266
- ? `policy of ${table}: only a global holder of its actions reaches a row`
267
- : `policy of ${table}: a caller of one ${dimension} reaches no row of another`
268
- const kitOf = app ? 'appPolicyIsolationKit' : 'policyIsolationKit'
269
- const database = testDatabaseLines(dialect, '../../../db/migrations/')
270
- const blocks = [describeBlock(title, isolation)]
271
- if (hidden.length > 0) blocks.push(describeBlock(`policy of ${table}: a column with its own read action is never returned`, hidden))
272
- const body = [
273
- `// The policy isolation tests of ${table}, written by fabrika db test-scaffold from src/db/tables.ts. They prove that`,
274
- "// the data layer enforces the policy, through a probe of their own: the application's handlers and stores do not run.",
275
- '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a policy change.',
276
- '',
277
- `import { ${['afterAll', 'describe', 'expect', kitOf, 'test'].sort().join(', ')} } from '@fabrika/app/testing/isolation'`,
278
- database.kit,
279
- "import { contract } from '../../../fabrika.contract'",
280
- "import { tables } from '../tables'",
281
- '',
282
- `const label = ${quote(`${table}${POLICY_TEST_SUFFIX}`)}`,
283
- database.open,
284
- '',
285
- `if (${database.name} !== null) {`,
286
- `\tafterAll(() => ${database.name}.close())`,
287
- `\tconst kit = ${kitOf}(contract, tables, ${quote(table)}, ${database.name})`,
288
- '',
289
- blocks.join('\n\n'),
290
- '}',
291
- '',
292
- ].join('\n')
293
- return { body, cases: [...isolation, ...hidden].map((item) => item.name) }
294
- }
295
-
296
- /** Whether an endpoint gets endpoint access cases: a procedure with an access form or several, for a person or a machine. */
297
- const isAccessTested = (row: EndpointRow): boolean => {
298
- if ((row.kind !== 'query' && row.kind !== 'mutation') || row.requirement === null || row.requirement.kind === 'member') return false
299
- return row.callers.some((caller) => caller === 'human' || caller === 'machine')
300
- }
301
-
302
- /** Whether an endpoint is a procedure of a link mount: its link holder reaches the object the key is bound to. */
303
- const isLinkProcedure = (row: EndpointRow): boolean =>
304
- (row.kind === 'query' || row.kind === 'mutation') && row.requirement?.kind === 'action' && row.callers.some((caller) => caller === 'link')
305
-
306
- /**
307
- * The input an endpoint's cases send: the author's fixture, else a sample of its schema; `undefined` when neither
308
- * exists. Each field its `members`, `invitations` or `links` name holds `GENERATED_MEMBER`, `GENERATED_INVITATION` or
309
- * `GENERATED_LINK`, which the kit replaces with a real member, an open invitation or a link it issued; each field its
310
- * `rows` name holds `GENERATED_ROW_PREFIX` and the table (and, under `<endpoint id>#<capability>`, the capability), which
311
- * the kit replaces with the key of a row it seeded; each file
312
- * field its `files` name holds its kind's marker (in a list, for a list of files), even where the sample left an optional
313
- * one out, which the kit sends as the named file.
314
- */
315
- const inputOf = (row: EndpointRow, fixtures: EndpointFixtures): Readonly<Record<string, Sample>> | undefined => {
316
- const fixture = fixtures.inputs[row.id]
317
- const input = fixture ?? (row.input === null ? {} : sample(row.input))
318
- if (input === undefined || !isSampleObject(input)) return undefined
319
- const generated = (fields: readonly string[] | undefined, marker: string) => (fields ?? []).map((field) => [field, marker])
320
- return {
321
- ...input,
322
- ...Object.fromEntries([
323
- ...generated(fixtures.members[row.id], GENERATED_MEMBER),
324
- ...generated(fixtures.invitations[row.id], GENERATED_INVITATION),
325
- ...generated(fixtures.links[row.id], GENERATED_LINK),
326
- ...Object.entries(fixtures.rows[row.id] ?? {}).map(([field, table]) => [field, `${GENERATED_ROW_PREFIX}${table}`]),
327
- ...Object.keys(row.requirement?.kind === 'capabilities' ? row.requirement.capabilities : {}).flatMap((name) =>
328
- Object.entries(fixtures.rows[`${row.id}${CAPABILITY_KEY}${name}`] ?? {}).map((
329
- [field, table],
330
- ) => [field, `${GENERATED_ROW_PREFIX}${table}${GENERATED_ROW_CAPABILITY}${name}`])
331
- ),
332
- ...Object.keys(fixtures.files[row.id] ?? {}).flatMap((field) => {
333
- const file = fileFieldOf(row.input, field)
334
- if (file === undefined) return []
335
- const marker = `${GENERATED_FILE_PREFIX}${file.kind}`
336
- return [[field, file.list ? [marker] : marker]]
337
- }),
338
- ]),
339
- }
340
- }
341
-
342
- /** What separates an endpoint id from a capability's name in a `rows` key: `api.tasks.copy#from`. */
343
- const CAPABILITY_KEY = '#'
344
-
345
- /** The file kind of a top-level file field of `input` (a file, an optional or nullable one, or a list of them), or `undefined`. */
346
- const fileFieldOf = (input: SchemaShape | null, field: string): { readonly kind: string; readonly list: boolean } | undefined => {
347
- const kindOf = (shape: SchemaShape | undefined): string | undefined =>
348
- shape?.type === 'file' ? shape.kind : shape?.type === 'optional' || shape?.type === 'nullable' ? kindOf(shape.inner) : undefined
349
- const shape = input?.type === 'object' ? input.fields[field] : undefined
350
- const unwrapped = shape?.type === 'optional' || shape?.type === 'nullable' ? shape.inner : shape
351
- if (unwrapped?.type === 'array') {
352
- const kind = kindOf(unwrapped.items)
353
- return kind === undefined ? undefined : { kind, list: true }
354
- }
355
- const kind = kindOf(shape)
356
- return kind === undefined ? undefined : { kind, list: false }
357
- }
358
-
359
- /** The ids of the endpoints with endpoint access cases. */
360
- const testedEndpoints = (artifact: ContractArtifact): ReadonlySet<string> =>
361
- new Set(artifact.endpoints.filter((row) => isAccessTested(row) || isLinkProcedure(row)).map((row) => row.id))
362
-
363
- /** How a generated endpoint access test reaches the application's root, where a file fixture's path starts. */
364
- const ROOT_FROM_ENDPOINT_TEST = '../'.repeat(ENDPOINT_ACCESS_TEST.split('/').length - 1)
365
-
366
- /**
367
- * The options of the generated test's kit: the file fixtures of the tested endpoints, each a URL beside the test, their
368
- * refusals and pins, and the caller rows. Empty without any, so a test without them stays as it was.
369
- */
370
- const kitOptions = (fixtures: EndpointFixtures, tested: ReadonlySet<string>): string => {
371
- const files = Object.entries(fixtures.files).sort(byKey).flatMap(([id, fields]) => {
372
- const valid = Object.entries(fields).sort(byKey).filter(([, path]) => isFixtureFilePath(path))
373
- if (!tested.has(id) || valid.length === 0) return []
374
- const rendered = valid.map(([field, path]) => `${renderKey(field)}: new URL(${quote(`${ROOT_FROM_ENDPOINT_TEST}${path}`)}, import.meta.url)`)
375
- return [`${quote(id)}: { ${rendered.join(', ')} }`]
376
- })
377
- const refusals = Object.entries(fixtures.refusals).sort(byKey).flatMap(([id, types]) => {
378
- const valid = types.filter(isDeclarableRefusal)
379
- return tested.has(id) && valid.length > 0 ? [`${quote(id)}: [${valid.map(quote).join(', ')}]`] : []
380
- })
381
- const pins = Object.entries(fixtures.pins).sort(byKey).flatMap(([id, columns]) => {
382
- const entries = Object.entries(columns).sort(byKey)
383
- return tested.has(id) && entries.length > 0
384
- ? [`${quote(id)}: { ${entries.map(([column, value]) => `${renderKey(column)}: ${quote(value)}`).join(', ')} }`]
385
- : []
386
- })
387
- const options = [
388
- ...(files.length === 0 ? [] : [`files: { ${files.join(', ')} }`]),
389
- ...(refusals.length === 0 ? [] : [`refusals: { ${refusals.join(', ')} }`]),
390
- ...(pins.length === 0 ? [] : [`pins: { ${pins.join(', ')} }`]),
391
- ...(Object.keys(fixtures.callerRows).length === 0 ? [] : [`callerRows: ${renderSample(fixtures.callerRows)}`]),
392
- ]
393
- return options.length === 0 ? '' : `, { ${options.join(', ')} }`
394
- }
395
-
396
- /** A refusal the fixtures may declare: a handler's own error type, never the input schema's (`validation`). */
397
- const isDeclarableRefusal = (type: string): boolean => type !== '' && type !== 'validation'
398
-
399
- /**
400
- * The own case of an endpoint: 200, or, where its fixtures declare the refusals its handler may answer its own object
401
- * with, also the 400 the kit hands back only for one of them.
402
- */
403
- const ownCase = (row: EndpointRow, fixtures: EndpointFixtures, name: string, args: string): Case => {
404
- const declared = (fixtures.refusals[row.id] ?? []).filter(isDeclarableRefusal)
405
- return declared.length === 0
406
- ? ownScopeCase(name, `expect(await kit.own(${args})).toEqual({ status: 200 })`)
407
- : ownScopeCase(`${name} (200, or a refusal its fixtures declare)`, `expect([200, 400]).toContain((await kit.own(${args})).status)`)
408
- }
409
-
410
- /** An object key as `renderSample` writes one: bare when it is an identifier, else quoted. */
411
- const renderKey = (key: string): string => (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : quote(key))
412
-
413
- /** Whether the endpoint's handler gets `ctx.links`: on or in a dimension a link mount's `issuedBy` names its action for. */
414
- const issuesLinks = (artifact: ContractArtifact, row: EndpointRow): boolean => {
415
- if (row.requirement?.kind !== 'action') return false
416
- const { action, access } = row.requirement
417
- return (access.form === 'on' || access.form === 'in')
418
- && Object.values(artifact.mounts).some((mount) => mount.kind === 'link' && mount.dimension === access.dimension && mount.issuedBy === action)
419
- }
420
-
421
- /** Whether `shape` admits a principal id: a string, optional or nullable. */
422
- const admitsString = (shape: SchemaShape | undefined): boolean =>
423
- shape?.type === 'string' || ((shape?.type === 'optional' || shape?.type === 'nullable') && admitsString(shape.inner))
424
-
425
- /**
426
- * Whether a row of `table` lies directly in an object of `dimension`, the only rows the kit seeds there: a dimension
427
- * table whose container is `dimension`, or a child table of the table that owns it. A row further down needs a
428
- * container between, which the kit does not seed.
429
- */
430
- const liesDirectlyIn = (policies: Policies, table: string, dimension: string): boolean => {
431
- const scope = policies[table]?.scope
432
- if (scope?.mode === 'dimension') return scope.container?.dimension === dimension
433
- const parent = scope?.mode === 'child' ? policies[scope.parent]?.scope : undefined
434
- return parent?.mode === 'dimension' && parent.dimension === dimension
435
- }
436
-
437
- /**
438
- * Whether a list of `dimension` (`over`) reaches the rows of `table`: a dimension table it contains or of its own when it
439
- * has no container, or a child of one.
440
- */
441
- const listedBy = (policies: Policies, table: string, dimension: string): boolean => {
442
- const listedIn = (scope: Policies[string]['scope'] | undefined): string | undefined =>
443
- scope?.mode === 'dimension' ? (scope.container?.dimension ?? scope.dimension) : undefined
444
- const scope = policies[table]?.scope
445
- return (scope?.mode === 'child' ? listedIn(policies[scope.parent]?.scope) : listedIn(scope)) === dimension
446
- }
447
-
448
- /**
449
- * Whether the kit seeds a row of `table` for an endpoint of `access`: in its object (`on`, `in` an object a table owns,
450
- * the table lying directly in it) or in the scopes it lists (`over`).
451
- */
452
- const rowPlace = (policies: Policies, access: ScopedAccess, table: string): boolean =>
453
- access.form === 'over'
454
- ? listedBy(policies, table, access.dimension)
455
- : ownerRead(policies, access.dimension) !== undefined && liesDirectlyIn(policies, table, access.dimension)
456
-
457
- /** An access form that names a scope: an object (`on`), a value (`in`) or a list (`over`). */
458
- type ScopedAccess = Extract<AccessForm, { readonly form: 'on' | 'in' | 'over' }>
459
-
460
- /** The read action of the table that owns `dimension`, or `undefined` when no table owns it. */
461
- const ownerRead = (policies: Policies, dimension: string): string | undefined =>
462
- tableActions(
463
- Object.values(policies).find((policy) => policy.scope.mode === 'dimension' && policy.scope.dimension === dimension)?.actions.read ?? null,
464
- )[0]
465
-
466
- /**
467
- * Whether an endpoint gets the `own` case: `on` an object a table owns, as a link procedure or with an action other
468
- * than the owner's read action (a caller holding only that one reaches every object, which proves nothing).
469
- */
470
- const hasOwnCase = (row: EndpointRow, policies: Policies): boolean => {
471
- if (row.requirement?.kind !== 'action') return false
472
- const { access, action } = row.requirement
473
- const read = access.form === 'on' ? ownerRead(policies, access.dimension) : undefined
474
- return read !== undefined && (isLinkProcedure(row) || read !== action)
475
- }
476
-
477
- /**
478
- * What the `own` case's caller holds: the endpoint's action, plus what IAM requires of a link's issuer (the actions the
479
- * link grants) and of a member manager (an assigning role and the assigned role's actions).
480
- */
481
- const ownGrants = (row: EndpointRow, artifact: ContractArtifact, action: string, dimension: string): string => {
482
- const issues = artifact.declared?.[row.id]?.issues
483
- const granted = Object.entries(artifact.mounts).flatMap(([name, mount]) =>
484
- mount.kind === 'link' && mount.dimension === dimension && mount.issuedBy === action && (issues === undefined || issues === name)
485
- ? mount.grants
486
- : []
487
- )
488
- const held = [action, ...new Set(granted)].join(', ')
489
- return endpointMembers(artifact, row) === 'manage' ? `${held}, an assigning role and the assigned role's actions` : held
490
- }
491
-
492
- /**
493
- * One endpoint's cases: an object or a value of another scope is refused; no answer holds another scope's rows unless
494
- * the endpoint declares `unscoped` (it reaches across scopes by design); a write action reads its own target.
495
- */
496
- const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: Policies, fixtures: EndpointFixtures): readonly Case[] => {
497
- const linked = isLinkProcedure(row)
498
- if ((!isAccessTested(row) && !linked) || row.requirement === null || row.requirement.kind !== 'action') return []
499
- const { access, action } = row.requirement
500
- const input = inputOf(row, fixtures)
501
- if (input === undefined) return []
502
- const seed = fixtures.seeds[row.id]
503
- const args = `${quote(row.id)}, ${renderSample(input)}`
504
- const seeded = seed === undefined ? args : `${args}, ${renderSample(seed)}`
505
- // The application rows reach every case that runs the handler on the caller's own object: its leak cases and its own
506
- // case. Only an endpoint with them gets the fourth argument, so every other generated file stays as it was.
507
- const appRows = fixtures.appRows[row.id]
508
- const rowsTail = appRows === undefined ? '' : `, ${renderSample(appRows)}`
509
- const unseededArgs = appRows === undefined ? args : `${args}, {}${rowsTail}`
510
- const seededArgs = seed === undefined ? unseededArgs : `${seeded}${rowsTail}`
511
- const declared = artifact.declared?.[row.id]
512
- const unscoped = declared !== undefined && Object.keys(declared.unscoped).length > 0
513
- const own = hasOwnCase(row, policies)
514
- const cases: Case[] = []
515
- // The unseeded probe always runs: a seed meets a precondition, and must not also set aside the state that leaks. The
516
- // application rows reach it too: they are rows of the whole application, which the handler needs to answer at all.
517
- const leaked = (): Case[] => [
518
- ownScopeCase(
519
- `${row.id}: the answer to one scope holds nothing of the scope answered before it`,
520
- `expect(await kit.leaked(${unseededArgs})).toEqual({ answered: true, leaked: [] })`,
521
- ),
522
- ...(seed === undefined ? [] : [
523
- ownScopeCase(
524
- `${row.id}: with its seed, the answer to one scope holds nothing of the scope answered before it`,
525
- `expect(await kit.leaked(${seededArgs})).toEqual({ answered: true, leaked: [] })`,
526
- ),
527
- ]),
528
- ]
529
- if (access.form === 'creates') {
530
- return [
531
- testCase(
532
- `${row.id}: a caller with ${action} in one ${access.dimension} only creates none (403)`,
533
- `expect(await kit.scoped(${args})).toEqual({ status: 403 })`,
534
- ),
535
- testCase(
536
- `${row.id}: a caller with ${action} held globally creates one`,
537
- `expect(await kit.global(${args})).toEqual({ answered: true })`,
538
- ),
539
- ]
540
- }
541
- if (access.form === 'app') {
542
- return [
543
- testCase(`${row.id}: a caller with ${action} in one scope only is 403`, `expect(await kit.scoped(${args})).toEqual({ status: 403 })`),
544
- testCase(`${row.id}: a caller with ${action} held globally reaches it`, `expect(await kit.global(${args})).toEqual({ answered: true })`),
545
- ]
546
- }
547
- if (linked) {
548
- if (own) {
549
- cases.push(ownCase(row, fixtures, `${row.id}: the holder of a link to a ${access.dimension} reaches it`, seededArgs))
550
- }
551
- return cases
552
- }
553
- if (access.form === 'on') {
554
- cases.push(testCase(`${row.id}: the ${access.dimension} of another scope is 404`, `expect(await kit.denied(${args})).toEqual({ status: 404 })`))
555
- if (!unscoped) cases.push(...leaked())
556
- if (own) {
557
- cases.push(
558
- ownCase(
559
- row,
560
- fixtures,
561
- `${row.id}: a caller with only ${ownGrants(row, artifact, action, access.dimension)} reaches its own ${access.dimension}`,
562
- seededArgs,
563
- ),
564
- )
565
- }
566
- }
567
- if (access.form === 'in') {
568
- cases.push(testCase(`${row.id}: the ${access.dimension} of another scope is 403`, `expect(await kit.denied(${args})).toEqual({ status: 403 })`))
569
- if (declared !== undefined && declared.sql !== null && !unscoped) cases.push(...leaked())
570
- }
571
- if (access.form === 'over' && !unscoped) cases.push(...leaked())
572
- return cases
573
- }
574
-
575
- /**
576
- * An endpoint of several capabilities: one denied case per capability, each refused while every other one passes. An
577
- * object of another scope is 404 (`on`), a value of another scope 403 (`in`), and a caller without the action 403
578
- * (`over`). An `over` capability whose action another one needs in a related dimension has none (`deniedCaseRuledOutBy`);
579
- * `notes` says so for each, in the generated test and in `fabrika db test-scaffold`'s output.
580
- */
581
- const capabilityCases = (
582
- row: EndpointRow,
583
- artifact: ContractArtifact,
584
- fixtures: EndpointFixtures,
585
- ): { readonly cases: readonly Case[]; readonly notes: readonly string[] } => {
586
- if (row.requirement?.kind !== 'capabilities' || !row.callers.some((caller) => caller === 'human' || caller === 'machine')) {
587
- return { cases: [], notes: [] }
588
- }
589
- const input = inputOf(row, fixtures)
590
- if (input === undefined) return { cases: [], notes: [] }
591
- const seed = fixtures.seeds[row.id]
592
- const { capabilities } = row.requirement
593
- const cases: Case[] = []
594
- const notes: string[] = []
595
- for (const [name, { action, access }] of Object.entries(capabilities)) {
596
- const args = `${quote(row.id)}, ${quote(name)}, ${renderSample(input)}${seed === undefined ? '' : `, ${renderSample(seed)}`}`
597
- const call = `await kit.capability(${args})`
598
- if (access.form === 'over') {
599
- const ruledOutBy = deniedCaseRuledOutBy(capabilities, name, artifact.dimensions)
600
- if (ruledOutBy === undefined) {
601
- cases.push(testCase(`${row.id}: a caller without ${action} (capability ${name}) is 403`, `expect(${call}).toEqual({ status: 403 })`))
602
- } else {
603
- notes.push(
604
- `${row.id}: capability ${name} has no denied case: ${ruledOutBy} needs ${action} in a related dimension, so every caller that passes it is answered the list`,
605
- )
606
- }
607
- continue
608
- }
609
- const status = access.form === 'on' ? 404 : 403
610
- cases.push(
611
- testCase(
612
- `${row.id}: the ${access.dimension} of another scope as capability ${name} is ${status}`,
613
- `expect(${call}).toEqual({ status: ${status} })`,
614
- ),
615
- )
616
- }
617
- return { cases, notes }
618
- }
619
-
620
- /**
621
- * A public procedure's case: anyone reaches it with no credential, or, behind a challenge, is refused without a solved
622
- * one. Its name carries the workload's actions, so a change of them makes the committed test stale.
623
- */
624
- const publicCases = (row: EndpointRow, artifact: ContractArtifact, fixtures: EndpointFixtures): readonly Case[] => {
625
- // A `challenge` row is the framework's own issuer of a procedure's ALTCHA challenge: it runs no handler to test.
626
- if (row.kind !== 'public' || row.source.kind !== 'mount') return []
627
- const input = inputOf(row, fixtures)
628
- if (input === undefined) return []
629
- const call = `await kit.anyone(${quote(row.id)}, ${renderSample(input)})`
630
- const actions = artifact.declared?.[row.id]?.actions ?? []
631
- if (artifact.procedures?.[row.id]?.challenge != null) {
632
- return [testCase(`${row.id}: anyone without a solved challenge is 400`, `expect(${call}).toEqual({ answered: false, status: 400 })`)]
633
- }
634
- return [
635
- testCase(`${row.id}: anyone reaches it with no credential, running with ${actions.join(', ')}`, `expect(${call}).toEqual({ answered: true })`),
636
- ]
637
- }
638
-
639
- /** The endpoints of the artifact by id, the order of their cases. */
640
- const sortedEndpoints = (artifact: ContractArtifact): readonly EndpointRow[] =>
641
- [...artifact.endpoints].sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))
642
-
643
- /** The endpoint access test of the application, or `undefined` when no endpoint has an access form to test. */
644
- const endpointTestBody = (
645
- artifact: ContractArtifact,
646
- policies: Policies,
647
- fixtures: EndpointFixtures,
648
- dialect: ApplicationDialect,
649
- ): { readonly body: string; readonly cases: readonly string[]; readonly notes: readonly string[] } | undefined => {
650
- const cases: Case[] = []
651
- const notes: string[] = []
652
- for (const row of sortedEndpoints(artifact)) {
653
- const capability = capabilityCases(row, artifact, fixtures)
654
- cases.push(...endpointCases(row, artifact, policies, fixtures), ...capability.cases, ...publicCases(row, artifact, fixtures))
655
- notes.push(...capability.notes)
656
- }
657
- if (cases.length === 0) return undefined
658
- const database = testDatabaseLines(dialect, '../../db/migrations/')
659
- const body = [
660
- '// The endpoint access tests of this application, written by fabrika db test-scaffold from fabrika.contract.ts and',
661
- '// src/db/tables.ts. They run src/app.ts itself: callers of two scopes that share no value ask every endpoint with an',
662
- "// access form, and a caller with only the endpoint's action, plus what IAM requires of a member manager or a link's",
663
- '// issuer, asks for its own object. A handler bug that needs other data or another order is beyond them; the state a',
664
- '// precondition needs is a seed in endpoint-access.fixtures.ts.',
665
- '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a contract change.',
666
- ...notes.map((note) => `// Not checked: ${note}.`),
667
- '',
668
- "import { afterAll, describe, endpointAccessKit, expect, test } from '@fabrika/app/testing/isolation'",
669
- database.kit,
670
- "import app from '../app'",
671
- "import { tables } from '../db/tables'",
672
- '',
673
- "const label = 'endpoint-access.test.ts'",
674
- database.open,
675
- '',
676
- `if (${database.name} !== null) {`,
677
- `\tafterAll(() => ${database.name}.close())`,
678
- `\tconst kit = endpointAccessKit(app, tables, ${database.name}${kitOptions(fixtures, testedEndpoints(artifact))})`,
679
- '',
680
- describeBlock('endpoints: a caller of one scope reaches nothing of another', cases),
681
- '}',
682
- '',
683
- ].join('\n')
684
- return { body, cases: cases.map((item) => item.name), notes }
685
- }
686
-
687
- const generated = async (
688
- { body, cases, notes = [] }: { readonly body: string; readonly cases: readonly string[]; readonly notes?: readonly string[] },
689
- ): Promise<GeneratedTest> => ({ text: `${await generatedTestHeader(body)}\n${body}`, cases, notes })
690
-
691
- /**
692
- * Every test the scaffold writes for these policies and, when the application has a contract, its artifact; by path.
693
- * Endpoint access tests exist only for an application on `@fabrika/db`, which has policies to seed rows from. They
694
- * open the test database of the application's dialect.
695
- */
696
- export const generatedTests = async (
697
- policies: Policies,
698
- artifact: ContractArtifact | null,
699
- fixtures: EndpointFixtures = NO_FIXTURES,
700
- dialect: ApplicationDialect = 'postgres',
701
- ): Promise<ReadonlyMap<string, GeneratedTest>> => {
702
- const files = new Map<string, GeneratedTest>()
703
- // The kit's scoped sites are `over` the vocabulary's first dimension: without one, no scoped site exists.
704
- const scopedSites = artifact !== null && Object.keys(artifact.dimensions).length > 0
705
- for (const table of Object.keys(policies).sort()) {
706
- const test = policyTestBody(policies, table, scopedSites, dialect)
707
- if (test !== undefined) files.set(policyTestPath(table), await generated(test))
708
- }
709
- const endpoints = artifact === null || files.size === 0 ? undefined : endpointTestBody(artifact, policies, fixtures, dialect)
710
- if (endpoints !== undefined) files.set(ENDPOINT_ACCESS_TEST, await generated(endpoints))
711
- return files
712
- }
713
-
714
- export interface ScaffoldInputs {
715
- /** What `src/db/tables.ts` defines, its column list included; `null` without the file. */
716
- readonly tables: Tables<unknown, unknown> | null
717
- readonly policies: Policies
718
- readonly artifact: ContractArtifact | null
719
- readonly fixtures: EndpointFixtures
720
- readonly dialect: ApplicationDialect
721
- }
722
-
723
- /**
724
- * Whether an endpoint's generated cases run its handler for the caller's own scope, which application rows can serve: a
725
- * leak or an own case, read off the cases `endpointCases` writes. An input it lacks a fixture for does not matter here.
726
- */
727
- const runsOnOwnScope = (row: EndpointRow, artifact: ContractArtifact, policies: Policies, fixtures: EndpointFixtures): boolean => {
728
- const withInput = { ...fixtures, inputs: { ...fixtures.inputs, [row.id]: fixtures.inputs[row.id] ?? {} } }
729
- return endpointCases(row, artifact, policies, withInput).some((item) => item.ownScope === true)
730
- }
731
-
732
- /** The allowed form of an `appRows` entry `applicationRowsPlan` refuses; the message is the kit's own words. */
733
- const appRowAllowed = (refusal: ApplicationRowRefusal): string => {
734
- switch (refusal.kind) {
735
- case 'table':
736
- return refusal.mode === null
737
- ? 'the name of a table with scope: { app } in src/db/tables.ts'
738
- : "rows, for a row in the endpoint's object; seeds, for the state of the object's own row"
739
- case 'column':
740
- return `a column of ${refusal.table} in src/db/schema.generated.ts`
741
- case 'stamped':
742
- case 'file':
743
- return "the row's other columns"
744
- case 'value':
745
- return 'a string, a number, a boolean or null'
746
- case 'partial-key':
747
- return `all of ${refusal.key.columns.join(', ')}, or none, which the kit then fills`
748
- case 'cycle':
749
- return 'a value for one of the foreign keys (null, where it may be), which the kit then does not fill'
750
- }
751
- }
752
-
753
- /** The finding of a `rows` table the kit seeds no row of for an endpoint of `access`, and its allowed form. */
754
- const unplacedRow = (policies: Policies, id: string, table: string, access: ScopedAccess): readonly [string, string] => {
755
- if (access.form === 'over') {
756
- return [
757
- `${id}: a list of ${access.dimension} reaches no ${table} row, so the kit seeds none in the scopes it lists`,
758
- `a dimension table whose container is ${access.dimension}, or a child table of one`,
759
- ]
760
- }
761
- if (ownerRead(policies, access.dimension) === undefined) {
762
- return [`${id}: no table owns ${access.dimension}, so the kit seeds no ${table} row in one`, `an endpoint on or in a dimension a table owns`]
763
- }
764
- return [
765
- `${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)`,
766
- `a child table of the table that owns ${access.dimension}, or a dimension table whose container is ${access.dimension}`,
767
- ]
768
- }
769
-
770
- /** What the scaffold reads from an application's files; throws `ContractSourceError` or `ContractError` as the reader does. */
771
- export const scaffoldInputs = (files: ReadonlyMap<string, string>): ScaffoldInputs => {
772
- const tables = readTablesDefinition(files)
773
- const policies = tables === null ? {} : tablePolicies(tables)
774
- const fixtures = readEndpointFixtures(files)
775
- if (!fixtures.ok) throw new ContractSourceError(fixtures.findings)
776
- // Endpoint tests seed rows from the policies, so without src/db/tables.ts there is nothing to compile them against.
777
- const artifact = files.has(CONTRACT_FILE) && tables !== null ? readContractSource(files, tables) : null
778
- return { tables, policies, artifact, fixtures: fixtures.fixtures, dialect: applicationDialect(files) }
779
- }
780
-
781
- /**
782
- * What stops the endpoint access tests from covering every endpoint: one whose input the scaffold cannot sample and
783
- * the author gave no fixture, and a fixture of no tested endpoint. Each is an `endpoint-fixture` finding.
784
- */
785
- export const missingEndpointFixtures = ({ tables, policies, artifact, fixtures }: ScaffoldInputs): readonly Finding[] => {
786
- if (artifact === null || tables === null || Object.keys(policies).length === 0) return []
787
- const at = (message: string, allowed: string): Finding => ({
788
- file: ENDPOINT_FIXTURES_FILE,
789
- line: 1,
790
- column: 1,
791
- severity: 'refusal',
792
- rule: 'endpoint-fixture',
793
- message,
794
- allowed,
795
- })
796
- const tested = artifact.endpoints.filter((row) => isAccessTested(row) || isLinkProcedure(row))
797
- const findings = tested.filter((row) => inputOf(row, fixtures) === undefined).map((row) =>
798
- at(
799
- `${row.id}: the scaffold cannot write an input its schema admits, so its endpoint access cases need one here`,
800
- `export const fixtures = { '${row.id}': { … } }, an input the endpoint's schema admits`,
801
- )
802
- )
803
- for (const id of Object.keys(fixtures.inputs).sort()) {
804
- if (!tested.some((row) => row.id === id)) {
805
- findings.push(
806
- 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'),
807
- )
808
- }
809
- }
810
- for (const [id, fields] of Object.entries(fixtures.members).sort(byKey)) {
811
- const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate))
812
- const directory = row === undefined ? null : endpointDirectory(artifact, row)
813
- if (row === undefined || directory === null) {
814
- findings.push(
815
- at(
816
- `${id} is no tested endpoint below a dimension with members, whose handler could look one up`,
817
- "export const members = { '<endpoint id>': ['<input field>'] }, for an endpoint on or in a dimension with members or below one",
818
- ),
819
- )
820
- continue
821
- }
822
- const input = row.input
823
- for (const field of fields) {
824
- if (input?.type !== 'object' || !admitsString(input.fields[field])) {
825
- 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'))
826
- }
827
- }
828
- }
829
- const holders = [
830
- {
831
- fields: fixtures.invitations,
832
- names: 'an invitation',
833
- admits: (row: EndpointRow) => endpointMembers(artifact, row) === 'manage',
834
- refusal: (id: string) => `${id} is no tested endpoint that manages a dimension's members, whose handler could cancel an invitation`,
835
- allowed: "export const invitations = { '<endpoint id>': ['<input field>'] }, for an endpoint with its dimension's members.manage",
836
- },
837
- {
838
- fields: fixtures.links,
839
- names: 'a share link',
840
- admits: (row: EndpointRow) => issuesLinks(artifact, row),
841
- refusal: (id: string) => `${id} is no tested endpoint that issues a share link, whose handler could revoke one`,
842
- allowed: "export const links = { '<endpoint id>': ['<input field>'] }, for an endpoint whose action a link mount's issuedBy names",
843
- },
844
- ]
845
- for (const holder of holders) {
846
- for (const [id, fields] of Object.entries(holder.fields).sort(byKey)) {
847
- const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate) && holder.admits(candidate))
848
- if (row === undefined) {
849
- findings.push(at(holder.refusal(id), holder.allowed))
850
- continue
851
- }
852
- for (const field of fields) {
853
- if (row.input?.type !== 'object' || !admitsString(row.input.fields[field])) {
854
- 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'))
855
- }
856
- }
857
- }
858
- }
859
- for (const [key, fields] of Object.entries(fixtures.rows).sort(byKey)) {
860
- const split = key.indexOf(CAPABILITY_KEY)
861
- const id = split === -1 ? key : key.slice(0, split)
862
- const named = split === -1 ? null : key.slice(split + 1)
863
- const row = tested.find((candidate) => candidate.id === id)
864
- const requirement = row?.requirement
865
- const severalCapabilities = requirement?.kind === 'capabilities'
866
- const access = requirement?.kind === 'action' && named === null
867
- ? requirement.access
868
- : requirement?.kind === 'capabilities' && named !== null && Object.hasOwn(requirement.capabilities, named)
869
- ? requirement.capabilities[named]?.access
870
- : undefined
871
- const scope = access?.form === 'on' || access?.form === 'in' || access?.form === 'over' ? access : undefined
872
- if (row === undefined || scope === undefined) {
873
- findings.push(
874
- severalCapabilities && named === null
875
- ? at(
876
- `${id} has several capabilities, so its rows name the one whose scope they lie in`,
877
- `export const rows = { '${id}${CAPABILITY_KEY}<capability>': { <input field>: '<table>' } }`,
878
- )
879
- : named !== null
880
- ? at(
881
- `${key} names no capability of a tested endpoint with several, in whose scope the kit could seed a row`,
882
- `export const rows = { '<endpoint id>${CAPABILITY_KEY}<capability>': { <input field>: '<table>' } }, a capability of the endpoint`,
883
- )
884
- : at(
885
- `${id} is no tested endpoint on, in or over a scope, in which the kit could seed a row`,
886
- "export const rows = { '<endpoint id>': { <input field>: '<table>' } }, for an endpoint on, in or over a dimension",
887
- ),
888
- )
889
- continue
890
- }
891
- for (const [field, table] of Object.entries(fields).sort(byKey)) {
892
- if (row.input?.type !== 'object' || !admitsString(row.input.fields[field])) {
893
- 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'))
894
- } else if (policies[table]?.view === true) {
895
- findings.push(
896
- at(
897
- `${id}: ${field} names the view ${table}, whose rows the kit cannot seed: they come from the tables it reads`,
898
- 'a row field that names a table the view reads',
899
- ),
900
- )
901
- } else if (!rowPlace(policies, scope, table)) {
902
- findings.push(at(...unplacedRow(policies, id, table, scope)))
903
- }
904
- }
905
- }
906
- for (const [id, rows] of Object.entries(fixtures.appRows).sort(byKey)) {
907
- if (!tested.some((row) => row.id === id && runsOnOwnScope(row, artifact, policies, fixtures))) {
908
- findings.push(
909
- at(
910
- `${id} is no endpoint with a leak or an own case, whose handler could read an application row the kit seeds`,
911
- "export const appRows = { '<endpoint id>': { <table>: { <column>: <value> } } }, for an endpoint on, in or over a scope",
912
- ),
913
- )
914
- continue
915
- }
916
- // The rule the kit seeds by, read from the policies and the column list: one rule, so the two cannot drift.
917
- for (const refusal of applicationRowsPlan(tables, rows).refusals) {
918
- findings.push(at(`${id}: ${applicationRowRefusalText(refusal)}`, appRowAllowed(refusal)))
919
- }
920
- }
921
- for (const refusal of applicationRowsPlan(tables, fixtures.callerRows).refusals) {
922
- findings.push(
923
- at(
924
- `callerRows: ${applicationRowRefusalText(refusal)}`,
925
- refusal.kind === 'table' ? 'the name of a table with scope: { app } in src/db/tables.ts' : appRowAllowed(refusal),
926
- ),
927
- )
928
- }
929
- for (const [id, fields] of Object.entries(fixtures.files).sort(byKey)) {
930
- const row = tested.find((candidate) => candidate.id === id)
931
- if (row === undefined) {
932
- findings.push(
933
- at(
934
- `${id} is no tested endpoint, whose cases could send a file`,
935
- "export const files = { '<endpoint id>': { <file field>: '<path from the application root>' } }, for a tested endpoint with a file input",
936
- ),
937
- )
938
- continue
939
- }
940
- for (const [field, path] of Object.entries(fields).sort(byKey)) {
941
- if (fileFieldOf(row.input, field) === undefined) {
942
- findings.push(at(`${id}: ${field} is no file field of its input, so no case sends a file there`, 'a top-level file field of the input'))
943
- } else if (!isFixtureFilePath(path)) {
944
- findings.push(
945
- at(
946
- `${id}: the file of ${field}, '${path}', is no path inside the application`,
947
- "a path from the application's root, '/'-separated, without '..', a leading '/' or '.', or characters other than letters, digits, '_', '-' and '.'",
948
- ),
949
- )
950
- }
951
- }
952
- }
953
- for (const [id, types] of Object.entries(fixtures.refusals).sort(byKey)) {
954
- if (!tested.some((row) => row.id === id)) {
955
- findings.push(
956
- at(
957
- `${id} is no tested endpoint, whose handler a case runs`,
958
- "export const refusals = { '<endpoint id>': ['<error type>'] }, for a tested endpoint",
959
- ),
960
- )
961
- continue
962
- }
963
- for (const type of types) {
964
- if (!isDeclarableRefusal(type)) {
965
- findings.push(
966
- at(
967
- `${id}: '${type}' is no refusal of its handler; an input the schema refuses (validation) is the fixture's mistake`,
968
- "the error type of a 400 the handler throws (new HttpError(400, '<type>', …))",
969
- ),
970
- )
971
- }
972
- }
973
- }
974
- const seeded = (row: EndpointRow): boolean =>
975
- row.requirement?.kind === 'action' && (row.requirement.access.form === 'on' || row.requirement.access.form === 'in')
976
- for (const id of Object.keys(fixtures.pins).sort()) {
977
- if (!tested.some((row) => row.id === id && (seeded(row) || isLinkProcedure(row)))) {
978
- findings.push(
979
- at(
980
- `${id} is no endpoint with an on or in access form, whose row a pin sets`,
981
- "export const pins = { '<endpoint id>': { <text column>: '<value>' } }",
982
- ),
983
- )
984
- }
985
- }
986
- for (const id of Object.keys(fixtures.seeds).sort()) {
987
- if (!tested.some((row) => row.id === id && seeded(row))) {
988
- findings.push(
989
- at(`${id} is no endpoint with an on or in access form, whose row a seed sets`, "export const seeds = { '<endpoint id>': { <column>: <value> } }"),
990
- )
991
- }
992
- }
993
- return findings
994
- }