@fabrika/check 0.0.0-stage → 0.0.1
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/package.json +48 -5
- package/src/ast.ts +268 -0
- package/src/bun-plugin.ts +63 -0
- package/src/check.ts +183 -0
- package/src/cli.ts +88 -0
- package/src/contract.ts +254 -0
- package/src/endpoint-fixtures.ts +221 -0
- package/src/finding.ts +88 -0
- package/src/graph.ts +206 -0
- package/src/index.ts +15 -0
- package/src/inputs.ts +88 -0
- package/src/jsonc.ts +63 -0
- package/src/layout.ts +115 -0
- package/src/limits.ts +15 -0
- package/src/packed.ts +66 -0
- package/src/reader/problems.ts +11 -0
- package/src/reader/schema.ts +551 -0
- package/src/reader/surface.ts +1087 -0
- package/src/reader/tables.ts +116 -0
- package/src/reader/value.ts +644 -0
- package/src/references.ts +95 -0
- package/src/resolution.ts +178 -0
- package/src/rules/contract.ts +78 -0
- package/src/rules/crontab.ts +147 -0
- package/src/rules/framework.ts +177 -0
- package/src/rules/identity.ts +80 -0
- package/src/rules/isolation.ts +79 -0
- package/src/rules/json.ts +28 -0
- package/src/rules/literal.ts +736 -0
- package/src/rules/migrations.ts +87 -0
- package/src/rules/modules.ts +226 -0
- package/src/rules/packages.ts +168 -0
- package/src/rules/runtime.ts +507 -0
- package/src/rules/structure.ts +299 -0
- package/src/rules/tests.ts +208 -0
- package/src/rules/types.ts +62 -0
- package/src/scaffold-sample.ts +108 -0
- package/src/scaffold.ts +605 -0
- package/src/scope.ts +108 -0
- package/src/slice.ts +339 -0
- package/src/toml.ts +159 -0
- package/src/trust.ts +189 -0
- package/src/version.ts +4 -0
- package/README.md +0 -3
package/src/scaffold.ts
ADDED
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
// The tests `fabrika db test-scaffold` writes. Policy isolation tests, one file per table a store reaches, from the
|
|
2
|
+
// table policies alone: they prove the data layer enforces each policy, on a layer of their own. Endpoint access tests,
|
|
3
|
+
// one file per application, from the contract: they run the application's own `serve(…)` and handlers. The checker
|
|
4
|
+
// regenerates both to find a missing, edited, stale or orphaned file. Browser-safe: no file API.
|
|
5
|
+
|
|
6
|
+
import { GENERATED_INVITATION, GENERATED_LINK, GENERATED_MEMBER, GENERATED_ROW_PREFIX } from '@fabrika/app/contract'
|
|
7
|
+
import {
|
|
8
|
+
type ContractArtifact,
|
|
9
|
+
endpointDirectory,
|
|
10
|
+
endpointMembers,
|
|
11
|
+
type EndpointRow,
|
|
12
|
+
type SchemaShape,
|
|
13
|
+
type TablePolicyArtifact,
|
|
14
|
+
} from '@fabrika/auth-core'
|
|
15
|
+
import { tablePolicies } from '@fabrika/db/tables'
|
|
16
|
+
import { ContractSourceError, readContractSource, readTablesDefinition } from './contract'
|
|
17
|
+
import { type EndpointFixtures, isSampleObject, NO_FIXTURES, readEndpointFixtures } from './endpoint-fixtures'
|
|
18
|
+
import type { Finding } from './finding'
|
|
19
|
+
import { CONTRACT_FILE, ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR } from './layout'
|
|
20
|
+
|
|
21
|
+
export { ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR } from './layout'
|
|
22
|
+
import { generatedTestHeader } from './rules/tests'
|
|
23
|
+
import { renderSample, type Sample, sample } from './scaffold-sample'
|
|
24
|
+
|
|
25
|
+
export const policyTestPath = (table: string): string => `${POLICY_TESTS_DIR}${table}${POLICY_TEST_SUFFIX}`
|
|
26
|
+
|
|
27
|
+
/** One generated test file: its full text, header included, and the name of every test case it registers. */
|
|
28
|
+
export interface GeneratedTest {
|
|
29
|
+
readonly text: string
|
|
30
|
+
readonly cases: readonly string[]
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type Policies = Readonly<Record<string, TablePolicyArtifact>>
|
|
34
|
+
|
|
35
|
+
interface Case {
|
|
36
|
+
readonly name: string
|
|
37
|
+
readonly lines: readonly string[]
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const testCase = (name: string, ...lines: readonly string[]): Case => ({ name, lines })
|
|
41
|
+
|
|
42
|
+
const quote = (text: string): string => `'${text.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`
|
|
43
|
+
|
|
44
|
+
const renderCase = (item: Case): string =>
|
|
45
|
+
[`\t\ttest(${quote(item.name)}, async () => {`, ...item.lines.map((line) => `\t\t\t${line}`), '\t\t})'].join('\n')
|
|
46
|
+
|
|
47
|
+
/** The dimension a caller's grants are scoped by: the container of a dimension table, or its own; a child's parent's. */
|
|
48
|
+
const grantDimension = (policies: Policies, policy: TablePolicyArtifact): string | undefined => {
|
|
49
|
+
const scope = policy.scope
|
|
50
|
+
if (scope.mode === 'dimension') return scope.container?.dimension ?? scope.dimension
|
|
51
|
+
if (scope.mode !== 'child') return undefined
|
|
52
|
+
const parent = policies[scope.parent]?.scope
|
|
53
|
+
return parent?.mode === 'dimension' ? (parent.container?.dimension ?? parent.dimension) : undefined
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const isolationCases = (policy: TablePolicyArtifact, dimension: string): readonly Case[] => {
|
|
57
|
+
const { actions, scope } = policy
|
|
58
|
+
const child = scope.mode === 'child'
|
|
59
|
+
const contained = scope.mode === 'child' || (scope.mode === 'dimension' && scope.container !== null)
|
|
60
|
+
const other = `another ${dimension}`
|
|
61
|
+
const writes = policy.update.length > 0 || policy.version !== null
|
|
62
|
+
const cases: Case[] = [
|
|
63
|
+
testCase('get answers its own row', "expect((await kit.get('own')).status).toBe(200)"),
|
|
64
|
+
testCase(`get of a row in ${other} is 404`, "expect((await kit.get('other')).status).toBe(404)"),
|
|
65
|
+
]
|
|
66
|
+
if (child) {
|
|
67
|
+
cases.push(testCase(`get of a key in ${other} through its own parent is 404`, "expect((await kit.get('crossed')).status).toBe(404)"))
|
|
68
|
+
cases.push(
|
|
69
|
+
testCase('a list by its own parent reaches only its own row', "expect(await kit.listByParent('own')).toEqual({ status: 200, rows: ['own'] })"),
|
|
70
|
+
)
|
|
71
|
+
cases.push(testCase(`a list by a parent in ${other} is 404`, "expect((await kit.listByParent('other')).status).toBe(404)"))
|
|
72
|
+
}
|
|
73
|
+
cases.push(testCase('a list reaches only its own row', "expect(await kit.list()).toEqual({ status: 200, rows: ['own'] })"))
|
|
74
|
+
cases.push(testCase('a count counts only its own row', "expect(await kit.count()).toEqual({ status: 200, count: '1' })"))
|
|
75
|
+
if (actions.insert !== null) {
|
|
76
|
+
if (contained) cases.push(testCase(`insert into its own ${dimension} succeeds`, "expect((await kit.insert('own')).status).toBe(200)"))
|
|
77
|
+
cases.push(testCase(`insert into ${other} is 403`, "expect((await kit.insert('other')).status).toBe(403)"))
|
|
78
|
+
}
|
|
79
|
+
if (actions.update !== null) {
|
|
80
|
+
if (writes) cases.push(testCase('update of its own row succeeds', "expect((await kit.update('own')).status).toBe(200)"))
|
|
81
|
+
cases.push(testCase(`update of a row in ${other} is 404`, "expect((await kit.update('other')).status).toBe(404)"))
|
|
82
|
+
if (child) {
|
|
83
|
+
cases.push(testCase(`update of a key in ${other} through its own parent is 404`, "expect((await kit.update('crossed')).status).toBe(404)"))
|
|
84
|
+
}
|
|
85
|
+
if (actions.update !== actions.read) {
|
|
86
|
+
cases.push(testCase(`update refuses a Ref for ${actions.read}`, 'expect(await kit.updateWithRead()).toEqual({ status: 200, refused: true })'))
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (actions.delete !== null) {
|
|
90
|
+
cases.push(testCase('remove of its own row succeeds', "expect((await kit.remove('own')).status).toBe(200)"))
|
|
91
|
+
cases.push(testCase(`remove of a row in ${other} is 404`, "expect((await kit.remove('other')).status).toBe(404)"))
|
|
92
|
+
if (child) {
|
|
93
|
+
cases.push(testCase(`remove of a key in ${other} through its own parent is 404`, "expect((await kit.remove('crossed')).status).toBe(404)"))
|
|
94
|
+
}
|
|
95
|
+
if (actions.delete !== actions.read) {
|
|
96
|
+
cases.push(testCase(`remove refuses a Ref for ${actions.read}`, 'expect(await kit.removeWithRead()).toEqual({ status: 200, refused: true })'))
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
for (const action of actions.appRead ?? []) {
|
|
100
|
+
cases.push(
|
|
101
|
+
testCase(
|
|
102
|
+
`an app endpoint of ${action} lists every row`,
|
|
103
|
+
`expect(await kit.appList(${quote(action)})).toEqual({ status: 200, rows: ['own', 'other'] })`,
|
|
104
|
+
),
|
|
105
|
+
testCase(
|
|
106
|
+
`an app endpoint of ${action} reads the columns of its own action`,
|
|
107
|
+
`expect(await kit.appColumns(${quote(action)})).toEqual({ status: 200, leaked: [], missing: [] })`,
|
|
108
|
+
),
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
for (const action of actions.appCount ?? []) {
|
|
112
|
+
cases.push(
|
|
113
|
+
testCase(`an app endpoint of ${action} counts every row`, `expect(await kit.appCount(${quote(action)})).toEqual({ status: 200, counted: 2 })`),
|
|
114
|
+
testCase(
|
|
115
|
+
`an app endpoint of ${action} lists no row`,
|
|
116
|
+
`expect(await kit.appListWithCount(${quote(action)})).toEqual({ status: 200, refused: true })`,
|
|
117
|
+
),
|
|
118
|
+
testCase(
|
|
119
|
+
`an app endpoint of ${action} groups no row`,
|
|
120
|
+
`expect(await kit.appGroupWithCount(${quote(action)})).toEqual({ status: 200, refused: true })`,
|
|
121
|
+
),
|
|
122
|
+
)
|
|
123
|
+
}
|
|
124
|
+
return cases
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* An application table's cases: its rows lie in no scope, so the boundary is the grant. A holder of the table's actions
|
|
129
|
+
* as global grants reaches each operation; a holder of the same actions in one scope only is refused by the proxy. Where
|
|
130
|
+
* the vocabulary has a dimension, a scoped site of the read action reads every row, and one of another action none.
|
|
131
|
+
*/
|
|
132
|
+
const appIsolationCases = (policy: TablePolicyArtifact, scopedSites: boolean): readonly Case[] => {
|
|
133
|
+
const { actions } = policy
|
|
134
|
+
const writes = policy.update.length > 0 || policy.version !== null
|
|
135
|
+
const pair = (operation: string, call: string, done: string): Case[] => [
|
|
136
|
+
testCase(`${operation} by a global holder succeeds`, `expect(${call.replace('CALLER', "'global'")}).${done}`),
|
|
137
|
+
testCase(`${operation} by a holder in one scope only is 403`, `expect((${call.replace('CALLER', "'scoped'")}).status).toBe(403)`),
|
|
138
|
+
]
|
|
139
|
+
const cases: Case[] = [
|
|
140
|
+
...pair('get', 'await kit.get(CALLER)', 'toMatchObject({ status: 200 })'),
|
|
141
|
+
...pair('a list', 'await kit.list(CALLER)', "toEqual({ status: 200, rows: ['own'] })"),
|
|
142
|
+
]
|
|
143
|
+
if (actions.insert !== null) cases.push(...pair('insert', 'await kit.insert(CALLER)', 'toEqual({ status: 200 })'))
|
|
144
|
+
if (actions.update !== null) {
|
|
145
|
+
if (writes) cases.push(...pair('update', 'await kit.update(CALLER)', 'toEqual({ status: 200 })'))
|
|
146
|
+
if (actions.update !== actions.read) {
|
|
147
|
+
cases.push(
|
|
148
|
+
testCase(`update refuses a capability of ${actions.read}`, 'expect(await kit.updateWithRead()).toEqual({ status: 200, refused: true })'),
|
|
149
|
+
)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (actions.delete !== null) {
|
|
153
|
+
cases.push(...pair('remove', 'await kit.remove(CALLER)', 'toEqual({ status: 200 })'))
|
|
154
|
+
if (actions.delete !== actions.read) {
|
|
155
|
+
cases.push(
|
|
156
|
+
testCase(`remove refuses a capability of ${actions.read}`, 'expect(await kit.removeWithRead()).toEqual({ status: 200, refused: true })'),
|
|
157
|
+
)
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (scopedSites) {
|
|
161
|
+
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)
|
|
163
|
+
if (other !== undefined) {
|
|
164
|
+
cases.push(
|
|
165
|
+
testCase(`a scoped site of ${other} reads no row`, 'expect(await kit.scopedListWithOther()).toEqual({ status: 200, refused: true })'),
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return cases
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const describeBlock = (title: string, cases: readonly Case[]): string =>
|
|
173
|
+
[`\tdescribe(${quote(title)}, () => {`, cases.map(renderCase).join('\n\n'), '\t})'].join('\n')
|
|
174
|
+
|
|
175
|
+
/** `table`'s policy isolation test (everything after the header), or `undefined` for a table no store reaches. */
|
|
176
|
+
const policyTestBody = (
|
|
177
|
+
policies: Policies,
|
|
178
|
+
table: string,
|
|
179
|
+
scopedSites: boolean,
|
|
180
|
+
): { readonly body: string; readonly cases: readonly string[] } | undefined => {
|
|
181
|
+
const policy = policies[table]
|
|
182
|
+
if (policy === undefined) return undefined
|
|
183
|
+
const app = policy.scope.mode === 'app'
|
|
184
|
+
const dimension = grantDimension(policies, policy)
|
|
185
|
+
if (dimension === undefined && !app) return undefined
|
|
186
|
+
const isolation = dimension === undefined ? appIsolationCases(policy, scopedSites) : isolationCases(policy, dimension)
|
|
187
|
+
const own = app ? "'global'" : "'own'"
|
|
188
|
+
// A column with only its own write action is read by the table's read action, so it is returned like any other.
|
|
189
|
+
const hidden = Object.keys(policy.columns).filter((column) => policy.columns[column]?.read !== undefined).sort().map((column) =>
|
|
190
|
+
testCase(`get leaves out ${column}, which has its own read action`, `expect((await kit.get(${own})).columns).not.toContain(${quote(column)})`)
|
|
191
|
+
)
|
|
192
|
+
const title = dimension === undefined
|
|
193
|
+
? `policy of ${table}: only a global holder of its actions reaches a row`
|
|
194
|
+
: `policy of ${table}: a caller of one ${dimension} reaches no row of another`
|
|
195
|
+
const kitOf = app ? 'appPolicyIsolationKit' : 'policyIsolationKit'
|
|
196
|
+
const blocks = [describeBlock(title, isolation)]
|
|
197
|
+
if (hidden.length > 0) blocks.push(describeBlock(`policy of ${table}: a column with its own read action is never returned`, hidden))
|
|
198
|
+
const body = [
|
|
199
|
+
`// The policy isolation tests of ${table}, written by fabrika db test-scaffold from src/db/tables.ts. They prove that`,
|
|
200
|
+
"// the data layer enforces the policy, through a probe of their own: the application's handlers and stores do not run.",
|
|
201
|
+
'// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a policy change.',
|
|
202
|
+
'',
|
|
203
|
+
`import { ${['afterAll', 'describe', 'expect', kitOf, 'test'].sort().join(', ')} } from '@fabrika/app/testing/isolation'`,
|
|
204
|
+
"import { testDatabase } from '@fabrika/db/testing'",
|
|
205
|
+
"import { contract } from '../../../fabrika.contract'",
|
|
206
|
+
"import { tables } from '../tables'",
|
|
207
|
+
'',
|
|
208
|
+
`const label = ${quote(`${table}${POLICY_TEST_SUFFIX}`)}`,
|
|
209
|
+
"const postgres = await testDatabase({ migrations: new URL('../../../db/migrations/', import.meta.url), label })",
|
|
210
|
+
'',
|
|
211
|
+
'if (postgres !== null) {',
|
|
212
|
+
'\tafterAll(() => postgres.close())',
|
|
213
|
+
`\tconst kit = ${kitOf}(contract, tables, ${quote(table)}, postgres)`,
|
|
214
|
+
'',
|
|
215
|
+
blocks.join('\n\n'),
|
|
216
|
+
'}',
|
|
217
|
+
'',
|
|
218
|
+
].join('\n')
|
|
219
|
+
return { body, cases: [...isolation, ...hidden].map((item) => item.name) }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Whether an endpoint gets endpoint access cases: a procedure with an access form, for a person or a machine. */
|
|
223
|
+
const isAccessTested = (row: EndpointRow): boolean => {
|
|
224
|
+
if ((row.kind !== 'query' && row.kind !== 'mutation') || row.requirement === null || row.requirement.kind !== 'action') return false
|
|
225
|
+
return row.callers.some((caller) => caller === 'human' || caller === 'machine')
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Whether an endpoint is a procedure of a link mount: its link holder reaches the object the key is bound to. */
|
|
229
|
+
const isLinkProcedure = (row: EndpointRow): boolean =>
|
|
230
|
+
(row.kind === 'query' || row.kind === 'mutation') && row.requirement?.kind === 'action' && row.callers.some((caller) => caller === 'link')
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* The input an endpoint's cases send: the author's fixture, else a sample of its schema; `undefined` when neither
|
|
234
|
+
* exists. Each field its `members`, `invitations` or `links` name holds `GENERATED_MEMBER`, `GENERATED_INVITATION` or
|
|
235
|
+
* `GENERATED_LINK`, which the kit replaces with a real member, an open invitation or a link it issued; each field its
|
|
236
|
+
* `rows` name holds `GENERATED_ROW_PREFIX` and the table, which the kit replaces with the key of a row it seeded.
|
|
237
|
+
*/
|
|
238
|
+
const inputOf = (row: EndpointRow, fixtures: EndpointFixtures): Readonly<Record<string, Sample>> | undefined => {
|
|
239
|
+
const fixture = fixtures.inputs[row.id]
|
|
240
|
+
const input = fixture ?? (row.input === null ? {} : sample(row.input))
|
|
241
|
+
if (input === undefined || !isSampleObject(input)) return undefined
|
|
242
|
+
const generated = (fields: readonly string[] | undefined, marker: string) => (fields ?? []).map((field) => [field, marker])
|
|
243
|
+
return {
|
|
244
|
+
...input,
|
|
245
|
+
...Object.fromEntries([
|
|
246
|
+
...generated(fixtures.members[row.id], GENERATED_MEMBER),
|
|
247
|
+
...generated(fixtures.invitations[row.id], GENERATED_INVITATION),
|
|
248
|
+
...generated(fixtures.links[row.id], GENERATED_LINK),
|
|
249
|
+
...Object.entries(fixtures.rows[row.id] ?? {}).map(([field, table]) => [field, `${GENERATED_ROW_PREFIX}${table}`]),
|
|
250
|
+
]),
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Whether the endpoint's handler gets `ctx.links`: on or in a dimension a link mount's `issuedBy` names its action for. */
|
|
255
|
+
const issuesLinks = (artifact: ContractArtifact, row: EndpointRow): boolean => {
|
|
256
|
+
if (row.requirement?.kind !== 'action') return false
|
|
257
|
+
const { action, access } = row.requirement
|
|
258
|
+
return (access.form === 'on' || access.form === 'in')
|
|
259
|
+
&& Object.values(artifact.mounts).some((mount) => mount.kind === 'link' && mount.dimension === access.dimension && mount.issuedBy === action)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Whether `shape` admits a principal id: a string, optional or nullable. */
|
|
263
|
+
const admitsString = (shape: SchemaShape | undefined): boolean =>
|
|
264
|
+
shape?.type === 'string' || ((shape?.type === 'optional' || shape?.type === 'nullable') && admitsString(shape.inner))
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Whether a row of `table` lies directly in an object of `dimension`, the only rows the kit seeds there: a dimension
|
|
268
|
+
* table whose container is `dimension`, or a child table of the table that owns it. A row further down needs a
|
|
269
|
+
* container between, which the kit does not seed.
|
|
270
|
+
*/
|
|
271
|
+
const liesDirectlyIn = (policies: Policies, table: string, dimension: string): boolean => {
|
|
272
|
+
const scope = policies[table]?.scope
|
|
273
|
+
if (scope?.mode === 'dimension') return scope.container?.dimension === dimension
|
|
274
|
+
const parent = scope?.mode === 'child' ? policies[scope.parent]?.scope : undefined
|
|
275
|
+
return parent?.mode === 'dimension' && parent.dimension === dimension
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** The read action of the table that owns `dimension`, or `undefined` when no table owns it. */
|
|
279
|
+
const ownerRead = (policies: Policies, dimension: string): string | undefined =>
|
|
280
|
+
Object.values(policies).find((policy) => policy.scope.mode === 'dimension' && policy.scope.dimension === dimension)?.actions.read
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* What the `own` case's caller holds: the endpoint's action, plus what IAM requires of a link's issuer (the actions the
|
|
284
|
+
* link grants) and of a member manager (an assigning role and the assigned role's actions).
|
|
285
|
+
*/
|
|
286
|
+
const ownGrants = (row: EndpointRow, artifact: ContractArtifact, action: string, dimension: string): string => {
|
|
287
|
+
const issues = artifact.declared?.[row.id]?.issues
|
|
288
|
+
const granted = Object.entries(artifact.mounts).flatMap(([name, mount]) =>
|
|
289
|
+
mount.kind === 'link' && mount.dimension === dimension && mount.issuedBy === action && (issues === undefined || issues === name)
|
|
290
|
+
? mount.grants
|
|
291
|
+
: []
|
|
292
|
+
)
|
|
293
|
+
const held = [action, ...new Set(granted)].join(', ')
|
|
294
|
+
return endpointMembers(artifact, row) === 'manage' ? `${held}, an assigning role and the assigned role's actions` : held
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* One endpoint's cases: an object or a value of another scope is refused; no answer holds another scope's rows unless
|
|
299
|
+
* the endpoint declares `unscoped` (it reaches across scopes by design); a write action reads its own target.
|
|
300
|
+
*/
|
|
301
|
+
const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: Policies, fixtures: EndpointFixtures): readonly Case[] => {
|
|
302
|
+
const linked = isLinkProcedure(row)
|
|
303
|
+
if ((!isAccessTested(row) && !linked) || row.requirement === null || row.requirement.kind !== 'action') return []
|
|
304
|
+
const { access, action } = row.requirement
|
|
305
|
+
const input = inputOf(row, fixtures)
|
|
306
|
+
if (input === undefined) return []
|
|
307
|
+
const seed = fixtures.seeds[row.id]
|
|
308
|
+
const args = `${quote(row.id)}, ${renderSample(input)}`
|
|
309
|
+
const seeded = seed === undefined ? args : `${args}, ${renderSample(seed)}`
|
|
310
|
+
const declared = artifact.declared?.[row.id]
|
|
311
|
+
const unscoped = declared !== undefined && Object.keys(declared.unscoped).length > 0
|
|
312
|
+
const read = access.form === 'on' ? ownerRead(policies, access.dimension) : undefined
|
|
313
|
+
const own = read !== undefined && (linked || read !== action)
|
|
314
|
+
const cases: Case[] = []
|
|
315
|
+
// The unseeded probe always runs: a seed meets a precondition, and must not also set aside the state that leaks.
|
|
316
|
+
const leaked = (): Case[] => [
|
|
317
|
+
testCase(
|
|
318
|
+
`${row.id}: the answer to one scope holds nothing of the scope answered before it`,
|
|
319
|
+
`expect(await kit.leaked(${args})).toEqual({ answered: true, leaked: [] })`,
|
|
320
|
+
),
|
|
321
|
+
...(seed === undefined ? [] : [
|
|
322
|
+
testCase(
|
|
323
|
+
`${row.id}: with its seed, the answer to one scope holds nothing of the scope answered before it`,
|
|
324
|
+
`expect(await kit.leaked(${seeded})).toEqual({ answered: true, leaked: [] })`,
|
|
325
|
+
),
|
|
326
|
+
]),
|
|
327
|
+
]
|
|
328
|
+
if (access.form === 'creates') {
|
|
329
|
+
return [
|
|
330
|
+
testCase(
|
|
331
|
+
`${row.id}: a caller with ${action} in one ${access.dimension} only creates none (403)`,
|
|
332
|
+
`expect(await kit.scoped(${args})).toEqual({ status: 403 })`,
|
|
333
|
+
),
|
|
334
|
+
testCase(
|
|
335
|
+
`${row.id}: a caller with ${action} held globally creates one`,
|
|
336
|
+
`expect(await kit.global(${args})).toEqual({ answered: true })`,
|
|
337
|
+
),
|
|
338
|
+
]
|
|
339
|
+
}
|
|
340
|
+
if (access.form === 'app') {
|
|
341
|
+
return [
|
|
342
|
+
testCase(`${row.id}: a caller with ${action} in one scope only is 403`, `expect(await kit.scoped(${args})).toEqual({ status: 403 })`),
|
|
343
|
+
testCase(`${row.id}: a caller with ${action} held globally reaches it`, `expect(await kit.global(${args})).toEqual({ answered: true })`),
|
|
344
|
+
]
|
|
345
|
+
}
|
|
346
|
+
if (linked) {
|
|
347
|
+
if (own) {
|
|
348
|
+
cases.push(
|
|
349
|
+
testCase(`${row.id}: the holder of a link to a ${access.dimension} reaches it`, `expect(await kit.own(${seeded})).toEqual({ status: 200 })`),
|
|
350
|
+
)
|
|
351
|
+
}
|
|
352
|
+
return cases
|
|
353
|
+
}
|
|
354
|
+
if (access.form === 'on') {
|
|
355
|
+
cases.push(testCase(`${row.id}: the ${access.dimension} of another scope is 404`, `expect(await kit.denied(${args})).toEqual({ status: 404 })`))
|
|
356
|
+
if (!unscoped) cases.push(...leaked())
|
|
357
|
+
if (own) {
|
|
358
|
+
cases.push(
|
|
359
|
+
testCase(
|
|
360
|
+
`${row.id}: a caller with only ${ownGrants(row, artifact, action, access.dimension)} reaches its own ${access.dimension}`,
|
|
361
|
+
`expect(await kit.own(${seeded})).toEqual({ status: 200 })`,
|
|
362
|
+
),
|
|
363
|
+
)
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
if (access.form === 'in') {
|
|
367
|
+
cases.push(testCase(`${row.id}: the ${access.dimension} of another scope is 403`, `expect(await kit.denied(${args})).toEqual({ status: 403 })`))
|
|
368
|
+
if (declared !== undefined && declared.sql !== null && !unscoped) cases.push(...leaked())
|
|
369
|
+
}
|
|
370
|
+
if (access.form === 'over' && !unscoped) cases.push(...leaked())
|
|
371
|
+
return cases
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
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.
|
|
377
|
+
*/
|
|
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
|
+
]
|
|
400
|
+
}
|
|
401
|
+
// The list is a query on the owner: the endpoint cases above cover it.
|
|
402
|
+
if (row.kind !== 'mutation') return []
|
|
403
|
+
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
|
+
]),
|
|
408
|
+
]
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** The endpoint access test of the application, or `undefined` when no endpoint has an access form to test. */
|
|
412
|
+
const endpointTestBody = (
|
|
413
|
+
artifact: ContractArtifact,
|
|
414
|
+
policies: Policies,
|
|
415
|
+
fixtures: EndpointFixtures,
|
|
416
|
+
): { readonly body: string; readonly cases: readonly string[] } | undefined => {
|
|
417
|
+
const cases = [...artifact.endpoints].sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).flatMap((
|
|
418
|
+
row,
|
|
419
|
+
) => [...endpointCases(row, artifact, policies, fixtures), ...fileCases(row, artifact)])
|
|
420
|
+
if (cases.length === 0) return undefined
|
|
421
|
+
const body = [
|
|
422
|
+
'// The endpoint access tests of this application, written by fabrika db test-scaffold from fabrika.contract.ts and',
|
|
423
|
+
'// src/db/tables.ts. They run src/app.ts itself: callers of two scopes that share no value ask every endpoint with an',
|
|
424
|
+
"// access form, and a caller with only the endpoint's action, plus what IAM requires of a member manager or a link's",
|
|
425
|
+
'// issuer, asks for its own object. A handler bug that needs other data or another order is beyond them; the state a',
|
|
426
|
+
'// precondition needs is a seed in endpoint-access.fixtures.ts.',
|
|
427
|
+
'// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a contract change.',
|
|
428
|
+
'',
|
|
429
|
+
"import { afterAll, describe, endpointAccessKit, expect, test } from '@fabrika/app/testing/isolation'",
|
|
430
|
+
"import { testDatabase } from '@fabrika/db/testing'",
|
|
431
|
+
"import app from '../app'",
|
|
432
|
+
"import { tables } from '../db/tables'",
|
|
433
|
+
'',
|
|
434
|
+
"const label = 'endpoint-access.test.ts'",
|
|
435
|
+
"const postgres = await testDatabase({ migrations: new URL('../../db/migrations/', import.meta.url), label })",
|
|
436
|
+
'',
|
|
437
|
+
'if (postgres !== null) {',
|
|
438
|
+
'\tafterAll(() => postgres.close())',
|
|
439
|
+
'\tconst kit = endpointAccessKit(app, tables, postgres)',
|
|
440
|
+
'',
|
|
441
|
+
describeBlock('endpoints: a caller of one scope reaches nothing of another', cases),
|
|
442
|
+
'}',
|
|
443
|
+
'',
|
|
444
|
+
].join('\n')
|
|
445
|
+
return { body, cases: cases.map((item) => item.name) }
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const generated = async ({ body, cases }: { readonly body: string; readonly cases: readonly string[] }): Promise<GeneratedTest> => ({
|
|
449
|
+
text: `${await generatedTestHeader(body)}\n${body}`,
|
|
450
|
+
cases,
|
|
451
|
+
})
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Every test the scaffold writes for these policies and, when the application has a contract, its artifact; by path.
|
|
455
|
+
* Endpoint access tests exist only for an application on `@fabrika/db`, which has policies to seed rows from.
|
|
456
|
+
*/
|
|
457
|
+
export const generatedTests = async (
|
|
458
|
+
policies: Policies,
|
|
459
|
+
artifact: ContractArtifact | null,
|
|
460
|
+
fixtures: EndpointFixtures = NO_FIXTURES,
|
|
461
|
+
): Promise<ReadonlyMap<string, GeneratedTest>> => {
|
|
462
|
+
const files = new Map<string, GeneratedTest>()
|
|
463
|
+
// The kit's scoped sites are `over` the vocabulary's first dimension: without one, no scoped site exists.
|
|
464
|
+
const scopedSites = artifact !== null && Object.keys(artifact.dimensions).length > 0
|
|
465
|
+
for (const table of Object.keys(policies).sort()) {
|
|
466
|
+
const test = policyTestBody(policies, table, scopedSites)
|
|
467
|
+
if (test !== undefined) files.set(policyTestPath(table), await generated(test))
|
|
468
|
+
}
|
|
469
|
+
const endpoints = artifact === null || files.size === 0 ? undefined : endpointTestBody(artifact, policies, fixtures)
|
|
470
|
+
if (endpoints !== undefined) files.set(ENDPOINT_ACCESS_TEST, await generated(endpoints))
|
|
471
|
+
return files
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
export interface ScaffoldInputs {
|
|
475
|
+
readonly policies: Policies
|
|
476
|
+
readonly artifact: ContractArtifact | null
|
|
477
|
+
readonly fixtures: EndpointFixtures
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** What the scaffold reads from an application's files; throws `ContractSourceError` or `ContractError` as the reader does. */
|
|
481
|
+
export const scaffoldInputs = (files: ReadonlyMap<string, string>): ScaffoldInputs => {
|
|
482
|
+
const tables = readTablesDefinition(files)
|
|
483
|
+
const policies = tables === null ? {} : tablePolicies(tables)
|
|
484
|
+
const fixtures = readEndpointFixtures(files)
|
|
485
|
+
if (!fixtures.ok) throw new ContractSourceError(fixtures.findings)
|
|
486
|
+
// Endpoint tests seed rows from the policies, so without src/db/tables.ts there is nothing to compile them against.
|
|
487
|
+
const artifact = files.has(CONTRACT_FILE) && tables !== null ? readContractSource(files, tables) : null
|
|
488
|
+
return { policies, artifact, fixtures: fixtures.fixtures }
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* What stops the endpoint access tests from covering every endpoint: one whose input the scaffold cannot sample and
|
|
493
|
+
* the author gave no fixture, and a fixture of no tested endpoint. Each is an `endpoint-fixture` finding.
|
|
494
|
+
*/
|
|
495
|
+
export const missingEndpointFixtures = ({ policies, artifact, fixtures }: ScaffoldInputs): readonly Finding[] => {
|
|
496
|
+
if (artifact === null || Object.keys(policies).length === 0) return []
|
|
497
|
+
const at = (message: string, allowed: string): Finding => ({
|
|
498
|
+
file: ENDPOINT_FIXTURES_FILE,
|
|
499
|
+
line: 1,
|
|
500
|
+
column: 1,
|
|
501
|
+
severity: 'refusal',
|
|
502
|
+
rule: 'endpoint-fixture',
|
|
503
|
+
message,
|
|
504
|
+
allowed,
|
|
505
|
+
})
|
|
506
|
+
const tested = artifact.endpoints.filter((row) => isAccessTested(row) || isLinkProcedure(row))
|
|
507
|
+
const findings = tested.filter((row) => inputOf(row, fixtures) === undefined).map((row) =>
|
|
508
|
+
at(
|
|
509
|
+
`${row.id}: the scaffold cannot write an input its schema admits, so its endpoint access cases need one here`,
|
|
510
|
+
`export const fixtures = { '${row.id}': { … } }, an input the endpoint's schema admits`,
|
|
511
|
+
)
|
|
512
|
+
)
|
|
513
|
+
for (const id of Object.keys(fixtures.inputs).sort()) {
|
|
514
|
+
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'))
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
for (const [id, fields] of Object.entries(fixtures.members).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
|
|
519
|
+
const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate))
|
|
520
|
+
const directory = row === undefined ? null : endpointDirectory(artifact, row)
|
|
521
|
+
if (row === undefined || directory === null) {
|
|
522
|
+
findings.push(
|
|
523
|
+
at(
|
|
524
|
+
`${id} is no tested endpoint below a dimension with members, whose handler could look one up`,
|
|
525
|
+
"export const members = { '<endpoint id>': ['<input field>'] }, for an endpoint on or in a dimension with members or below one",
|
|
526
|
+
),
|
|
527
|
+
)
|
|
528
|
+
continue
|
|
529
|
+
}
|
|
530
|
+
const input = row.input
|
|
531
|
+
for (const field of fields) {
|
|
532
|
+
if (input?.type !== 'object' || !admitsString(input.fields[field])) {
|
|
533
|
+
findings.push(at(`${id}: ${field} is no string field of its input, so it cannot name a member`, 'a top-level string field of the input'))
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
const sortedById = (fields: Readonly<Record<string, readonly string[]>>) =>
|
|
538
|
+
Object.entries(fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
539
|
+
const holders = [
|
|
540
|
+
{
|
|
541
|
+
fields: fixtures.invitations,
|
|
542
|
+
names: 'an invitation',
|
|
543
|
+
admits: (row: EndpointRow) => endpointMembers(artifact, row) === 'manage',
|
|
544
|
+
refusal: (id: string) => `${id} is no tested endpoint that manages a dimension's members, whose handler could cancel an invitation`,
|
|
545
|
+
allowed: "export const invitations = { '<endpoint id>': ['<input field>'] }, for an endpoint with its dimension's members.manage",
|
|
546
|
+
},
|
|
547
|
+
{
|
|
548
|
+
fields: fixtures.links,
|
|
549
|
+
names: 'a share link',
|
|
550
|
+
admits: (row: EndpointRow) => issuesLinks(artifact, row),
|
|
551
|
+
refusal: (id: string) => `${id} is no tested endpoint that issues a share link, whose handler could revoke one`,
|
|
552
|
+
allowed: "export const links = { '<endpoint id>': ['<input field>'] }, for an endpoint whose action a link mount's issuedBy names",
|
|
553
|
+
},
|
|
554
|
+
]
|
|
555
|
+
for (const holder of holders) {
|
|
556
|
+
for (const [id, fields] of sortedById(holder.fields)) {
|
|
557
|
+
const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate) && holder.admits(candidate))
|
|
558
|
+
if (row === undefined) {
|
|
559
|
+
findings.push(at(holder.refusal(id), holder.allowed))
|
|
560
|
+
continue
|
|
561
|
+
}
|
|
562
|
+
for (const field of fields) {
|
|
563
|
+
if (row.input?.type !== 'object' || !admitsString(row.input.fields[field])) {
|
|
564
|
+
findings.push(at(`${id}: ${field} is no string field of its input, so it cannot name ${holder.names}`, 'a top-level string field of the input'))
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
for (const [id, fields] of Object.entries(fixtures.rows).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
|
|
570
|
+
const row = tested.find((candidate) => candidate.id === id)
|
|
571
|
+
const access = row?.requirement?.kind === 'action' ? row.requirement.access : undefined
|
|
572
|
+
const owned = access?.form === 'on' && ownerRead(policies, access.dimension) !== undefined
|
|
573
|
+
if (row === undefined || access?.form !== 'on' || !owned) {
|
|
574
|
+
findings.push(
|
|
575
|
+
at(
|
|
576
|
+
`${id} is no tested endpoint on an object a table owns, in which the kit could seed a row`,
|
|
577
|
+
"export const rows = { '<endpoint id>': { <input field>: '<table>' } }, for an endpoint on a dimension a table owns",
|
|
578
|
+
),
|
|
579
|
+
)
|
|
580
|
+
continue
|
|
581
|
+
}
|
|
582
|
+
for (const [field, table] of Object.entries(fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
|
|
583
|
+
if (row.input?.type !== 'object' || !admitsString(row.input.fields[field])) {
|
|
584
|
+
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'))
|
|
585
|
+
} else if (!liesDirectlyIn(policies, table, access.dimension)) {
|
|
586
|
+
findings.push(
|
|
587
|
+
at(
|
|
588
|
+
`${id}: ${table} is no dimension or child table that lies directly in a ${access.dimension}, so the kit seeds none in the endpoint's object (it seeds no container between)`,
|
|
589
|
+
`a child table of the table that owns ${access.dimension}, or a dimension table whose container is ${access.dimension}`,
|
|
590
|
+
),
|
|
591
|
+
)
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
const seeded = (row: EndpointRow): boolean =>
|
|
596
|
+
row.requirement?.kind === 'action' && (row.requirement.access.form === 'on' || row.requirement.access.form === 'in')
|
|
597
|
+
for (const id of Object.keys(fixtures.seeds).sort()) {
|
|
598
|
+
if (!tested.some((row) => row.id === id && seeded(row))) {
|
|
599
|
+
findings.push(
|
|
600
|
+
at(`${id} is no endpoint with an on or in access form, whose row a seed sets`, "export const seeds = { '<endpoint id>': { <column>: <value> } }"),
|
|
601
|
+
)
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
return findings
|
|
605
|
+
}
|