@fabrika/check 0.9.0-dev.1 → 0.9.0-dev.11

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 (74) hide show
  1. package/package.json +12 -11
  2. package/src/check.ts +58 -9
  3. package/src/cli.ts +23 -4
  4. package/src/dialect.ts +29 -0
  5. package/src/endpoint-fixtures.ts +99 -13
  6. package/src/finding.ts +12 -3
  7. package/src/index.ts +4 -1
  8. package/src/layout.ts +16 -1
  9. package/src/migration-base.ts +85 -0
  10. package/src/reader/surface.ts +15 -0
  11. package/src/reader/value.ts +1 -1
  12. package/src/resolution.ts +2 -2
  13. package/src/rules/cloudflare.ts +59 -0
  14. package/src/rules/framework.ts +2 -2
  15. package/src/rules/isolation.ts +5 -1
  16. package/src/rules/migration-history.ts +70 -0
  17. package/src/rules/migrations.ts +63 -0
  18. package/src/rules/modules.ts +3 -3
  19. package/src/rules/platform-migrations.ts +93 -0
  20. package/src/rules/runtime.ts +13 -7
  21. package/src/rules/structure.ts +26 -1
  22. package/src/rules/tests.ts +1 -1
  23. package/src/scaffold.ts +398 -71
  24. package/src/trust.ts +8 -4
  25. package/types/src/ast.d.ts +65 -0
  26. package/types/src/bun-plugin.d.ts +12 -0
  27. package/types/src/check.d.ts +22 -0
  28. package/types/src/cli.d.ts +2 -0
  29. package/types/src/contract.d.ts +58 -0
  30. package/types/src/dialect.d.ts +8 -0
  31. package/types/src/endpoint-fixtures.d.ts +54 -0
  32. package/types/src/finding.d.ts +39 -0
  33. package/types/src/graph.d.ts +68 -0
  34. package/types/src/index.d.ts +9 -0
  35. package/types/src/inputs.d.ts +9 -0
  36. package/types/src/jsonc.d.ts +2 -0
  37. package/types/src/layout.d.ts +76 -0
  38. package/types/src/limits.d.ts +15 -0
  39. package/types/src/lockfile.d.ts +19 -0
  40. package/types/src/migration-base.d.ts +9 -0
  41. package/types/src/packed.d.ts +15 -0
  42. package/types/src/reader/problems.d.ts +7 -0
  43. package/types/src/reader/schema.d.ts +18 -0
  44. package/types/src/reader/surface.d.ts +5 -0
  45. package/types/src/reader/tables.d.ts +6 -0
  46. package/types/src/reader/value.d.ts +113 -0
  47. package/types/src/references.d.ts +15 -0
  48. package/types/src/resolution.d.ts +20 -0
  49. package/types/src/rules/cloudflare.d.ts +9 -0
  50. package/types/src/rules/contract.d.ts +8 -0
  51. package/types/src/rules/crontab.d.ts +15 -0
  52. package/types/src/rules/framework.d.ts +19 -0
  53. package/types/src/rules/identity.d.ts +5 -0
  54. package/types/src/rules/isolation.d.ts +18 -0
  55. package/types/src/rules/json.d.ts +3 -0
  56. package/types/src/rules/literal.d.ts +63 -0
  57. package/types/src/rules/migration-history.d.ts +12 -0
  58. package/types/src/rules/migrations.d.ts +40 -0
  59. package/types/src/rules/modules.d.ts +12 -0
  60. package/types/src/rules/packages.d.ts +7 -0
  61. package/types/src/rules/platform-migrations.d.ts +13 -0
  62. package/types/src/rules/runtime.d.ts +34 -0
  63. package/types/src/rules/structure.d.ts +41 -0
  64. package/types/src/rules/tests.d.ts +22 -0
  65. package/types/src/rules/types.d.ts +4 -0
  66. package/types/src/scaffold-sample.d.ts +8 -0
  67. package/types/src/scaffold.d.ts +36 -0
  68. package/types/src/scope.d.ts +6 -0
  69. package/types/src/slice.d.ts +30 -0
  70. package/types/src/source-maps-cli.d.ts +4 -0
  71. package/types/src/source-maps.d.ts +32 -0
  72. package/types/src/toml.d.ts +30 -0
  73. package/types/src/trust.d.ts +15 -0
  74. package/types/src/version.d.ts +2 -0
package/src/scaffold.ts CHANGED
@@ -3,8 +3,17 @@
3
3
  // one file per application, from the contract: they run the application's own `serve(…)` and handlers. The checker
4
4
  // regenerates both to find a missing, edited, stale or orphaned file. Browser-safe: no file API.
5
5
 
6
- import { GENERATED_INVITATION, GENERATED_LINK, GENERATED_MEMBER, GENERATED_ROW_PREFIX } from '@fabrika/app/contract'
7
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,
8
17
  type ContractArtifact,
9
18
  endpointDirectory,
10
19
  endpointMembers,
@@ -13,9 +22,10 @@ import {
13
22
  tableActions,
14
23
  type TablePolicyArtifact,
15
24
  } from '@fabrika/auth-core'
