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

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 +323 -61
  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,7 +3,14 @@
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'
6
+ import {
7
+ deniedCaseRuledOutBy,
8
+ GENERATED_FILE_PREFIX,
9
+ GENERATED_INVITATION,
10
+ GENERATED_LINK,
11
+ GENERATED_MEMBER,
12
+ GENERATED_ROW_PREFIX,
13
+ } from '@fabrika/app/contract'
7
14
  import {
8
15
  type ContractArtifact,
9
16
  endpointDirectory,
@@ -13,9 +20,10 @@ import {
13
20
  tableActions,
14
21
  type TablePolicyArtifact,
15
22
  } from '@fabrika/auth-core'
16
- import { tablePolicies } from '@fabrika/db/tables'
23
+ import { type ApplicationRowRefusal, applicationRowRefusalText, applicationRowsPlan, tablePolicies, type Tables } from '@fabrika/db/tables'
17
24
  import { ContractSourceError, readContractSource, readTablesDefinition } from './contract'
18
- import { type EndpointFixtures, isSampleObject, NO_FIXTURES, readEndpointFixtures } from './endpoint-fixtures'
25
+ import { type ApplicationDialect, applicationDialect } from './dialect'
26
+ import { type EndpointFixtures, isFixtureFilePath, isSampleObject, NO_FIXTURES, readEndpointFixtures } from './endpoint-fixtures'
19
27
  import type { Finding } from './finding'
20
28
  import { CONTRACT_FILE, ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR } from './layout'
21
29
 
@@ -29,17 +37,46 @@ export const policyTestPath = (table: string): string => `${POLICY_TESTS_DIR}${t
29
37
  export interface GeneratedTest {
30
38
  readonly text: string
31
39
  readonly cases: readonly string[]
40
+ /** What the test cannot check, one line each, which `fabrika db test-scaffold` prints: a ruled-out capability case. */
41
+ readonly notes: readonly string[]
32
42
  }
33
43
 
34
44
  type Policies = Readonly<Record<string, TablePolicyArtifact>>
35
45
 
46
+ /** The test database kit of each dialect, and the name a generated test gives the database it opens. */
47
+ const TEST_KITS: Readonly<Record<ApplicationDialect, { readonly module: string; readonly name: string }>> = {
48
+ postgres: { module: '@fabrika/db/testing', name: 'postgres' },
49
+ sqlite: { module: '@fabrika/db/testing-sqlite', name: 'database' },
50
+ }
51
+
52
+ /** The lines of a generated test that open its database: the kit's import and the call, against `migrations`. */
53
+ const testDatabaseLines = (
54
+ dialect: ApplicationDialect,
55
+ migrations: string,
56
+ ): { readonly kit: string; readonly open: string; readonly name: string } => {
57
+ const { module, name } = TEST_KITS[dialect]
58
+ return {
59
+ kit: `import { testDatabase } from '${module}'`,
60
+ open: `const ${name} = await testDatabase({ migrations: new URL('${migrations}', import.meta.url), label })`,
61
+ name,
62
+ }
63
+ }
64
+
36
65
  interface Case {
37
66
  readonly name: string
38
67
  readonly lines: readonly string[]
68
+ /** A leak or an own case: it runs the handler for the caller's own scope, which application rows can serve. */
69
+ readonly ownScope?: true
39
70
  }
40
71
 
41
72
  const testCase = (name: string, ...lines: readonly string[]): Case => ({ name, lines })
42
73
 
74
+ /** A case that runs the handler for the caller's own scope: a leak or an own case. */
75
+ const ownScopeCase = (name: string, line: string): Case => ({ name, lines: [line], ownScope: true })
76
+
77
+ /** Orders entries by their key, as every fixture is reported and seeded. */
78
+ const byKey = ([left]: readonly [string, unknown], [right]: readonly [string, unknown]): number => (left < right ? -1 : left > right ? 1 : 0)
79
+
43
80
  const quote = (text: string): string => `'${text.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`
44
81
 
45
82
  const renderCase = (item: Case): string =>
@@ -209,6 +246,7 @@ const policyTestBody = (
209
246
  policies: Policies,
210
247
  table: string,
211
248
  scopedSites: boolean,
249
+ dialect: ApplicationDialect,
212
250
  ): { readonly body: string; readonly cases: readonly string[] } | undefined => {
213
251
  const policy = policies[table]
214
252
  if (policy === undefined) return undefined
@@ -225,6 +263,7 @@ const policyTestBody = (
225
263
  ? `policy of ${table}: only a global holder of its actions reaches a row`
226
264
  : `policy of ${table}: a caller of one ${dimension} reaches no row of another`
227
265
  const kitOf = app ? 'appPolicyIsolationKit' : 'policyIsolationKit'
266
+ const database = testDatabaseLines(dialect, '../../../db/migrations/')
228
267
  const blocks = [describeBlock(title, isolation)]
229
268
  if (hidden.length > 0) blocks.push(describeBlock(`policy of ${table}: a column with its own read action is never returned`, hidden))
230
269
  const body = [
@@ -233,16 +272,16 @@ const policyTestBody = (
233
272
  '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a policy change.',
234
273
  '',
235
274
  `import { ${['afterAll', 'describe', 'expect', kitOf, 'test'].sort().join(', ')} } from '@fabrika/app/testing/isolation'`,
236
- "import { testDatabase } from '@fabrika/db/testing'",
275
+ database.kit,
237
276
  "import { contract } from '../../../fabrika.contract'",
238
277
  "import { tables } from '../tables'",
239
278
  '',
240
279
  `const label = ${quote(`${table}${POLICY_TEST_SUFFIX}`)}`,
241
- "const postgres = await testDatabase({ migrations: new URL('../../../db/migrations/', import.meta.url), label })",
280
+ database.open,
242
281
  '',
243
- 'if (postgres !== null) {',
244
- '\tafterAll(() => postgres.close())',
245
- `\tconst kit = ${kitOf}(contract, tables, ${quote(table)}, postgres)`,
282
+ `if (${database.name} !== null) {`,
283
+ `\tafterAll(() => ${database.name}.close())`,
284
+ `\tconst kit = ${kitOf}(contract, tables, ${quote(table)}, ${database.name})`,
246
285
  '',
247
286
  blocks.join('\n\n'),
248
287
  '}',
@@ -265,7 +304,9 @@ const isLinkProcedure = (row: EndpointRow): boolean =>
265
304
  * The input an endpoint's cases send: the author's fixture, else a sample of its schema; `undefined` when neither
266
305
  * exists. Each field its `members`, `invitations` or `links` name holds `GENERATED_MEMBER`, `GENERATED_INVITATION` or
267
306
  * `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.
307
+ * `rows` name holds `GENERATED_ROW_PREFIX` and the table, which the kit replaces with the key of a row it seeded; each file
308
+ * field its `files` name holds its kind's marker (in a list, for a list of files), even where the sample left an optional
309
+ * one out, which the kit sends as the named file.
269
310
  */
270
311
  const inputOf = (row: EndpointRow, fixtures: EndpointFixtures): Readonly<Record<string, Sample>> | undefined => {
271
312
  const fixture = fixtures.inputs[row.id]
@@ -279,10 +320,83 @@ const inputOf = (row: EndpointRow, fixtures: EndpointFixtures): Readonly<Record<
279
320
  ...generated(fixtures.invitations[row.id], GENERATED_INVITATION),
280
321
  ...generated(fixtures.links[row.id], GENERATED_LINK),
281
322
  ...Object.entries(fixtures.rows[row.id] ?? {}).map(([field, table]) => [field, `${GENERATED_ROW_PREFIX}${table}`]),
323
+ ...Object.keys(fixtures.files[row.id] ?? {}).flatMap((field) => {
324
+ const file = fileFieldOf(row.input, field)
325
+ if (file === undefined) return []
326
+ const marker = `${GENERATED_FILE_PREFIX}${file.kind}`
327
+ return [[field, file.list ? [marker] : marker]]
328
+ }),
282
329
  ]),
283
330
  }
284
331
  }
285
332
 
333
+ /** 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`. */
334
+ const fileFieldOf = (input: SchemaShape | null, field: string): { readonly kind: string; readonly list: boolean } | undefined => {
335
+ const kindOf = (shape: SchemaShape | undefined): string | undefined =>
336
+ shape?.type === 'file' ? shape.kind : shape?.type === 'optional' || shape?.type === 'nullable' ? kindOf(shape.inner) : undefined
337
+ const shape = input?.type === 'object' ? input.fields[field] : undefined
338
+ const unwrapped = shape?.type === 'optional' || shape?.type === 'nullable' ? shape.inner : shape
339
+ if (unwrapped?.type === 'array') {
340
+ const kind = kindOf(unwrapped.items)
341
+ return kind === undefined ? undefined : { kind, list: true }
342
+ }
343
+ const kind = kindOf(shape)
344
+ return kind === undefined ? undefined : { kind, list: false }
345
+ }
346
+
347
+ /** The ids of the endpoints with endpoint access cases. */
348
+ const testedEndpoints = (artifact: ContractArtifact): ReadonlySet<string> =>
349
+ new Set(artifact.endpoints.filter((row) => isAccessTested(row) || isLinkProcedure(row)).map((row) => row.id))
350
+
351
+ /** How a generated endpoint access test reaches the application's root, where a file fixture's path starts. */
352
+ const ROOT_FROM_ENDPOINT_TEST = '../'.repeat(ENDPOINT_ACCESS_TEST.split('/').length - 1)
353
+
354
+ /**
355
+ * The options of the generated test's kit: the file fixtures of the tested endpoints, each a URL beside the test. Empty
356
+ * without any, so a test without file fixtures stays as it was.
357
+ */
358
+ const kitOptions = (fixtures: EndpointFixtures, tested: ReadonlySet<string>): string => {
359
+ const files = Object.entries(fixtures.files).sort(byKey).flatMap(([id, fields]) => {
360
+ const valid = Object.entries(fields).sort(byKey).filter(([, path]) => isFixtureFilePath(path))
361
+ if (!tested.has(id) || valid.length === 0) return []
362
+ const rendered = valid.map(([field, path]) => `${renderKey(field)}: new URL(${quote(`${ROOT_FROM_ENDPOINT_TEST}${path}`)}, import.meta.url)`)
363
+ return [`${quote(id)}: { ${rendered.join(', ')} }`]
364
+ })
365
+ const refusals = Object.entries(fixtures.refusals).sort(byKey).flatMap(([id, types]) => {
366
+ const valid = types.filter(isDeclarableRefusal)
367
+ return tested.has(id) && valid.length > 0 ? [`${quote(id)}: [${valid.map(quote).join(', ')}]`] : []
368
+ })
369
+ const pins = Object.entries(fixtures.pins).sort(byKey).flatMap(([id, columns]) => {
370
+ const entries = Object.entries(columns).sort(byKey)
371
+ return tested.has(id) && entries.length > 0
372
+ ? [`${quote(id)}: { ${entries.map(([column, value]) => `${renderKey(column)}: ${quote(value)}`).join(', ')} }`]
373
+ : []
374
+ })
375
+ const options = [
376
+ ...(files.length === 0 ? [] : [`files: { ${files.join(', ')} }`]),
377
+ ...(refusals.length === 0 ? [] : [`refusals: { ${refusals.join(', ')} }`]),
378
+ ...(pins.length === 0 ? [] : [`pins: { ${pins.join(', ')} }`]),
379
+ ]
380
+ return options.length === 0 ? '' : `, { ${options.join(', ')} }`
381
+ }
382
+
383
+ /** A refusal the fixtures may declare: a handler's own error type, never the input schema's (`validation`). */
384
+ const isDeclarableRefusal = (type: string): boolean => type !== '' && type !== 'validation'
385
+
386
+ /**
387
+ * The own case of an endpoint: 200, or, where its fixtures declare the refusals its handler may answer its own object
388
+ * with, also the 400 the kit hands back only for one of them.
389
+ */
390
+ const ownCase = (row: EndpointRow, fixtures: EndpointFixtures, name: string, args: string): Case => {
391
+ const declared = (fixtures.refusals[row.id] ?? []).filter(isDeclarableRefusal)
392
+ return declared.length === 0
393
+ ? ownScopeCase(name, `expect(await kit.own(${args})).toEqual({ status: 200 })`)
394
+ : ownScopeCase(`${name} (200, or a refusal its fixtures declare)`, `expect([200, 400]).toContain((await kit.own(${args})).status)`)
395
+ }
396
+
397
+ /** An object key as `renderSample` writes one: bare when it is an identifier, else quoted. */
398
+ const renderKey = (key: string): string => (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : quote(key))
399
+
286
400
  /** Whether the endpoint's handler gets `ctx.links`: on or in a dimension a link mount's `issuedBy` names its action for. */
287
401
  const issuesLinks = (artifact: ContractArtifact, row: EndpointRow): boolean => {
288
402
  if (row.requirement?.kind !== 'action') return false
@@ -313,6 +427,17 @@ const ownerRead = (policies: Policies, dimension: string): string | undefined =>
313
427
  Object.values(policies).find((policy) => policy.scope.mode === 'dimension' && policy.scope.dimension === dimension)?.actions.read ?? null,
314
428
  )[0]
315
429
 
430
+ /**
431
+ * Whether an endpoint gets the `own` case: `on` an object a table owns, as a link procedure or with an action other
432
+ * than the owner's read action (a caller holding only that one reaches every object, which proves nothing).
433
+ */
434
+ const hasOwnCase = (row: EndpointRow, policies: Policies): boolean => {
435
+ if (row.requirement?.kind !== 'action') return false
436
+ const { access, action } = row.requirement
437
+ const read = access.form === 'on' ? ownerRead(policies, access.dimension) : undefined
438
+ return read !== undefined && (isLinkProcedure(row) || read !== action)
439
+ }
440
+
316
441
  /**
317
442
  * What the `own` case's caller holds: the endpoint's action, plus what IAM requires of a link's issuer (the actions the
318
443
  * link grants) and of a member manager (an assigning role and the assigned role's actions).
@@ -341,21 +466,27 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
341
466
  const seed = fixtures.seeds[row.id]
342
467
  const args = `${quote(row.id)}, ${renderSample(input)}`
343
468
  const seeded = seed === undefined ? args : `${args}, ${renderSample(seed)}`
469
+ // The application rows reach every case that runs the handler on the caller's own object: its leak cases and its own
470
+ // case. Only an endpoint with them gets the fourth argument, so every other generated file stays as it was.
471
+ const appRows = fixtures.appRows[row.id]
472
+ const rowsTail = appRows === undefined ? '' : `, ${renderSample(appRows)}`
473
+ const unseededArgs = appRows === undefined ? args : `${args}, {}${rowsTail}`
474
+ const seededArgs = seed === undefined ? unseededArgs : `${seeded}${rowsTail}`
344
475
  const declared = artifact.declared?.[row.id]
345
476
  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)
477
+ const own = hasOwnCase(row, policies)
348
478
  const cases: Case[] = []
349
- // The unseeded probe always runs: a seed meets a precondition, and must not also set aside the state that leaks.
479
+ // The unseeded probe always runs: a seed meets a precondition, and must not also set aside the state that leaks. The
480
+ // application rows reach it too: they are rows of the whole application, which the handler needs to answer at all.
350
481
  const leaked = (): Case[] => [
351
- testCase(
482
+ ownScopeCase(
352
483
  `${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: [] })`,
484
+ `expect(await kit.leaked(${unseededArgs})).toEqual({ answered: true, leaked: [] })`,
354
485
  ),
355
486
  ...(seed === undefined ? [] : [
356
- testCase(
487
+ ownScopeCase(
357
488
  `${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: [] })`,
489
+ `expect(await kit.leaked(${seededArgs})).toEqual({ answered: true, leaked: [] })`,
359
490
  ),
360
491
  ]),
361
492
  ]
@@ -379,9 +510,7 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
379
510
  }
380
511
  if (linked) {
381
512
  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
- )
513
+ cases.push(ownCase(row, fixtures, `${row.id}: the holder of a link to a ${access.dimension} reaches it`, seededArgs))
385
514
  }
386
515
  return cases
387
516
  }
@@ -390,9 +519,11 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
390
519
  if (!unscoped) cases.push(...leaked())
391
520
  if (own) {
392
521
  cases.push(
393
- testCase(
522
+ ownCase(
523
+ row,
524
+ fixtures,
394
525
  `${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 })`,
526
+ seededArgs,
396
527
  ),
397
528
  )
398
529
  }
@@ -407,25 +538,47 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
407
538
 
408
539
  /**
409
540
  * 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`).
541
+ * object of another scope is 404 (`on`), a value of another scope 403 (`in`), and a caller without the action 403
542
+ * (`over`). An `over` capability whose action another one needs in a related dimension has none (`deniedCaseRuledOutBy`);
543
+ * `notes` says so for each, in the generated test and in `fabrika db test-scaffold`'s output.
411
544
  */
412
- const capabilityCases = (row: EndpointRow, fixtures: EndpointFixtures): readonly Case[] => {
413
- if (row.requirement?.kind !== 'capabilities' || !row.callers.some((caller) => caller === 'human' || caller === 'machine')) return []
545
+ const capabilityCases = (
546
+ row: EndpointRow,
547
+ artifact: ContractArtifact,
548
+ fixtures: EndpointFixtures,
549
+ ): { readonly cases: readonly Case[]; readonly notes: readonly string[] } => {
550
+ if (row.requirement?.kind !== 'capabilities' || !row.callers.some((caller) => caller === 'human' || caller === 'machine')) {
551
+ return { cases: [], notes: [] }
552
+ }
414
553
  const input = inputOf(row, fixtures)
415
- if (input === undefined) return []
554
+ if (input === undefined) return { cases: [], notes: [] }
416
555
  const seed = fixtures.seeds[row.id]
417
- return Object.entries(row.requirement.capabilities).map(([name, { action, access }]) => {
556
+ const { capabilities } = row.requirement
557
+ const cases: Case[] = []
558
+ const notes: string[] = []
559
+ for (const [name, { action, access }] of Object.entries(capabilities)) {
418
560
  const args = `${quote(row.id)}, ${quote(name)}, ${renderSample(input)}${seed === undefined ? '' : `, ${renderSample(seed)}`}`
419
561
  const call = `await kit.capability(${args})`
420
562
  if (access.form === 'over') {
421
- return testCase(`${row.id}: a caller without ${action} (capability ${name}) is 403`, `expect(${call}).toEqual({ status: 403 })`)
563
+ const ruledOutBy = deniedCaseRuledOutBy(capabilities, name, artifact.dimensions)
564
+ if (ruledOutBy === undefined) {
565
+ cases.push(testCase(`${row.id}: a caller without ${action} (capability ${name}) is 403`, `expect(${call}).toEqual({ status: 403 })`))
566
+ } else {
567
+ notes.push(
568
+ `${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`,
569
+ )
570
+ }
571
+ continue
422
572
  }
423
573
  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} })`,
574
+ cases.push(
575
+ testCase(
576
+ `${row.id}: the ${access.dimension} of another scope as capability ${name} is ${status}`,
577
+ `expect(${call}).toEqual({ status: ${status} })`,
578
+ ),
427
579
  )
428
- })
580
+ }
581
+ return { cases, notes }
429
582
  }
430
583
 
431
584
  /**
@@ -447,20 +600,26 @@ const publicCases = (row: EndpointRow, artifact: ContractArtifact, fixtures: End
447
600
  ]
448
601
  }
449
602
 
603
+ /** The endpoints of the artifact by id, the order of their cases. */
604
+ const sortedEndpoints = (artifact: ContractArtifact): readonly EndpointRow[] =>
605
+ [...artifact.endpoints].sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))
606
+
450
607
  /** The endpoint access test of the application, or `undefined` when no endpoint has an access form to test. */
451
608
  const endpointTestBody = (
452
609
  artifact: ContractArtifact,
453
610
  policies: Policies,
454
611
  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
- ])
612
+ dialect: ApplicationDialect,
613
+ ): { readonly body: string; readonly cases: readonly string[]; readonly notes: readonly string[] } | undefined => {
614
+ const cases: Case[] = []
615
+ const notes: string[] = []
616
+ for (const row of sortedEndpoints(artifact)) {
617
+ const capability = capabilityCases(row, artifact, fixtures)
618
+ cases.push(...endpointCases(row, artifact, policies, fixtures), ...capability.cases, ...publicCases(row, artifact, fixtures))
619
+ notes.push(...capability.notes)
620
+ }
463
621
  if (cases.length === 0) return undefined
622
+ const database = testDatabaseLines(dialect, '../../db/migrations/')
464
623
  const body = [
465
624
  '// The endpoint access tests of this application, written by fabrika db test-scaffold from fabrika.contract.ts and',
466
625
  '// 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 +627,91 @@ const endpointTestBody = (
468
627
  '// issuer, asks for its own object. A handler bug that needs other data or another order is beyond them; the state a',
469
628
  '// precondition needs is a seed in endpoint-access.fixtures.ts.',
470
629
  '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a contract change.',
630
+ ...notes.map((note) => `// Not checked: ${note}.`),
471
631
  '',
472
632
  "import { afterAll, describe, endpointAccessKit, expect, test } from '@fabrika/app/testing/isolation'",
473
- "import { testDatabase } from '@fabrika/db/testing'",
633
+ database.kit,
474
634
  "import app from '../app'",
475
635
  "import { tables } from '../db/tables'",
476
636
  '',
477
637
  "const label = 'endpoint-access.test.ts'",
478
- "const postgres = await testDatabase({ migrations: new URL('../../db/migrations/', import.meta.url), label })",
638
+ database.open,
479
639
  '',
480
- 'if (postgres !== null) {',
481
- '\tafterAll(() => postgres.close())',
482
- '\tconst kit = endpointAccessKit(app, tables, postgres)',
640
+ `if (${database.name} !== null) {`,
641
+ `\tafterAll(() => ${database.name}.close())`,
642
+ `\tconst kit = endpointAccessKit(app, tables, ${database.name}${kitOptions(fixtures, testedEndpoints(artifact))})`,
483
643
  '',
484
644
  describeBlock('endpoints: a caller of one scope reaches nothing of another', cases),
485
645
  '}',
486
646
  '',
487
647
  ].join('\n')
488
- return { body, cases: cases.map((item) => item.name) }
648
+ return { body, cases: cases.map((item) => item.name), notes }
489
649
  }
490
650
 
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
- })
651
+ const generated = async (
652
+ { body, cases, notes = [] }: { readonly body: string; readonly cases: readonly string[]; readonly notes?: readonly string[] },
653
+ ): Promise<GeneratedTest> => ({ text: `${await generatedTestHeader(body)}\n${body}`, cases, notes })
495
654
 
496
655
  /**
497
656
  * 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.
657
+ * Endpoint access tests exist only for an application on `@fabrika/db`, which has policies to seed rows from. They
658
+ * open the test database of the application's dialect.
499
659
  */
500
660
  export const generatedTests = async (
501
661
  policies: Policies,
502
662
  artifact: ContractArtifact | null,
503
663
  fixtures: EndpointFixtures = NO_FIXTURES,
664
+ dialect: ApplicationDialect = 'postgres',
504
665
  ): Promise<ReadonlyMap<string, GeneratedTest>> => {
505
666
  const files = new Map<string, GeneratedTest>()
506
667
  // The kit's scoped sites are `over` the vocabulary's first dimension: without one, no scoped site exists.
507
668
  const scopedSites = artifact !== null && Object.keys(artifact.dimensions).length > 0
508
669
  for (const table of Object.keys(policies).sort()) {
509
- const test = policyTestBody(policies, table, scopedSites)
670
+ const test = policyTestBody(policies, table, scopedSites, dialect)
510
671
  if (test !== undefined) files.set(policyTestPath(table), await generated(test))
511
672
  }
512
- const endpoints = artifact === null || files.size === 0 ? undefined : endpointTestBody(artifact, policies, fixtures)
673
+ const endpoints = artifact === null || files.size === 0 ? undefined : endpointTestBody(artifact, policies, fixtures, dialect)
513
674
  if (endpoints !== undefined) files.set(ENDPOINT_ACCESS_TEST, await generated(endpoints))
514
675
  return files
515
676
  }
516
677
 
517
678
  export interface ScaffoldInputs {
679
+ /** What `src/db/tables.ts` defines, its column list included; `null` without the file. */
680
+ readonly tables: Tables<unknown, unknown> | null
518
681
  readonly policies: Policies
519
682
  readonly artifact: ContractArtifact | null
520
683
  readonly fixtures: EndpointFixtures
684
+ readonly dialect: ApplicationDialect
685
+ }
686
+
687
+ /**
688
+ * Whether an endpoint's generated cases run its handler for the caller's own scope, which application rows can serve: a
689
+ * leak or an own case, read off the cases `endpointCases` writes. An input it lacks a fixture for does not matter here.
690
+ */
691
+ const runsOnOwnScope = (row: EndpointRow, artifact: ContractArtifact, policies: Policies, fixtures: EndpointFixtures): boolean => {
692
+ const withInput = { ...fixtures, inputs: { ...fixtures.inputs, [row.id]: fixtures.inputs[row.id] ?? {} } }
693
+ return endpointCases(row, artifact, policies, withInput).some((item) => item.ownScope === true)
694
+ }
695
+
696
+ /** The allowed form of an `appRows` entry `applicationRowsPlan` refuses; the message is the kit's own words. */
697
+ const appRowAllowed = (refusal: ApplicationRowRefusal): string => {
698
+ switch (refusal.kind) {
699
+ case 'table':
700
+ return refusal.mode === null
701
+ ? 'the name of a table with scope: { app } in src/db/tables.ts'
702
+ : "rows, for a row in the endpoint's object; seeds, for the state of the object's own row"
703
+ case 'column':
704
+ return `a column of ${refusal.table} in src/db/schema.generated.ts`
705
+ case 'stamped':
706
+ case 'file':
707
+ return "the row's other columns"
708
+ case 'value':
709
+ return 'a string, a number, a boolean or null'
710
+ case 'partial-key':
711
+ return `all of ${refusal.key.columns.join(', ')}, or none, which the kit then fills`
712
+ case 'cycle':
713
+ return 'a value for one of the foreign keys (null, where it may be), which the kit then does not fill'
714
+ }
521
715
  }
522
716
 
523
717
  /** What the scaffold reads from an application's files; throws `ContractSourceError` or `ContractError` as the reader does. */
@@ -528,15 +722,15 @@ export const scaffoldInputs = (files: ReadonlyMap<string, string>): ScaffoldInpu
528
722
  if (!fixtures.ok) throw new ContractSourceError(fixtures.findings)
529
723
  // Endpoint tests seed rows from the policies, so without src/db/tables.ts there is nothing to compile them against.
530
724
  const artifact = files.has(CONTRACT_FILE) && tables !== null ? readContractSource(files, tables) : null
531
- return { policies, artifact, fixtures: fixtures.fixtures }
725
+ return { tables, policies, artifact, fixtures: fixtures.fixtures, dialect: applicationDialect(files) }
532
726
  }
533
727
 
534
728
  /**
535
729
  * What stops the endpoint access tests from covering every endpoint: one whose input the scaffold cannot sample and
536
730
  * the author gave no fixture, and a fixture of no tested endpoint. Each is an `endpoint-fixture` finding.
537
731
  */
538
- export const missingEndpointFixtures = ({ policies, artifact, fixtures }: ScaffoldInputs): readonly Finding[] => {
539
- if (artifact === null || Object.keys(policies).length === 0) return []
732
+ export const missingEndpointFixtures = ({ tables, policies, artifact, fixtures }: ScaffoldInputs): readonly Finding[] => {
733
+ if (artifact === null || tables === null || Object.keys(policies).length === 0) return []
540
734
  const at = (message: string, allowed: string): Finding => ({
541
735
  file: ENDPOINT_FIXTURES_FILE,
542
736
  line: 1,
@@ -560,7 +754,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
560
754
  )
561
755
  }
562
756
  }
563
- for (const [id, fields] of Object.entries(fixtures.members).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
757
+ for (const [id, fields] of Object.entries(fixtures.members).sort(byKey)) {
564
758
  const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate))
565
759
  const directory = row === undefined ? null : endpointDirectory(artifact, row)
566
760
  if (row === undefined || directory === null) {
@@ -579,8 +773,6 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
579
773
  }
580
774
  }
581
775
  }
582
- const sortedById = (fields: Readonly<Record<string, readonly string[]>>) =>
583
- Object.entries(fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
584
776
  const holders = [
585
777
  {
586
778
  fields: fixtures.invitations,
@@ -598,7 +790,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
598
790
  },
599
791
  ]
600
792
  for (const holder of holders) {
601
- for (const [id, fields] of sortedById(holder.fields)) {
793
+ for (const [id, fields] of Object.entries(holder.fields).sort(byKey)) {
602
794
  const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate) && holder.admits(candidate))
603
795
  if (row === undefined) {
604
796
  findings.push(at(holder.refusal(id), holder.allowed))
@@ -611,7 +803,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
611
803
  }
612
804
  }
613
805
  }
614
- for (const [id, fields] of Object.entries(fixtures.rows).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
806
+ for (const [id, fields] of Object.entries(fixtures.rows).sort(byKey)) {
615
807
  const row = tested.find((candidate) => candidate.id === id)
616
808
  const access = row?.requirement?.kind === 'action' ? row.requirement.access : undefined
617
809
  const owned = access?.form === 'on' && ownerRead(policies, access.dimension) !== undefined
@@ -624,7 +816,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
624
816
  )
625
817
  continue
626
818
  }
627
- for (const [field, table] of Object.entries(fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
819
+ for (const [field, table] of Object.entries(fields).sort(byKey)) {
628
820
  if (row.input?.type !== 'object' || !admitsString(row.input.fields[field])) {
629
821
  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
822
  } else if (!liesDirectlyIn(policies, table, access.dimension)) {
@@ -637,8 +829,78 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
637
829
  }
638
830
  }
639
831
  }
832
+ for (const [id, rows] of Object.entries(fixtures.appRows).sort(byKey)) {
833
+ if (!tested.some((row) => row.id === id && runsOnOwnScope(row, artifact, policies, fixtures))) {
834
+ findings.push(
835
+ at(
836
+ `${id} is no endpoint with a leak or an own case, whose handler could read an application row the kit seeds`,
837
+ "export const appRows = { '<endpoint id>': { <table>: { <column>: <value> } } }, for an endpoint on, in or over a scope",
838
+ ),
839
+ )
840
+ continue
841
+ }
842
+ // The rule the kit seeds by, read from the policies and the column list: one rule, so the two cannot drift.
843
+ for (const refusal of applicationRowsPlan(tables, rows).refusals) {
844
+ findings.push(at(`${id}: ${applicationRowRefusalText(refusal)}`, appRowAllowed(refusal)))
845
+ }
846
+ }
847
+ for (const [id, fields] of Object.entries(fixtures.files).sort(byKey)) {
848
+ const row = tested.find((candidate) => candidate.id === id)
849
+ if (row === undefined) {
850
+ findings.push(
851
+ at(
852
+ `${id} is no tested endpoint, whose cases could send a file`,
853
+ "export const files = { '<endpoint id>': { <file field>: '<path from the application root>' } }, for a tested endpoint with a file input",
854
+ ),
855
+ )
856
+ continue
857
+ }
858
+ for (const [field, path] of Object.entries(fields).sort(byKey)) {
859
+ if (fileFieldOf(row.input, field) === undefined) {
860
+ 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'))
861
+ } else if (!isFixtureFilePath(path)) {
862
+ findings.push(
863
+ at(
864
+ `${id}: the file of ${field}, '${path}', is no path inside the application`,
865
+ "a path from the application's root, '/'-separated, without '..', a leading '/' or '.', or characters other than letters, digits, '_', '-' and '.'",
866
+ ),
867
+ )
868
+ }
869
+ }
870
+ }
871
+ for (const [id, types] of Object.entries(fixtures.refusals).sort(byKey)) {
872
+ if (!tested.some((row) => row.id === id)) {
873
+ findings.push(
874
+ at(
875
+ `${id} is no tested endpoint, whose handler a case runs`,
876
+ "export const refusals = { '<endpoint id>': ['<error type>'] }, for a tested endpoint",
877
+ ),
878
+ )
879
+ continue
880
+ }
881
+ for (const type of types) {
882
+ if (!isDeclarableRefusal(type)) {
883
+ findings.push(
884
+ at(
885
+ `${id}: '${type}' is no refusal of its handler; an input the schema refuses (validation) is the fixture's mistake`,
886
+ "the error type of a 400 the handler throws (new HttpError(400, '<type>', …))",
887
+ ),
888
+ )
889
+ }
890
+ }
891
+ }
640
892
  const seeded = (row: EndpointRow): boolean =>
641
893
  row.requirement?.kind === 'action' && (row.requirement.access.form === 'on' || row.requirement.access.form === 'in')
894
+ for (const id of Object.keys(fixtures.pins).sort()) {
895
+ if (!tested.some((row) => row.id === id && (seeded(row) || isLinkProcedure(row)))) {
896
+ findings.push(
897
+ at(
898
+ `${id} is no endpoint with an on or in access form, whose row a pin sets`,
899
+ "export const pins = { '<endpoint id>': { <text column>: '<value>' } }",
900
+ ),
901
+ )
902
+ }
903
+ }
642
904
  for (const id of Object.keys(fixtures.seeds).sort()) {
643
905
  if (!tested.some((row) => row.id === id && seeded(row))) {
644
906
  findings.push(
package/src/trust.ts CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import type { Finding } from './finding'
6
6
  import { parseJsonc } from './jsonc'
7
- import { isIgnoredSegment, isRelativeSpecifier, isSourceFile, joinRelative } from './layout'
7
+ import { isIgnoredSegment, isRelativeSpecifier, isSourceFile, isToolModule, joinRelative } from './layout'
8
8
  import { isKey, parseToml } from './toml'
9
9
 
10
10
  /** Packages whose exports the reader trusts by name, and the packages they rely on. */
@@ -141,11 +141,15 @@ function checkTsconfig(path: string, text: string, files: ReadonlyMap<string, st
141
141
  }
142
142
  }
143
143
 
144
- /** A test preload must be a checked application file: a skipped or generated one runs unchecked during the build. */
144
+ /**
145
+ * A test preload must be a checked application file: a skipped or generated one runs unchecked during the build, and a
146
+ * developer's tool is not checked as application code.
147
+ */
145
148
  const isCheckedTestPreload = (target: string): boolean => {
146
149
  if (!target.startsWith('./')) return false
147
150
  const segments = target.slice(2).split('/')
148
- return segments[0] !== 'fabrika' && segments.every((segment) => segment !== '' && segment !== '..' && !isIgnoredSegment(segment))
151
+ return segments[0] !== 'fabrika' && !isToolModule(target.slice(2))
152
+ && segments.every((segment) => segment !== '' && segment !== '..' && !isIgnoredSegment(segment))
149
153
  && isSourceFile(target)
150
154
  }
151
155
 
@@ -180,7 +184,7 @@ function checkBunfig(text: string, report: (needle: string, message: string, all
180
184
  report(
181
185
  at(entry.line),
182
186
  'a test preload outside the checked application files runs unchecked in the platform build',
183
- "'./<path>' of a source file the checker reads, outside fabrika/, dist/, node_modules/ and dot directories",
187
+ "'./<path>' of a source file the checker reads, outside fabrika/, tools/, dist/, node_modules/ and dot directories",
184
188
  )
185
189
  }
186
190
  }