@fabrika/check 0.9.0-dev.4 → 0.9.0-dev.6

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.
@@ -2,11 +2,13 @@ import {
2
2
  afterName,
3
3
  closingParenthesis,
4
4
  isPunct,
5
+ lexSqlite,
5
6
  nameText,
6
7
  objectNameAt,
7
8
  skipWords,
8
9
  splitAtCommas,
9
10
  type SqlToken,
11
+ statementsOf,
10
12
  topLevelStatements,
11
13
  upperWord,
12
14
  } from '@fabrika/platform-node/sql'
@@ -43,6 +45,67 @@ export const checkMigrationNames = (paths: readonly string[]): Finding[] => {
43
45
  return findings
44
46
  }
45
47
 
48
+ /** The default a SQLite timestamp column takes: the UTC ISO text every read of the table parses. */
49
+ const SQLITE_NOW_DEFAULT = "DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
50
+
51
+ /**
52
+ * On SQLite `DEFAULT CURRENT_TIMESTAMP` stores `YYYY-MM-DD HH:MM:SS`, which every read of the table refuses as
53
+ * `unexpected_row` (backlog 216 item 13). Refused with or without parentheses, at the line of `CURRENT_TIMESTAMP`.
54
+ */
55
+ export const checkCurrentTimestampDefaults = (files: ReadonlyMap<string, string>): Finding[] => {
56
+ const findings: Finding[] = []
57
+ for (const [path, sql] of files) {
58
+ if (!path.startsWith(MIGRATIONS_DIR) || !path.endsWith('.sql')) continue
59
+ for (const { tokens } of topLevelStatements(sql)) {
60
+ tokens.forEach((token, index) => {
61
+ if (upperWord(token) !== 'DEFAULT') return
62
+ const value = isPunct(tokens[index + 1], '(') ? tokens[index + 2] : tokens[index + 1]
63
+ if (value === undefined || upperWord(value) !== 'CURRENT_TIMESTAMP') return
64
+ findings.push({
65
+ file: path,
66
+ line: value.line,
67
+ column: 1,
68
+ severity: 'refusal',
69
+ rule: 'cloudflare-current-timestamp',
70
+ message: 'DEFAULT CURRENT_TIMESTAMP stores YYYY-MM-DD HH:MM:SS on SQLite, which every read of the table refuses as unexpected_row',
71
+ allowed: SQLITE_NOW_DEFAULT,
72
+ })
73
+ })
74
+ }
75
+ }
76
+ return findings
77
+ }
78
+
79
+ /**
80
+ * On SQLite an application migration runs verbatim, with no name rule, so a view or a trigger over a framework table
81
+ * would reach what `ctx.sql`'s name rule keeps it from. Every `fabrika_*` name is refused (any case, quoted, bracketed,
82
+ * or as a string SQLite may read as a name) but `fabrika_files` right after `REFERENCES`, a file column's foreign key.
83
+ */
84
+ export const checkSqliteFrameworkNames = (files: ReadonlyMap<string, string>): Finding[] => {
85
+ const findings: Finding[] = []
86
+ for (const [path, sql] of files) {
87
+ if (!path.startsWith(MIGRATIONS_DIR) || !path.endsWith('.sql')) continue
88
+ for (const { tokens } of statementsOf(lexSqlite(sql).tokens)) {
89
+ tokens.forEach((token, index) => {
90
+ const text = token.kind === 'word' || token.kind === 'quoted' || token.kind === 'string' ? token.text : undefined
91
+ const name = text?.toLowerCase()
92
+ if (name === undefined || !name.startsWith('fabrika_')) return
93
+ if (name === FILES_TABLE && token.kind !== 'string' && upperWord(tokens[index - 1]) === 'REFERENCES') return
94
+ findings.push({
95
+ file: path,
96
+ line: token.line,
97
+ column: 1,
98
+ severity: 'refusal',
99
+ rule: 'cloudflare-framework-name',
100
+ message: `'${text}' is the framework's: a migration on Cloudflare names no fabrika_* table, which ctx.sql could then reach through it`,
101
+ allowed: `the application's own tables, and REFERENCES ${FILES_TABLE} (id) for a file column`,
102
+ })
103
+ })
104
+ }
105
+ }
106
+ return findings
107
+ }
108
+
46
109
  /** A declared file column: `table.column` holds files of `kind`. */
47
110
  export interface FileColumn {
48
111
  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
 
@@ -94,7 +94,7 @@ const ALLOWED_ENV = 'values the framework hands the handler through deps or ctx'
94
94
  * The test kits: the application's signs tokens with its own key and boots the application a second way; the
95
95
  * database's reaches tables by name and seeds rows past the data layer. Production never loads either.
96
96
  */
97
- const TEST_KITS = ['@fabrika/app/testing', '@fabrika/app/react/testing', '@fabrika/db/testing']
97
+ const TEST_KITS = ['@fabrika/app/testing', '@fabrika/app/react/testing', '@fabrika/db/testing', '@fabrika/db/testing-sqlite']
98
98
  const TEST_ONLY_ALLOWED = 'the kit in a test file (*.test.ts, *.spec.ts or a __tests__ directory) only'
99
99
 
100
100
  export const isTestKit = (specifier: string): boolean => TEST_KITS.some((kit) => specifier === kit || specifier.startsWith(`${kit}/`))
@@ -114,7 +114,7 @@ const checkTestOnly = (reference: ModuleReference, target: string, report: Repor
114
114
  /** A path from the root that a mapping or an import lands on, judged by where the checker reads. */
115
115
  const containmentProblem = (target: string | undefined): string | undefined => {
116
116
  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'
117
+ if (isSkippedPath(target)) return 'resolves into a directory the checker skips'
118
118
  return undefined
119
119
  }
120
120
 
@@ -33,7 +33,7 @@ const isAssertionCall = (node: AstNode): boolean => {
33
33
  const path = memberPath(callee)
34
34
  const [root] = path ?? []
35
35
  const last = path?.[path.length - 1]
36
- return root !== undefined && root !== 'expect' && (/^assert/.test(root) || (last !== undefined && ASSERTION_NAME.test(last)))
36
+ return root !== undefined && root !== 'expect' && (root.startsWith('assert') || (last !== undefined && ASSERTION_NAME.test(last)))
37
37
  }
38
38
 
39
39
  /** Whether a test body runs an assertion; a nested function counts only where it is called or passed to a call. */
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(
@@ -0,0 +1,8 @@
1
+ /** The database an application's data layer runs on: SQLite in its Durable Object on Cloudflare (ADR-0065), else Postgres. */
2
+ export type ApplicationDialect = 'postgres' | 'sqlite';
3
+ /**
4
+ * Read statically from `fabrika.config.ts`: SQLite when its default export is a call of the `defineApp` that
5
+ * `@fabrika/provider-cloudflare` exports, the config every Cloudflare application writes. Postgres otherwise,
6
+ * including without a config or when the call's origin is not static.
7
+ */
8
+ export declare const applicationDialect: (files: ReadonlyMap<string, string>) => ApplicationDialect;