16
- import { tablePolicies } from '@fabrika/db/tables'
25
+ import { type ApplicationRowRefusal, applicationRowRefusalText, applicationRowsPlan, tablePolicies, type Tables } from '@fabrika/db/tables'
17
26
  import { ContractSourceError, readContractSource, readTablesDefinition } from './contract'
18
- import { type EndpointFixtures, isSampleObject, NO_FIXTURES, readEndpointFixtures } from './endpoint-fixtures'
27
+ import { type ApplicationDialect, applicationDialect } from './dialect'
28
+ import { type EndpointFixtures, isFixtureFilePath, isSampleObject, NO_FIXTURES, readEndpointFixtures } from './endpoint-fixtures'
19
29
  import type { Finding } from './finding'
20
30
  import { CONTRACT_FILE, ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR } from './layout'
21
31
 
@@ -29,17 +39,46 @@ export const policyTestPath = (table: string): string => `${POLICY_TESTS_DIR}${t
29
39
  export interface GeneratedTest {
30
40
  readonly text: string
31
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[]
32
44
  }
33
45
 
34
46
  type Policies = Readonly<Record<string, TablePolicyArtifact>>
35
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
+
36
67
  interface Case {
37
68
  readonly name: string
38
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
39
72
  }
40
73
 
41
74
  const testCase = (name: string, ...lines: readonly string[]): Case => ({ name, lines })
42
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
+
43
82
  const quote = (text: string): string => `'${text.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`
44
83
 
45
84
  const renderCase = (item: Case): string =>
