architecture-harness 0.4.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/package.json +80 -0
- package/src/cli/check.mjs +535 -0
- package/src/cli/cli.test.mjs +120 -0
- package/src/cli/commit-attribution.mjs +68 -0
- package/src/cli/commit-attribution.test.mjs +47 -0
- package/src/cli/decisions.mjs +223 -0
- package/src/cli/doctor.mjs +135 -0
- package/src/cli/doctor.test.mjs +57 -0
- package/src/cli/init.mjs +98 -0
- package/src/cli/install-hooks.mjs +26 -0
- package/src/cli/qc.mjs +89 -0
- package/src/cli/scaffold.mjs +194 -0
- package/src/cli/sync-enforcement-map.mjs +28 -0
- package/src/cli/work-order-guard.mjs +0 -0
- package/src/cli/work-order-guard.test.mjs +79 -0
- package/src/cli/worktree-isolation.mjs +94 -0
- package/src/cli/worktree-isolation.test.mjs +82 -0
- package/src/config.mjs +338 -0
- package/src/config.test.mjs +59 -0
- package/src/decisions.mjs +198 -0
- package/src/decisions.test.mjs +183 -0
- package/src/descriptions.mjs +28 -0
- package/src/descriptions.test.mjs +27 -0
- package/src/enforcement-map.mjs +46 -0
- package/src/enforcement-map.test.mjs +60 -0
- package/src/eslint/index.mjs +37 -0
- package/src/eslint/options.mjs +53 -0
- package/src/eslint/preset.mjs +192 -0
- package/src/eslint/preset.test.mjs +96 -0
- package/src/eslint/rules/durable-idempotency-key.mjs +120 -0
- package/src/eslint/rules/external-service-only-in-adapter.mjs +52 -0
- package/src/eslint/rules/module-boundary.mjs +12 -0
- package/src/eslint/rules/name-the-pattern.mjs +111 -0
- package/src/eslint/rules/no-comment-paragraph.mjs +101 -0
- package/src/eslint/rules/no-cross-feature-internals.mjs +57 -0
- package/src/eslint/rules/no-number-in-comment.mjs +89 -0
- package/src/eslint/rules/no-offset-pagination.mjs +29 -0
- package/src/eslint/rules/no-orchestration-in-trigger.mjs +56 -0
- package/src/eslint/rules/no-promise-then.mjs +43 -0
- package/src/eslint/rules/no-promise-then.test.mjs +63 -0
- package/src/eslint/rules/no-raw-fetch.mjs +27 -0
- package/src/eslint/rules/no-status-literal.mjs +34 -0
- package/src/eslint/rules/no-supersession-trail.mjs +51 -0
- package/src/eslint/rules/scoped-repository.mjs +43 -0
- package/src/eslint/rules/signal-last-param.mjs +43 -0
- package/src/eslint/rules/storage-only-in-resource.mjs +52 -0
- package/src/eslint/rules/tenant-scoped-table.mjs +71 -0
- package/src/eslint/rules.test.mjs +627 -0
- package/src/gates/adr-format.mjs +87 -0
- package/src/gates/adr-format.test.mjs +54 -0
- package/src/gates/audit-append-only.mjs +34 -0
- package/src/gates/audit-append-only.test.mjs +36 -0
- package/src/gates/citations.mjs +93 -0
- package/src/gates/citations.test.mjs +115 -0
- package/src/gates/claimed-requirements.mjs +53 -0
- package/src/gates/claimed-requirements.test.mjs +60 -0
- package/src/gates/comment-style.mjs +76 -0
- package/src/gates/comment-style.test.mjs +46 -0
- package/src/gates/config-floor.mjs +68 -0
- package/src/gates/config-floor.test.mjs +52 -0
- package/src/gates/contract-compose.mjs +38 -0
- package/src/gates/contract-compose.test.mjs +40 -0
- package/src/gates/eight-blocks.mjs +223 -0
- package/src/gates/eight-blocks.test.mjs +359 -0
- package/src/gates/enforcement-map.mjs +62 -0
- package/src/gates/enforcement-map.test.mjs +41 -0
- package/src/gates/english-source.mjs +176 -0
- package/src/gates/english-source.test.mjs +122 -0
- package/src/gates/frontend-boundaries.mjs +154 -0
- package/src/gates/frontend-boundaries.test.mjs +72 -0
- package/src/gates/gate-tests.mjs +44 -0
- package/src/gates/gate-tests.test.mjs +41 -0
- package/src/gates/headless-sagas.mjs +54 -0
- package/src/gates/headless-sagas.test.mjs +71 -0
- package/src/gates/internal-routes.mjs +76 -0
- package/src/gates/internal-routes.test.mjs +53 -0
- package/src/gates/public-routes.mjs +67 -0
- package/src/gates/public-routes.test.mjs +38 -0
- package/src/gates/registry-agreement.mjs +37 -0
- package/src/gates/registry-agreement.test.mjs +36 -0
- package/src/gates/saga-tests.mjs +94 -0
- package/src/gates/saga-tests.test.mjs +92 -0
- package/src/gates/sql-identifiers.mjs +244 -0
- package/src/gates/sql-identifiers.test.mjs +197 -0
- package/src/gates/tenant-predicate.mjs +175 -0
- package/src/gates/tenant-predicate.test.mjs +161 -0
- package/src/gates/tenant-tables.mjs +65 -0
- package/src/gates/tenant-tables.test.mjs +56 -0
- package/src/gates/test-mirror.mjs +47 -0
- package/src/gates/test-mirror.test.mjs +31 -0
- package/src/index.mjs +9 -0
- package/templates/.jscpd.json +15 -0
- package/templates/CLAUDE.md +54 -0
- package/templates/decisions.examples.md +25 -0
- package/templates/docs/adr-template.md +58 -0
- package/templates/docs/architecture.md +179 -0
- package/templates/docs/decisions.md +72 -0
- package/templates/docs/enforcement.md +94 -0
- package/templates/docs/glossary.md +16 -0
- package/templates/docs/guards.md +23 -0
- package/templates/docs/pagination.md +113 -0
- package/templates/docs/performance.md +35 -0
- package/templates/docs/ui.md +32 -0
- package/templates/githooks/commit-msg +4 -0
- package/templates/githooks/pre-commit +18 -0
- package/templates/githooks/pre-push +6 -0
- package/templates/github/workflows/ci.yml +21 -0
- package/templates/qc.config.json +6 -0
- package/templates/quality-thresholds.json +114 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { checkSqlIdentifiers, declaredColumns, tableOwners, usedIdentifiers } from "./sql-identifiers.mjs";
|
|
4
|
+
|
|
5
|
+
const ddl = `
|
|
6
|
+
create table if not exists projects (
|
|
7
|
+
id uuid primary key default gen_random_uuid(),
|
|
8
|
+
tenant_id uuid not null,
|
|
9
|
+
code text not null,
|
|
10
|
+
created_at timestamptz not null default now(),
|
|
11
|
+
primary key (tenant_id, id)
|
|
12
|
+
);
|
|
13
|
+
`;
|
|
14
|
+
|
|
15
|
+
test("columns are read out of a create table, and a constraint line is not one", () => {
|
|
16
|
+
const tables = declaredColumns([ddl]);
|
|
17
|
+
assert.deepEqual([...tables.get("projects")].sort(), ["code", "created_at", "id", "tenant_id"]);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test("a later expand migration adds its column to the same table", () => {
|
|
21
|
+
const tables = declaredColumns([ddl, "alter table projects add column archived_at timestamptz;"]);
|
|
22
|
+
assert.ok(tables.get("projects").has("archived_at"));
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const resource = (sql) => `const SQL = \`${sql}\`;`;
|
|
26
|
+
|
|
27
|
+
test("an agreeing slice has no finding", () => {
|
|
28
|
+
const tables = declaredColumns([ddl]);
|
|
29
|
+
const source = resource("select id, tenant_id, code from projects where tenant_id = $1");
|
|
30
|
+
assert.deepEqual(checkSqlIdentifiers(tables, [{ path: "r.ts", source }]), []);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("a column no migration declares is named", () => {
|
|
34
|
+
const tables = declaredColumns([ddl]);
|
|
35
|
+
const source = resource("select id, project_code from projects where tenant_id = $1");
|
|
36
|
+
const problems = checkSqlIdentifiers(tables, [{ path: "r.ts", source }]);
|
|
37
|
+
assert.equal(problems.length, 1);
|
|
38
|
+
assert.match(problems[0].detail, /'project_code'/);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("a table no migration declares is named", () => {
|
|
42
|
+
const tables = declaredColumns([ddl]);
|
|
43
|
+
const source = resource("select id from project_tags where tenant_id = $1");
|
|
44
|
+
const problems = checkSqlIdentifiers(tables, [{ path: "r.ts", source }]);
|
|
45
|
+
assert.deepEqual(problems.map((problem) => problem.rule), ["undeclared-sql-identifier"]);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("a value in quotes is not mistaken for a column", () => {
|
|
49
|
+
const tables = declaredColumns([ddl]);
|
|
50
|
+
const source = resource("select id from projects where tenant_id = $1 and code = 'site_admin'");
|
|
51
|
+
assert.deepEqual(checkSqlIdentifiers(tables, [{ path: "r.ts", source }]), []);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("an output alias in double quotes is not mistaken for a column", () => {
|
|
55
|
+
const tables = declaredColumns([ddl]);
|
|
56
|
+
const source = resource(`select tenant_id as "tenantId" from projects where tenant_id = $1`);
|
|
57
|
+
assert.deepEqual(checkSqlIdentifiers(tables, [{ path: "r.ts", source }]), []);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test("an index the slice declares itself is known", () => {
|
|
61
|
+
const source = `const i = index("projects_tenant_created_idx").on(a, b);
|
|
62
|
+
const SQL = \`select id from projects where tenant_id = $1\`;`;
|
|
63
|
+
assert.ok(usedIdentifiers(source).declaredIndexes.has("projects_tenant_created_idx"));
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("a template literal that is not a statement is ignored", () => {
|
|
67
|
+
const tables = declaredColumns([ddl]);
|
|
68
|
+
const source = "const key = `blueprints/${tenantId}/${blueprint_id}`;";
|
|
69
|
+
assert.deepEqual(checkSqlIdentifiers(tables, [{ path: "r.ts", source }]), []);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test("a common table expression names itself and is not a missing table", () => {
|
|
73
|
+
const tables = declaredColumns([ddl]);
|
|
74
|
+
const source = resource(
|
|
75
|
+
"with settled_rows as (select id from projects where tenant_id = $1) select id from settled_rows",
|
|
76
|
+
);
|
|
77
|
+
assert.deepEqual(checkSqlIdentifiers(tables, [{ path: "r.ts", source }]), []);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test("a second common table expression in the same statement is bound too", () => {
|
|
81
|
+
const tables = declaredColumns([ddl]);
|
|
82
|
+
const source = resource(
|
|
83
|
+
"with first_pass as (select id from projects), second_pass as (select id from first_pass) select id from second_pass",
|
|
84
|
+
);
|
|
85
|
+
assert.deepEqual(checkSqlIdentifiers(tables, [{ path: "r.ts", source }]), []);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("a snake_case table alias is bound by its own statement", () => {
|
|
89
|
+
const tables = declaredColumns([ddl]);
|
|
90
|
+
const source = resource("select live_projects.id from projects as live_projects where live_projects.tenant_id = $1");
|
|
91
|
+
assert.deepEqual(checkSqlIdentifiers(tables, [{ path: "r.ts", source }]), []);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("a binding does not hide a genuine typo elsewhere", () => {
|
|
95
|
+
const tables = declaredColumns([ddl]);
|
|
96
|
+
const source = resource("with rows_now as (select id from projects) select project_code from rows_now");
|
|
97
|
+
const problems = checkSqlIdentifiers(tables, [{ path: "r.ts", source }]);
|
|
98
|
+
assert.equal(problems.length, 1);
|
|
99
|
+
assert.match(problems[0].detail, /'project_code'/);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test("a column type the gate has never heard of is still a column", () => {
|
|
103
|
+
const tables = declaredColumns([
|
|
104
|
+
`create table if not exists pins (
|
|
105
|
+
id uuid primary key,
|
|
106
|
+
tenant_id uuid not null,
|
|
107
|
+
fx real not null,
|
|
108
|
+
fy double precision not null,
|
|
109
|
+
label varchar(120),
|
|
110
|
+
shape geometry_kind not null,
|
|
111
|
+
tags text[] not null default '{}',
|
|
112
|
+
check (fx >= 0)
|
|
113
|
+
);`,
|
|
114
|
+
]);
|
|
115
|
+
const columns = tables.get("pins");
|
|
116
|
+
for (const column of ["fx", "fy", "label", "shape", "tags"]) {
|
|
117
|
+
assert.ok(columns.has(column), `${column} should be a column`);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test("a constraint line is never mistaken for a column", () => {
|
|
122
|
+
const tables = declaredColumns([
|
|
123
|
+
`create table if not exists a (
|
|
124
|
+
id uuid primary key,
|
|
125
|
+
primary key (id),
|
|
126
|
+
unique (id),
|
|
127
|
+
constraint a_ck check (id is not null),
|
|
128
|
+
foreign key (id) references b (id)
|
|
129
|
+
);`,
|
|
130
|
+
]);
|
|
131
|
+
assert.deepEqual([...tables.get("a")], ["id"]);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
test("a feature reading its own table is fine", () => {
|
|
135
|
+
const migrations = [{ file: "0002_projects.sql", sql: ddl }];
|
|
136
|
+
const owners = tableOwners(migrations);
|
|
137
|
+
const source = resource("select id from projects where tenant_id = $1");
|
|
138
|
+
const problems = checkSqlIdentifiers(declaredColumns([ddl]), [{ path: "r.ts", source, feature: "projects" }], owners);
|
|
139
|
+
assert.deepEqual(problems, []);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test("a feature reading another feature's table is named, with its owner", () => {
|
|
143
|
+
const migrations = [{ file: "0002_projects.sql", sql: ddl }];
|
|
144
|
+
const owners = tableOwners(migrations);
|
|
145
|
+
const source = resource("select id from projects where tenant_id = $1");
|
|
146
|
+
const problems = checkSqlIdentifiers(declaredColumns([ddl]), [{ path: "r.ts", source, feature: "pins" }], owners);
|
|
147
|
+
assert.equal(problems.length, 1);
|
|
148
|
+
assert.equal(problems[0].rule, "cross-feature-table");
|
|
149
|
+
assert.match(problems[0].detail, /belongs to feature 'projects'/);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test("a migration filename with an underscore names a hyphenated feature", () => {
|
|
153
|
+
const owners = tableOwners([{ file: "0001_identity_tenancy.sql", sql: ddl }]);
|
|
154
|
+
assert.equal(owners.get("projects"), "identity-tenancy");
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
test("a recursive common table expression binds its own name", () => {
|
|
158
|
+
const tables = declaredColumns([ddl]);
|
|
159
|
+
const source = resource(
|
|
160
|
+
"with recursive descendants as (select id from projects where tenant_id = $1) select id from descendants",
|
|
161
|
+
);
|
|
162
|
+
assert.deepEqual(checkSqlIdentifiers(tables, [{ path: "r.ts", source }]), []);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test("an upsert's `do update set` names no table", () => {
|
|
166
|
+
const tables = declaredColumns([ddl]);
|
|
167
|
+
const source = resource(
|
|
168
|
+
"insert into projects (id, tenant_id) values ($1, $2) on conflict (id) do update set code = $3",
|
|
169
|
+
);
|
|
170
|
+
assert.deepEqual(checkSqlIdentifiers(tables, [{ path: "r.ts", source }]), []);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("a single-word table no migration declares is still caught", () => {
|
|
174
|
+
const tables = declaredColumns([ddl]);
|
|
175
|
+
const source = resource("select id from drawings where tenant_id = $1");
|
|
176
|
+
const problems = checkSqlIdentifiers(tables, [{ path: "r.ts", source }]);
|
|
177
|
+
assert.equal(problems.length, 1);
|
|
178
|
+
assert.match(problems[0].detail, /'drawings'/);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
test("a feature may own a second migration with a descriptive suffix", () => {
|
|
182
|
+
const owners = tableOwners(
|
|
183
|
+
[{ file: "0006_blueprints_render_pages.sql", sql: ddl }],
|
|
184
|
+
["blueprints", "pins", "projects"],
|
|
185
|
+
);
|
|
186
|
+
assert.equal(owners.get("projects"), "blueprints");
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test("the longest matching feature name wins, so a prefix does not steal a migration", () => {
|
|
190
|
+
const owners = tableOwners([{ file: "0009_photo_ledger.sql", sql: ddl }], ["photo", "photo-ledger"]);
|
|
191
|
+
assert.equal(owners.get("projects"), "photo-ledger");
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test("a slug matching no feature keeps its own name, so an unowned table is still attributed", () => {
|
|
195
|
+
const owners = tableOwners([{ file: "0010_orphan.sql", sql: ddl }], ["blueprints"]);
|
|
196
|
+
assert.equal(owners.get("projects"), "orphan");
|
|
197
|
+
});
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// Tenant isolation is the security model, and its first leg is the repository
|
|
2
|
+
// predicate: every statement that touches a business table names the tenant.
|
|
3
|
+
// Each feature proves its own with a two-tenant test; this proves all of them at
|
|
4
|
+
// once, and proves it for the statement nobody wrote a test for.
|
|
5
|
+
// docs/architecture.md, .claude/rules/security.md.
|
|
6
|
+
//
|
|
7
|
+
// It reads the predicate, not the value. That a predicate is present is
|
|
8
|
+
// structural; that it is correct is what the two-tenant test is for.
|
|
9
|
+
|
|
10
|
+
const DEFAULT_TENANT_COLUMN = "tenant_id";
|
|
11
|
+
const DEFAULT_INSERT_HELPER = "insertReturning";
|
|
12
|
+
|
|
13
|
+
function escape(text) {
|
|
14
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Naming the column is not scoping by it: a select list mentioning the tenant
|
|
18
|
+
// column reads every tenant's rows just as happily. The predicate is what counts.
|
|
19
|
+
function scopedPattern(column) {
|
|
20
|
+
return new RegExp(`\\b${escape(column)}\\s*=`);
|
|
21
|
+
}
|
|
22
|
+
// Nine of eleven features write their generic helpers with the table name as a
|
|
23
|
+
// runtime value — `from ${table}`. Matching only literal names skipped those
|
|
24
|
+
// statements silently, which is worse than failing: the check reported OK while
|
|
25
|
+
// looking at nothing. A statement on a table named at runtime is still a
|
|
26
|
+
// statement on a business table, and still has to carry the tenant.
|
|
27
|
+
const DYNAMIC_TABLE = /\b(?:from|join|into|update)\s+\$\{/;
|
|
28
|
+
|
|
29
|
+
/** True when the statement actually filters or writes the tenant, not merely names it. */
|
|
30
|
+
function scopedBy(sql, column) {
|
|
31
|
+
if (scopedPattern(column).test(sql)) return true;
|
|
32
|
+
const inserted = /insert\s+into\s+(?:\w+|\$\{[^}]*\})\s*\(([^)]*)\)/i.exec(sql);
|
|
33
|
+
return inserted ? new RegExp(`\\b${escape(column)}\\b`).test(inserted[1]) : false;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A statement that reads only a bound name touches no table and needs no predicate. */
|
|
37
|
+
function namesOwnedTable(statement, owned, bound) {
|
|
38
|
+
for (const table of owned) {
|
|
39
|
+
const pattern = new RegExp(`\\b(?:from|join|into|update)\\s+${table}\\b`);
|
|
40
|
+
if (pattern.test(statement) && !bound.has(table)) return table;
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @param {{path: string, statements: {sql: string, bound: Set<string>}[]}[]} resources
|
|
47
|
+
* @param {Set<string>} owned every business table any migration declares
|
|
48
|
+
* @returns {{path: string, rule: string, detail: string}[]}
|
|
49
|
+
*/
|
|
50
|
+
export function checkTenantPredicate(resources, owned, options = {}) {
|
|
51
|
+
const column = options.column ?? DEFAULT_TENANT_COLUMN;
|
|
52
|
+
const problems = [];
|
|
53
|
+
for (const { path, statements } of resources) {
|
|
54
|
+
for (const { sql, bound, exemption } of statements) {
|
|
55
|
+
const table = namesOwnedTable(sql, owned, bound) ?? (DYNAMIC_TABLE.test(sql) ? "a table named at runtime" : null);
|
|
56
|
+
if (!table) continue;
|
|
57
|
+
if (exemption) continue;
|
|
58
|
+
if (scopedBy(sql, column)) continue;
|
|
59
|
+
problems.push({
|
|
60
|
+
path,
|
|
61
|
+
rule: "unscoped-statement",
|
|
62
|
+
detail: `a statement on '${table}' does not filter on ${column}. Carry the tenant, or mark the statement exempt with its reason`,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return problems;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Adopting the shared `insertReturning` moved the statement text out of the file
|
|
70
|
+
// that calls it, so the predicate check above stops seeing it. The tenant is now
|
|
71
|
+
// carried in the caller's column list instead — which is still in the caller's
|
|
72
|
+
// file, and still checkable. Without this, cleaning up duplication would have
|
|
73
|
+
// quietly bought a weaker gate.
|
|
74
|
+
// A call, not a declaration: `function insertReturning<Row>(` is where the helper
|
|
75
|
+
// is defined, and its own parameters are not a column list.
|
|
76
|
+
function sharedInsertPattern(helper) {
|
|
77
|
+
return new RegExp(`(?<!function\\s)${escape(helper)}\\s*(?:<[^>]*>)?\\s*\\(`, "g");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function tenantLiteralPattern(column) {
|
|
81
|
+
return new RegExp(`["']${escape(column)}["']`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The arguments of a call, split at the top level so a nested array stays whole. */
|
|
85
|
+
function callArguments(source, openIndex) {
|
|
86
|
+
const args = [];
|
|
87
|
+
let depth = 0;
|
|
88
|
+
let current = "";
|
|
89
|
+
for (let i = openIndex; i < source.length; i += 1) {
|
|
90
|
+
const ch = source[i];
|
|
91
|
+
if (ch === "(" || ch === "[" || ch === "{") depth += 1;
|
|
92
|
+
if (ch === ")" || ch === "]" || ch === "}") {
|
|
93
|
+
depth -= 1;
|
|
94
|
+
if (depth === 0) {
|
|
95
|
+
args.push(current);
|
|
96
|
+
return args;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (ch === "," && depth === 1) {
|
|
100
|
+
args.push(current);
|
|
101
|
+
current = "";
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (!(depth === 1 && i === openIndex)) current += ch;
|
|
105
|
+
}
|
|
106
|
+
return args;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The body of the factory a call passed its columns to. Only a call — `f()` — is
|
|
111
|
+
* followed. A bare name is left to the enclosing-function window, because a local
|
|
112
|
+
* one is free to repeat: resolving `columns` by name would find the first `const
|
|
113
|
+
* columns` in the file and let a correct list two functions away vouch for this one.
|
|
114
|
+
*/
|
|
115
|
+
function factoryBody(source, argument) {
|
|
116
|
+
const called = /^([A-Za-z_$][\w$]*)\s*\(/.exec(argument.trim());
|
|
117
|
+
if (called === null) return "";
|
|
118
|
+
const declared = new RegExp(`function\\s+${called[1]}\\b`).exec(source);
|
|
119
|
+
return declared === null ? "" : source.slice(declared.index, declared.index + 700);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Every call to the shared insert must name the tenant column: inline in the
|
|
124
|
+
* argument list, in a `columns` array built just above it, or in the definition
|
|
125
|
+
* of whatever it passed — a named factory is one indirection and is followed,
|
|
126
|
+
* because a check that cries wolf is a check somebody turns off.
|
|
127
|
+
*
|
|
128
|
+
* @param {{path: string, source: string}[]} resources
|
|
129
|
+
* @returns {{path: string, rule: string, detail: string}[]}
|
|
130
|
+
*/
|
|
131
|
+
export function checkSharedInsertCallSites(resources, options = {}) {
|
|
132
|
+
const column = options.column ?? DEFAULT_TENANT_COLUMN;
|
|
133
|
+
const sharedInsert = sharedInsertPattern(options.insertHelper ?? DEFAULT_INSERT_HELPER);
|
|
134
|
+
const tenantLiteral = tenantLiteralPattern(column);
|
|
135
|
+
const problems = [];
|
|
136
|
+
for (const { path, source } of resources) {
|
|
137
|
+
sharedInsert.lastIndex = 0;
|
|
138
|
+
let match = sharedInsert.exec(source);
|
|
139
|
+
while (match !== null) {
|
|
140
|
+
// Look back only as far as the enclosing function starts, so a neighbouring
|
|
141
|
+
// insert that does name the tenant cannot vouch for this one, and forward
|
|
142
|
+
// across this call's own argument list.
|
|
143
|
+
const before = source.slice(0, match.index);
|
|
144
|
+
const boundary = Math.max(
|
|
145
|
+
before.lastIndexOf("function "),
|
|
146
|
+
before.lastIndexOf("=> {"),
|
|
147
|
+
before.lastIndexOf("\n}"),
|
|
148
|
+
);
|
|
149
|
+
const from = boundary === -1 ? Math.max(0, match.index - 400) : boundary;
|
|
150
|
+
const args = callArguments(source, match.index + match[0].length - 1);
|
|
151
|
+
const followed = factoryBody(source, args[2] ?? "");
|
|
152
|
+
const neighbourhood = source.slice(from, match.index + 700) + followed;
|
|
153
|
+
if (!tenantLiteral.test(neighbourhood)) {
|
|
154
|
+
problems.push({
|
|
155
|
+
path,
|
|
156
|
+
rule: "insert-without-tenant",
|
|
157
|
+
detail: `line ${before.split("\n").length}: a shared insert names no ${column} column — the tenant moved into the caller's list, so the caller is what carries it`,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
match = sharedInsert.exec(source);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return problems;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Every statement whose exemption was taken, so a reviewer can count them. */
|
|
167
|
+
export function exemptions(resources) {
|
|
168
|
+
const taken = [];
|
|
169
|
+
for (const { path, statements } of resources) {
|
|
170
|
+
for (const { exemption } of statements) {
|
|
171
|
+
if (exemption) taken.push({ path, reason: exemption });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return taken;
|
|
175
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { checkSharedInsertCallSites, checkTenantPredicate } from "./tenant-predicate.mjs";
|
|
4
|
+
|
|
5
|
+
const owned = new Set(["projects", "pin_annotations"]);
|
|
6
|
+
const one = (sql, bound = new Set()) => [{ path: "r.ts", statements: [{ sql, bound }] }];
|
|
7
|
+
|
|
8
|
+
test("a scoped read passes", () => {
|
|
9
|
+
assert.deepEqual(checkTenantPredicate(one("select id from projects where tenant_id = $1"), owned), []);
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
test("a read with no tenant predicate is a finding, and names the table", () => {
|
|
13
|
+
const problems = checkTenantPredicate(one("select id from projects where id = $1"), owned);
|
|
14
|
+
assert.equal(problems.length, 1);
|
|
15
|
+
assert.equal(problems[0].rule, "unscoped-statement");
|
|
16
|
+
assert.match(problems[0].detail, /'projects'/);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test("an insert that does not carry the tenant is a finding", () => {
|
|
20
|
+
const problems = checkTenantPredicate(one("insert into projects (id, code) values ($1, $2)"), owned);
|
|
21
|
+
assert.equal(problems.length, 1);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("an update that does not carry the tenant is a finding", () => {
|
|
25
|
+
const problems = checkTenantPredicate(one("update pin_annotations set name = $1 where id = $2"), owned);
|
|
26
|
+
assert.equal(problems.length, 1);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("a statement reading only a common table expression needs no predicate", () => {
|
|
30
|
+
const bound = new Set(["projects"]);
|
|
31
|
+
assert.deepEqual(checkTenantPredicate(one("select id from projects", bound), owned), []);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("a statement touching no business table is left alone", () => {
|
|
35
|
+
assert.deepEqual(checkTenantPredicate(one("select current_setting('app.tenant_id')"), owned), []);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("a table whose name merely starts the same is not matched", () => {
|
|
39
|
+
assert.deepEqual(checkTenantPredicate(one("select id from projects_archive where id = $1"), owned), []);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("a shared insert naming the tenant inline passes", () => {
|
|
43
|
+
const source = `return insertReturning(tx, "projects", ["id", "tenant_id", "code"], [a, b, c], COLS, onDup, signal);`;
|
|
44
|
+
assert.deepEqual(checkSharedInsertCallSites([{ path: "r.ts", source }]), []);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("a shared insert naming the tenant in a columns array just above passes", () => {
|
|
48
|
+
const source = `
|
|
49
|
+
async function insertProject(tx, input, signal) {
|
|
50
|
+
const columns = ["id", "tenant_id", "code", "name"];
|
|
51
|
+
const values = [input.id, input.tenantId, input.code, input.name];
|
|
52
|
+
return insertReturning(tx, "projects", columns, values, COLS, onDup, signal);
|
|
53
|
+
}`;
|
|
54
|
+
assert.deepEqual(checkSharedInsertCallSites([{ path: "r.ts", source }]), []);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("a shared insert that forgot the tenant is caught", () => {
|
|
58
|
+
const source = `
|
|
59
|
+
async function insertProject(tx, input, signal) {
|
|
60
|
+
const columns = ["id", "code", "name"];
|
|
61
|
+
const values = [input.id, input.code, input.name];
|
|
62
|
+
return insertReturning(tx, "projects", columns, values, COLS, onDup, signal);
|
|
63
|
+
}`;
|
|
64
|
+
const problems = checkSharedInsertCallSites([{ path: "r.ts", source }]);
|
|
65
|
+
assert.equal(problems.length, 1);
|
|
66
|
+
assert.equal(problems[0].rule, "insert-without-tenant");
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("a generic call with a type argument is still matched", () => {
|
|
70
|
+
const source = `return insertReturning<ProjectRow>(tx, "projects", ["id", "code"], [a, b], COLS, onDup);`;
|
|
71
|
+
assert.equal(checkSharedInsertCallSites([{ path: "r.ts", source }]).length, 1);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test("every call is checked, and a neighbour naming the tenant cannot vouch for one that does not", () => {
|
|
75
|
+
const source = `
|
|
76
|
+
function insertA(tx, v) {
|
|
77
|
+
return insertReturning(tx, "a", ["id", "tenant_id"], v, C, f);
|
|
78
|
+
}
|
|
79
|
+
function insertB(tx, v) {
|
|
80
|
+
return insertReturning(tx, "b", ["id"], v, C, f);
|
|
81
|
+
}
|
|
82
|
+
function insertC(tx, v) {
|
|
83
|
+
return insertReturning(tx, "c", ["id"], v, C, f);
|
|
84
|
+
}`;
|
|
85
|
+
assert.equal(checkSharedInsertCallSites([{ path: "r.ts", source }]).length, 2);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("a columns factory one call away is followed, not guessed at", () => {
|
|
89
|
+
const source = `
|
|
90
|
+
function newPhotoColumns() {
|
|
91
|
+
return ["id", "tenant_id", "delivery_id"];
|
|
92
|
+
}
|
|
93
|
+
export async function insertPhoto(tx, input, signal) {
|
|
94
|
+
return insertReturning(tx, "photos", newPhotoColumns(), newPhotoValues(input), COLS, onDup, signal);
|
|
95
|
+
}`;
|
|
96
|
+
assert.deepEqual(checkSharedInsertCallSites([{ path: "r.ts", source }]), []);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("a columns factory that forgets the tenant is still caught through the indirection", () => {
|
|
100
|
+
const source = `
|
|
101
|
+
function newPhotoColumns() {
|
|
102
|
+
return ["id", "delivery_id"];
|
|
103
|
+
}
|
|
104
|
+
export async function insertPhoto(tx, input, signal) {
|
|
105
|
+
return insertReturning(tx, "photos", newPhotoColumns(), newPhotoValues(input), COLS, onDup, signal);
|
|
106
|
+
}`;
|
|
107
|
+
assert.equal(checkSharedInsertCallSites([{ path: "r.ts", source }]).length, 1);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test("a repeated local name is not resolved to the first one in the file", () => {
|
|
111
|
+
const source = `
|
|
112
|
+
export async function insertOne(tx, input, signal) {
|
|
113
|
+
const columns = ["id", "tenant_id", "name"];
|
|
114
|
+
return insertReturning(tx, "a", columns, values(input), COLS, onDup, signal);
|
|
115
|
+
}
|
|
116
|
+
export async function insertTwo(tx, input, signal) {
|
|
117
|
+
const columns = ["id", "name"];
|
|
118
|
+
return insertReturning(tx, "b", columns, values(input), COLS, onDup, signal);
|
|
119
|
+
}`;
|
|
120
|
+
const found = checkSharedInsertCallSites([{ path: "r.ts", source }]);
|
|
121
|
+
assert.equal(found.length, 1);
|
|
122
|
+
assert.match(found[0].detail, /line 8:/);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
test("a statement on a table named at runtime is still checked", () => {
|
|
127
|
+
const sql = "select id from ${table} where id = $1";
|
|
128
|
+
const problems = checkTenantPredicate(one(sql), owned);
|
|
129
|
+
assert.equal(problems.length, 1);
|
|
130
|
+
assert.match(problems[0].detail, /named at runtime/);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test("a runtime-named table that does carry the tenant passes", () => {
|
|
134
|
+
const sql = "select id from ${table} where tenant_id = $1 and client_mutation_id = $2";
|
|
135
|
+
assert.deepEqual(checkTenantPredicate(one(sql), owned), []);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
test("an insert into a runtime-named table must list the tenant column", () => {
|
|
139
|
+
const bad = "insert into ${table} (id, name) values ($1, $2)";
|
|
140
|
+
assert.equal(checkTenantPredicate(one(bad), owned).length, 1);
|
|
141
|
+
const good = "insert into ${table} (id, tenant_id, name) values ($1, $2, $3)";
|
|
142
|
+
assert.deepEqual(checkTenantPredicate(one(good), owned), []);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test("the tenant column and the shared insert helper come from options", () => {
|
|
146
|
+
const resources = [
|
|
147
|
+
{ path: "a/resource.ts", statements: [{ sql: "select * from pins where org_id = $1", bound: new Set() }] },
|
|
148
|
+
];
|
|
149
|
+
const owned = new Set(["pins"]);
|
|
150
|
+
assert.deepEqual(checkTenantPredicate(resources, owned, { column: "org_id" }), []);
|
|
151
|
+
const problems = checkTenantPredicate(resources, owned, { column: "tenant_id" });
|
|
152
|
+
assert.equal(problems.length, 1);
|
|
153
|
+
assert.ok(problems[0].detail.includes("tenant_id"));
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test("a renamed shared insert helper is still followed to its call sites", () => {
|
|
157
|
+
const resources = [{ path: "a/resource.ts", source: 'await addRow(uow, "pins", ["name"], [n]);' }];
|
|
158
|
+
const problems = checkSharedInsertCallSites(resources, { insertHelper: "addRow", column: "org_id" });
|
|
159
|
+
assert.equal(problems.length, 1);
|
|
160
|
+
assert.ok(problems[0].detail.includes("org_id"));
|
|
161
|
+
});
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Which tables row-level security must protect, read out of the feature that
|
|
2
|
+
// declares them. A feature owns its schema slice; no work order edits a shared
|
|
3
|
+
// policy file, so the policy file is generated. .claude/rules/swarm.md.
|
|
4
|
+
|
|
5
|
+
const DEFAULT_TABLE_FACTORY = "pgTable";
|
|
6
|
+
const DEFAULT_COLUMN = "tenantId";
|
|
7
|
+
const DEFAULT_SQL_COLUMN = "tenant_id";
|
|
8
|
+
const DEFAULT_SETTING = "app.tenant_id";
|
|
9
|
+
const DEFAULT_CAST = "uuid";
|
|
10
|
+
|
|
11
|
+
function escape(text) {
|
|
12
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
/** The text between the opening brace at `open` and its match. */
|
|
17
|
+
function block(source, open) {
|
|
18
|
+
let depth = 0;
|
|
19
|
+
for (let index = open; index < source.length; index += 1) {
|
|
20
|
+
const character = source[index];
|
|
21
|
+
if (character === "{") depth += 1;
|
|
22
|
+
if (character === "}") {
|
|
23
|
+
depth -= 1;
|
|
24
|
+
if (depth === 0) return source.slice(open, index);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return source.slice(open);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Every table in one resource slice that carries a tenant column. A table
|
|
32
|
+
* without one is not listed: it is either not a business table, or it is a
|
|
33
|
+
* finding for `qc/tenant-scoped-table`, and this file is not the place to say so.
|
|
34
|
+
*/
|
|
35
|
+
export function tenantScopedTables(source, options = {}) {
|
|
36
|
+
const factory = escape(options.tableFactory ?? DEFAULT_TABLE_FACTORY);
|
|
37
|
+
const tablePattern = new RegExp(`${factory}\\(\\s*"([a-z_][a-z0-9_]*)"\\s*,\\s*\\{`, "g");
|
|
38
|
+
const column = new RegExp(`\\b${escape(options.column ?? DEFAULT_COLUMN)}\\b`);
|
|
39
|
+
|
|
40
|
+
const found = new Set();
|
|
41
|
+
let match = tablePattern.exec(source);
|
|
42
|
+
while (match !== null) {
|
|
43
|
+
const body = block(source, match.index + match[0].length - 1);
|
|
44
|
+
if (column.test(body)) found.add(match[1]);
|
|
45
|
+
match = tablePattern.exec(source);
|
|
46
|
+
}
|
|
47
|
+
return [...found].sort();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The same predicate for every table, so a table added later is two more lines. */
|
|
51
|
+
export function policyStatements(table, options = {}) {
|
|
52
|
+
const sqlColumn = options.sqlColumn ?? DEFAULT_SQL_COLUMN;
|
|
53
|
+
const setting = options.setting ?? DEFAULT_SETTING;
|
|
54
|
+
const cast = options.cast ?? DEFAULT_CAST;
|
|
55
|
+
const predicate = `${sqlColumn} = current_setting('${setting}')::${cast}`;
|
|
56
|
+
return [
|
|
57
|
+
`alter table ${table} enable row level security;`,
|
|
58
|
+
`alter table ${table} force row level security;`,
|
|
59
|
+
"",
|
|
60
|
+
`drop policy if exists ${table}_isolation on ${table};`,
|
|
61
|
+
`create policy ${table}_isolation on ${table}`,
|
|
62
|
+
` using (${predicate})`,
|
|
63
|
+
` with check (${predicate});`,
|
|
64
|
+
].join("\n");
|
|
65
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { policyStatements, tenantScopedTables } from "./tenant-tables.mjs";
|
|
4
|
+
|
|
5
|
+
const slice = `
|
|
6
|
+
export const tenants = pgTable("tenants", {
|
|
7
|
+
tenantId: "tenant_id",
|
|
8
|
+
name: "name",
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
export const memberships = pgTable("memberships", {
|
|
12
|
+
tenantId: "tenant_id",
|
|
13
|
+
userId: "user_id",
|
|
14
|
+
});
|
|
15
|
+
`;
|
|
16
|
+
|
|
17
|
+
test("a tenant-scoped table is listed", () => {
|
|
18
|
+
assert.deepEqual(tenantScopedTables(slice), ["memberships", "tenants"]);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test("a table with no tenant column is not listed", () => {
|
|
22
|
+
const source = `export const rates = pgTable("exchange_rates", { code: "code" });`;
|
|
23
|
+
assert.deepEqual(tenantScopedTables(source), []);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("a nested object inside a column definition does not end the table early", () => {
|
|
27
|
+
const source = `export const photos = pgTable("photos", {
|
|
28
|
+
id: uuid("id").default({ mode: "random" }),
|
|
29
|
+
tenantId: uuid("tenant_id"),
|
|
30
|
+
});`;
|
|
31
|
+
assert.deepEqual(tenantScopedTables(source), ["photos"]);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("a source with no table yields nothing", () => {
|
|
35
|
+
assert.deepEqual(tenantScopedTables("export const queries = {};"), []);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("every policy forces row level security, so the owning role is filtered too", () => {
|
|
39
|
+
const sql = policyStatements("photos");
|
|
40
|
+
assert.match(sql, /force row level security/);
|
|
41
|
+
assert.match(sql, /drop policy if exists photos_isolation/);
|
|
42
|
+
assert.match(sql, /with check \(tenant_id = current_setting\('app\.tenant_id'\)::uuid\)/);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("the table factory, tenant column and policy setting come from options", () => {
|
|
46
|
+
const source = 'export const pins = table("pins", { orgId: uuid(), name: text() });';
|
|
47
|
+
const found = tenantScopedTables(source, { tableFactory: "table", column: "orgId" });
|
|
48
|
+
assert.deepEqual(found, ["pins"]);
|
|
49
|
+
const policy = policyStatements("pins", { sqlColumn: "org_id", setting: "app.org", cast: "text" });
|
|
50
|
+
assert.ok(policy.includes("org_id = current_setting('app.org')::text"));
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("a table carrying a different column than the configured one is not listed", () => {
|
|
54
|
+
const source = 'export const pins = table("pins", { tenantId: uuid() });';
|
|
55
|
+
assert.deepEqual(tenantScopedTables(source, { tableFactory: "table", column: "orgId" }), []);
|
|
56
|
+
});
|