@fabrika/check 0.8.2 → 0.9.0-cloudflare.2

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 (63) hide show
  1. package/package.json +12 -11
  2. package/src/check.ts +49 -12
  3. package/src/dialect.ts +29 -0
  4. package/src/endpoint-fixtures.ts +99 -13
  5. package/src/finding.ts +7 -3
  6. package/src/index.ts +2 -1
  7. package/src/layout.ts +8 -1
  8. package/src/reader/surface.ts +16 -1
  9. package/src/resolution.ts +2 -2
  10. package/src/rules/cloudflare.ts +58 -0
  11. package/src/rules/framework.ts +2 -2
  12. package/src/rules/isolation.ts +5 -1
  13. package/src/rules/migrations.ts +31 -0
  14. package/src/rules/modules.ts +9 -3
  15. package/src/rules/runtime.ts +7 -3
  16. package/src/scaffold.ts +265 -38
  17. package/types/src/ast.d.ts +65 -0
  18. package/types/src/bun-plugin.d.ts +12 -0
  19. package/types/src/check.d.ts +19 -0
  20. package/types/src/cli.d.ts +2 -0
  21. package/types/src/contract.d.ts +58 -0
  22. package/types/src/dialect.d.ts +8 -0
  23. package/types/src/endpoint-fixtures.d.ts +54 -0
  24. package/types/src/finding.d.ts +39 -0
  25. package/types/src/graph.d.ts +68 -0
  26. package/types/src/index.d.ts +7 -0
  27. package/types/src/inputs.d.ts +9 -0
  28. package/types/src/jsonc.d.ts +2 -0
  29. package/types/src/layout.d.ts +69 -0
  30. package/types/src/limits.d.ts +15 -0
  31. package/types/src/lockfile.d.ts +19 -0
  32. package/types/src/packed.d.ts +15 -0
  33. package/types/src/reader/problems.d.ts +7 -0
  34. package/types/src/reader/schema.d.ts +18 -0
  35. package/types/src/reader/surface.d.ts +5 -0
  36. package/types/src/reader/tables.d.ts +6 -0
  37. package/types/src/reader/value.d.ts +113 -0
  38. package/types/src/references.d.ts +15 -0
  39. package/types/src/resolution.d.ts +20 -0
  40. package/types/src/rules/cloudflare.d.ts +9 -0
  41. package/types/src/rules/contract.d.ts +8 -0
  42. package/types/src/rules/crontab.d.ts +15 -0
  43. package/types/src/rules/framework.d.ts +19 -0
  44. package/types/src/rules/identity.d.ts +5 -0
  45. package/types/src/rules/isolation.d.ts +18 -0
  46. package/types/src/rules/json.d.ts +3 -0
  47. package/types/src/rules/literal.d.ts +63 -0
  48. package/types/src/rules/migrations.d.ts +34 -0
  49. package/types/src/rules/modules.d.ts +12 -0
  50. package/types/src/rules/packages.d.ts +7 -0
  51. package/types/src/rules/runtime.d.ts +32 -0
  52. package/types/src/rules/structure.d.ts +36 -0
  53. package/types/src/rules/tests.d.ts +22 -0
  54. package/types/src/rules/types.d.ts +4 -0
  55. package/types/src/scaffold-sample.d.ts +8 -0
  56. package/types/src/scaffold.d.ts +34 -0
  57. package/types/src/scope.d.ts +6 -0
  58. package/types/src/slice.d.ts +30 -0
  59. package/types/src/source-maps-cli.d.ts +4 -0
  60. package/types/src/source-maps.d.ts +32 -0
  61. package/types/src/toml.d.ts +30 -0
  62. package/types/src/trust.d.ts +15 -0
  63. package/types/src/version.d.ts +2 -0
@@ -79,7 +79,7 @@ export const trustedBindings = (file: string, program: AstNode, mappings: Import
79
79
  }
80
80
 
81
81
  /**
82
- * The trusted binding a member chain starts from (`Database.postgres`, `db['Database'].postgres` → `Database`, `db`),
82
+ * The trusted binding a member chain starts from (`Database.fromEngine`, `db['Database'].fromEngine` → `Database`, `db`),
83
83
  * when the name at `ancestors` denotes that declaration and no local that shadows it.
84
84
  */