@@ -209,6 +248,7 @@ const policyTestBody = (
209
248
  policies: Policies,
210
249
  table: string,
211
250
  scopedSites: boolean,
251
+ dialect: ApplicationDialect,
212
252
  ): { readonly body: string; readonly cases: readonly string[] } | undefined => {
213
253
  const policy = policies[table]
214
254
  if (policy === undefined) return undefined
@@ -225,6 +265,7 @@ const policyTestBody = (
225
265
  ? `policy of ${table}: only a global holder of its actions reaches a row`
226
266
  : `policy of ${table}: a caller of one ${dimension} reaches no row of another`
227
267
  const kitOf = app ? 'appPolicyIsolationKit' : 'policyIsolationKit'
268
+ const database = testDatabaseLines(dialect, '../../../db/migrations/')
228
269
  const blocks = [describeBlock(title, isolation)]
229
270
  if (hidden.length > 0) blocks.push(describeBlock(`policy of ${table}: a column with its own read action is never returned`, hidden))
230
271
  const body = [
@@ -233,16 +274,16 @@ const policyTestBody = (
233
274
  '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a policy change.',
234
275
  '',
235
276
  `import { ${['afterAll', 'describe', 'expect', kitOf, 'test'].sort().join(', ')} } from '@fabrika/app/testing/isolation'`,
236
- "import { testDatabase } from '@fabrika/db/testing'",
277
+ database.kit,
237
278
  "import { contract } from '../../../fabrika.contract'",
238
279
  "import { tables } from '../tables'",
239
280
  '',
240
281
  `const label = ${quote(`${table}${POLICY_TEST_SUFFIX}`)}`,
241
- "const postgres = await testDatabase({ migrations: new URL('../../../db/migrations/', import.meta.url), label })",
282
+ database.open,
242
283
  '',
243
- 'if (postgres !== null) {',
244
- '\tafterAll(() => postgres.close())',
245
- `\tconst kit = ${kitOf}(contract, tables, ${quote(table)}, postgres)`,
284
+ `if (${database.name} !== null) {`,
285
+ `\tafterAll(() => ${database.name}.close())`,
286
+ `\tconst kit = ${kitOf}(contract, tables, ${quote(table)}, ${database.name})`,
246
287
  '',
247
288
  blocks.join('\n\n'),
248
289
  '}',
@@ -265,7 +306,10 @@ const isLinkProcedure = (row: EndpointRow): boolean =>
265
306
  * The input an endpoint's cases send: the author's fixture, else a sample of its schema; `undefined` when neither
266
307
  * exists. Each field its `members`, `invitations` or `links` name holds `GENERATED_MEMBER`, `GENERATED_INVITATION` or
267
308
  * `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.
309
+ * `rows` name holds `GENERATED_ROW_PREFIX` and the table (and, under `<endpoint id>#<capability>`, the capability), which
310
+ * the kit replaces with the key of a row it seeded; each file
311
+ * field its `files` name holds its kind's marker (in a list, for a list of files), even where the sample left an optional
312
+ * one out, which the kit sends as the named file.
269
313
  */
270
314
  const inputOf = (row: EndpointRow, fixtures: EndpointFixtures): Readonly<Record<string, Sample>> | undefined => {
271
315
  const fixture = fixtures.inputs[row.id]
@@ -279,10 +323,91 @@ const inputOf = (row: EndpointRow, fixtures: EndpointFixtures): Readonly<Record<
279
323
  ...generated(fixtures.invitations[row.id], GENERATED_INVITATION),
280
324
  ...generated(fixtures.links[row.id], GENERATED_LINK),
281
325
  ...Object.entries(fixtures.rows[row.id] ?? {}).map(([field, table]) => [field, `${GENERATED_ROW_PREFIX}${table}`]),
326
+ ...Object.keys(row.requirement?.kind === 'capabilities' ? row.requirement.capabilities : {}).flatMap((name) =>
327
+ Object.entries(fixtures.rows[`${row.id}${CAPABILITY_KEY}${name}`] ?? {}).map((
328
+ [field, table],
329
+ ) => [field, `${GENERATED_ROW_PREFIX}${table}${GENERATED_ROW_CAPABILITY}${name}`])
330
+ ),
331
+ ...Object.keys(fixtures.files[row.id] ?? {}).flatMap((field) => {
332
+ const file = fileFieldOf(row.input, field)
333
+ if (file === undefined) return []
334
+ const marker = `${GENERATED_FILE_PREFIX}${file.kind}`
335
+ return [[field, file.list ? [marker] : marker]]
336
+ }),
282
337
  ]),
283
338
  }
284
339
  }
285
340
 
341
+ /** What separates an endpoint id from a capability's name in a `rows` key: `api.tasks.copy#from`. */
342
+ const CAPABILITY_KEY = '#'
343
+
344
+ /** 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`. */
345
+ const fileFieldOf = (input: SchemaShape | null, field: string): { readonly kind: string; readonly list: boolean } | undefined => {
346
+ const kindOf = (shape: SchemaShape | undefined): string | undefined =>
347
+ shape?.type === 'file' ? shape.kind : shape?.type === 'optional' || shape?.type === 'nullable' ? kindOf(shape.inner) : undefined
348
+ const shape = input?.type === 'object' ? input.fields[field] : undefined
349
+ const unwrapped = shape?.type === 'optional' || shape?.type === 'nullable' ? shape.inner : shape
350
+ if (unwrapped?.type === 'array') {
351
+ const kind = kindOf(unwrapped.items)
352
+ return kind === undefined ? undefined : { kind, list: true }
353
+ }
354
+ const kind = kindOf(shape)
355
+ return kind === undefined ? undefined : { kind, list: false }
356
+ }
357
+
358
+ /** The ids of the endpoints with endpoint access cases. */
359
+ const testedEndpoints = (artifact: ContractArtifact): ReadonlySet<string> =>
360
+ new Set(artifact.endpoints.filter((row) => isAccessTested(row) || isLinkProcedure(row)).map((row) => row.id))
361
+
362
+ /** How a generated endpoint access test reaches the application's root, where a file fixture's path starts. */
363
+ const ROOT_FROM_ENDPOINT_TEST = '../'.repeat(ENDPOINT_ACCESS_TEST.split('/').length - 1)
364
+
365
+ /**
366
+ * The options of the generated test's kit: the file fixtures of the tested endpoints, each a URL beside the test. Empty
367
+ * without any, so a test without file fixtures stays as it was.
368
+ */
369
+ const kitOptions = (fixtures: EndpointFixtures, tested: ReadonlySet<string>): string => {
370
+ const files = Object.entries(fixtures.files).sort(byKey).flatMap(([id, fields]) => {
371
+ const valid = Object.entries(fields).sort(byKey).filter(([, path]) => isFixtureFilePath(path))
372
+ if (!tested.has(id) || valid.length === 0) return []
373
+ const rendered = valid.map(([field, path]) => `${renderKey(field)}: new URL(${quote(`${ROOT_FROM_ENDPOINT_TEST}${path}`)}, import.meta.url)`)
374
+ return [`${quote(id)}: { ${rendered.join(', ')} }`]
375
+ })
376
+ const refusals = Object.entries(fixtures.refusals).sort(byKey).flatMap(([id, types]) => {
377
+ const valid = types.filter(isDeclarableRefusal)
378
+ return tested.has(id) && valid.length > 0 ? [`${quote(id)}: [${valid.map(quote).join(', ')}]`] : []
379
+ })
380
+ const pins = Object.entries(fixtures.pins).sort(byKey).flatMap(([id, columns]) => {
381
+ const entries = Object.entries(columns).sort(byKey)
382
+ return tested.has(id) && entries.length > 0
383
+ ? [`${quote(id)}: { ${entries.map(([column, value]) => `${renderKey(column)}: ${quote(value)}`).join(', ')} }`]
384
+ : []
385
+ })
386
+ const options = [
387
+ ...(files.length === 0 ? [] : [`files: { ${files.join(', ')} }`]),
388
+ ...(refusals.length === 0 ? [] : [`refusals: { ${refusals.join(', ')} }`]),
389
+ ...(pins.length === 0 ? [] : [`pins: { ${pins.join(', ')} }`]),
390
+ ]
391
+ return options.length === 0 ? '' : `, { ${options.join(', ')} }`
392
+ }
393
+
394
+ /** A refusal the fixtures may declare: a handler's own error type, never the input schema's (`validation`). */
395
+ const isDeclarableRefusal = (type: string): boolean => type !== '' && type !== 'validation'
396
+
397
+ /**
398
+ * The own case of an endpoint: 200, or, where its fixtures declare the refusals its handler may answer its own object
399
+ * with, also the 400 the kit hands back only for one of them.
400
+ */
401
+ const ownCase = (row: EndpointRow, fixtures: EndpointFixtures, name: string, args: string): Case => {
402
+ const declared = (fixtures.refusals[row.id] ?? []).filter(isDeclarableRefusal)
403
+ return declared.length === 0
404
+ ? ownScopeCase(name, `expect(await kit.own(${args})).toEqual({ status: 200 })`)
405
+ : ownScopeCase(`${name} (200, or a refusal its fixtures declare)`, `expect([200, 400]).toContain((await kit.own(${args})).status)`)
406
+ }
407
+
408
+ /** An object key as `renderSample` writes one: bare when it is an identifier, else quoted. */
409
+ const renderKey = (key: string): string => (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : quote(key))
410
+
286
411
  /** Whether the endpoint's handler gets `ctx.links`: on or in a dimension a link mount's `issuedBy` names its action for. */
287
412
  const issuesLinks = (artifact: ContractArtifact, row: EndpointRow): boolean => {
288
413
  if (row.requirement?.kind !== 'action') return false
@@ -307,12 +432,46 @@ const liesDirectlyIn = (policies: Policies, table: string, dimension: string): b
307
432
  return parent?.mode === 'dimension' && parent.dimension === dimension
308
433
  }
309
434
 
435
+ /**
436
+ * Whether a list of `dimension` (`over`) reaches the rows of `table`: a dimension table it contains or of its own when it
437
+ * has no container, or a child of one.
438
+ */
439
+ const listedBy = (policies: Policies, table: string, dimension: string): boolean => {
440
+ const listedIn = (scope: Policies[string]['scope'] | undefined): string | undefined =>
441
+ scope?.mode === 'dimension' ? (scope.container?.dimension ?? scope.dimension) : undefined
442
+ const scope = policies[table]?.scope
443
+ return (scope?.mode === 'child' ? listedIn(policies[scope.parent]?.scope) : listedIn(scope)) === dimension
444
+ }
445
+
446
+ /**
447
+ * Whether the kit seeds a row of `table` for an endpoint of `access`: in its object (`on`, `in` an object a table owns,
448
+ * the table lying directly in it) or in the scopes it lists (`over`).
449
+ */
450
+ const rowPlace = (policies: Policies, access: ScopedAccess, table: string): boolean =>
451
+ access.form === 'over'
452
+ ? listedBy(policies, table, access.dimension)
453
+ : ownerRead(policies, access.dimension) !== undefined && liesDirectlyIn(policies, table, access.dimension)
454
+
455
+ /** An access form that names a scope: an object (`on`), a value (`in`) or a list (`over`). */
456
+ type ScopedAccess = Extract<AccessForm, { readonly form: 'on' | 'in' | 'over' }>
457
+
310
458
  /** The read action of the table that owns `dimension`, or `undefined` when no table owns it. */
311
459
  const ownerRead = (policies: Policies, dimension: string): string | undefined =>
312
460
  tableActions(
313
461
  Object.values(policies).find((policy) => policy.scope.mode === 'dimension' && policy.scope.dimension === dimension)?.actions.read ?? null,
314
462
  )[0]
315
463
 
464
+ /**
465
+ * Whether an endpoint gets the `own` case: `on` an object a table owns, as a link procedure or with an action other
466
+ * than the owner's read action (a caller holding only that one reaches every object, which proves nothing).
467
+ */
468
+ const hasOwnCase = (row: EndpointRow, policies: Policies): boolean => {
469
+ if (row.requirement?.kind !== 'action') return false
470
+ const { access, action } = row.requirement
471
+ const read = access.form === 'on' ? ownerRead(policies, access.dimension) : undefined
472
+ return read !== undefined && (isLinkProcedure(row) || read !== action)
473
+ }
474
+
316
475
  /**
317
476
  * What the `own` case's caller holds: the endpoint's action, plus what IAM requires of a link's issuer (the actions the
318
477
  * link grants) and of a member manager (an assigning role and the assigned role's actions).
@@ -341,21 +500,27 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
341
500
  const seed = fixtures.seeds[row.id]
342
501
  const args = `${quote(row.id)}, ${renderSample(input)}`
343
502
  const seeded = seed === undefined ? args : `${args}, ${renderSample(seed)}`
503
+ // The application rows reach every case that runs the handler on the caller's own object: its leak cases and its own
504
+ // case. Only an endpoint with them gets the fourth argument, so every other generated file stays as it was.
505
+ const appRows = fixtures.appRows[row.id]
506
+ const rowsTail = appRows === undefined ? '' : `, ${renderSample(appRows)}`
507
+ const unseededArgs = appRows === undefined ? args : `${args}, {}${rowsTail}`
508
+ const seededArgs = seed === undefined ? unseededArgs : `${seeded}${rowsTail}`
344
509
  const declared = artifact.declared?.[row.id]
345
510
  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)
511
+ const own = hasOwnCase(row, policies)
348
512
  const cases: Case[] = []
349
- // The unseeded probe always runs: a seed meets a precondition, and must not also set aside the state that leaks.
513
+ // The unseeded probe always runs: a seed meets a precondition, and must not also set aside the state that leaks. The
514
+ // application rows reach it too: they are rows of the whole application, which the handler needs to answer at all.
350
515
  const leaked = (): Case[] => [
351
- testCase(
516
+ ownScopeCase(
352
517
  `${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: [] })`,
518
+ `expect(await kit.leaked(${unseededArgs})).toEqual({ answered: true, leaked: [] })`,
354
519
  ),
355
520
  ...(seed === undefined ? [] : [
356
- testCase(
521
+ ownScopeCase(
357
522
  `${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: [] })`,
523
+ `expect(await kit.leaked(${seededArgs})).toEqual({ answered: true, leaked: [] })`,
359
524
  ),
360
525
  ]),
361
526
  ]
@@ -379,9 +544,7 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
379
544
  }
380
545
  if (linked) {
381
546
  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
- )
547
+ cases.push(ownCase(row, fixtures, `${row.id}: the holder of a link to a ${access.dimension} reaches it`, seededArgs))
385
548
  }
386
549
  return cases
387
550
  }
@@ -390,9 +553,11 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
390
553
  if (!unscoped) cases.push(...leaked())
391
554
  if (own) {
392
555
  cases.push(
393
- testCase(
556
+ ownCase(
557
+ row,
558
+ fixtures,
394
559
  `${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 })`,
560
+ seededArgs,
396
561
  ),
397
562
  )
398
563
  }
@@ -407,25 +572,47 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
407
572
 
408
573
  /**
409
574
  * 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`).
575
+ * object of another scope is 404 (`on`), a value of another scope 403 (`in`), and a caller without the action 403
576
+ * (`over`). An `over` capability whose action another one needs in a related dimension has none (`deniedCaseRuledOutBy`);
577
+ * `notes` says so for each, in the generated test and in `fabrika db test-scaffold`'s output.
411
578
  */
412
- const capabilityCases = (row: EndpointRow, fixtures: EndpointFixtures): readonly Case[] => {
413
- if (row.requirement?.kind !== 'capabilities' || !row.callers.some((caller) => caller === 'human' || caller === 'machine')) return []
579
+ const capabilityCases = (
580
+ row: EndpointRow,
581
+ artifact: ContractArtifact,
582
+ fixtures: EndpointFixtures,
583
+ ): { readonly cases: readonly Case[]; readonly notes: readonly string[] } => {
584
+ if (row.requirement?.kind !== 'capabilities' || !row.callers.some((caller) => caller === 'human' || caller === 'machine')) {
585
+ return { cases: [], notes: [] }
586
+ }
414
587
  const input = inputOf(row, fixtures)
415
- if (input === undefined) return []
588
+ if (input === undefined) return { cases: [], notes: [] }
416
589
  const seed = fixtures.seeds[row.id]
417
- return Object.entries(row.requirement.capabilities).map(([name, { action, access }]) => {
590
+ const { capabilities } = row.requirement
591
+ const cases: Case[] = []
592
+ const notes: string[] = []
593
+ for (const [name, { action, access }] of Object.entries(capabilities)) {
418
594
  const args = `${quote(row.id)}, ${quote(name)}, ${renderSample(input)}${seed === undefined ? '' : `, ${renderSample(seed)}`}`
419
595
  const call = `await kit.capability(${args})`
420
596
  if (access.form === 'over') {
421
- return testCase(`${row.id}: a caller without ${action} (capability ${name}) is 403`, `expect(${call}).toEqual({ status: 403 })`)
597
+ const ruledOutBy = deniedCaseRuledOutBy(capabilities, name, artifact.dimensions)
598
+ if (ruledOutBy === undefined) {
599
+ cases.push(testCase(`${row.id}: a caller without ${action} (capability ${name}) is 403`, `expect(${call}).toEqual({ status: 403 })`))
600
+ } else {
601
+ notes.push(
602
+ `${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`,
603
+ )
604
+ }
605
+ continue
422
606
  }
423
607
  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} })`,
608
+ cases.push(
609
+ testCase(
610
+ `${row.id}: the ${access.dimension} of another scope as capability ${name} is ${status}`,
611
+ `expect(${call}).toEqual({ status: ${status} })`,
612
+ ),
427
613
  )
428
- })
614
+ }
615
+ return { cases, notes }
429
616
  }
430
617
 
431
618
  /**
@@ -447,20 +634,26 @@ const publicCases = (row: EndpointRow, artifact: ContractArtifact, fixtures: End
447
634
  ]
448
635
  }
449
636
 
637
+ /** The endpoints of the artifact by id, the order of their cases. */
638
+ const sortedEndpoints = (artifact: ContractArtifact): readonly EndpointRow[] =>
639
+ [...artifact.endpoints].sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))
640
+
450
641
  /** The endpoint access test of the application, or `undefined` when no endpoint has an access form to test. */
451
642
  const endpointTestBody = (
452
643
  artifact: ContractArtifact,
453
644
  policies: Policies,
454
645
  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
- ])
646
+ dialect: ApplicationDialect,
647
+ ): { readonly body: string; readonly cases: readonly string[]; readonly notes: readonly string[] } | undefined => {
648
+ const cases: Case[] = []
649
+ const notes: string[] = []
650
+ for (const row of sortedEndpoints(artifact)) {
651
+ const capability = capabilityCases(row, artifact, fixtures)
652
+ cases.push(...endpointCases(row, artifact, policies, fixtures), ...capability.cases, ...publicCases(row, artifact, fixtures))
653
+ notes.push(...capability.notes)
654
+ }
463
655
  if (cases.length === 0) return undefined
656
+ const database = testDatabaseLines(dialect, '../../db/migrations/')
464
657
  const body = [
465
658
  '// The endpoint access tests of this application, written by fabrika db test-scaffold from fabrika.contract.ts and',
466
659
  '// src/db/tables.ts. They run src/app.ts itself: callers of two scopes that share no value ask every endpoint with an',
@@ -468,56 +661,108 @@ const endpointTestBody = (
468
661
  '// issuer, asks for its own object. A handler bug that needs other data or another order is beyond them; the state a',
469
662
  '// precondition needs is a seed in endpoint-access.fixtures.ts.',
470
663
  '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a contract change.',
664
+ ...notes.map((note) => `// Not checked: ${note}.`),
471
665
  '',
472
666
  "import { afterAll, describe, endpointAccessKit, expect, test } from '@fabrika/app/testing/isolation'",
473
- "import { testDatabase } from '@fabrika/db/testing'",
667
+ database.kit,
474
668
  "import app from '../app'",
475
669
  "import { tables } from '../db/tables'",
476
670
  '',
477
671
  "const label = 'endpoint-access.test.ts'",
478
- "const postgres = await testDatabase({ migrations: new URL('../../db/migrations/', import.meta.url), label })",
672
+ database.open,
479
673
  '',
480
- 'if (postgres !== null) {',
481
- '\tafterAll(() => postgres.close())',
482
- '\tconst kit = endpointAccessKit(app, tables, postgres)',
674
+ `if (${database.name} !== null) {`,
675
+ `\tafterAll(() => ${database.name}.close())`,
676
+ `\tconst kit = endpointAccessKit(app, tables, ${database.name}${kitOptions(fixtures, testedEndpoints(artifact))})`,
483
677
  '',
484
678
  describeBlock('endpoints: a caller of one scope reaches nothing of another', cases),
485
679
  '}',
486
680
  '',
487
681
  ].join('\n')
488
- return { body, cases: cases.map((item) => item.name) }
682
+ return { body, cases: cases.map((item) => item.name), notes }
489
683
  }
490
684
 
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
- })
685
+ const generated = async (
686
+ { body, cases, notes = [] }: { readonly body: string; readonly cases: readonly string[]; readonly notes?: readonly string[] },
687
+ ): Promise<GeneratedTest> => ({ text: `${await generatedTestHeader(body)}\n${body}`, cases, notes })
495
688
 
