@fabrika/check 0.9.0-dev.2 → 0.9.0-dev.20
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 +7 -7
- package/src/ast.ts +69 -6
- package/src/check.ts +135 -32
- package/src/cli.ts +23 -4
- package/src/contract.ts +42 -6
- package/src/dialect.ts +29 -0
- package/src/finding.ts +14 -6
- package/src/index.ts +4 -12
- package/src/inputs.ts +4 -2
- package/src/layout.ts +21 -10
- package/src/limits.ts +13 -3
- package/src/migration-base.ts +85 -0
- package/src/reader/schema.ts +42 -512
- package/src/reader/surface.ts +43 -5
- package/src/reader/value.ts +18 -6
- package/src/resolution.ts +2 -2
- package/src/rules/cloudflare.ts +59 -0
- package/src/rules/compile.ts +32 -0
- package/src/rules/framework.ts +2 -2
- package/src/rules/literal.ts +3 -1
- package/src/rules/migration-history.ts +70 -0
- package/src/rules/migrations.ts +248 -9
- package/src/rules/modules.ts +9 -3
- package/src/rules/platform-migrations.ts +100 -0
- package/src/rules/runtime.ts +45 -14
- package/src/rules/structure.ts +32 -15
- package/src/rules/tests.ts +9 -60
- package/src/trust.ts +8 -4
- package/types/src/ast.d.ts +6 -0
- package/types/src/check.d.ts +3 -0
- package/types/src/contract.d.ts +1 -0
- package/types/src/dialect.d.ts +8 -0
- package/types/src/finding.d.ts +6 -5
- package/types/src/index.d.ts +4 -3
- package/types/src/layout.d.ts +18 -9
- package/types/src/limits.d.ts +12 -2
- package/types/src/migration-base.d.ts +9 -0
- package/types/src/reader/schema.d.ts +5 -2
- package/types/src/reader/value.d.ts +2 -2
- package/types/src/rules/cloudflare.d.ts +9 -0
- package/types/src/rules/compile.d.ts +7 -0
- package/types/src/rules/framework.d.ts +1 -1
- package/types/src/rules/migration-history.d.ts +12 -0
- package/types/src/rules/migrations.d.ts +28 -0
- package/types/src/rules/platform-migrations.d.ts +15 -0
- package/types/src/rules/runtime.d.ts +7 -2
- package/types/src/rules/structure.d.ts +8 -3
- package/types/src/rules/tests.d.ts +6 -14
- package/src/endpoint-fixtures.ts +0 -221
- package/src/rules/isolation.ts +0 -79
- package/src/scaffold-sample.ts +0 -111
- package/src/scaffold.ts +0 -650
- package/types/src/endpoint-fixtures.d.ts +0 -36
- package/types/src/rules/isolation.d.ts +0 -18
- package/types/src/scaffold-sample.d.ts +0 -8
- package/types/src/scaffold.d.ts +0 -28
package/src/rules/migrations.ts
CHANGED
|
@@ -2,16 +2,18 @@ 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'
|
|
13
15
|
import type { Finding } from '../finding'
|
|
14
|
-
import { MIGRATIONS_DIR } from '../layout'
|
|
16
|
+
import { MIGRATIONS_DIR, TABLES_FILE } from '../layout'
|
|
15
17
|
|
|
16
18
|
const MIGRATION_NAME = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})_[a-z0-9]+(?:_[a-z0-9]+)*\.sql$/
|
|
17
19
|
const ALLOWED = 'db/migrations/YYYYMMDDHHMMSS_slug.sql with a lowercase snake_case slug, as fabrika db new <slug> writes it'
|
|
@@ -43,6 +45,98 @@ 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 statementsOf(lexSqlite(sql).tokens)) {
|
|
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
|
+
|
|
109
|
+
/**
|
|
110
|
+
* A view is read-only (ADR-0072); on SQLite an INSTEAD OF trigger would make a view writable, so it is refused. SQLite
|
|
111
|
+
* takes INSTEAD OF only on a view, so the timing alone, written before the trigger's `ON`, names one.
|
|
112
|
+
*/
|
|
113
|
+
export const checkSqliteViewTriggers = (files: ReadonlyMap<string, string>): Finding[] => {
|
|
114
|
+
const findings: Finding[] = []
|
|
115
|
+
for (const [path, sql] of files) {
|
|
116
|
+
if (!path.startsWith(MIGRATIONS_DIR) || !path.endsWith('.sql')) continue
|
|
117
|
+
for (const { tokens } of statementsOf(lexSqlite(sql).tokens)) {
|
|
118
|
+
if (upperWord(tokens[0]) !== 'CREATE') continue
|
|
119
|
+
const at = skipWords(tokens, skipWords(tokens, 1, 'TEMP'), 'TEMPORARY')
|
|
120
|
+
if (upperWord(tokens[at]) !== 'TRIGGER') continue
|
|
121
|
+
for (let index = at + 1; index < tokens.length && upperWord(tokens[index]) !== 'ON'; index++) {
|
|
122
|
+
const token = tokens[index]
|
|
123
|
+
if (token === undefined || upperWord(token) !== 'INSTEAD' || upperWord(tokens[index + 1]) !== 'OF') continue
|
|
124
|
+
findings.push({
|
|
125
|
+
file: path,
|
|
126
|
+
line: token.line,
|
|
127
|
+
column: 1,
|
|
128
|
+
severity: 'refusal',
|
|
129
|
+
rule: 'cloudflare-view-trigger',
|
|
130
|
+
message: 'an INSTEAD OF trigger makes a view writable, and a view is read-only (ADR-0072)',
|
|
131
|
+
allowed: 'a view without triggers, written through its source tables',
|
|
132
|
+
})
|
|
133
|
+
break
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return findings
|
|
138
|
+
}
|
|
139
|
+
|
|
46
140
|
/** A declared file column: `table.column` holds files of `kind`. */
|
|
47
141
|
export interface FileColumn {
|
|
48
142
|
readonly table: string
|
|
@@ -263,6 +357,108 @@ export const checkConflictIndexes = (
|
|
|
263
357
|
return checked.filter((insert) => !present.has(`${insert.table}(${keyOf(insert.columns)})`)).map((insert) => insert.finding)
|
|
264
358
|
}
|
|
265
359
|
|
|
360
|
+
/** A table that names an access view under `key` (ADR-0076). */
|
|
361
|
+
export interface AccessKey {
|
|
362
|
+
readonly table: string
|
|
363
|
+
readonly key: string
|
|
364
|
+
readonly views: readonly string[]
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* A table that names an access view needs its key unique on its own, or the view's `row` names several rows at once
|
|
369
|
+
* (ADR-0076 section 1). A view as the target keeps its key unique by its SQL; any other name no migration creates as a
|
|
370
|
+
* table is refused, so a statement the reader does not follow fails closed.
|
|
371
|
+
*/
|
|
372
|
+
export const checkAccessViewKeys = (files: ReadonlyMap<string, string>, keys: readonly AccessKey[]): Finding[] => {
|
|
373
|
+
if (keys.length === 0) {
|
|
374
|
+
return []
|
|
375
|
+
}
|
|
376
|
+
const unique: UniqueIndex[] = []
|
|
377
|
+
const created = new Map<string, { readonly path: string; readonly line: number }>()
|
|
378
|
+
const views = new Set<string>()
|
|
379
|
+
const migrations = [...files.entries()]
|
|
380
|
+
.filter(([path]) => path.startsWith(MIGRATIONS_DIR) && path.endsWith('.sql'))
|
|
381
|
+
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
382
|
+
for (const [path, sql] of migrations) {
|
|
383
|
+
for (const statement of topLevelStatements(sql)) {
|
|
384
|
+
readUniqueIndexes(statement.tokens, unique)
|
|
385
|
+
const table = createdTable(statement.tokens)
|
|
386
|
+
if (table !== undefined) created.set(table, { path, line: statement.line })
|
|
387
|
+
const view = createdView(statement.tokens)
|
|
388
|
+
if (view !== undefined) views.add(view)
|
|
389
|
+
for (const dropped of droppedTables(statement.tokens)) created.delete(dropped)
|
|
390
|
+
const renamed = renamedTable(statement.tokens)
|
|
391
|
+
const at = renamed === undefined ? undefined : created.get(renamed.from)
|
|
392
|
+
if (renamed !== undefined && at !== undefined) {
|
|
393
|
+
created.delete(renamed.from)
|
|
394
|
+
created.set(renamed.to, at)
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
const findings: Finding[] = []
|
|
399
|
+
for (const { table, key, views: named } of keys) {
|
|
400
|
+
const at = created.get(table)
|
|
401
|
+
if (at === undefined && views.has(table)) continue
|
|
402
|
+
if (at !== undefined && unique.some((index) => index.table === table && index.columns.length === 1 && index.columns[0] === key)) continue
|
|
403
|
+
findings.push({
|
|
404
|
+
file: at?.path ?? TABLES_FILE,
|
|
405
|
+
line: at?.line ?? 1,
|
|
406
|
+
column: 1,
|
|
407
|
+
severity: 'refusal',
|
|
408
|
+
rule: 'access-view-key',
|
|
409
|
+
message: at === undefined
|
|
410
|
+
? `${table} names the access view ${named.join(', ')}, and no migration creates ${table} as a table or a view`
|
|
411
|
+
: `${table} names the access view ${named.join(', ')}, and no migration makes its key ${key} unique on its own`,
|
|
412
|
+
allowed: `${key} as the primary key of ${table}, or create unique index ${table}_${key} on ${table} (${key})`,
|
|
413
|
+
})
|
|
414
|
+
}
|
|
415
|
+
return findings
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** The table a `CREATE [UNLOGGED | TEMP | TEMPORARY] TABLE` statement creates. */
|
|
419
|
+
function createdTable(tokens: readonly SqlToken[]): string | undefined {
|
|
420
|
+
if (upperWord(tokens[0]) !== 'CREATE') return undefined
|
|
421
|
+
const at = skipOne(tokens, 1, 'UNLOGGED', 'TEMP', 'TEMPORARY')
|
|
422
|
+
if (upperWord(tokens[at]) !== 'TABLE') return undefined
|
|
423
|
+
return objectNameAt(tokens, skipWords(tokens, at + 1, 'IF', 'NOT', 'EXISTS'))?.name
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** The view a `CREATE [OR REPLACE] [TEMP] [MATERIALIZED] VIEW` statement creates. */
|
|
427
|
+
function createdView(tokens: readonly SqlToken[]): string | undefined {
|
|
428
|
+
if (upperWord(tokens[0]) !== 'CREATE') return undefined
|
|
429
|
+
const at = skipOne(tokens, skipOne(tokens, skipWords(tokens, 1, 'OR', 'REPLACE'), 'TEMP', 'TEMPORARY'), 'MATERIALIZED')
|
|
430
|
+
if (upperWord(tokens[at]) !== 'VIEW') return undefined
|
|
431
|
+
return objectNameAt(tokens, skipWords(tokens, at + 1, 'IF', 'NOT', 'EXISTS'))?.name
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** Past one of `words` at `at`, when the token there is one of them. */
|
|
435
|
+
function skipOne(tokens: readonly SqlToken[], at: number, ...words: readonly string[]): number {
|
|
436
|
+
const word = upperWord(tokens[at])
|
|
437
|
+
return word !== undefined && words.includes(word) ? at + 1 : at
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** The tables a `DROP TABLE` statement drops. */
|
|
441
|
+
function droppedTables(tokens: readonly SqlToken[]): string[] {
|
|
442
|
+
if (upperWord(tokens[0]) !== 'DROP' || upperWord(tokens[1]) !== 'TABLE') return []
|
|
443
|
+
const at = skipWords(tokens, 2, 'IF', 'EXISTS')
|
|
444
|
+
return splitAtCommas(tokens.slice(at)).flatMap((part) => objectNameAt(part, 0)?.name ?? [])
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** `ALTER TABLE from RENAME TO to`. */
|
|
448
|
+
function renamedTable(tokens: readonly SqlToken[]): { readonly from: string; readonly to: string } | undefined {
|
|
449
|
+
if (upperWord(tokens[0]) !== 'ALTER' || upperWord(tokens[1]) !== 'TABLE') return undefined
|
|
450
|
+
const at = skipWords(tokens, skipWords(tokens, 2, 'IF', 'EXISTS'), 'ONLY')
|
|
451
|
+
const from = objectNameAt(tokens, at)?.name
|
|
452
|
+
const end = afterName(tokens, at)
|
|
453
|
+
if (from === undefined || end === undefined || upperWord(tokens[end]) !== 'RENAME' || upperWord(tokens[end + 1]) !== 'TO') return undefined
|
|
454
|
+
const to = objectNameAt(tokens, end + 2)?.name
|
|
455
|
+
return to === undefined ? undefined : { from, to }
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function defaultConstraintName(table: string, primary: boolean, columns: readonly string[]): string {
|
|
459
|
+
return primary ? `${table}_pkey` : `${table}_${columns.join('_')}_key`
|
|
460
|
+
}
|
|
461
|
+
|
|
266
462
|
interface UniqueIndex {
|
|
267
463
|
readonly name: string | undefined
|
|
268
464
|
readonly table: string
|
|
@@ -272,23 +468,28 @@ interface UniqueIndex {
|
|
|
272
468
|
function readUniqueIndexes(tokens: readonly SqlToken[], unique: UniqueIndex[]): void {
|
|
273
469
|
const verb = upperWord(tokens[0])
|
|
274
470
|
const object = upperWord(tokens[1])
|
|
275
|
-
|
|
276
|
-
|
|
471
|
+
const keep = (kept: (index: UniqueIndex) => boolean) => unique.splice(0, unique.length, ...unique.filter(kept))
|
|
472
|
+
const tableAt = verb === 'CREATE' ? skipOne(tokens, 1, 'UNLOGGED', 'TEMP', 'TEMPORARY') : 1
|
|
473
|
+
if (verb === 'CREATE' && upperWord(tokens[tableAt]) === 'TABLE') {
|
|
474
|
+
const at = skipWords(tokens, tableAt + 1, 'IF', 'NOT', 'EXISTS')
|
|
277
475
|
const table = objectNameAt(tokens, at)?.name
|
|
278
476
|
const open = afterName(tokens, at)
|
|
279
477
|
const close = open === undefined ? undefined : closingParenthesis(tokens, open)
|
|
280
478
|
if (table === undefined || open === undefined || close === undefined) return
|
|
479
|
+
keep((index) => index.table !== table)
|
|
281
480
|
for (const element of splitAtCommas(tokens.slice(open + 1, close))) {
|
|
282
481
|
readUniqueElement(table, element, unique)
|
|
283
482
|
}
|
|
483
|
+
} else if (verb === 'DROP' && object === 'TABLE') {
|
|
484
|
+
const dropped = new Set(splitAtCommas(tokens.slice(skipWords(tokens, 2, 'IF', 'EXISTS'))).map((part) => objectNameAt(part, 0)?.name))
|
|
485
|
+
keep((index) => !dropped.has(index.table))
|
|
284
486
|
} else if (verb === 'ALTER' && object === 'TABLE') {
|
|
285
487
|
const at = skipWords(tokens, skipWords(tokens, 2, 'IF', 'EXISTS'), 'ONLY')
|
|
286
488
|
const table = objectNameAt(tokens, at)?.name
|
|
287
489
|
const end = afterName(tokens, at)
|
|
288
490
|
if (table === undefined || end === undefined) return
|
|
289
491
|
for (const action of splitAtCommas(tokens.slice(end))) {
|
|
290
|
-
|
|
291
|
-
readUniqueElement(table, action.slice(skipWords(action, skipWords(action, 1, 'COLUMN'), 'IF', 'NOT', 'EXISTS')), unique)
|
|
492
|
+
alterUnique(table, action, unique, keep)
|
|
292
493
|
}
|
|
293
494
|
} else if (verb === 'CREATE' && object === 'UNIQUE' && upperWord(tokens[2]) === 'INDEX') {
|
|
294
495
|
const rest = tokens.slice(3)
|
|
@@ -312,7 +513,41 @@ function readUniqueIndexes(tokens: readonly SqlToken[], unique: UniqueIndex[]):
|
|
|
312
513
|
}
|
|
313
514
|
}
|
|
314
515
|
|
|
315
|
-
/**
|
|
516
|
+
/**
|
|
517
|
+
* One action of `ALTER TABLE table`: `ADD` a unique column or constraint, `DROP CONSTRAINT` one by name, `DROP COLUMN`,
|
|
518
|
+
* or `RENAME` the table or a column, which the unique keys follow.
|
|
519
|
+
*/
|
|
520
|
+
function alterUnique(table: string, action: readonly SqlToken[], unique: UniqueIndex[], keep: (kept: (index: UniqueIndex) => boolean) => void): void {
|
|
521
|
+
const verb = upperWord(action[0])
|
|
522
|
+
if (verb === 'ADD') {
|
|
523
|
+
readUniqueElement(table, action.slice(skipWords(action, skipWords(action, 1, 'COLUMN'), 'IF', 'NOT', 'EXISTS')), unique)
|
|
524
|
+
} else if (verb === 'DROP' && upperWord(action[1]) === 'CONSTRAINT') {
|
|
525
|
+
const name = objectNameAt(action, skipWords(action, 2, 'IF', 'EXISTS'))?.name
|
|
526
|
+
keep((index) => index.table !== table || index.name !== name)
|
|
527
|
+
} else if (verb === 'DROP') {
|
|
528
|
+
const column = objectNameAt(action, skipWords(action, skipWords(action, 1, 'COLUMN'), 'IF', 'EXISTS'))?.name
|
|
529
|
+
keep((index) => index.table !== table || column === undefined || !index.columns.includes(column))
|
|
530
|
+
} else if (verb === 'RENAME' && upperWord(action[1]) === 'TO') {
|
|
531
|
+
const to = objectNameAt(action, 2)?.name
|
|
532
|
+
if (to !== undefined) unique.splice(0, unique.length, ...unique.map((index) => (index.table === table ? { ...index, table: to } : index)))
|
|
533
|
+
} else if (verb === 'RENAME') {
|
|
534
|
+
const at = skipWords(action, 1, 'COLUMN')
|
|
535
|
+
const from = objectNameAt(action, at)?.name
|
|
536
|
+
const after = afterName(action, at)
|
|
537
|
+
const to = after === undefined || upperWord(action[after]) !== 'TO' ? undefined : objectNameAt(action, after + 1)?.name
|
|
538
|
+
if (from === undefined || to === undefined) return
|
|
539
|
+
unique.splice(
|
|
540
|
+
0,
|
|
541
|
+
unique.length,
|
|
542
|
+
...unique.map((index) => index.table === table ? { ...index, columns: index.columns.map((column) => (column === from ? to : column)) } : index),
|
|
543
|
+
)
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* A column with `UNIQUE` or `PRIMARY KEY`, or a `UNIQUE (…)` or `PRIMARY KEY (…)` table constraint, named as declared or
|
|
549
|
+
* as Postgres names it by default (`<table>_pkey`, `<table>_<columns>_key`), so a later `DROP CONSTRAINT` finds it.
|
|
550
|
+
*/
|
|
316
551
|
function readUniqueElement(table: string, element: readonly SqlToken[], unique: UniqueIndex[]): void {
|
|
317
552
|
const head = upperWord(element[0])
|
|
318
553
|
if (head !== undefined && TABLE_CONSTRAINTS.has(head)) {
|
|
@@ -322,12 +557,16 @@ function readUniqueElement(table: string, element: readonly SqlToken[], unique:
|
|
|
322
557
|
const list = open === undefined ? undefined : columnList(constraint, open)
|
|
323
558
|
const columns = list?.columns.filter((column) => column !== undefined) ?? []
|
|
324
559
|
if (list !== undefined && columns.length > 0 && columns.length === list.columns.length) {
|
|
325
|
-
|
|
560
|
+
const declared = head === 'CONSTRAINT' ? nameText(element[1]) : undefined
|
|
561
|
+
unique.push({ name: declared ?? defaultConstraintName(table, kind === 'PRIMARY', columns), table, columns })
|
|
326
562
|
}
|
|
327
563
|
return
|
|
328
564
|
}
|
|
329
565
|
const column = nameText(element[0])
|
|
330
|
-
|
|
331
|
-
|
|
566
|
+
const words = depthZeroWords(element.slice(1))
|
|
567
|
+
if (column !== undefined && words.some((word) => word === 'UNIQUE' || word === 'PRIMARY')) {
|
|
568
|
+
const named = element.findIndex((token) => upperWord(token) === 'CONSTRAINT')
|
|
569
|
+
const declared = named < 0 ? undefined : nameText(element[named + 1])
|
|
570
|
+
unique.push({ name: declared ?? defaultConstraintName(table, words.includes('PRIMARY'), [column]), table, columns: [column] })
|
|
332
571
|
}
|
|
333
572
|
}
|
package/src/rules/modules.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Report } from '../finding'
|
|
2
|
-
import {
|
|
2
|
+
import { isRelativeSpecifier, isSkippedPath, isTestFile, joinRelative, resolveRelative } from '../layout'
|
|
3
3
|
import type { ModuleReference } from '../references'
|
|
4
4
|
import { type ImportMappings, mappedTargets } from '../resolution'
|
|
5
5
|
|
|
@@ -15,6 +15,11 @@ const NETWORK: Forbidden = {
|
|
|
15
15
|
what: 'a raw network module',
|
|
16
16
|
allowed: 'endpoints declared in the contract; another application through a connector import',
|
|
17
17
|
}
|
|
18
|
+
/** `Bun.fetch`: Bun's own `fetch`, which the egress guard on the global one does not wrap. */
|
|
19
|
+
const BUN_FETCH: Forbidden = {
|
|
20
|
+
what: "Bun's own fetch, past the egress guard",
|
|
21
|
+
allowed: "the global fetch, under the site's egress: ['<origin>'] or a cron job's egress: 'public'",
|
|
22
|
+
}
|
|
18
23
|
const PROCESSES: Forbidden = { what: 'a process-spawning module', allowed: 'a job declared in the contract (c.cron)' }
|
|
19
24
|
|
|
20
25
|
const FORBIDDEN_PACKAGES: ReadonlyMap<string, Forbidden> = new Map([
|
|
@@ -78,6 +83,7 @@ export const FORBIDDEN_BUN_MEMBERS: ReadonlyMap<string, Forbidden> = new Map([
|
|
|
78
83
|
...['sql', 'SQL'].map((name): [string, Forbidden] => [name, DATABASE]),
|
|
79
84
|
...['S3Client', 's3'].map((name): [string, Forbidden] => [name, STORAGE]),
|
|
80
85
|
...['serve', 'connect', 'listen', 'udpSocket'].map((name): [string, Forbidden] => [name, NETWORK]),
|
|
86
|
+
['fetch', BUN_FETCH],
|
|
81
87
|
...['spawn', 'spawnSync', '$'].map((name): [string, Forbidden] => [name, PROCESSES]),
|
|
82
88
|
])
|
|
83
89
|
|
|
@@ -94,7 +100,7 @@ const ALLOWED_ENV = 'values the framework hands the handler through deps or ctx'
|
|
|
94
100
|
* The test kits: the application's signs tokens with its own key and boots the application a second way; the
|
|
95
101
|
* database's reaches tables by name and seeds rows past the data layer. Production never loads either.
|
|
96
102
|
*/
|
|
97
|
-
const TEST_KITS = ['@fabrika/app/testing', '@fabrika/app/react/testing', '@fabrika/db/testing']
|
|
103
|
+
const TEST_KITS = ['@fabrika/app/testing', '@fabrika/app/react/testing', '@fabrika/db/testing', '@fabrika/db/testing-sqlite']
|
|
98
104
|
const TEST_ONLY_ALLOWED = 'the kit in a test file (*.test.ts, *.spec.ts or a __tests__ directory) only'
|
|
99
105
|
|
|
100
106
|
export const isTestKit = (specifier: string): boolean => TEST_KITS.some((kit) => specifier === kit || specifier.startsWith(`${kit}/`))
|
|
@@ -114,7 +120,7 @@ const checkTestOnly = (reference: ModuleReference, target: string, report: Repor
|
|
|
114
120
|
/** A path from the root that a mapping or an import lands on, judged by where the checker reads. */
|
|
115
121
|
const containmentProblem = (target: string | undefined): string | undefined => {
|
|
116
122
|
if (target === undefined) return 'resolves outside the application root, where the checker does not look'
|
|
117
|
-
if (target
|
|
123
|
+
if (isSkippedPath(target)) return 'resolves into a directory the checker skips'
|
|
118
124
|
return undefined
|
|
119
125
|
}
|
|
120
126
|
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// What the platform refuses of an application's migrations, found before the push instead of in a deploy's run log:
|
|
2
|
+
// the classifier Control runs on every snapshot, and on Cloudflare the backup's plan of the migrated schema, which every
|
|
3
|
+
// migration deploy takes first.
|
|
4
|
+
|
|
5
|
+
import { describeOpsDumpSchema, planOpsDump } from '@fabrika/auth-core'
|
|
6
|
+
import { withMigratedSqlite } from '@fabrika/db/codegen-sqlite'
|
|
7
|
+
import { FRAMEWORK_MIGRATION_BUNDLE } from '@fabrika/db/migrations'
|
|
8
|
+
import { SQLITE_FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations-sqlite'
|
|
9
|
+
import { applicationDatabaseSchema, classifyMigrations, type MigrationDialect } from '@fabrika/platform-node/sql'
|
|
10
|
+
import type { Finding } from '../finding'
|
|
11
|
+
import { MIGRATIONS_DIR } from '../layout'
|
|
12
|
+
|
|
13
|
+
interface MigrationText {
|
|
14
|
+
readonly path: string
|
|
15
|
+
readonly name: string
|
|
16
|
+
readonly sql: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The files of `db/migrations` itself, by name: the order the runner and Control read them in. */
|
|
20
|
+
const migrationTexts = (files: ReadonlyMap<string, string>): MigrationText[] =>
|
|
21
|
+
[...files].flatMap(([path, sql]) => {
|
|
22
|
+
const name = path.slice(MIGRATIONS_DIR.length)
|
|
23
|
+
return path.startsWith(MIGRATIONS_DIR) && name.endsWith('.sql') && !name.includes('/') ? [{ path, name, sql }] : []
|
|
24
|
+
}).sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Every statement Control's classifier refuses, at its file and line, against the application's access tables and in its
|
|
28
|
+
* dialect. Control refuses a deploy whose new migration holds
|
|
29
|
+
* one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
|
|
30
|
+
* checked, applied or not: the checker does not know which an environment holds.
|
|
31
|
+
*/
|
|
32
|
+
export const checkMigrationClassification = (
|
|
33
|
+
files: ReadonlyMap<string, string>,
|
|
34
|
+
appId: string,
|
|
35
|
+
accessTables: readonly string[],
|
|
36
|
+
dialect: MigrationDialect,
|
|
37
|
+
): Finding[] => {
|
|
38
|
+
const texts = migrationTexts(files)
|
|
39
|
+
if (texts.length === 0) return []
|
|
40
|
+
const paths = new Map(texts.map((text) => [text.name, text.path]))
|
|
41
|
+
const options = { accessTables: new Set(accessTables), dialect }
|
|
42
|
+
return classifyMigrations(texts.map(({ name, sql }) => ({ name, sql })), applicationDatabaseSchema(appId), options).files.flatMap((file) =>
|
|
43
|
+
file.refused.map((refusal): Finding => ({
|
|
44
|
+
file: paths.get(refusal.file) ?? `${MIGRATIONS_DIR}${refusal.file}`,
|
|
45
|
+
line: refusal.line,
|
|
46
|
+
column: 1,
|
|
47
|
+
severity: 'refusal',
|
|
48
|
+
rule: 'migration-refused',
|
|
49
|
+
message: `${refusal.reason} is not allowed: Control refuses the deploy that brings this migration`,
|
|
50
|
+
allowed: 'the statements, functions and objects the migration classifier admits (application-runtime reference, "Migrations")',
|
|
51
|
+
}))
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* On Cloudflare, the backup's refusal of the migrated schema (`planOpsDump`), at the newest migration that names the
|
|
57
|
+
* table. Every migration deploy backs the environment up first, so a schema the backup refuses blocks every migration
|
|
58
|
+
* after the one that made it. A migration set that does not apply is codegen's to report, so it finds nothing here.
|
|
59
|
+
*/
|
|
60
|
+
export const checkBackupPlan = async (files: ReadonlyMap<string, string>): Promise<Finding[]> => {
|
|
61
|
+
const texts = migrationTexts(files)
|
|
62
|
+
if (texts.length === 0) return []
|
|
63
|
+
let refused: { readonly table: string | null } | null
|
|
64
|
+
try {
|
|
65
|
+
refused = await withMigratedSqlite([
|
|
66
|
+
{ bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: SQLITE_FRAMEWORK_MIGRATIONS },
|
|
67
|
+
{ bundle: 'app', migrations: texts.map(({ name, sql }) => ({ name, sql })) },
|
|
68
|
+
], (db) => {
|
|
69
|
+
const plan = planOpsDump(describeOpsDumpSchema((query, ...bindings) => db.query<Record<string, unknown>, string[]>(query).all(...bindings)))
|
|
70
|
+
return 'refused' in plan ? plan : null
|
|
71
|
+
})
|
|
72
|
+
} catch {
|
|
73
|
+
return []
|
|
74
|
+
}
|
|
75
|
+
if (refused === null) return []
|
|
76
|
+
const at = refused.table === null ? undefined : newestNaming(texts, refused.table)
|
|
77
|
+
const last = texts[texts.length - 1]
|
|
78
|
+
return [{
|
|
79
|
+
file: at?.path ?? last?.path ?? MIGRATIONS_DIR,
|
|
80
|
+
line: at?.line ?? 1,
|
|
81
|
+
column: 1,
|
|
82
|
+
severity: 'refusal',
|
|
83
|
+
rule: 'backup-schema',
|
|
84
|
+
message: refused.table === null
|
|
85
|
+
? 'the migrated schema cannot be backed up (a table name the data layer does not admit, or two tables of one name)'
|
|
86
|
+
: `table ${refused.table} cannot be backed up, and every migration deploy takes a backup first`,
|
|
87
|
+
allowed:
|
|
88
|
+
"a foreign key inside its table's cycle that is nullable, outside the primary key, referenced by no other key and named by no CHECK (ADR-0070 section 2); or no such key",
|
|
89
|
+
}]
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The newest migration that names `table`, and the first line there that does. */
|
|
93
|
+
const newestNaming = (texts: readonly MigrationText[], table: string): { path: string; line: number } | undefined => {
|
|
94
|
+
const word = new RegExp(`(^|[^A-Za-z0-9_$])["\`[]?${table.replace(/[$]/g, '\\$&')}["\`\\]]?($|[^A-Za-z0-9_$])`, 'i')
|
|
95
|
+
for (const text of [...texts].reverse()) {
|
|
96
|
+
const index = text.sql.split('\n').findIndex((line) => word.test(line))
|
|
97
|
+
if (index >= 0) return { path: text.path, line: index + 1 }
|
|
98
|
+
}
|
|
99
|
+
return undefined
|
|
100
|
+
}
|
package/src/rules/runtime.ts
CHANGED
|
@@ -28,16 +28,22 @@ export interface SourceContext {
|
|
|
28
28
|
readonly rawSql: ReadonlySet<string>
|
|
29
29
|
/** A module under `src/` that is not a test: it reaches no global object and no `Bun` at all. */
|
|
30
30
|
readonly isServerModule: boolean
|
|
31
|
-
/**
|
|
32
|
-
|
|
31
|
+
/**
|
|
32
|
+
* A `fetch` of an absolute URL, by its static prefix and, for a template whose first label alone is interpolated, its
|
|
33
|
+
* authority with that label as `*`: refused once the contract shows that no site declares its origin in `egress`.
|
|
34
|
+
*/
|
|
35
|
+
readonly absoluteFetch: (node: AstNode, target: string, labelled: string | undefined) => void
|
|
33
36
|
/** A `ctx.url('<endpoint id>', …)` with a literal id: refused once the contract shows that it names no procedure. */
|
|
34
37
|
readonly appUrl: (node: AstNode, endpoint: string) => void
|
|
35
38
|
/** A `<table>.insert(values, { onConflict: { columns } })`: refused once the migrations show no unique index of them. */
|
|
36
39
|
readonly conflictInsert: (node: AstNode, table: string, columns: readonly string[]) => void
|
|
37
40
|
}
|
|
38
41
|
|
|
39
|
-
/**
|
|
40
|
-
|
|
42
|
+
/**
|
|
43
|
+
* The global objects, `Bun`, and `WebSocket`, a socket the egress guard on `fetch` does not see: a server module reaches
|
|
44
|
+
* the platform and the outside through the framework only.
|
|
45
|
+
*/
|
|
46
|
+
const SERVER_REFUSED_GLOBALS = new Set(['globalThis', 'global', 'self', 'window', 'Bun', 'WebSocket'])
|
|
41
47
|
|
|
42
48
|
/**
|
|
43
49
|
* The local names a module binds to a value named `sql` it loads: `import { sql as q } from 'kysely'` and
|
|
@@ -130,10 +136,28 @@ const staticPrefix = (node: AstNode | undefined): string | undefined => {
|
|
|
130
136
|
const ABSOLUTE_URL = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i
|
|
131
137
|
const LOCAL_SCHEMES = /^(?:data|blob):/i
|
|
132
138
|
|
|
139
|
+
/**
|
|
140
|
+
* The authority of `https://${label}.<domain>…` with the interpolated label as `*` (`*.<domain>[:port]`), when the
|
|
141
|
+
* template's static text after it reaches the path, query or fragment; the runtime guard checks the label itself.
|
|
142
|
+
*/
|
|
143
|
+
const labelledAuthority = (node: AstNode | undefined): string | undefined => {
|
|
144
|
+
if (node === undefined) return undefined
|
|
145
|
+
if (node.type === 'NewExpression' && ['URL', 'Request'].includes(identifierName(child(node, 'callee')) ?? '')) {
|
|
146
|
+
return labelledAuthority(argumentAt(node, 0))
|
|
147
|
+
}
|
|
148
|
+
if (node.type !== 'TemplateLiteral') return undefined
|
|
149
|
+
const [head, next] = children(node, 'quasis')
|
|
150
|
+
if (!head || !next || templateText(head).cooked !== 'https://') return undefined
|
|
151
|
+
const rest = templateText(next).cooked ?? ''
|
|
152
|
+
const end = rest.search(/[/?#]/)
|
|
153
|
+
return rest.startsWith('.') && end > 1 ? `*${rest.slice(0, end)}` : undefined
|
|
154
|
+
}
|
|
155
|
+
|
|
133
156
|
const checkFetch = (node: AstNode, path: readonly string[], context: SourceContext): void => {
|
|
134
|
-
const
|
|
157
|
+
const argument = invokedArgument(node, path, 'fetch')
|
|
158
|
+
const target = staticPrefix(argument)
|
|
135
159
|
if (target === undefined || !ABSOLUTE_URL.test(target) || LOCAL_SCHEMES.test(target)) return
|
|
136
|
-
context.absoluteFetch(node, target)
|
|
160
|
+
context.absoluteFetch(node, target, labelledAuthority(argument))
|
|
137
161
|
}
|
|
138
162
|
|
|
139
163
|
/** `ctx.url('<endpoint id>', …)`, also on a `ctx` reached through a member (`args.ctx.url`). */
|
|
@@ -177,7 +201,8 @@ const propertyValue = (object: AstNode, name: string): AstNode | undefined => {
|
|
|
177
201
|
/** The finding of a `fetch` of an absolute URL whose origin no site of the contract declares. */
|
|
178
202
|
export const crossAppFetchMessage = (target: string): { readonly message: string; readonly allowed: string } => ({
|
|
179
203
|
message: `fetch to the absolute origin '${target}' is a hand-written integration`,
|
|
180
|
-
allowed:
|
|
204
|
+
allowed:
|
|
205
|
+
"a same-origin path to a declared endpoint, another application through a connector import, egress: ['<origin>' | 'https://*.<domain>'] on the site, or a public host of http(s) under a cron job's egress: 'public'",
|
|
181
206
|
})
|
|
182
207
|
|
|
183
208
|
const checkDynamicCode = (node: AstNode, path: readonly string[], context: SourceContext): void => {
|
|
@@ -482,9 +507,9 @@ const checkPrototypeWrite = (node: AstNode, context: SourceContext): void => {
|
|
|
482
507
|
|
|
483
508
|
const KEY_PREFIX = 'px_'
|
|
484
509
|
|
|
485
|
-
const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[],
|
|
510
|
+
const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[], report: Report): void => {
|
|
486
511
|
if (texts.some((text) => text?.includes(KEY_PREFIX))) {
|
|
487
|
-
|
|
512
|
+
report(
|
|
488
513
|
node,
|
|
489
514
|
'key-literal',
|
|
490
515
|
`'${KEY_PREFIX}' in a literal: a key or a session cookie name in source`,
|
|
@@ -493,6 +518,15 @@ const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[
|
|
|
493
518
|
}
|
|
494
519
|
}
|
|
495
520
|
|
|
521
|
+
/** `key-literal` over a string or a template's text: also the one rule of this module a developer's tool is held to. */
|
|
522
|
+
export const checkKeyLiteralNode = (node: AstNode, report: Report): void => {
|
|
523
|
+
if (node.type === 'Literal') checkStringContent(node, [staticString(node)], report)
|
|
524
|
+
else if (node.type === 'TemplateElement') {
|
|
525
|
+
const { raw, cooked } = templateText(node)
|
|
526
|
+
checkStringContent(node, [raw, cooked], report)
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
496
530
|
const isTypeOnlyImport = (specifier: AstNode, parent: AstNode | undefined): boolean =>
|
|
497
531
|
stringField(specifier, 'importKind') === 'type' || (parent !== undefined && stringField(parent, 'importKind') === 'type')
|
|
498
532
|
|
|
@@ -536,11 +570,8 @@ export const checkRuntimeNode = (node: AstNode, ancestors: readonly AstNode[], c
|
|
|
536
570
|
return
|
|
537
571
|
}
|
|
538
572
|
case 'Literal':
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
const { raw, cooked } = templateText(node)
|
|
542
|
-
return checkStringContent(node, [raw, cooked], context)
|
|
543
|
-
}
|
|
573
|
+
case 'TemplateElement':
|
|
574
|
+
return checkKeyLiteralNode(node, context.report)
|
|
544
575
|
case 'JSXAttribute': {
|
|
545
576
|
const name = child(node, 'name')
|
|
546
577
|
if (name?.type === 'JSXIdentifier' && stringField(name, 'name') === 'dangerouslySetInnerHTML') {
|