85
85
  const trustedRoot = (
@@ -135,7 +135,7 @@ const WRITERS = new Set([
135
135
 
136
136
  /**
137
137
  * A write to a member of a value from `@fabrika/*` or `zod`: an assignment, `delete`, `++`, or a writer call on it. A
138
- * replaced `Database.postgres` receives the database URL; a patched schema changes what the contract admits. A write
138
+ * replaced `openPostgres` receives the database URL; a patched schema changes what the contract admits. A write
139
139
  * through a prototype is `prototype-assignment`'s. A local that shadows such a name is not one.
140
140
  */
141
141
  export const checkFrameworkWrite = (node: AstNode, ancestors: readonly AstNode[], bindings: TrustedBindings, report: Report): void => {
@@ -33,7 +33,11 @@ export const expectedGeneratedTests = async (
33
33
  > => {
34
34
  try {
35
35
  const inputs = scaffoldInputs(files)
36
- return { ok: true, tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures), missing: missingEndpointFixtures(inputs) }
36
+ return {
37
+ ok: true,
38
+ tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures, inputs.dialect),
39
+ missing: missingEndpointFixtures(inputs),
40
+ }
37
41
  } catch (error) {
38
42
  if (error instanceof ContractSourceError) return { ok: false, findings: error.findings }
39
43
  if (error instanceof ContractError) {
@@ -43,6 +43,37 @@ export const checkMigrationNames = (paths: readonly string[]): Finding[] => {
43
43
  return findings
44
44
  }
45
45
 
46
+ /** The default a SQLite timestamp column takes: the UTC ISO text every read of the table parses. */
47
+ const SQLITE_NOW_DEFAULT = "DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
48
+
49
+ /**
50
+ * On SQLite `DEFAULT CURRENT_TIMESTAMP` stores `YYYY-MM-DD HH:MM:SS`, which every read of the table refuses as
51
+ * `unexpected_row` (backlog 216 item 13). Refused with or without parentheses, at the line of `CURRENT_TIMESTAMP`.
52
+ */
53
+ export const checkCurrentTimestampDefaults = (files: ReadonlyMap<string, string>): Finding[] => {
54
+ const findings: Finding[] = []
55
+ for (const [path, sql] of files) {
56
+ if (!path.startsWith(MIGRATIONS_DIR) || !path.endsWith('.sql')) continue
57
+ for (const { tokens } of topLevelStatements(sql)) {
58
+ tokens.forEach((token, index) => {
59
+ if (upperWord(token) !== 'DEFAULT') return
60
+ const value = isPunct(tokens[index + 1], '(') ? tokens[index + 2] : tokens[index + 1]
61
+ if (value === undefined || upperWord(value) !== 'CURRENT_TIMESTAMP') return
62
+ findings.push({
63
+ file: path,
64
+ line: value.line,
65
+ column: 1,
66
+ severity: 'refusal',
67
+ rule: 'cloudflare-current-timestamp',
68
+ message: 'DEFAULT CURRENT_TIMESTAMP stores YYYY-MM-DD HH:MM:SS on SQLite, which every read of the table refuses as unexpected_row',
69
+ allowed: SQLITE_NOW_DEFAULT,
70
+ })
71
+ })
72
+ }
73
+ }
74
+ return findings
75
+ }
76
+
46
77
  /** A declared file column: `table.column` holds files of `kind`. */
47
78
  export interface FileColumn {
48
79
  readonly table: string
@@ -1,5 +1,5 @@
1
1
  import type { Report } from '../finding'
2
- import { isIgnoredSegment, isRelativeSpecifier, isTestFile, joinRelative, resolveRelative } from '../layout'
2
+ import { isRelativeSpecifier, isSkippedPath, isTestFile, joinRelative, resolveRelative } from '../layout'
3
3
  import type { ModuleReference } from '../references'
4
4
  import { type ImportMappings, mappedTargets } from '../resolution'
5
5
 
@@ -15,6 +15,11 @@ const NETWORK: Forbidden = {
15
15
  what: 'a raw network module',
16
16
  allowed: 'endpoints declared in the contract; another application through a connector import',
17
17
  }
18
+ /** `Bun.fetch`: Bun's own `fetch`, which the egress guard on the global one does not wrap. */
19
+ const BUN_FETCH: Forbidden = {
20
+ what: "Bun's own fetch, past the egress guard",
21
+ allowed: "the global fetch, under the site's egress: ['<origin>'] or a cron job's egress: 'public'",
22
+ }
18
23
  const PROCESSES: Forbidden = { what: 'a process-spawning module', allowed: 'a job declared in the contract (c.cron)' }
19
24
 
20
25
  const FORBIDDEN_PACKAGES: ReadonlyMap<string, Forbidden> = new Map([
@@ -78,6 +83,7 @@ export const FORBIDDEN_BUN_MEMBERS: ReadonlyMap<string, Forbidden> = new Map([
78
83
  ...['sql', 'SQL'].map((name): [string, Forbidden] => [name, DATABASE]),
79
84
  ...['S3Client', 's3'].map((name): [string, Forbidden] => [name, STORAGE]),
80
85
  ...['serve', 'connect', 'listen', 'udpSocket'].map((name): [string, Forbidden] => [name, NETWORK]),
86
+ ['fetch', BUN_FETCH],
81
87
  ...['spawn', 'spawnSync', '$'].map((name): [string, Forbidden] => [name, PROCESSES]),
82
88
  ])
83
89
 
@@ -94,7 +100,7 @@ const ALLOWED_ENV = 'values the framework hands the handler through deps or ctx'
94
100
  * The test kits: the application's signs tokens with its own key and boots the application a second way; the
95
101
  * database's reaches tables by name and seeds rows past the data layer. Production never loads either.
96
102
  */
97
- const TEST_KITS = ['@fabrika/app/testing', '@fabrika/app/react/testing', '@fabrika/db/testing']
103
+ const TEST_KITS = ['@fabrika/app/testing', '@fabrika/app/react/testing', '@fabrika/db/testing', '@fabrika/db/testing-sqlite']
98
104
  const TEST_ONLY_ALLOWED = 'the kit in a test file (*.test.ts, *.spec.ts or a __tests__ directory) only'
99
105
 
100
106
  export const isTestKit = (specifier: string): boolean => TEST_KITS.some((kit) => specifier === kit || specifier.startsWith(`${kit}/`))
@@ -114,7 +120,7 @@ const checkTestOnly = (reference: ModuleReference, target: string, report: Repor
114
120
  /** A path from the root that a mapping or an import lands on, judged by where the checker reads. */
115
121
  const containmentProblem = (target: string | undefined): string | undefined => {
116
122
  if (target === undefined) return 'resolves outside the application root, where the checker does not look'
117
- if (target.split('/').some(isIgnoredSegment)) return 'resolves into a directory the checker skips'
123
+ if (isSkippedPath(target)) return 'resolves into a directory the checker skips'
118
124
  return undefined
119
125
  }
120
126
 
@@ -36,8 +36,11 @@ export interface SourceContext {
36
36
  readonly conflictInsert: (node: AstNode, table: string, columns: readonly string[]) => void
37
37
  }
38
38
 
39
- /** The global objects and `Bun`: a server module reaches the platform through the framework only. */
40
- const SERVER_REFUSED_GLOBALS = new Set(['globalThis', 'global', 'self', 'window', 'Bun'])
39
+ /**
40
+ * The global objects, `Bun`, and `WebSocket`, a socket the egress guard on `fetch` does not see: a server module reaches
41
+ * the platform and the outside through the framework only.
42
+ */
43
+ const SERVER_REFUSED_GLOBALS = new Set(['globalThis', 'global', 'self', 'window', 'Bun', 'WebSocket'])
41
44
 
42
45
  /**
43
46
  * The local names a module binds to a value named `sql` it loads: `import { sql as q } from 'kysely'` and
@@ -177,7 +180,8 @@ const propertyValue = (object: AstNode, name: string): AstNode | undefined => {
177
180
  /** The finding of a `fetch` of an absolute URL whose origin no site of the contract declares. */
178
181
  export const crossAppFetchMessage = (target: string): { readonly message: string; readonly allowed: string } => ({
179
182
  message: `fetch to the absolute origin '${target}' is a hand-written integration`,
180
- allowed: "a same-origin path to a declared endpoint, another application through a connector import, or egress: ['<origin>'] on the site",
183
+ allowed:
184
+ "a same-origin path to a declared endpoint, another application through a connector import, egress: ['<origin>'] on the site, or a public host of http(s) under a cron job's egress: 'public'",
181
185
  })
182
186
 
183
187
  const checkDynamicCode = (node: AstNode, path: readonly string[], context: SourceContext): void => {
package/src/scaffold.ts CHANGED
@@ -3,7 +3,7 @@
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 { GENERATED_FILE_PREFIX, GENERATED_INVITATION, GENERATED_LINK, GENERATED_MEMBER, GENERATED_ROW_PREFIX } from '@fabrika/app/contract'
7
7
  import {
8
8
  type ContractArtifact,
9
9
  endpointDirectory,
@@ -13,9 +13,10 @@ import {
13
13
  tableActions,
14
14
  type TablePolicyArtifact,
15
15
  } from '@fabrika/auth-core'
16
- import { tablePolicies } from '@fabrika/db/tables'
16
+ import { type ApplicationRowRefusal, applicationRowRefusalText, applicationRowsPlan, tablePolicies, type Tables } from '@fabrika/db/tables'
17
17
  import { ContractSourceError, readContractSource, readTablesDefinition } from './contract'
18
- import { type EndpointFixtures, isSampleObject, NO_FIXTURES, readEndpointFixtures } from './endpoint-fixtures'
18
+ import { type ApplicationDialect, applicationDialect } from './dialect'
19
+ import { type EndpointFixtures, isFixtureFilePath, isSampleObject, NO_FIXTURES, readEndpointFixtures } from './endpoint-fixtures'
19
20
  import type { Finding } from './finding'
20
21
  import { CONTRACT_FILE, ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR } from './layout'
21
22
 
@@ -33,13 +34,40 @@ export interface GeneratedTest {
33
34
 
34
35
  type Policies = Readonly<Record<string, TablePolicyArtifact>>
35
36
 
37
+ /** The test database kit of each dialect, and the name a generated test gives the database it opens. */
38
+ const TEST_KITS: Readonly<Record<ApplicationDialect, { readonly module: string; readonly name: string }>> = {
39
+ postgres: { module: '@fabrika/db/testing', name: 'postgres' },
40
+ sqlite: { module: '@fabrika/db/testing-sqlite', name: 'database' },
41
+ }
42
+
43
+ /** The lines of a generated test that open its database: the kit's import and the call, against `migrations`. */
44
+ const testDatabaseLines = (
45
+ dialect: ApplicationDialect,
46
+ migrations: string,
47
+ ): { readonly kit: string; readonly open: string; readonly name: string } => {
48
+ const { module, name } = TEST_KITS[dialect]
49
+ return {
50
+ kit: `import { testDatabase } from '${module}'`,
51
+ open: `const ${name} = await testDatabase({ migrations: new URL('${migrations}', import.meta.url), label })`,
52
+ name,
53
+ }
54
+ }
55
+
36
56
  interface Case {
37
57
  readonly name: string
38
58
  readonly lines: readonly string[]
59
+ /** A leak or an own case: it runs the handler for the caller's own scope, which application rows can serve. */
60
+ readonly ownScope?: true
39
61
  }
40
62
 
41
63
  const testCase = (name: string, ...lines: readonly string[]): Case => ({ name, lines })
42
64
 
65
+ /** A case that runs the handler for the caller's own scope: a leak or an own case. */
66
+ const ownScopeCase = (name: string, line: string): Case => ({ name, lines: [line], ownScope: true })
67
+
68
+ /** Orders entries by their key, as every fixture is reported and seeded. */
69
+ const byKey = ([left]: readonly [string, unknown], [right]: readonly [string, unknown]): number => (left < right ? -1 : left > right ? 1 : 0)
70
+
43
71
  const quote = (text: string): string => `'${text.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`
44
72
 
45
73
  const renderCase = (item: Case): string =>
@@ -209,6 +237,7 @@ const policyTestBody = (
209
237
  policies: Policies,
210
238
  table: string,
211
239
  scopedSites: boolean,
240
+ dialect: ApplicationDialect,
212
241
  ): { readonly body: string; readonly cases: readonly string[] } | undefined => {
213
242
  const policy = policies[table]
214
243
  if (policy === undefined) return undefined
@@ -225,6 +254,7 @@ const policyTestBody = (
225
254
  ? `policy of ${table}: only a global holder of its actions reaches a row`
226
255
  : `policy of ${table}: a caller of one ${dimension} reaches no row of another`
227
256
  const kitOf = app ? 'appPolicyIsolationKit' : 'policyIsolationKit'
257
+ const database = testDatabaseLines(dialect, '../../../db/migrations/')
228
258
  const blocks = [describeBlock(title, isolation)]
229
259
  if (hidden.length > 0) blocks.push(describeBlock(`policy of ${table}: a column with its own read action is never returned`, hidden))
230
260
  const body = [
@@ -233,16 +263,16 @@ const policyTestBody = (
233
263
  '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a policy change.',
234
264
  '',
235
265
  `import { ${['afterAll', 'describe', 'expect', kitOf, 'test'].sort().join(', ')} } from '@fabrika/app/testing/isolation'`,
236
- "import { testDatabase } from '@fabrika/db/testing'",
266
+ database.kit,
237
267
  "import { contract } from '../../../fabrika.contract'",
238
268
  "import { tables } from '../tables'",
239
269
  '',
240
270
  `const label = ${quote(`${table}${POLICY_TEST_SUFFIX}`)}`,
241
- "const postgres = await testDatabase({ migrations: new URL('../../../db/migrations/', import.meta.url), label })",
271
+ database.open,
242
272
  '',
243
- 'if (postgres !== null) {',
244
- '\tafterAll(() => postgres.close())',
245
- `\tconst kit = ${kitOf}(contract, tables, ${quote(table)}, postgres)`,
273
+ `if (${database.name} !== null) {`,
274
+ `\tafterAll(() => ${database.name}.close())`,
275
+ `\tconst kit = ${kitOf}(contract, tables, ${quote(table)}, ${database.name})`,
246
276
  '',
247
277
  blocks.join('\n\n'),
248
278
  '}',
@@ -265,7 +295,9 @@ const isLinkProcedure = (row: EndpointRow): boolean =>
265
295
  * The input an endpoint's cases send: the author's fixture, else a sample of its schema; `undefined` when neither
266
296
  * exists. Each field its `members`, `invitations` or `links` name holds `GENERATED_MEMBER`, `GENERATED_INVITATION` or
267
297
  * `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.
298
+ * `rows` name holds `GENERATED_ROW_PREFIX` and the table, which the kit replaces with the key of a row it seeded; each file
299
+ * field its `files` name holds its kind's marker (in a list, for a list of files), even where the sample left an optional
300
+ * one out, which the kit sends as the named file.
269
301
  */
270
302
  const inputOf = (row: EndpointRow, fixtures: EndpointFixtures): Readonly<Record<string, Sample>> | undefined => {
271
303
  const fixture = fixtures.inputs[row.id]
@@ -279,10 +311,83 @@ const inputOf = (row: EndpointRow, fixtures: EndpointFixtures): Readonly<Record<
279
311
  ...generated(fixtures.invitations[row.id], GENERATED_INVITATION),
280
312
  ...generated(fixtures.links[row.id], GENERATED_LINK),
281
313
  ...Object.entries(fixtures.rows[row.id] ?? {}).map(([field, table]) => [field, `${GENERATED_ROW_PREFIX}${table}`]),
314
+ ...Object.keys(fixtures.files[row.id] ?? {}).flatMap((field) => {
315
+ const file = fileFieldOf(row.input, field)
316
+ if (file === undefined) return []
317
+ const marker = `${GENERATED_FILE_PREFIX}${file.kind}`
318
+ return [[field, file.list ? [marker] : marker]]
319
+ }),
282
320
  ]),
283
321
  }
284
322
  }
285
323
 
324
+ /** 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`. */
325
+ const fileFieldOf = (input: SchemaShape | null, field: string): { readonly kind: string; readonly list: boolean } | undefined => {
326
+ const kindOf = (shape: SchemaShape | undefined): string | undefined =>
327
+ shape?.type === 'file' ? shape.kind : shape?.type === 'optional' || shape?.type === 'nullable' ? kindOf(shape.inner) : undefined
328
+ const shape = input?.type === 'object' ? input.fields[field] : undefined
329
+ const unwrapped = shape?.type === 'optional' || shape?.type === 'nullable' ? shape.inner : shape
330
+ if (unwrapped?.type === 'array') {
331
+ const kind = kindOf(unwrapped.items)
332
+ return kind === undefined ? undefined : { kind, list: true }
333
+ }
334
+ const kind = kindOf(shape)
335
+ return kind === undefined ? undefined : { kind, list: false }
336
+ }
337
+
338
+ /** The ids of the endpoints with endpoint access cases. */
339
+ const testedEndpoints = (artifact: ContractArtifact): ReadonlySet<string> =>
340
+ new Set(artifact.endpoints.filter((row) => isAccessTested(row) || isLinkProcedure(row)).map((row) => row.id))
341
+
342
+ /** How a generated endpoint access test reaches the application's root, where a file fixture's path starts. */
343
+ const ROOT_FROM_ENDPOINT_TEST = '../'.repeat(ENDPOINT_ACCESS_TEST.split('/').length - 1)
344
+
345
+ /**
346
+ * The options of the generated test's kit: the file fixtures of the tested endpoints, each a URL beside the test. Empty
347
+ * without any, so a test without file fixtures stays as it was.
348
+ */
349
+ const kitOptions = (fixtures: EndpointFixtures, tested: ReadonlySet<string>): string => {
350
+ const files = Object.entries(fixtures.files).sort(byKey).flatMap(([id, fields]) => {
351
+ const valid = Object.entries(fields).sort(byKey).filter(([, path]) => isFixtureFilePath(path))
352
+ if (!tested.has(id) || valid.length === 0) return []
353
+ const rendered = valid.map(([field, path]) => `${renderKey(field)}: new URL(${quote(`${ROOT_FROM_ENDPOINT_TEST}${path}`)}, import.meta.url)`)
354
+ return [`${quote(id)}: { ${rendered.join(', ')} }`]
355
+ })
356
+ const refusals = Object.entries(fixtures.refusals).sort(byKey).flatMap(([id, types]) => {
357
+ const valid = types.filter(isDeclarableRefusal)
358
+ return tested.has(id) && valid.length > 0 ? [`${quote(id)}: [${valid.map(quote).join(', ')}]`] : []
359
+ })
360
+ const pins = Object.entries(fixtures.pins).sort(byKey).flatMap(([id, columns]) => {
361
+ const entries = Object.entries(columns).sort(byKey)
362
+ return tested.has(id) && entries.length > 0
363
+ ? [`${quote(id)}: { ${entries.map(([column, value]) => `${renderKey(column)}: ${quote(value)}`).join(', ')} }`]
364
+ : []
365
+ })
366
+ const options = [
367
+ ...(files.length === 0 ? [] : [`files: { ${files.join(', ')} }`]),
368
+ ...(refusals.length === 0 ? [] : [`refusals: { ${refusals.join(', ')} }`]),
369
+ ...(pins.length === 0 ? [] : [`pins: { ${pins.join(', ')} }`]),
370
+ ]
371
+ return options.length === 0 ? '' : `, { ${options.join(', ')} }`
372
+ }
373
+
374
+ /** A refusal the fixtures may declare: a handler's own error type, never the input schema's (`validation`). */
375
+ const isDeclarableRefusal = (type: string): boolean => type !== '' && type !== 'validation'
376
+
377
+ /**
378
+ * The own case of an endpoint: 200, or, where its fixtures declare the refusals its handler may answer its own object
379
+ * with, also the 400 the kit hands back only for one of them.
380
+ */
381
+ const ownCase = (row: EndpointRow, fixtures: EndpointFixtures, name: string, args: string): Case => {
382
+ const declared = (fixtures.refusals[row.id] ?? []).filter(isDeclarableRefusal)
383
+ return declared.length === 0
384
+ ? ownScopeCase(name, `expect(await kit.own(${args})).toEqual({ status: 200 })`)
385
+ : ownScopeCase(`${name} (200, or a refusal its fixtures declare)`, `expect([200, 400]).toContain((await kit.own(${args})).status)`)
386
+ }
387
+
388
+ /** An object key as `renderSample` writes one: bare when it is an identifier, else quoted. */
389
+ const renderKey = (key: string): string => (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : quote(key))
390
+
286
391
  /** Whether the endpoint's handler gets `ctx.links`: on or in a dimension a link mount's `issuedBy` names its action for. */
287
392
  const issuesLinks = (artifact: ContractArtifact, row: EndpointRow): boolean => {
288
393
  if (row.requirement?.kind !== 'action') return false
@@ -313,6 +418,17 @@ const ownerRead = (policies: Policies, dimension: string): string | undefined =>
313
418
  Object.values(policies).find((policy) => policy.scope.mode === 'dimension' && policy.scope.dimension === dimension)?.actions.read ?? null,
314
419
  )[0]
315
420
 
421
+ /**
422
+ * Whether an endpoint gets the `own` case: `on` an object a table owns, as a link procedure or with an action other
423
+ * than the owner's read action (a caller holding only that one reaches every object, which proves nothing).
424
+ */
425
+ const hasOwnCase = (row: EndpointRow, policies: Policies): boolean => {
426
+ if (row.requirement?.kind !== 'action') return false
427
+ const { access, action } = row.requirement
428
+ const read = access.form === 'on' ? ownerRead(policies, access.dimension) : undefined
429
+ return read !== undefined && (isLinkProcedure(row) || read !== action)
430
+ }
431
+
316
432
  /**
317
433
  * What the `own` case's caller holds: the endpoint's action, plus what IAM requires of a link's issuer (the actions the
318
434
  * link grants) and of a member manager (an assigning role and the assigned role's actions).
@@ -341,21 +457,27 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
341
457
  const seed = fixtures.seeds[row.id]
342
458
  const args = `${quote(row.id)}, ${renderSample(input)}`
343
459
  const seeded = seed === undefined ? args : `${args}, ${renderSample(seed)}`
460
+ // The application rows reach every case that runs the handler on the caller's own object: its leak cases and its own
461
+ // case. Only an endpoint with them gets the fourth argument, so every other generated file stays as it was.
462
+ const appRows = fixtures.appRows[row.id]
463
+ const rowsTail = appRows === undefined ? '' : `, ${renderSample(appRows)}`
464
+ const unseededArgs = appRows === undefined ? args : `${args}, {}${rowsTail}`
465
+ const seededArgs = seed === undefined ? unseededArgs : `${seeded}${rowsTail}`
344
466
  const declared = artifact.declared?.[row.id]
345
467
  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)
468
+ const own = hasOwnCase(row, policies)
348
469
  const cases: Case[] = []
349
- // The unseeded probe always runs: a seed meets a precondition, and must not also set aside the state that leaks.
470
+ // The unseeded probe always runs: a seed meets a precondition, and must not also set aside the state that leaks. The
471
+ // application rows reach it too: they are rows of the whole application, which the handler needs to answer at all.
350
472
  const leaked = (): Case[] => [
351
- testCase(
473
+ ownScopeCase(
352
474
  `${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: [] })`,
475
+ `expect(await kit.leaked(${unseededArgs})).toEqual({ answered: true, leaked: [] })`,
354
476
  ),
355
477
  ...(seed === undefined ? [] : [
356
- testCase(
478
+ ownScopeCase(
357
479
  `${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: [] })`,
480
+ `expect(await kit.leaked(${seededArgs})).toEqual({ answered: true, leaked: [] })`,
359
481
  ),
360
482
  ]),
361
483
  ]
@@ -379,9 +501,7 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
379
501
  }
380
502
  if (linked) {
381
503
  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
- )
504
+ cases.push(ownCase(row, fixtures, `${row.id}: the holder of a link to a ${access.dimension} reaches it`, seededArgs))
385
505
  }
386
506
  return cases
387
507
  }
@@ -390,9 +510,11 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
390
510
  if (!unscoped) cases.push(...leaked())
391
511
  if (own) {
392
512
  cases.push(
393
- testCase(
513
+ ownCase(
514
+ row,
515
+ fixtures,
394
516
  `${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 })`,
517
+ seededArgs,
396
518
  ),
397
519
  )
398
520
  }
@@ -452,6 +574,7 @@ const endpointTestBody = (
452
574
  artifact: ContractArtifact,
453
575
  policies: Policies,
454
576
  fixtures: EndpointFixtures,
577
+ dialect: ApplicationDialect,
455
578
  ): { readonly body: string; readonly cases: readonly string[] } | undefined => {
456
579
  const cases = [...artifact.endpoints].sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).flatMap((
457
580
  row,
@@ -461,6 +584,7 @@ const endpointTestBody = (
461
584
  ...publicCases(row, artifact, fixtures),
462
585
  ])
463
586
  if (cases.length === 0) return undefined
587
+ const database = testDatabaseLines(dialect, '../../db/migrations/')
464
588
  const body = [
465
589
  '// The endpoint access tests of this application, written by fabrika db test-scaffold from fabrika.contract.ts and',
466
590
  '// src/db/tables.ts. They run src/app.ts itself: callers of two scopes that share no value ask every endpoint with an',
@@ -470,16 +594,16 @@ const endpointTestBody = (
470
594
  '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a contract change.',
471
595
  '',
472
596
  "import { afterAll, describe, endpointAccessKit, expect, test } from '@fabrika/app/testing/isolation'",
473
- "import { testDatabase } from '@fabrika/db/testing'",
597
+ database.kit,
474
598
  "import app from '../app'",
475
599
  "import { tables } from '../db/tables'",
476
600
  '',
477
601
  "const label = 'endpoint-access.test.ts'",
478
- "const postgres = await testDatabase({ migrations: new URL('../../db/migrations/', import.meta.url), label })",
602
+ database.open,
479
603
  '',
480
- 'if (postgres !== null) {',
481
- '\tafterAll(() => postgres.close())',
482
- '\tconst kit = endpointAccessKit(app, tables, postgres)',
604
+ `if (${database.name} !== null) {`,
605
+ `\tafterAll(() => ${database.name}.close())`,
606
+ `\tconst kit = endpointAccessKit(app, tables, ${database.name}${kitOptions(fixtures, testedEndpoints(artifact))})`,
483
607
  '',
484
608
  describeBlock('endpoints: a caller of one scope reaches nothing of another', cases),
485
609
  '}',
@@ -495,29 +619,64 @@ const generated = async ({ body, cases }: { readonly body: string; readonly case
495
619
 
496
620
  /**
497
621
  * 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.
622
+ * Endpoint access tests exist only for an application on `@fabrika/db`, which has policies to seed rows from. They
623
+ * open the test database of the application's dialect.
499
624
  */
500
625
  export const generatedTests = async (
501
626
  policies: Policies,
502
627
  artifact: ContractArtifact | null,
503
628
  fixtures: EndpointFixtures = NO_FIXTURES,
629
+ dialect: ApplicationDialect = 'postgres',
504
630
  ): Promise<ReadonlyMap<string, GeneratedTest>> => {
505
631
  const files = new Map<string, GeneratedTest>()
506
632
  // The kit's scoped sites are `over` the vocabulary's first dimension: without one, no scoped site exists.
507
633
  const scopedSites = artifact !== null && Object.keys(artifact.dimensions).length > 0
508
634
  for (const table of Object.keys(policies).sort()) {
509
- const test = policyTestBody(policies, table, scopedSites)
635
+ const test = policyTestBody(policies, table, scopedSites, dialect)
510
636
  if (test !== undefined) files.set(policyTestPath(table), await generated(test))
511
637
  }
512
- const endpoints = artifact === null || files.size === 0 ? undefined : endpointTestBody(artifact, policies, fixtures)
638
+ const endpoints = artifact === null || files.size === 0 ? undefined : endpointTestBody(artifact, policies, fixtures, dialect)
513
639
  if (endpoints !== undefined) files.set(ENDPOINT_ACCESS_TEST, await generated(endpoints))
514
640
  return files
515
641
  }
516
642
 
517
643
  export interface ScaffoldInputs {
644
+ /** What `src/db/tables.ts` defines, its column list included; `null` without the file. */
645
+ readonly tables: Tables<unknown, unknown> | null
518
646
  readonly policies: Policies
519
647
  readonly artifact: ContractArtifact | null
520
648
  readonly fixtures: EndpointFixtures
649
+ readonly dialect: ApplicationDialect
650
+ }
651
+
652
+ /**
653
+ * Whether an endpoint's generated cases run its handler for the caller's own scope, which application rows can serve: a
654
+ * leak or an own case, read off the cases `endpointCases` writes. An input it lacks a fixture for does not matter here.
655
+ */
656
+ const runsOnOwnScope = (row: EndpointRow, artifact: ContractArtifact, policies: Policies, fixtures: EndpointFixtures): boolean => {
657
+ const withInput = { ...fixtures, inputs: { ...fixtures.inputs, [row.id]: fixtures.inputs[row.id] ?? {} } }
658
+ return endpointCases(row, artifact, policies, withInput).some((item) => item.ownScope === true)
659
+ }
660
+
661
+ /** The allowed form of an `appRows` entry `applicationRowsPlan` refuses; the message is the kit's own words. */
662
+ const appRowAllowed = (refusal: ApplicationRowRefusal): string => {
663
+ switch (refusal.kind) {
664
+ case 'table':
665
+ return refusal.mode === null
666
+ ? 'the name of a table with scope: { app } in src/db/tables.ts'
667
+ : "rows, for a row in the endpoint's object; seeds, for the state of the object's own row"
668
+ case 'column':
669
+ return `a column of ${refusal.table} in src/db/schema.generated.ts`
670
+ case 'stamped':
671
+ case 'file':
672
+ return "the row's other columns"
673
+ case 'value':
674
+ return 'a string, a number, a boolean or null'
675
+ case 'partial-key':
676
+ return `all of ${refusal.key.columns.join(', ')}, or none, which the kit then fills`
677
+ case 'cycle':
678
+ return 'a value for one of the foreign keys (null, where it may be), which the kit then does not fill'
679
+ }
521
680
  }
522
681
 
523
682
  /** What the scaffold reads from an application's files; throws `ContractSourceError` or `ContractError` as the reader does. */
@@ -528,15 +687,15 @@ export const scaffoldInputs = (files: ReadonlyMap<string, string>): ScaffoldInpu
528
687
  if (!fixtures.ok) throw new ContractSourceError(fixtures.findings)
529
688
  // Endpoint tests seed rows from the policies, so without src/db/tables.ts there is nothing to compile them against.
530
689
  const artifact = files.has(CONTRACT_FILE) && tables !== null ? readContractSource(files, tables) : null
531
- return { policies, artifact, fixtures: fixtures.fixtures }
690
+ return { tables, policies, artifact, fixtures: fixtures.fixtures, dialect: applicationDialect(files) }
532
691
  }
533
692
 
534
693
  /**
535
694
  * What stops the endpoint access tests from covering every endpoint: one whose input the scaffold cannot sample and
536
695
  * the author gave no fixture, and a fixture of no tested endpoint. Each is an `endpoint-fixture` finding.
537
696
  */
538
- export const missingEndpointFixtures = ({ policies, artifact, fixtures }: ScaffoldInputs): readonly Finding[] => {
539
- if (artifact === null || Object.keys(policies).length === 0) return []
697
+ export const missingEndpointFixtures = ({ tables, policies, artifact, fixtures }: ScaffoldInputs): readonly Finding[] => {
698
+ if (artifact === null || tables === null || Object.keys(policies).length === 0) return []
540
699
  const at = (message: string, allowed: string): Finding => ({
541
700
  file: ENDPOINT_FIXTURES_FILE,
542
701
  line: 1,
@@ -560,7 +719,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
560
719
  )
561
720
  }
562
721
  }
563
- for (const [id, fields] of Object.entries(fixtures.members).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
722
+ for (const [id, fields] of Object.entries(fixtures.members).sort(byKey)) {
564
723
  const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate))
565
724
  const directory = row === undefined ? null : endpointDirectory(artifact, row)
566
725
  if (row === undefined || directory === null) {
@@ -579,8 +738,6 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
579
738
  }
580
739
  }
581
740
  }
582
- const sortedById = (fields: Readonly<Record<string, readonly string[]>>) =>
583
- Object.entries(fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
584
741
  const holders = [
585
742
  {
586
743
  fields: fixtures.invitations,
@@ -598,7 +755,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
598
755
  },
599
756
  ]
600
757
  for (const holder of holders) {
601
- for (const [id, fields] of sortedById(holder.fields)) {
758
+ for (const [id, fields] of Object.entries(holder.fields).sort(byKey)) {
602
759
  const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate) && holder.admits(candidate))
603
760
  if (row === undefined) {
604
761
  findings.push(at(holder.refusal(id), holder.allowed))
@@ -611,7 +768,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
611
768
  }
612
769
  }
613
770
  }
614
- for (const [id, fields] of Object.entries(fixtures.rows).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
771
+ for (const [id, fields] of Object.entries(fixtures.rows).sort(byKey)) {
615
772
  const row = tested.find((candidate) => candidate.id === id)
616
773
  const access = row?.requirement?.kind === 'action' ? row.requirement.access : undefined
617
774
  const owned = access?.form === 'on' && ownerRead(policies, access.dimension) !== undefined
@@ -624,7 +781,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
624
781
  )
625
782
  continue
626
783
  }
627
- for (const [field, table] of Object.entries(fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
784
+ for (const [field, table] of Object.entries(fields).sort(byKey)) {
628
785
  if (row.input?.type !== 'object' || !admitsString(row.input.fields[field])) {
629
786
  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
787
  } else if (!liesDirectlyIn(policies, table, access.dimension)) {
@@ -637,8 +794,78 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
637
794
  }
638
795
  }
639
796
  }
797
+ for (const [id, rows] of Object.entries(fixtures.appRows).sort(byKey)) {
798
+ if (!tested.some((row) => row.id === id && runsOnOwnScope(row, artifact, policies, fixtures))) {
799
+ findings.push(
800
+ at(
801
+ `${id} is no endpoint with a leak or an own case, whose handler could read an application row the kit seeds`,
802
+ "export const appRows = { '<endpoint id>': { <table>: { <column>: <value> } } }, for an endpoint on, in or over a scope",
803
+ ),
804
+ )
805
+ continue
806
+ }
807
+ // The rule the kit seeds by, read from the policies and the column list: one rule, so the two cannot drift.
808
+ for (const refusal of applicationRowsPlan(tables, rows).refusals) {
809
+ findings.push(at(`${id}: ${applicationRowRefusalText(refusal)}`, appRowAllowed(refusal)))
810
+ }
811
+ }
812
+ for (const [id, fields] of Object.entries(fixtures.files).sort(byKey)) {
813
+ const row = tested.find((candidate) => candidate.id === id)
814
+ if (row === undefined) {
815
+ findings.push(
816
+ at(
817
+ `${id} is no tested endpoint, whose cases could send a file`,
818
+ "export const files = { '<endpoint id>': { <file field>: '<path from the application root>' } }, for a tested endpoint with a file input",
819
+ ),
820
+ )
821
+ continue
822
+ }
823
+ for (const [field, path] of Object.entries(fields).sort(byKey)) {
824
+ if (fileFieldOf(row.input, field) === undefined) {
825
+ 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'))
826
+ } else if (!isFixtureFilePath(path)) {
827
+ findings.push(
828
+ at(
829
+ `${id}: the file of ${field}, '${path}', is no path inside the application`,
830
+ "a path from the application's root, '/'-separated, without '..', a leading '/' or '.', or characters other than letters, digits, '_', '-' and '.'",
831
+ ),
832
+ )
833
+ }
834
+ }
835
+ }
836
+ for (const [id, types] of Object.entries(fixtures.refusals).sort(byKey)) {
837
+ if (!tested.some((row) => row.id === id)) {
838
+ findings.push(
839
+ at(
840
+ `${id} is no tested endpoint, whose handler a case runs`,
841
+ "export const refusals = { '<endpoint id>': ['<error type>'] }, for a tested endpoint",
842
+ ),
843
+ )
844
+ continue
845
+ }
846
+ for (const type of types) {
847
+ if (!isDeclarableRefusal(type)) {
848
+ findings.push(
849
+ at(
850
+ `${id}: '${type}' is no refusal of its handler; an input the schema refuses (validation) is the fixture's mistake`,
851
+ "the error type of a 400 the handler throws (new HttpError(400, '<type>', …))",
852
+ ),
853
+ )
854
+ }
855
+ }
856
+ }
640
857
  const seeded = (row: EndpointRow): boolean =>
641
858
  row.requirement?.kind === 'action' && (row.requirement.access.form === 'on' || row.requirement.access.form === 'in')
859
+ for (const id of Object.keys(fixtures.pins).sort()) {
860
+ if (!tested.some((row) => row.id === id && (seeded(row) || isLinkProcedure(row)))) {
861
+ findings.push(
862
+ at(
863
+ `${id} is no endpoint with an on or in access form, whose row a pin sets`,
864
+ "export const pins = { '<endpoint id>': { <text column>: '<value>' } }",
865
+ ),
866
+ )
867
+ }
868
+ }
642
869
  for (const id of Object.keys(fixtures.seeds).sort()) {
643
870
  if (!tested.some((row) => row.id === id && seeded(row))) {
644
871
  findings.push(