496
689
  /**
497
690
  * 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.
691
+ * Endpoint access tests exist only for an application on `@fabrika/db`, which has policies to seed rows from. They
692
+ * open the test database of the application's dialect.
499
693
  */
500
694
  export const generatedTests = async (
501
695
  policies: Policies,
502
696
  artifact: ContractArtifact | null,
503
697
  fixtures: EndpointFixtures = NO_FIXTURES,
698
+ dialect: ApplicationDialect = 'postgres',
504
699
  ): Promise<ReadonlyMap<string, GeneratedTest>> => {
505
700
  const files = new Map<string, GeneratedTest>()
506
701
  // The kit's scoped sites are `over` the vocabulary's first dimension: without one, no scoped site exists.
507
702
  const scopedSites = artifact !== null && Object.keys(artifact.dimensions).length > 0
508
703
  for (const table of Object.keys(policies).sort()) {
509
- const test = policyTestBody(policies, table, scopedSites)
704
+ const test = policyTestBody(policies, table, scopedSites, dialect)
510
705
  if (test !== undefined) files.set(policyTestPath(table), await generated(test))
511
706
  }
512
- const endpoints = artifact === null || files.size === 0 ? undefined : endpointTestBody(artifact, policies, fixtures)
707
+ const endpoints = artifact === null || files.size === 0 ? undefined : endpointTestBody(artifact, policies, fixtures, dialect)
513
708
  if (endpoints !== undefined) files.set(ENDPOINT_ACCESS_TEST, await generated(endpoints))
514
709
  return files
515
710
  }
