@fabrika/check 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/scaffold.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  endpointMembers,
11
11
  type EndpointRow,
12
12
  type SchemaShape,
13
+ tableActions,
13
14
  type TablePolicyArtifact,
14
15
  } from '@fabrika/auth-core'
15
16
  import { tablePolicies } from '@fabrika/db/tables'
@@ -53,8 +54,38 @@ const grantDimension = (policies: Policies, policy: TablePolicyArtifact): string
53
54
  return parent?.mode === 'dimension' ? (parent.container?.dimension ?? parent.dimension) : undefined
54
55
  }
55
56
 
57
+ /**
58
+ * The actions the generated cases probe: the first of each operation, whose kit endpoint holds it. A refusal case runs
59
+ * only where the probed read action is not also an action of the operation it is refused.
60
+ */
61
+ interface ProbedActions {
62
+ readonly read: string
63
+ readonly insert: string | null
64
+ readonly update: string | null
65
+ readonly delete: string | null
66
+ readonly updateRefusesRead: boolean
67
+ readonly deleteRefusesRead: boolean
68
+ readonly appRead?: readonly string[]
69
+ readonly appCount?: readonly string[]
70
+ }
71
+
72
+ const probedActions = (actions: TablePolicyArtifact['actions']): ProbedActions => {
73
+ const read = tableActions(actions.read)[0] ?? ''
74
+ return {
75
+ read,
76
+ insert: tableActions(actions.insert)[0] ?? null,
77
+ update: tableActions(actions.update)[0] ?? null,
78
+ delete: tableActions(actions.delete)[0] ?? null,
79
+ updateRefusesRead: !tableActions(actions.update).includes(read),
80
+ deleteRefusesRead: !tableActions(actions.delete).includes(read),
81
+ ...(actions.appRead === undefined ? {} : { appRead: actions.appRead }),
82
+ ...(actions.appCount === undefined ? {} : { appCount: actions.appCount }),
83
+ }
84
+ }
85
+
56
86
  const isolationCases = (policy: TablePolicyArtifact, dimension: string): readonly Case[] => {
57
- const { actions, scope } = policy
87
+ const { scope } = policy
88
+ const actions = probedActions(policy.actions)
58
89
  const child = scope.mode === 'child'
59
90
  const contained = scope.mode === 'child' || (scope.mode === 'dimension' && scope.container !== null)
60
91
  const other = `another ${dimension}`
@@ -82,7 +113,7 @@ const isolationCases = (policy: TablePolicyArtifact, dimension: string): readonl
82
113
  if (child) {
83
114
  cases.push(testCase(`update of a key in ${other} through its own parent is 404`, "expect((await kit.update('crossed')).status).toBe(404)"))
84
115
  }
85
- if (actions.update !== actions.read) {
116
+ if (actions.updateRefusesRead) {
86
117
  cases.push(testCase(`update refuses a Ref for ${actions.read}`, 'expect(await kit.updateWithRead()).toEqual({ status: 200, refused: true })'))
87
118
  }
88
119
  }
@@ -92,7 +123,7 @@ const isolationCases = (policy: TablePolicyArtifact, dimension: string): readonl
92
123
  if (child) {
93
124
  cases.push(testCase(`remove of a key in ${other} through its own parent is 404`, "expect((await kit.remove('crossed')).status).toBe(404)"))
94
125
  }
95
- if (actions.delete !== actions.read) {
126
+ if (actions.deleteRefusesRead) {
96
127
  cases.push(testCase(`remove refuses a Ref for ${actions.read}`, 'expect(await kit.removeWithRead()).toEqual({ status: 200, refused: true })'))
97
128
  }
98
129
  }
@@ -130,7 +161,7 @@ const isolationCases = (policy: TablePolicyArtifact, dimension: string): readonl
130
161
  * the vocabulary has a dimension, a scoped site of the read action reads every row, and one of another action none.
131
162
  */
132
163
  const appIsolationCases = (policy: TablePolicyArtifact, scopedSites: boolean): readonly Case[] => {
133
- const { actions } = policy
164
+ const actions = probedActions(policy.actions)
134
165
  const writes = policy.update.length > 0 || policy.version !== null
135
166
  const pair = (operation: string, call: string, done: string): Case[] => [
136
167
  testCase(`${operation} by a global holder succeeds`, `expect(${call.replace('CALLER', "'global'")}).${done}`),
@@ -143,7 +174,7 @@ const appIsolationCases = (policy: TablePolicyArtifact, scopedSites: boolean): r
143
174
  if (actions.insert !== null) cases.push(...pair('insert', 'await kit.insert(CALLER)', 'toEqual({ status: 200 })'))
144
175
  if (actions.update !== null) {
145
176
  if (writes) cases.push(...pair('update', 'await kit.update(CALLER)', 'toEqual({ status: 200 })'))
146
- if (actions.update !== actions.read) {
177
+ if (actions.updateRefusesRead) {
147
178
  cases.push(
148
179
  testCase(`update refuses a capability of ${actions.read}`, 'expect(await kit.updateWithRead()).toEqual({ status: 200, refused: true })'),
149
180
  )
@@ -151,7 +182,7 @@ const appIsolationCases = (policy: TablePolicyArtifact, scopedSites: boolean): r
151
182
  }
152
183
  if (actions.delete !== null) {
153
184
  cases.push(...pair('remove', 'await kit.remove(CALLER)', 'toEqual({ status: 200 })'))
154
- if (actions.delete !== actions.read) {
185
+ if (actions.deleteRefusesRead) {
155
186
  cases.push(
156
187
  testCase(`remove refuses a capability of ${actions.read}`, 'expect(await kit.removeWithRead()).toEqual({ status: 200, refused: true })'),
157
188
  )
@@ -159,7 +190,8 @@ const appIsolationCases = (policy: TablePolicyArtifact, scopedSites: boolean): r
159
190
  }
160
191
  if (scopedSites) {
161
192
  cases.push(testCase(`a scoped site of ${actions.read} reads every row`, "expect(await kit.scopedList()).toEqual({ status: 200, rows: ['own'] })"))
162
- const other = [actions.insert, actions.update, actions.delete].find((action) => action !== null && action !== actions.read)
193
+ const reads = tableActions(policy.actions.read)
194
+ const other = [actions.insert, actions.update, actions.delete].find((action) => action !== null && !reads.includes(action))
163
195
  if (other !== undefined) {
164
196
  cases.push(
165
197
  testCase(`a scoped site of ${other} reads no row`, 'expect(await kit.scopedListWithOther()).toEqual({ status: 200, refused: true })'),
@@ -219,9 +251,9 @@ const policyTestBody = (
219
251
  return { body, cases: [...isolation, ...hidden].map((item) => item.name) }
220
252
  }
221
253
 
222
- /** Whether an endpoint gets endpoint access cases: a procedure with an access form, for a person or a machine. */
254
+ /** Whether an endpoint gets endpoint access cases: a procedure with an access form or several, for a person or a machine. */
223
255
  const isAccessTested = (row: EndpointRow): boolean => {
224
- if ((row.kind !== 'query' && row.kind !== 'mutation') || row.requirement === null || row.requirement.kind !== 'action') return false
256
+ if ((row.kind !== 'query' && row.kind !== 'mutation') || row.requirement === null || row.requirement.kind === 'member') return false
225
257
  return row.callers.some((caller) => caller === 'human' || caller === 'machine')
226
258
  }
227
259
 
@@ -277,7 +309,9 @@ const liesDirectlyIn = (policies: Policies, table: string, dimension: string): b
277
309
 
278
310
  /** The read action of the table that owns `dimension`, or `undefined` when no table owns it. */
279
311
  const ownerRead = (policies: Policies, dimension: string): string | undefined =>
280
- Object.values(policies).find((policy) => policy.scope.mode === 'dimension' && policy.scope.dimension === dimension)?.actions.read
312
+ tableActions(
313
+ Object.values(policies).find((policy) => policy.scope.mode === 'dimension' && policy.scope.dimension === dimension)?.actions.read ?? null,
314
+ )[0]
281
315
 
282
316
  /**
283
317
  * What the `own` case's caller holds: the endpoint's action, plus what IAM requires of a link's issuer (the actions the
@@ -372,39 +406,43 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
372
406
  }
373
407
 
374
408
  /**
375
- * A file endpoint's own cases, over a file the kit seeds in each scope. Their names carry the collection's actions, so a
376
- * change of one makes the committed test stale; a read action that also writes or removes loses its refusal case.
409
+ * 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`).
377
411
  */
378
- const fileCases = (row: EndpointRow, artifact: ContractArtifact): readonly Case[] => {
379
- if (row.source.kind !== 'files') return []
380
- const name = row.source.name
381
- const collection = artifact.files[name]
382
- if (collection === undefined) return []
383
- const call = (operation: string, caller: string, status: number) =>
384
- `expect(await kit.file(${quote(name)}, ${quote(operation)}, ${quote(caller)})).toEqual({ status: ${status} })`
385
- const owner = `${collection.owner} row`
386
- if (row.kind === 'upload') {
387
- return [
388
- testCase(`${row.id}: a caller with ${collection.write} uploads to an own ${owner}`, call('upload', 'own', 200)),
389
- testCase(`${row.id}: the ${owner} of another scope is 404`, call('upload', 'other', 404)),
390
- ...(collection.write === collection.read ? [] : [
391
- testCase(`${row.id}: a caller with only ${collection.read} cannot upload`, call('upload', 'reader', 403)),
392
- ]),
393
- ]
394
- }
395
- if (row.kind === 'download') {
396
- return [
397
- testCase(`${row.id}: a caller with ${collection.read} downloads an own file`, call('download', 'own', 200)),
398
- testCase(`${row.id}: a file of another scope is 404`, call('download', 'other', 404)),
399
- ]
412
+ const capabilityCases = (row: EndpointRow, fixtures: EndpointFixtures): readonly Case[] => {
413
+ if (row.requirement?.kind !== 'capabilities' || !row.callers.some((caller) => caller === 'human' || caller === 'machine')) return []
414
+ const input = inputOf(row, fixtures)
415
+ if (input === undefined) return []
416
+ const seed = fixtures.seeds[row.id]
417
+ return Object.entries(row.requirement.capabilities).map(([name, { action, access }]) => {
418
+ const args = `${quote(row.id)}, ${quote(name)}, ${renderSample(input)}${seed === undefined ? '' : `, ${renderSample(seed)}`}`
419
+ const call = `await kit.capability(${args})`
420
+ if (access.form === 'over') {
421
+ return testCase(`${row.id}: a caller without ${action} (capability ${name}) is 403`, `expect(${call}).toEqual({ status: 403 })`)
422
+ }
423
+ 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} })`,
427
+ )
428
+ })
429
+ }
430
+
431
+ /**
432
+ * A public procedure's case: anyone reaches it with no credential, or, behind a challenge, is refused without a solved
433
+ * one. Its name carries the workload's actions, so a change of them makes the committed test stale.
434
+ */
435
+ const publicCases = (row: EndpointRow, artifact: ContractArtifact, fixtures: EndpointFixtures): readonly Case[] => {
436
+ if (row.kind !== 'public') return []
437
+ const input = inputOf(row, fixtures)
438
+ if (input === undefined) return []
439
+ const call = `await kit.anyone(${quote(row.id)}, ${renderSample(input)})`
440
+ const actions = artifact.declared?.[row.id]?.actions ?? []
441
+ if (artifact.procedures?.[row.id]?.challenge != null) {
442
+ return [testCase(`${row.id}: anyone without a solved challenge is 400`, `expect(${call}).toEqual({ answered: false, status: 400 })`)]
400
443
  }
401
- // The list is a query on the owner: the endpoint cases above cover it.
402
- if (row.kind !== 'mutation') return []
403
444
  return [
404
- testCase(`${row.id}: a caller with ${collection.delete} removes an own file`, call('remove', 'own', 200)),
405
- ...(collection.delete === collection.read ? [] : [
406
- testCase(`${row.id}: a caller with only ${collection.read} cannot remove`, call('remove', 'reader', 403)),
407
- ]),
445
+ testCase(`${row.id}: anyone reaches it with no credential, running with ${actions.join(', ')}`, `expect(${call}).toEqual({ answered: true })`),
408
446
  ]
409
447
  }
410
448
 
@@ -416,7 +454,11 @@ const endpointTestBody = (
416
454
  ): { readonly body: string; readonly cases: readonly string[] } | undefined => {
417
455
  const cases = [...artifact.endpoints].sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).flatMap((
418
456
  row,
419
- ) => [...endpointCases(row, artifact, policies, fixtures), ...fileCases(row, artifact)])
457
+ ) => [
458
+ ...endpointCases(row, artifact, policies, fixtures),
459
+ ...capabilityCases(row, fixtures),
460
+ ...publicCases(row, artifact, fixtures),
461
+ ])
420
462
  if (cases.length === 0) return undefined
421
463
  const body = [
422
464
  '// The endpoint access tests of this application, written by fabrika db test-scaffold from fabrika.contract.ts and',
@@ -512,7 +554,9 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
512
554
  )
513
555
  for (const id of Object.keys(fixtures.inputs).sort()) {
514
556
  if (!tested.some((row) => row.id === id)) {
515
- findings.push(at(`${id} is no endpoint with an on, in, over, app or creates access form`, 'a fixture of a tested endpoint, or none'))
557
+ findings.push(
558
+ at(`${id} is no endpoint with an on, in, over, app or creates access form, or several capabilities`, 'a fixture of a tested endpoint, or none'),
559
+ )
516
560
  }
517
561
  }
518
562
  for (const [id, fields] of Object.entries(fixtures.members).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
package/src/slice.ts CHANGED
@@ -140,9 +140,15 @@ function handleSite(node: AstNode): HandleSite | undefined {
140
140
  return { ranges: [{ start: receiverRange.end, end: call.end }], receiver }
141
141
  }
142
142
 
143
- /** Whether an identifier names a type or a value here, rather than a key, a property or a label. */
144
- function isReference(node: AstNode, parent: AstNode | undefined): boolean {
143
+ /**
144
+ * Whether an identifier names a type or a value here, rather than a key, a property or a label. `export { name }`
145
+ * without a source names a binding of the module.
146
+ */
147
+ function isReference(node: AstNode, ancestors: readonly AstNode[]): boolean {
148
+ const parent = ancestors.at(-1)
145
149
  switch (parent?.type) {
150
+ case 'ExportSpecifier':
151
+ return parent['local'] === node && ancestors.at(-2)?.['source'] == null
146
152
  case 'TSTypeReference':
147
153
  return parent['typeName'] === node
148
154
  case 'TSQualifiedName':
@@ -224,7 +230,7 @@ function referencedNames(statements: readonly AstNode[], skipped: (node: AstNode
224
230
  walk(statement, (node, ancestors) => {
225
231
  if (skipped(node)) return 'skip'
226
232
  const name = identifierName(node)
227
- if (name !== undefined && !own.has(node) && isReference(node, ancestors.at(-1))) referenced.add(name)
233
+ if (name !== undefined && !own.has(node) && isReference(node, ancestors)) referenced.add(name)
228
234
  return undefined
229
235
  })
230
236
  }