516
711
 
517
712
  export interface ScaffoldInputs {
713
+ /** What `src/db/tables.ts` defines, its column list included; `null` without the file. */
714
+ readonly tables: Tables<unknown, unknown> | null
518
715
  readonly policies: Policies
519
716
  readonly artifact: ContractArtifact | null
520
717
  readonly fixtures: EndpointFixtures
718
+ readonly dialect: ApplicationDialect
719
+ }
720
+
721
+ /**
722
+ * Whether an endpoint's generated cases run its handler for the caller's own scope, which application rows can serve: a
723
+ * leak or an own case, read off the cases `endpointCases` writes. An input it lacks a fixture for does not matter here.
724
+ */
725
+ const runsOnOwnScope = (row: EndpointRow, artifact: ContractArtifact, policies: Policies, fixtures: EndpointFixtures): boolean => {
726
+ const withInput = { ...fixtures, inputs: { ...fixtures.inputs, [row.id]: fixtures.inputs[row.id] ?? {} } }
727
+ return endpointCases(row, artifact, policies, withInput).some((item) => item.ownScope === true)
728
+ }
729
+
730
+ /** The allowed form of an `appRows` entry `applicationRowsPlan` refuses; the message is the kit's own words. */
731
+ const appRowAllowed = (refusal: ApplicationRowRefusal): string => {
732
+ switch (refusal.kind) {
733
+ case 'table':
734
+ return refusal.mode === null
735
+ ? 'the name of a table with scope: { app } in src/db/tables.ts'
736
+ : "rows, for a row in the endpoint's object; seeds, for the state of the object's own row"
737
+ case 'column':
738
+ return `a column of ${refusal.table} in src/db/schema.generated.ts`
739
+ case 'stamped':
740
+ case 'file':
741
+ return "the row's other columns"
742
+ case 'value':
743
+ return 'a string, a number, a boolean or null'
744
+ case 'partial-key':
745
+ return `all of ${refusal.key.columns.join(', ')}, or none, which the kit then fills`
746
+ case 'cycle':
747
+ return 'a value for one of the foreign keys (null, where it may be), which the kit then does not fill'
748
+ }
749
+ }
750
+
751
+ /** The finding of a `rows` table the kit seeds no row of for an endpoint of `access`, and its allowed form. */
752
+ const unplacedRow = (policies: Policies, id: string, table: string, access: ScopedAccess): readonly [string, string] => {
753
+ if (access.form === 'over') {
754
+ return [
755
+ `${id}: a list of ${access.dimension} reaches no ${table} row, so the kit seeds none in the scopes it lists`,
756
+ `a dimension table whose container is ${access.dimension}, or a child table of one`,
757
+ ]
758
+ }
759
+ if (ownerRead(policies, access.dimension) === undefined) {
760
+ 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`]
761
+ }
762
+ return [
763
+ `${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)`,
764
+ `a child table of the table that owns ${access.dimension}, or a dimension table whose container is ${access.dimension}`,
765
+ ]
521
766
  }
522
767
 
523
768
  /** What the scaffold reads from an application's files; throws `ContractSourceError` or `ContractError` as the reader does. */
@@ -528,15 +773,15 @@ export const scaffoldInputs = (files: ReadonlyMap<string, string>): ScaffoldInpu
528
773
  if (!fixtures.ok) throw new ContractSourceError(fixtures.findings)
529
774
  // Endpoint tests seed rows from the policies, so without src/db/tables.ts there is nothing to compile them against.
530
775
  const artifact = files.has(CONTRACT_FILE) && tables !== null ? readContractSource(files, tables) : null
531
- return { policies, artifact, fixtures: fixtures.fixtures }
776
+ return { tables, policies, artifact, fixtures: fixtures.fixtures, dialect: applicationDialect(files) }
532
777
  }
533
778
 
534
779
  /**
535
780
  * What stops the endpoint access tests from covering every endpoint: one whose input the scaffold cannot sample and
536
781
  * the author gave no fixture, and a fixture of no tested endpoint. Each is an `endpoint-fixture` finding.
537
782
  */
538
- export const missingEndpointFixtures = ({ policies, artifact, fixtures }: ScaffoldInputs): readonly Finding[] => {
539
- if (artifact === null || Object.keys(policies).length === 0) return []
783
+ export const missingEndpointFixtures = ({ tables, policies, artifact, fixtures }: ScaffoldInputs): readonly Finding[] => {
784
+ if (artifact === null || tables === null || Object.keys(policies).length === 0) return []
540
785
  const at = (message: string, allowed: string): Finding => ({
541
786
  file: ENDPOINT_FIXTURES_FILE,
542
787
  line: 1,
@@ -560,7 +805,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
560
805
  )
561
806
  }
562
807
  }
563
- for (const [id, fields] of Object.entries(fixtures.members).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
808
+ for (const [id, fields] of Object.entries(fixtures.members).sort(byKey)) {
564
809
  const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate))
565
810
  const directory = row === undefined ? null : endpointDirectory(artifact, row)
566
811
  if (row === undefined || directory === null) {
@@ -579,8 +824,6 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
579
824
  }
580
825
  }
581
826
  }
582
- const sortedById = (fields: Readonly<Record<string, readonly string[]>>) =>
583
- Object.entries(fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
584
827
  const holders = [
585
828
  {
586
829
  fields: fixtures.invitations,
@@ -598,7 +841,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
598
841
  },
599
842
  ]
600
843
  for (const holder of holders) {
601
- for (const [id, fields] of sortedById(holder.fields)) {
844
+ for (const [id, fields] of Object.entries(holder.fields).sort(byKey)) {
602
845
  const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate) && holder.admits(candidate))
603
846
  if (row === undefined) {
604
847
  findings.push(at(holder.refusal(id), holder.allowed))
@@ -611,27 +854,101 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
611
854
  }
612
855
  }
613
856
  }
614
- for (const [id, fields] of Object.entries(fixtures.rows).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
857
+ for (const [key, fields] of Object.entries(fixtures.rows).sort(byKey)) {
858
+ const split = key.indexOf(CAPABILITY_KEY)
859
+ const id = split === -1 ? key : key.slice(0, split)
860
+ const named = split === -1 ? null : key.slice(split + 1)
615
861
  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) {
862
+ const requirement = row?.requirement
863
+ const severalCapabilities = requirement?.kind === 'capabilities'
864
+ const access = requirement?.kind === 'action' && named === null
865
+ ? requirement.access
866
+ : requirement?.kind === 'capabilities' && named !== null && Object.hasOwn(requirement.capabilities, named)
867
+ ? requirement.capabilities[named]?.access
868
+ : undefined
869
+ const scope = access?.form === 'on' || access?.form === 'in' || access?.form === 'over' ? access : undefined
870
+ if (row === undefined || scope === undefined) {
619
871
  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
- ),
872
+ severalCapabilities && named === null
873
+ ? at(
874
+ `${id} has several capabilities, so its rows name the one whose scope they lie in`,
875
+ `export const rows = { '${id}${CAPABILITY_KEY}<capability>': { <input field>: '<table>' } }`,
876
+ )
877
+ : named !== null
878
+ ? at(
879
+ `${key} names no capability of a tested endpoint with several, in whose scope the kit could seed a row`,
880
+ `export const rows = { '<endpoint id>${CAPABILITY_KEY}<capability>': { <input field>: '<table>' } }, a capability of the endpoint`,
881
+ )
882
+ : at(
883
+ `${id} is no tested endpoint on, in or over a scope, in which the kit could seed a row`,
884
+ "export const rows = { '<endpoint id>': { <input field>: '<table>' } }, for an endpoint on, in or over a dimension",
885
+ ),
624
886
  )
625
887
  continue
626
888
  }
627
- for (const [field, table] of Object.entries(fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
889
+ for (const [field, table] of Object.entries(fields).sort(byKey)) {
628
890
  if (row.input?.type !== 'object' || !admitsString(row.input.fields[field])) {
629
891
  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)) {
892
+ } else if (!rowPlace(policies, scope, table)) {
893
+ findings.push(at(...unplacedRow(policies, id, table, scope)))
894
+ }
895
+ }
896
+ }
897
+ for (const [id, rows] of Object.entries(fixtures.appRows).sort(byKey)) {
898
+ if (!tested.some((row) => row.id === id && runsOnOwnScope(row, artifact, policies, fixtures))) {
899
+ findings.push(
900
+ at(
901
+ `${id} is no endpoint with a leak or an own case, whose handler could read an application row the kit seeds`,
902
+ "export const appRows = { '<endpoint id>': { <table>: { <column>: <value> } } }, for an endpoint on, in or over a scope",
903
+ ),
904
+ )
905
+ continue
906
+ }
907
+ // The rule the kit seeds by, read from the policies and the column list: one rule, so the two cannot drift.
908
+ for (const refusal of applicationRowsPlan(tables, rows).refusals) {
909
+ findings.push(at(`${id}: ${applicationRowRefusalText(refusal)}`, appRowAllowed(refusal)))
910
+ }
911
+ }
912
+ for (const [id, fields] of Object.entries(fixtures.files).sort(byKey)) {
913
+ const row = tested.find((candidate) => candidate.id === id)
914
+ if (row === undefined) {
915
+ findings.push(
916
+ at(
917
+ `${id} is no tested endpoint, whose cases could send a file`,
918
+ "export const files = { '<endpoint id>': { <file field>: '<path from the application root>' } }, for a tested endpoint with a file input",
919
+ ),
920
+ )
921
+ continue
922
+ }
923
+ for (const [field, path] of Object.entries(fields).sort(byKey)) {
924
+ if (fileFieldOf(row.input, field) === undefined) {
925
+ 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'))
926
+ } else if (!isFixtureFilePath(path)) {
927
+ findings.push(
928
+ at(
929
+ `${id}: the file of ${field}, '${path}', is no path inside the application`,
930
+ "a path from the application's root, '/'-separated, without '..', a leading '/' or '.', or characters other than letters, digits, '_', '-' and '.'",
931
+ ),
932
+ )
933
+ }
934
+ }
935
+ }
936
+ for (const [id, types] of Object.entries(fixtures.refusals).sort(byKey)) {
937
+ if (!tested.some((row) => row.id === id)) {
938
+ findings.push(
939
+ at(
940
+ `${id} is no tested endpoint, whose handler a case runs`,
941
+ "export const refusals = { '<endpoint id>': ['<error type>'] }, for a tested endpoint",
942
+ ),
943
+ )
944
+ continue
945
+ }
946
+ for (const type of types) {
947
+ if (!isDeclarableRefusal(type)) {
631
948
  findings.push(
632
949
  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}`,
950
+ `${id}: '${type}' is no refusal of its handler; an input the schema refuses (validation) is the fixture's mistake`,
951
+ "the error type of a 400 the handler throws (new HttpError(400, '<type>', …))",
635
952
  ),
636
953
  )
637
954
  }
@@ -639,6 +956,16 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
639
956
  }
640
957
  const seeded = (row: EndpointRow): boolean =>
641
958
  row.requirement?.kind === 'action' && (row.requirement.access.form === 'on' || row.requirement.access.form === 'in')
959
+ for (const id of Object.keys(fixtures.pins).sort()) {
960
+ if (!tested.some((row) => row.id === id && (seeded(row) || isLinkProcedure(row)))) {
961
+ findings.push(
962
+ at(
963
+ `${id} is no endpoint with an on or in access form, whose row a pin sets`,
964
+ "export const pins = { '<endpoint id>': { <text column>: '<value>' } }",
965
+ ),
966
+ )
967
+ }
968
+ }
642
969
  for (const id of Object.keys(fixtures.seeds).sort()) {
643
970
  if (!tested.some((row) => row.id === id && seeded(row))) {
644
971
  findings.push(