@ultimat3/testing 31.23.0 → 31.25.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/CLAUDE.md +2 -0
- package/README.md +1 -0
- package/package.json +22 -22
- package/src/admin-mount-boundary.ts +29 -0
- package/src/driver-store-boundary.ts +39 -0
- package/src/entity-conformance-checks.ts +2 -0
- package/src/entity-conformance-entities.ts +8 -0
- package/src/entity-conformance-tree.ts +199 -0
- package/src/exercise-report.ts +15 -1
- package/src/exercise.ts +15 -9
- package/src/import-graph.ts +102 -0
- package/src/job-driver-checks-settle.ts +61 -2
- package/src/registry-environment.ts +82 -0
- package/src/registry-leak-guard.ts +98 -14
- package/src/registry-snapshot.ts +27 -5
- package/src/sealed-network.ts +39 -0
- package/src/storage-conformance-stream-checks.ts +0 -1
- package/src/tenant-proof.ts +73 -7
package/CLAUDE.md
CHANGED
|
@@ -85,6 +85,8 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
|
|
|
85
85
|
| Leaks are the file's, not the next file's | `installRegistryLeakGuard()` runs from the preload and fails the run naming the FILE that left cache tags declared or a cache tier registered after its last test (`X_TEST_REGISTRY_LEAK`). |
|
|
86
86
|
| Reported and restored are different sets | the guard also RESTORES, at the same file boundary, the registries whose module-scope declarations a neighbour's cleanup destroys |
|
|
87
87
|
| A catalog restore is a MERGE, never a replace | the other three registries are replaced with the snapshot. `registerCatalog` has no inverse, so all a file can cost its neighbour is a `resetCatalogs()` |
|
|
88
|
+
| A file's policy environment is ITS import graph | at the body's start the permission set and role map narrow to names a module the file's import graph reaches declared (`import-graph.ts`, `registry-environment.ts`), plus the preload's and any first declared during this load; the body's own declarations end with the file. Framework repo only: an app keeps the union (`loadApp()` is no static edge) |
|
|
89
|
+
| Noted driver stores and mounted admins end with the file | `driver-store-boundary.ts`: back to the preload's notes (a store noted at a fixture's import is no later file's); `admin-mount-boundary.ts`: back to what the body inherited. Read through the require cache / the global symbol — never an import |
|
|
88
90
|
| Permissions are still REPLACED at a file boundary, and it is measured | a dynamic `loadApp()`'s `definePermissions()` is dropped there. Open. Full rule: `docs/history/testing.md` |
|
|
89
91
|
| Guarded state is boot state | the guard covers only registries that must be clean at file end — `declareTags` and `registerTier` are boot installs; "filled" and "cleared" are two questions. Full rule: `docs/history/testing.md` |
|
|
90
92
|
| An empty registry is a premise you state | a test whose subject is "nothing is declared" — `x db gen` with nothing to generate — calls `isolateEntityRegistry()` and restores in a `finally`. |
|
package/README.md
CHANGED
|
@@ -439,6 +439,7 @@ seeded row that moved across a B leg is `X_TENANT_WRITE_CROSSED`. Both are red i
|
|
|
439
439
|
| `crossed` | any `TenantFinding` (`code`, `leg: 'before' \| 'after'`, `path` or `table` + `id`) |
|
|
440
440
|
| `unproven` | A's own call was not `reached` |
|
|
441
441
|
| `public` | the policy admits an anonymous caller: read half skipped, write half kept |
|
|
442
|
+
| `global` | a query whose every statement was a repository read of an `entity({ global })` table: no row of A's to miss, write half kept |
|
|
442
443
|
| `unproven` | a query whose A answer held none of A's rows |
|
|
443
444
|
| `proven` | otherwise |
|
|
444
445
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/testing",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.25.0",
|
|
4
4
|
"description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -47,26 +47,26 @@
|
|
|
47
47
|
"test": "bun test"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@ultimat3/action": "31.
|
|
51
|
-
"@ultimat3/ai": "31.
|
|
52
|
-
"@ultimat3/auth": "31.
|
|
53
|
-
"@ultimat3/cache": "31.
|
|
54
|
-
"@ultimat3/core": "31.
|
|
55
|
-
"@ultimat3/db": "31.
|
|
56
|
-
"@ultimat3/entity": "31.
|
|
57
|
-
"@ultimat3/http": "31.
|
|
58
|
-
"@ultimat3/i18n": "31.
|
|
59
|
-
"@ultimat3/jobs": "31.
|
|
60
|
-
"@ultimat3/mail": "31.
|
|
61
|
-
"@ultimat3/notify": "31.
|
|
62
|
-
"@ultimat3/policy": "31.
|
|
63
|
-
"@ultimat3/pwa": "31.
|
|
64
|
-
"@ultimat3/query": "31.
|
|
65
|
-
"@ultimat3/realtime": "31.
|
|
66
|
-
"@ultimat3/render": "31.
|
|
67
|
-
"@ultimat3/schema": "31.
|
|
68
|
-
"@ultimat3/scraping": "31.
|
|
69
|
-
"@ultimat3/seo": "31.
|
|
70
|
-
"@ultimat3/time": "31.
|
|
50
|
+
"@ultimat3/action": "31.25.0",
|
|
51
|
+
"@ultimat3/ai": "31.25.0",
|
|
52
|
+
"@ultimat3/auth": "31.25.0",
|
|
53
|
+
"@ultimat3/cache": "31.25.0",
|
|
54
|
+
"@ultimat3/core": "31.25.0",
|
|
55
|
+
"@ultimat3/db": "31.25.0",
|
|
56
|
+
"@ultimat3/entity": "31.25.0",
|
|
57
|
+
"@ultimat3/http": "31.25.0",
|
|
58
|
+
"@ultimat3/i18n": "31.25.0",
|
|
59
|
+
"@ultimat3/jobs": "31.25.0",
|
|
60
|
+
"@ultimat3/mail": "31.25.0",
|
|
61
|
+
"@ultimat3/notify": "31.25.0",
|
|
62
|
+
"@ultimat3/policy": "31.25.0",
|
|
63
|
+
"@ultimat3/pwa": "31.25.0",
|
|
64
|
+
"@ultimat3/query": "31.25.0",
|
|
65
|
+
"@ultimat3/realtime": "31.25.0",
|
|
66
|
+
"@ultimat3/render": "31.25.0",
|
|
67
|
+
"@ultimat3/schema": "31.25.0",
|
|
68
|
+
"@ultimat3/scraping": "31.25.0",
|
|
69
|
+
"@ultimat3/seo": "31.25.0",
|
|
70
|
+
"@ultimat3/time": "31.25.0"
|
|
71
71
|
}
|
|
72
72
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// The admins `defineAdmin()` mounted, put back at the file boundary to what the file inherited:
|
|
2
|
+
// ~50 admin suites mount one and never clear it, and the `i18n` step audits EVERY mounted admin,
|
|
3
|
+
// so on a shared worker one file's admin was a later file's X_CATALOG_MISSING_KEYS.
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `@ultimat3/admin`'s `ADMIN_MOUNTS`, restated as `@ultimat3/cli`'s `runtime-admin.ts` does —
|
|
7
|
+
* never imported: `testing` is tier 5 beside `admin`, and an app with no admin must not load one.
|
|
8
|
+
*/
|
|
9
|
+
const ADMIN_MOUNTS = Symbol.for('ultimate.admin.mounts');
|
|
10
|
+
|
|
11
|
+
type Mounted = readonly (readonly [string, unknown])[];
|
|
12
|
+
|
|
13
|
+
const held = (): Map<string, unknown> | undefined => {
|
|
14
|
+
const value = (globalThis as { [key: symbol]: unknown })[ADMIN_MOUNTS];
|
|
15
|
+
return value instanceof Map ? (value as Map<string, unknown>) : undefined;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** Every mount by base path, in declaration order; nothing while no admin was ever declared. */
|
|
19
|
+
export function captureAdminMounts(): Mounted {
|
|
20
|
+
return [...(held() ?? new Map<string, unknown>())];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Exactly `mounted` again, in its order — the same Map, so a reader holding it sees the change. */
|
|
24
|
+
export function restoreAdminMounts(mounted: Mounted): void {
|
|
25
|
+
const live = held();
|
|
26
|
+
if (live === undefined) return;
|
|
27
|
+
live.clear();
|
|
28
|
+
for (const [basePath, app] of mounted) live.set(basePath, app);
|
|
29
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// The driver kinds `@ultimat3/entity` has noted (`driverStores()`), put back at the file boundary
|
|
2
|
+
// to what the preload had noted: the drift step reads that record to tell a Postgres app from a
|
|
3
|
+
// `defineDriver` one, and one file's custom driver made every later file's fixture app non-SQL.
|
|
4
|
+
|
|
5
|
+
import type { clearDriverStores, driverStores, noteDriverStore } from '@ultimat3/entity/adapter';
|
|
6
|
+
import { loaded } from './per-test-reset';
|
|
7
|
+
|
|
8
|
+
interface DriverRegistry {
|
|
9
|
+
readonly driverStores: typeof driverStores;
|
|
10
|
+
readonly clearDriverStores: typeof clearDriverStores;
|
|
11
|
+
readonly noteDriverStore: typeof noteDriverStore;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type Noted = ReturnType<typeof driverStores>;
|
|
15
|
+
|
|
16
|
+
const EMPTY: Noted = { sql: [], custom: [] };
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The registry module when something in this process loaded it, else `undefined`. Read through the
|
|
20
|
+
* `require` cache, never imported: `@ultimat3/entity` stays out of every `packages/core` graph.
|
|
21
|
+
*/
|
|
22
|
+
const registry = (): DriverRegistry | undefined => {
|
|
23
|
+
const path = loaded('@ultimat3/entity', 'driver-registry.ts');
|
|
24
|
+
return path === undefined ? undefined : (require(path) as DriverRegistry);
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** What is noted now; nothing when the package was never loaded. */
|
|
28
|
+
export function captureDriverStores(): Noted {
|
|
29
|
+
return registry()?.driverStores() ?? EMPTY;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Exactly `noted` again — a REPLACE, as the permission set is. A no-op while entity is unloaded. */
|
|
33
|
+
export function restoreDriverStores(noted: Noted): void {
|
|
34
|
+
const live = registry();
|
|
35
|
+
if (live === undefined) return;
|
|
36
|
+
live.clearDriverStores();
|
|
37
|
+
for (const name of noted.sql) live.noteDriverStore('sql', name);
|
|
38
|
+
for (const name of noted.custom) live.noteDriverStore('custom', name);
|
|
39
|
+
}
|
|
@@ -17,6 +17,7 @@ import { MEASURE_CHECKS } from './entity-conformance-measures';
|
|
|
17
17
|
import { PAGE_BYTE_CHECKS } from './entity-conformance-page-bytes';
|
|
18
18
|
import { READ_CHECKS } from './entity-conformance-reads';
|
|
19
19
|
import { TENANCY_CHECKS } from './entity-conformance-tenancy';
|
|
20
|
+
import { TREE_CHECKS } from './entity-conformance-tree';
|
|
20
21
|
import { UNRETURNED_CHECKS } from './entity-conformance-unreturned';
|
|
21
22
|
import { UPDATE_MANY_CHECKS } from './entity-conformance-update-many';
|
|
22
23
|
import { VALUE_CHECKS } from './entity-conformance-values';
|
|
@@ -38,6 +39,7 @@ export const ENTITY_DRIVER_CHECKS: readonly EntityDriverCheck[] = [
|
|
|
38
39
|
...MEASURE_CHECKS,
|
|
39
40
|
...CONTAINS_CHECKS,
|
|
40
41
|
...TENANCY_CHECKS,
|
|
42
|
+
...TREE_CHECKS,
|
|
41
43
|
...BATCH_CHECKS,
|
|
42
44
|
...LATEST_BY_CHECKS,
|
|
43
45
|
...LOCK_CHECKS,
|
|
@@ -42,6 +42,14 @@ export const probes = (driver: Driver): Readonly<Record<DriverCapability, () =>
|
|
|
42
42
|
series: () => repo().series?.({ on: 'at', unit: 'day', timeZone: 'UTC', value: 'count' }),
|
|
43
43
|
upsert: () => repo().upsertAll([PROBE_ROW], { onConflict: ['id'] }),
|
|
44
44
|
matches: () => repo().findMany({ where: [{ column: '$search', op: 'matches', value: 'x' }] }),
|
|
45
|
+
'predicate:or': () =>
|
|
46
|
+
table()
|
|
47
|
+
.andWhereNode({ or: [{ column: 'n', op: 'eq', value: 1 }] })
|
|
48
|
+
.all(),
|
|
49
|
+
'predicate:via': () =>
|
|
50
|
+
table()
|
|
51
|
+
.andWhereNode({ via: { column: 'id', entity: 'ec_probe', target: 'id' }, where: [] })
|
|
52
|
+
.all(),
|
|
45
53
|
'aggregate:countBy': () => repo().countBy('label'),
|
|
46
54
|
'aggregate:sum': () => repo().aggregate('sum', 'n'),
|
|
47
55
|
'aggregate:avg': () => repo().aggregate('avg', 'n'),
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
// Entity conformance · the PREDICATE TREE: `andWhereNode` with an `or` group and a `via` hop answers
|
|
2
|
+
// the same rows on every driver, and a hop's subselect runs under its TARGET's tenant and soft
|
|
3
|
+
// delete — a friendship recorded in another org never widens this org's read. The security half of
|
|
4
|
+
// the feature is the tenancy checks here; each would pass on a driver that read the target raw.
|
|
5
|
+
|
|
6
|
+
import { expect } from 'bun:test';
|
|
7
|
+
import type { Database } from '@ultimat3/entity';
|
|
8
|
+
import { entity, text, timestamp, uuid } from '@ultimat3/entity';
|
|
9
|
+
import { remember } from './entity-conformance-entities';
|
|
10
|
+
import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
|
|
11
|
+
import type { EntityDriverCheck } from './entity-driver-conformance';
|
|
12
|
+
|
|
13
|
+
const posts = remember(
|
|
14
|
+
entity('ec_tree_posts', {
|
|
15
|
+
columns: {
|
|
16
|
+
id: uuid().primaryKey(),
|
|
17
|
+
orgId: uuid().tenant(),
|
|
18
|
+
authorId: uuid(),
|
|
19
|
+
audience: text({ max: 10 }),
|
|
20
|
+
body: text({ max: 20 }),
|
|
21
|
+
},
|
|
22
|
+
}),
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
const friendships = remember(
|
|
26
|
+
entity('ec_tree_friendships', {
|
|
27
|
+
columns: {
|
|
28
|
+
id: uuid().primaryKey(),
|
|
29
|
+
orgId: uuid().tenant(),
|
|
30
|
+
userId: uuid(),
|
|
31
|
+
friendId: uuid(),
|
|
32
|
+
deletedAt: timestamp().nullable(),
|
|
33
|
+
},
|
|
34
|
+
}),
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
/** Untenanted and undeclared: a hop into it from a tenant table is an unscoped read. */
|
|
38
|
+
const handles = remember(
|
|
39
|
+
entity('ec_tree_handles', { columns: { id: uuid().primaryKey(), userId: uuid() } }),
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
/** Untenanted and SAID so: a hop into it is the reach `shared:` already declares. */
|
|
43
|
+
const badges = remember(
|
|
44
|
+
entity('ec_tree_badges', {
|
|
45
|
+
columns: { id: uuid().primaryKey(), userId: uuid(), kind: text({ max: 10 }) },
|
|
46
|
+
shared: 'a badge hangs off a user, whichever org reads it',
|
|
47
|
+
}),
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
const ORG = idAt('b1');
|
|
51
|
+
const OTHER_ORG = idAt('b2');
|
|
52
|
+
const ME = idAt('c1');
|
|
53
|
+
const FRIEND = idAt('c2');
|
|
54
|
+
const STRANGER = idAt('c3');
|
|
55
|
+
const EX = idAt('c4');
|
|
56
|
+
|
|
57
|
+
/** Untenanted and the same for every tenant (`global:`): a catalog any org may hop into. */
|
|
58
|
+
const staff = remember(
|
|
59
|
+
entity('ec_tree_staff', {
|
|
60
|
+
columns: { id: uuid().primaryKey(), userId: uuid() },
|
|
61
|
+
global: 'the platform staff roster, the same for every org',
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
const tables = { posts, friendships, handles, badges, staff };
|
|
66
|
+
type Tree = Database<typeof tables>;
|
|
67
|
+
|
|
68
|
+
/** Seeded as a script would, naming every tenant: the table's own answer. */
|
|
69
|
+
const seed = async (db: Tree): Promise<void> => {
|
|
70
|
+
const post = (n: number, authorId: string, audience: string, orgId = ORG) =>
|
|
71
|
+
db.posts.insert({ id: idAt(`d${n}`), orgId, authorId, audience, body: `p${n}` });
|
|
72
|
+
await post(1, ME, 'private');
|
|
73
|
+
await post(2, FRIEND, 'friends');
|
|
74
|
+
await post(3, STRANGER, 'friends');
|
|
75
|
+
await post(4, STRANGER, 'public');
|
|
76
|
+
await post(5, EX, 'friends');
|
|
77
|
+
await post(6, FRIEND, 'public', OTHER_ORG);
|
|
78
|
+
const friend = (n: number, friendId: string, orgId: string, deletedAt: Date | null = null) =>
|
|
79
|
+
db.friendships.insert({ id: idAt(`e${n}`), orgId, userId: ME, friendId, deletedAt });
|
|
80
|
+
await friend(1, FRIEND, ORG);
|
|
81
|
+
// The whole point: in ANOTHER org, ME is friends with STRANGER. Read in ORG, it must not count.
|
|
82
|
+
await friend(2, STRANGER, OTHER_ORG);
|
|
83
|
+
// A friendship that ended: soft-deleted, so it must not count either.
|
|
84
|
+
await friend(3, EX, ORG, new Date('2026-01-01T00:00:00.000Z'));
|
|
85
|
+
await db.handles.insert({ id: idAt('f1'), userId: FRIEND });
|
|
86
|
+
await db.badges.insert({ id: idAt('f2'), userId: FRIEND, kind: 'gold' });
|
|
87
|
+
await db.staff.insert({ id: idAt('f3'), userId: STRANGER });
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const bodies = (rows: readonly { readonly body: string }[]): readonly string[] =>
|
|
91
|
+
rows.map((row) => row.body).sort();
|
|
92
|
+
|
|
93
|
+
const friendsOfMe = {
|
|
94
|
+
via: { column: 'authorId', entity: 'ec_tree_friendships', target: 'friendId' },
|
|
95
|
+
where: [{ column: 'userId', op: 'eq', value: ME }],
|
|
96
|
+
} as const;
|
|
97
|
+
|
|
98
|
+
export const TREE_CHECKS: readonly EntityDriverCheck[] = [
|
|
99
|
+
checkOver(
|
|
100
|
+
tables,
|
|
101
|
+
'an or group answers the rows any member matches, and an empty one answers none',
|
|
102
|
+
async (db) => {
|
|
103
|
+
await seed(db);
|
|
104
|
+
const visible = await inOrg(ORG, () =>
|
|
105
|
+
db.posts
|
|
106
|
+
.andWhereNode({
|
|
107
|
+
or: [
|
|
108
|
+
{ column: 'audience', op: 'eq', value: 'public' },
|
|
109
|
+
{ column: 'authorId', op: 'eq', value: ME },
|
|
110
|
+
],
|
|
111
|
+
})
|
|
112
|
+
.all(),
|
|
113
|
+
);
|
|
114
|
+
expect(bodies(visible)).toEqual(['p1', 'p4']);
|
|
115
|
+
expect(await inOrg(ORG, () => db.posts.andWhereNode({ or: [] }).all())).toEqual([]);
|
|
116
|
+
const counted = await inOrg(ORG, () =>
|
|
117
|
+
db.posts
|
|
118
|
+
.andWhereNode({ or: [{ column: 'audience', op: 'in', value: ['friends', 'private'] }] })
|
|
119
|
+
.count(),
|
|
120
|
+
);
|
|
121
|
+
expect(counted).toBe(4);
|
|
122
|
+
},
|
|
123
|
+
['predicate:or'],
|
|
124
|
+
),
|
|
125
|
+
checkOver(
|
|
126
|
+
tables,
|
|
127
|
+
'a via hop reads its target under the target’s tenant: another org’s friendship never counts',
|
|
128
|
+
async (db) => {
|
|
129
|
+
await seed(db);
|
|
130
|
+
const read = await inOrg(ORG, () => db.posts.andWhereNode(friendsOfMe).all());
|
|
131
|
+
// p2 (FRIEND, an ORG friendship). Not p3/p4: ME↔STRANGER is OTHER_ORG's row. Not p5: ended.
|
|
132
|
+
expect(bodies(read)).toEqual(['p2']);
|
|
133
|
+
const there = await inOrg(OTHER_ORG, () => db.posts.andWhereNode(friendsOfMe).all());
|
|
134
|
+
// In OTHER_ORG the friendship with STRANGER counts, and FRIEND's ORG friendship does not.
|
|
135
|
+
expect(bodies(there)).toEqual([]);
|
|
136
|
+
},
|
|
137
|
+
['predicate:via'],
|
|
138
|
+
),
|
|
139
|
+
checkOver(
|
|
140
|
+
tables,
|
|
141
|
+
'the demo’s visibility rule is one tree: mine, public, or a friend’s friends-only post',
|
|
142
|
+
async (db) => {
|
|
143
|
+
await seed(db);
|
|
144
|
+
const rule = {
|
|
145
|
+
or: [
|
|
146
|
+
{ column: 'authorId', op: 'eq', value: ME },
|
|
147
|
+
{ column: 'audience', op: 'eq', value: 'public' },
|
|
148
|
+
{ and: [{ column: 'audience', op: 'eq', value: 'friends' }, friendsOfMe] },
|
|
149
|
+
],
|
|
150
|
+
} as const;
|
|
151
|
+
const read = await inOrg(ORG, () => db.posts.andWhereNode(rule).all());
|
|
152
|
+
// p1 mine, p4 public, p2 a friend's friends-only post. Not p3 (STRANGER is a friend only in
|
|
153
|
+
// OTHER_ORG), not p5 (that friendship ended), not p6 (another org's post).
|
|
154
|
+
expect(bodies(read)).toEqual(['p1', 'p2', 'p4']);
|
|
155
|
+
const counted = await inOrg(ORG, () => db.posts.andWhereNode(rule).count());
|
|
156
|
+
expect(counted).toBe(3);
|
|
157
|
+
},
|
|
158
|
+
['predicate:or', 'predicate:via'],
|
|
159
|
+
),
|
|
160
|
+
checkOver(
|
|
161
|
+
tables,
|
|
162
|
+
'a hop into an untenanted table is refused unless it declares shared: or global:',
|
|
163
|
+
async (db) => {
|
|
164
|
+
await seed(db);
|
|
165
|
+
const into = (name: string) =>
|
|
166
|
+
db.posts
|
|
167
|
+
.andWhereNode({
|
|
168
|
+
via: { column: 'authorId', entity: name, target: 'userId' },
|
|
169
|
+
where: [],
|
|
170
|
+
})
|
|
171
|
+
.all();
|
|
172
|
+
expect(await inOrg(ORG, () => codeOf(() => into('ec_tree_handles')))).toBe(
|
|
173
|
+
'X_TENANCY_UNSCOPED',
|
|
174
|
+
);
|
|
175
|
+
expect(bodies(await inOrg(ORG, () => into('ec_tree_badges')))).toEqual(['p2']);
|
|
176
|
+
// A global catalog reads alike for every org: STRANGER's ORG posts, never OTHER_ORG's.
|
|
177
|
+
expect(bodies(await inOrg(ORG, () => into('ec_tree_staff')))).toEqual(['p3', 'p4']);
|
|
178
|
+
},
|
|
179
|
+
['predicate:via'],
|
|
180
|
+
),
|
|
181
|
+
checkOver(
|
|
182
|
+
tables,
|
|
183
|
+
'outside a request a hop into a tenant table must name its tenant, as a read of it must',
|
|
184
|
+
async (db) => {
|
|
185
|
+
await seed(db);
|
|
186
|
+
const unnamed = () => db.posts.where({ orgId: ORG }).andWhereNode(friendsOfMe).all();
|
|
187
|
+
expect(await codeOf(unnamed)).toBe('X_TENANCY_UNSCOPED');
|
|
188
|
+
const named = await db.posts
|
|
189
|
+
.where({ orgId: ORG })
|
|
190
|
+
.andWhereNode({
|
|
191
|
+
via: friendsOfMe.via,
|
|
192
|
+
where: [...friendsOfMe.where, { column: 'orgId', op: 'eq', value: ORG }],
|
|
193
|
+
})
|
|
194
|
+
.all();
|
|
195
|
+
expect(bodies(named)).toEqual(['p2']);
|
|
196
|
+
},
|
|
197
|
+
['predicate:via'],
|
|
198
|
+
),
|
|
199
|
+
];
|
package/src/exercise-report.ts
CHANGED
|
@@ -61,6 +61,8 @@ export type TenantProof =
|
|
|
61
61
|
| { readonly verdict: 'proven' }
|
|
62
62
|
/** The policy admits anonymous: read half skipped, write half kept and clean. */
|
|
63
63
|
| { readonly verdict: 'public'; readonly reason: string }
|
|
64
|
+
/** A read touching only `entity({ global })` entities: no row of A's to miss, write half kept. */
|
|
65
|
+
| { readonly verdict: 'global'; readonly reason: string }
|
|
64
66
|
/** A's positive control was not reached, so B's clean answer proves nothing. */
|
|
65
67
|
| { readonly verdict: 'unproven'; readonly reason: string }
|
|
66
68
|
| { readonly verdict: 'crossed'; readonly findings: readonly TenantFinding[] };
|
|
@@ -195,6 +197,11 @@ export interface Observed {
|
|
|
195
197
|
readonly payloads: readonly EffectPayload[];
|
|
196
198
|
/** Each statement shape and how often, the `expectedQueryLoop` ones told apart. */
|
|
197
199
|
readonly shapes: readonly StatementTally[];
|
|
200
|
+
/**
|
|
201
|
+
* Every entity a statement was attributed to, first seen first; `null` once one carried none —
|
|
202
|
+
* hand-written SQL reads tables nobody can name. Optional: a merged or hand-built one may omit it.
|
|
203
|
+
*/
|
|
204
|
+
readonly reads?: readonly string[] | null;
|
|
198
205
|
}
|
|
199
206
|
|
|
200
207
|
/** What `observe` hands back: what the call did, and its value or what it threw. */
|
|
@@ -241,12 +248,16 @@ export async function openExerciseRoom(): Promise<ExerciseRoom> {
|
|
|
241
248
|
let subject: string | undefined;
|
|
242
249
|
const rows: string[] = [];
|
|
243
250
|
const shapes = new Map<string, { count: number; unexpected: number; expected?: string }>();
|
|
251
|
+
const reads = new Set<string>();
|
|
252
|
+
let unattributed = false;
|
|
244
253
|
const sent = new Map<string, { primitives: Set<string>; scan?: string }>();
|
|
245
254
|
// Every observer below returns at once unless the sender is the observed call: the bus delivers
|
|
246
255
|
// synchronously in the sender's context (`instrument`), so `owns()` reads the sender's marker.
|
|
247
256
|
const counting = (event: DbStatementEvent): void => {
|
|
248
257
|
if (!owns()) return;
|
|
249
258
|
statements += 1;
|
|
259
|
+
if (event.attribution === undefined) unattributed = true;
|
|
260
|
+
else reads.add(event.attribution.entity);
|
|
250
261
|
const fingerprint = statementFingerprint(event);
|
|
251
262
|
const shape = shapes.get(fingerprint) ?? { count: 0, unexpected: 0 };
|
|
252
263
|
shape.count += 1;
|
|
@@ -280,6 +291,8 @@ export async function openExerciseRoom(): Promise<ExerciseRoom> {
|
|
|
280
291
|
subject = name;
|
|
281
292
|
statements = 0;
|
|
282
293
|
shapes.clear();
|
|
294
|
+
reads.clear();
|
|
295
|
+
unattributed = false;
|
|
283
296
|
rows.length = 0;
|
|
284
297
|
calls.length = 0;
|
|
285
298
|
mail.clear();
|
|
@@ -332,7 +345,8 @@ export async function openExerciseRoom(): Promise<ExerciseRoom> {
|
|
|
332
345
|
];
|
|
333
346
|
subject = undefined;
|
|
334
347
|
const tallies = [...shapes].map(([fingerprint, shape]) => ({ fingerprint, ...shape }));
|
|
335
|
-
|
|
348
|
+
const read = unattributed ? null : [...reads];
|
|
349
|
+
return { statements, effects, refusedHosts, payloads, shapes: tallies, reads: read };
|
|
336
350
|
};
|
|
337
351
|
|
|
338
352
|
return {
|
package/src/exercise.ts
CHANGED
|
@@ -57,8 +57,14 @@ import { deferredMayStayNull, pairGraph, seedPass, tenantPair } from './seed-gra
|
|
|
57
57
|
import type { SeedGraph, SeedWriter } from './seed-graph-plan';
|
|
58
58
|
import type { SeedEntity } from './seed-graph-shape';
|
|
59
59
|
import { tenantTaint } from './tenant-canary';
|
|
60
|
-
import type { LegAnswer } from './tenant-proof';
|
|
61
|
-
import {
|
|
60
|
+
import type { ControlAnswer, LegAnswer } from './tenant-proof';
|
|
61
|
+
import {
|
|
62
|
+
globalEntities,
|
|
63
|
+
proveTenant,
|
|
64
|
+
publicReason,
|
|
65
|
+
readsOf,
|
|
66
|
+
withoutCrossTenant,
|
|
67
|
+
} from './tenant-proof';
|
|
62
68
|
|
|
63
69
|
export interface ExercisePassOptions {
|
|
64
70
|
readonly entities: readonly SeedEntity[];
|
|
@@ -143,6 +149,9 @@ interface Prepared {
|
|
|
143
149
|
readonly ceiling: ExerciseStatementCeiling | undefined;
|
|
144
150
|
}
|
|
145
151
|
|
|
152
|
+
/** A's control as the tenant proof reads it, plus the input its last call was reached with. */
|
|
153
|
+
type Controlled = ControlAnswer & { readonly input: unknown };
|
|
154
|
+
|
|
146
155
|
/** Thrown out of 39's loop by a bind that failed: the record is the entry's, never the loop's. */
|
|
147
156
|
class BindThrew {
|
|
148
157
|
constructor(readonly error: unknown) {}
|
|
@@ -152,11 +161,7 @@ class BindThrew {
|
|
|
152
161
|
* A's positive control: 39's loop, as the pass has always run it. The room records each CALL
|
|
153
162
|
* alone: an override's input runs between calls, and what it sends is never this primitive's.
|
|
154
163
|
*/
|
|
155
|
-
async function control(
|
|
156
|
-
run: Prepared,
|
|
157
|
-
room: ExerciseRoom,
|
|
158
|
-
sampler: Sampler,
|
|
159
|
-
): Promise<{ readonly record: ExerciseRecord; readonly output: unknown; readonly input: unknown }> {
|
|
164
|
+
async function control(run: Prepared, room: ExerciseRoom, sampler: Sampler): Promise<Controlled> {
|
|
160
165
|
const { subject, key, actor, tenant, declaredRuns, lookups, bindInput } = run;
|
|
161
166
|
const { kind, name } = subject;
|
|
162
167
|
let binds = 0;
|
|
@@ -221,7 +226,7 @@ async function control(
|
|
|
221
226
|
ms: Math.round(performance.now() - started),
|
|
222
227
|
...inputThrew(name, key, error.error),
|
|
223
228
|
};
|
|
224
|
-
return { record, output, input: lastInput };
|
|
229
|
+
return { record, output, input: lastInput, reads: readsOf(segments) };
|
|
225
230
|
}
|
|
226
231
|
const ms = Math.round(performance.now() - started);
|
|
227
232
|
const observed = mergeObserved(segments);
|
|
@@ -246,7 +251,7 @@ async function control(
|
|
|
246
251
|
...(defect === undefined ? {} : { defect }),
|
|
247
252
|
...(statementCeiling === undefined ? {} : { statementCeiling }),
|
|
248
253
|
};
|
|
249
|
-
return { record, output, input: lastInput };
|
|
254
|
+
return { record, output, input: lastInput, reads: readsOf(segments) };
|
|
250
255
|
}
|
|
251
256
|
|
|
252
257
|
/** One B leg: B's actor, A's ids, a queue of its own. What it answered and every effect it had. */
|
|
@@ -367,6 +372,7 @@ async function exerciseOne(
|
|
|
367
372
|
read: kind === 'query',
|
|
368
373
|
sweep: kind === 'job',
|
|
369
374
|
tenantless: seat?.kind === 'none',
|
|
375
|
+
globals: globalEntities(options.entities),
|
|
370
376
|
attack: () => attack(subject, key, input, intruder, other, room),
|
|
371
377
|
control: async () => {
|
|
372
378
|
const done = await control(run, room, sampler);
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// Every module a test file can reach by import, read from source: what a shared worker uses to
|
|
2
|
+
// tell a file's OWN environment from the declarations an earlier file's imports left behind. Bun
|
|
3
|
+
// publishes no module graph (`require.cache` entries carry no `children` for ESM), so it is scanned.
|
|
4
|
+
|
|
5
|
+
/** The closure, and whether every module in it could be read: an incomplete one filters nothing. */
|
|
6
|
+
export interface ImportGraph {
|
|
7
|
+
readonly modules: ReadonlySet<string>;
|
|
8
|
+
readonly complete: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Only these are scanned; a `.json` or `.css` import is a leaf that declares nothing. */
|
|
12
|
+
const CODE = /\.[cm]?[jt]sx?$/;
|
|
13
|
+
|
|
14
|
+
/** `bin.ts` opens with a shebang, which the transpiler refuses as a syntax error. */
|
|
15
|
+
const withoutShebang = (source: string): string =>
|
|
16
|
+
source.startsWith('#!') ? `//${source.slice(2)}` : source;
|
|
17
|
+
|
|
18
|
+
const transpilers = {
|
|
19
|
+
ts: new Bun.Transpiler({ loader: 'ts' }),
|
|
20
|
+
tsx: new Bun.Transpiler({ loader: 'tsx' }),
|
|
21
|
+
js: new Bun.Transpiler({ loader: 'js' }),
|
|
22
|
+
jsx: new Bun.Transpiler({ loader: 'jsx' }),
|
|
23
|
+
} as const;
|
|
24
|
+
|
|
25
|
+
const transpilerFor = (path: string): Bun.Transpiler => {
|
|
26
|
+
if (path.endsWith('.tsx')) return transpilers.tsx;
|
|
27
|
+
if (path.endsWith('.jsx')) return transpilers.jsx;
|
|
28
|
+
if (/\.[cm]?ts$/.test(path)) return transpilers.ts;
|
|
29
|
+
return transpilers.js;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const dirOf = (path: string): string => path.slice(0, Math.max(path.lastIndexOf('/'), 0)) || '/';
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A module's direct imports, resolved, or `undefined` when its source could not be read. Third-
|
|
36
|
+
* party code under `node_modules` is a leaf: it never declares an Ultimate permission, and walking
|
|
37
|
+
* it would multiply the scan for nothing. A specifier that does not resolve statically (a template
|
|
38
|
+
* `import()`, a plugin's virtual module) is skipped — the caller keeps anything first declared
|
|
39
|
+
* during the file, so a module reached that way is not lost on its first evaluation.
|
|
40
|
+
*/
|
|
41
|
+
async function directImports(path: string): Promise<readonly string[] | undefined> {
|
|
42
|
+
if (!CODE.test(path) || path.endsWith('.d.ts') || path.includes('/node_modules/')) return [];
|
|
43
|
+
let source: string;
|
|
44
|
+
try {
|
|
45
|
+
source = await Bun.file(path).text();
|
|
46
|
+
} catch {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
let specifiers: readonly string[];
|
|
50
|
+
try {
|
|
51
|
+
specifiers = transpilerFor(path)
|
|
52
|
+
.scanImports(withoutShebang(source))
|
|
53
|
+
.map((entry) => entry.path);
|
|
54
|
+
} catch {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
const dir = dirOf(path);
|
|
58
|
+
const resolved: string[] = [];
|
|
59
|
+
for (const specifier of specifiers) {
|
|
60
|
+
if (specifier.startsWith('bun:') || specifier.startsWith('node:')) continue;
|
|
61
|
+
try {
|
|
62
|
+
resolved.push(Bun.resolveSync(specifier, dir));
|
|
63
|
+
} catch {
|
|
64
|
+
// Unresolvable statically: see the doc comment.
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return resolved;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** One reader per process: a module's imports are read once however many files reach it. */
|
|
71
|
+
export function importGraphReader(): (entry: string) => Promise<ImportGraph> {
|
|
72
|
+
const direct = new Map<string, Promise<readonly string[] | undefined>>();
|
|
73
|
+
const importsOf = (path: string): Promise<readonly string[] | undefined> => {
|
|
74
|
+
let pending = direct.get(path);
|
|
75
|
+
if (pending === undefined) {
|
|
76
|
+
pending = directImports(path);
|
|
77
|
+
direct.set(path, pending);
|
|
78
|
+
}
|
|
79
|
+
return pending;
|
|
80
|
+
};
|
|
81
|
+
return async (entry) => {
|
|
82
|
+
const modules = new Set<string>([entry]);
|
|
83
|
+
let complete = true;
|
|
84
|
+
let frontier = [entry];
|
|
85
|
+
while (frontier.length > 0) {
|
|
86
|
+
const next: string[] = [];
|
|
87
|
+
for (const imports of await Promise.all(frontier.map(importsOf))) {
|
|
88
|
+
if (imports === undefined) {
|
|
89
|
+
complete = false;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
for (const module of imports) {
|
|
93
|
+
if (modules.has(module)) continue;
|
|
94
|
+
modules.add(module);
|
|
95
|
+
next.push(module);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
frontier = next;
|
|
99
|
+
}
|
|
100
|
+
return { modules, complete };
|
|
101
|
+
};
|
|
102
|
+
}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
// What every `JobDriver` records for `onSettled` (J11): a settle that ENDS a run of a job with a
|
|
2
2
|
// hook owes it, the hook's return clears the debt under that claim, and a debt a crash left is
|
|
3
|
-
// taken once per grace
|
|
3
|
+
// taken once per grace — and a row the CLAIM settles (a final-attempt burial, an expiry) owes it
|
|
4
|
+
// too, named by `ClaimOptions.settleOwed`. A driver with no `settleDebt` fails here.
|
|
5
|
+
//
|
|
4
6
|
// Type-only imports: the barrel never loads `@ultimat3/jobs`.
|
|
5
7
|
|
|
6
8
|
import { expect } from 'bun:test';
|
|
7
|
-
import type { JobDriver, SettleDebt } from '@ultimat3/jobs';
|
|
9
|
+
import type { JobDriver, JobRecord, SettleDebt } from '@ultimat3/jobs';
|
|
8
10
|
import type { JobDriverCheck } from './job-driver-checks';
|
|
9
11
|
|
|
10
12
|
let minted = 0;
|
|
@@ -93,4 +95,61 @@ export const SETTLE_DEBT_CHECKS: readonly JobDriverCheck[] = [
|
|
|
93
95
|
expect(await lost(debt, at.name)).toEqual([]);
|
|
94
96
|
},
|
|
95
97
|
},
|
|
98
|
+
{
|
|
99
|
+
name: 'a row the claim buries or expires owes onSettled when settleOwed names its job',
|
|
100
|
+
async run(driver) {
|
|
101
|
+
const debt = debtOf(driver);
|
|
102
|
+
const hooked = scope();
|
|
103
|
+
const plain = scope();
|
|
104
|
+
// A final attempt whose lease lapsed (0 ms), for each job; and an expired row of the hooked.
|
|
105
|
+
const lapsing = async (at: typeof hooked): Promise<string> => {
|
|
106
|
+
const { id } = await driver.enqueue({
|
|
107
|
+
name: at.name,
|
|
108
|
+
queue: at.queue,
|
|
109
|
+
input: {},
|
|
110
|
+
idempotencyKey: 'lapsing',
|
|
111
|
+
maxAttempts: 1,
|
|
112
|
+
});
|
|
113
|
+
const taken = await driver.claim({
|
|
114
|
+
queues: [at.queue],
|
|
115
|
+
limit: 1,
|
|
116
|
+
visibilityTimeoutMs: 0,
|
|
117
|
+
workerId: 'w-gone',
|
|
118
|
+
});
|
|
119
|
+
expect(taken.map((row) => row.id)).toEqual([id]);
|
|
120
|
+
return id;
|
|
121
|
+
};
|
|
122
|
+
const dead = await lapsing(hooked);
|
|
123
|
+
const unowed = await lapsing(plain);
|
|
124
|
+
const expired = await driver.enqueue({
|
|
125
|
+
name: hooked.name,
|
|
126
|
+
queue: hooked.queue,
|
|
127
|
+
input: {},
|
|
128
|
+
idempotencyKey: 'expired',
|
|
129
|
+
maxAttempts: 3,
|
|
130
|
+
expiresAt: 1,
|
|
131
|
+
});
|
|
132
|
+
const buried: JobRecord[] = [];
|
|
133
|
+
for (const at of [hooked, plain]) {
|
|
134
|
+
const handed = await driver.claim({
|
|
135
|
+
queues: [at.queue],
|
|
136
|
+
limit: 10,
|
|
137
|
+
visibilityTimeoutMs: 30_000,
|
|
138
|
+
workerId: 'w-burier',
|
|
139
|
+
settleOwed: [hooked.name],
|
|
140
|
+
onExhausted: (rows) => buried.push(...rows),
|
|
141
|
+
});
|
|
142
|
+
expect(handed).toEqual([]);
|
|
143
|
+
}
|
|
144
|
+
expect(buried.map((row) => row.id).sort()).toEqual([dead, expired.id, unowed].sort());
|
|
145
|
+
// Recorded by the claim's own write: a burier that dies now leaves it for the leader.
|
|
146
|
+
expect([...(await lost(debt, hooked.name))].sort()).toEqual([dead, expired.id].sort());
|
|
147
|
+
expect(await lost(debt, plain.name)).toEqual([]);
|
|
148
|
+
// Paid under the claim the buried row carries — the one the burier was handed.
|
|
149
|
+
for (const row of buried.filter((each) => each.name === hooked.name)) {
|
|
150
|
+
expect(await debt.clear(row.id, row.claim ?? 0)).toBe(true);
|
|
151
|
+
}
|
|
152
|
+
expect(await lost(debt, hooked.name)).toEqual([]);
|
|
153
|
+
},
|
|
154
|
+
},
|
|
96
155
|
];
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The permissions and roles a test file inherits on a shared worker: what a module in ITS import
|
|
2
|
+
// graph declared, never what a module only an earlier file imported left behind. Read from each
|
|
3
|
+
// name's declaration site; `registry-leak-guard.ts` owns WHEN, `import-graph.ts` the graph.
|
|
4
|
+
|
|
5
|
+
import type { RoleMap } from '@ultimat3/policy';
|
|
6
|
+
import type { ImportGraph } from './import-graph';
|
|
7
|
+
import type { ProcessRegistrySnapshot } from './registry-snapshot';
|
|
8
|
+
|
|
9
|
+
/** The policy half of a snapshot — the only half this narrows. */
|
|
10
|
+
export type PolicyEnvironment = Pick<
|
|
11
|
+
ProcessRegistrySnapshot,
|
|
12
|
+
'permissions' | 'permissionSites' | 'roles' | 'roleSites'
|
|
13
|
+
>;
|
|
14
|
+
|
|
15
|
+
/** Names kept whatever the graph says: the preload's, and those first declared during THIS load. */
|
|
16
|
+
export interface KeptNames {
|
|
17
|
+
readonly permissions: ReadonlySet<string>;
|
|
18
|
+
readonly roles: ReadonlySet<string>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** `?x-reload=…` is a loader's cache key, not part of the file. */
|
|
22
|
+
const withoutQuery = (path: string): string => path.replace(/\?.*$/, '');
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The file a stack frame names — `at /a/b.ts:5:1`, `at fn (/a/b.ts:5:1)`, `at async C:\a\b.ts:5:1`
|
|
26
|
+
* — `/`-normalised, or `undefined` for a frame that names none (`unknown site`, `<anonymous>`).
|
|
27
|
+
*/
|
|
28
|
+
export function siteFile(frame: string): string | undefined {
|
|
29
|
+
const line = frame.trim();
|
|
30
|
+
const file = (/\(([^()]+):\d+:\d+\)$/.exec(line) ??
|
|
31
|
+
/^at (?:async )?(.+):\d+:\d+$/.exec(line))?.[1];
|
|
32
|
+
if (file === undefined || file.startsWith('<') || file.startsWith('native')) return undefined;
|
|
33
|
+
return withoutQuery(file.replaceAll('\\', '/'));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* In the graph when ANY site is, and when a site cannot be read at all: an unreadable site is
|
|
38
|
+
* provenance this cannot judge, and dropping a name a cached module really declared is the one
|
|
39
|
+
* failure a file cannot repair from inside.
|
|
40
|
+
*/
|
|
41
|
+
const reachable = (sites: readonly string[], modules: ReadonlySet<string>): boolean =>
|
|
42
|
+
sites.length === 0 ||
|
|
43
|
+
sites.some((site) => {
|
|
44
|
+
const file = siteFile(site);
|
|
45
|
+
return file === undefined || modules.has(file);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* `inherited` narrowed to the names `graph` reaches, plus `kept`. An incomplete graph narrows
|
|
50
|
+
* nothing: a module it could not read may be the one that declared.
|
|
51
|
+
*/
|
|
52
|
+
export function ownEnvironment(
|
|
53
|
+
inherited: PolicyEnvironment,
|
|
54
|
+
graph: ImportGraph,
|
|
55
|
+
kept: KeptNames,
|
|
56
|
+
): PolicyEnvironment {
|
|
57
|
+
if (!graph.complete) return inherited;
|
|
58
|
+
const modules = new Set([...graph.modules].map((path) => path.replaceAll('\\', '/')));
|
|
59
|
+
const permissions = inherited.permissions.filter(
|
|
60
|
+
(name) =>
|
|
61
|
+
kept.permissions.has(name) ||
|
|
62
|
+
reachable(
|
|
63
|
+
Object.hasOwn(inherited.permissionSites, name)
|
|
64
|
+
? (inherited.permissionSites[name] ?? [])
|
|
65
|
+
: [],
|
|
66
|
+
modules,
|
|
67
|
+
),
|
|
68
|
+
);
|
|
69
|
+
const roles: Record<string, RoleMap[string]> = {};
|
|
70
|
+
const roleSites: Record<string, string> = {};
|
|
71
|
+
for (const [name, definition] of Object.entries(inherited.roles)) {
|
|
72
|
+
const site = Object.hasOwn(inherited.roleSites, name) ? inherited.roleSites[name] : undefined;
|
|
73
|
+
if (!kept.roles.has(name) && !reachable(site === undefined ? [] : [site], modules)) continue;
|
|
74
|
+
roles[name] = definition;
|
|
75
|
+
if (site !== undefined) roleSites[name] = site;
|
|
76
|
+
}
|
|
77
|
+
const permitted = new Set(permissions);
|
|
78
|
+
const permissionSites = Object.fromEntries(
|
|
79
|
+
Object.entries(inherited.permissionSites).filter(([name]) => permitted.has(name)),
|
|
80
|
+
);
|
|
81
|
+
return { permissions, permissionSites, roles, roleSites };
|
|
82
|
+
}
|
|
@@ -5,13 +5,19 @@
|
|
|
5
5
|
|
|
6
6
|
import { afterAll } from 'bun:test';
|
|
7
7
|
import { knownTags, registeredTiers } from '@ultimat3/cache';
|
|
8
|
+
import { configureLocales } from '@ultimat3/i18n';
|
|
9
|
+
import { captureAdminMounts, restoreAdminMounts } from './admin-mount-boundary';
|
|
8
10
|
import { isAppRoot } from './app-root';
|
|
11
|
+
import { captureDriverStores, restoreDriverStores } from './driver-store-boundary';
|
|
9
12
|
import { RegistryLeakError } from './errors';
|
|
10
13
|
import { runBoundaryHooks, runFileBoundary } from './file-boundary';
|
|
14
|
+
import { type ImportGraph, importGraphReader } from './import-graph';
|
|
15
|
+
import { ownEnvironment } from './registry-environment';
|
|
11
16
|
import type { ProcessRegistrySnapshot } from './registry-snapshot';
|
|
12
17
|
import {
|
|
13
18
|
captureProcessRegistries,
|
|
14
19
|
mergeSnapshots,
|
|
20
|
+
restorePolicyRegistries,
|
|
15
21
|
restoreProcessRegistries,
|
|
16
22
|
} from './registry-snapshot';
|
|
17
23
|
import { rerunDeclarations } from './rerun-declarations';
|
|
@@ -34,14 +40,14 @@ import { frameworkDeclarationRegistries } from './rerun-registries';
|
|
|
34
40
|
* "Idiomatic to leave filled" says nothing about a file that calls `clear*()`/`reset*()` and takes
|
|
35
41
|
* a module-scope declaration from every file after it — a module evaluates once per process, so the
|
|
36
42
|
* next file's own `import` is a cache hit that declares nothing. That is what `registry-snapshot.ts`
|
|
37
|
-
* repairs, and it repairs
|
|
43
|
+
* repairs, and it repairs SEVEN registries out of the set that has one:
|
|
38
44
|
*
|
|
39
45
|
* | registry | reset export | owner | in the snapshot? |
|
|
40
46
|
* |---|---|---|---|
|
|
41
47
|
* | locales / catalogs | `resetCatalogs` | `@ultimat3/i18n` | yes |
|
|
42
48
|
* | permissions / roles | `restorePermissions` / `restoreRoles` | `@ultimat3/policy` | yes |
|
|
43
49
|
* | routes | `clearRoutes` | `@ultimat3/render` | **no** |
|
|
44
|
-
* | jobs | `resetJobs` / `restoreJobs` | `@ultimat3/jobs` |
|
|
50
|
+
* | jobs | `resetJobs` / `restoreJobs` | `@ultimat3/jobs` | yes (2026-11) |
|
|
45
51
|
* | tasks | `restoreTasks` | `@ultimat3/jobs` | yes (22.7) |
|
|
46
52
|
* | measurement actor | `resetMeasurementActor` | `@ultimat3/core` | yes |
|
|
47
53
|
* | actions | `resetActions` | `@ultimat3/action` | **no** |
|
|
@@ -109,7 +115,10 @@ const repoRelative = (path: string): string => {
|
|
|
109
115
|
*/
|
|
110
116
|
const BASELINE_HOOK = '__ultimateRegistryLeakBaseline';
|
|
111
117
|
|
|
112
|
-
/**
|
|
118
|
+
/**
|
|
119
|
+
* Appended: the TAG baseline is the file's whole module scope, its body's declarations included.
|
|
120
|
+
* The RESTORE baseline is not — it is taken at `BODY_START_HOOK`, below.
|
|
121
|
+
*/
|
|
113
122
|
const SAMPLE_BASELINE = `\n;globalThis[${JSON.stringify(BASELINE_HOOK)}]?.();\n`;
|
|
114
123
|
|
|
115
124
|
/**
|
|
@@ -117,6 +126,14 @@ const SAMPLE_BASELINE = `\n;globalThis[${JSON.stringify(BASELINE_HOOK)}]?.();\n`
|
|
|
117
126
|
* and before its body (measured on Bun 1.4.4) — the start of the window in which the BODY declares
|
|
118
127
|
* (`rerun-declarations.ts`). On line 1 with no newline, so every line number a stack trace or a
|
|
119
128
|
* coverage report names is the file's own.
|
|
129
|
+
*
|
|
130
|
+
* It is also where the RESTORE snapshot is taken, and why there rather than after the body: the
|
|
131
|
+
* imports are the file's environment — a cached module never declares again, so what it declared
|
|
132
|
+
* has to outlive the file — but a `.test.ts` body is imported by no other file, so nothing it
|
|
133
|
+
* declared is anyone's cache hit. Sampled after the body (until 2026-11), every test file's
|
|
134
|
+
* module-scope `definePermissions()` / `defineRoles()` was folded into what each later file on the
|
|
135
|
+
* worker inherited: strict permission checking switched on for files that declared nothing, and
|
|
136
|
+
* `X_ROLE_REDEFINED` in the next file that defined the same role its own way.
|
|
120
137
|
*/
|
|
121
138
|
const BODY_START_HOOK = '__ultimateBodyStart';
|
|
122
139
|
const SAMPLE_BODY_START = `;globalThis[${JSON.stringify(BODY_START_HOOK)}]?.();`;
|
|
@@ -146,8 +163,10 @@ export function installRegistryLeakGuard(): void {
|
|
|
146
163
|
let current:
|
|
147
164
|
| {
|
|
148
165
|
readonly file: string;
|
|
149
|
-
|
|
166
|
+
/** Unset until the body ends: a body that threw is restored, never judged for tags. */
|
|
167
|
+
before: RegistrySample | undefined;
|
|
150
168
|
readonly snapshot: ProcessRegistrySnapshot;
|
|
169
|
+
readonly admins: ReturnType<typeof captureAdminMounts>;
|
|
151
170
|
}
|
|
152
171
|
| undefined;
|
|
153
172
|
const leaks: RegistryLeak[] = [];
|
|
@@ -157,14 +176,30 @@ export function installRegistryLeakGuard(): void {
|
|
|
157
176
|
const pristineLocales = JSON.stringify(captureProcessRegistries().locales);
|
|
158
177
|
const inApp = isAppRoot();
|
|
159
178
|
const reruns = rerunDeclarations(frameworkDeclarationRegistries);
|
|
179
|
+
// The preload's own declarations are every file's: no test file's graph reaches the preload.
|
|
180
|
+
const atPreload = captureProcessRegistries();
|
|
181
|
+
const preloadNames = {
|
|
182
|
+
permissions: new Set(atPreload.permissions),
|
|
183
|
+
roles: new Set(Object.keys(atPreload.roles)),
|
|
184
|
+
};
|
|
185
|
+
// What the last boundary put back: a name live at a body's start and absent here was declared
|
|
186
|
+
// by a module THIS file's load evaluated for the first time — its own, whatever the graph says.
|
|
187
|
+
let lastBoundary = atPreload;
|
|
188
|
+
const preloadStores = captureDriverStores();
|
|
189
|
+
const graphOf = importGraphReader();
|
|
190
|
+
let graph: ImportGraph | undefined;
|
|
160
191
|
|
|
161
192
|
const close = (): void => {
|
|
162
193
|
if (current === undefined) return;
|
|
163
|
-
const leak =
|
|
194
|
+
const leak =
|
|
195
|
+
current.before === undefined
|
|
196
|
+
? undefined
|
|
197
|
+
: leakBetween(current.file, current.before, sampleRegistries());
|
|
164
198
|
if (leak !== undefined) leaks.push(leak);
|
|
165
199
|
// The repair, at the only point it is safe: the file is over and the next one has not
|
|
166
200
|
// evaluated yet, so what goes back is exactly what that file inherited — module-scope
|
|
167
|
-
// declarations included, which is the half a plain `resetX()` in a `beforeEach` destroys
|
|
201
|
+
// declarations included, which is the half a plain `resetX()` in a `beforeEach` destroys —
|
|
202
|
+
// and the file's own BODY excluded (`BODY_START_HOOK`).
|
|
168
203
|
//
|
|
169
204
|
// In an APP, declarations are put back as a UNION with what the process holds now (22.7,
|
|
170
205
|
// shared worker): an app module a test imported lazily declared its permissions and roles once,
|
|
@@ -189,23 +224,70 @@ export function installRegistryLeakGuard(): void {
|
|
|
189
224
|
...merged,
|
|
190
225
|
locales: declaredLazily ? live.locales : current.snapshot.locales,
|
|
191
226
|
tasks: current.snapshot.tasks,
|
|
227
|
+
jobs: current.snapshot.jobs,
|
|
192
228
|
};
|
|
193
229
|
restoreProcessRegistries(restored);
|
|
230
|
+
// To the PRELOAD's notes, never the body's start: a store is noted as its driver is built,
|
|
231
|
+
// and a fixture module that builds one at import noted it for every later file on the worker —
|
|
232
|
+
// whose drift step then read its fixture app as "a store that owns its own schema".
|
|
233
|
+
restoreDriverStores(preloadStores);
|
|
234
|
+
restoreAdminMounts(current.admins);
|
|
194
235
|
accumulated = mergeSnapshots(accumulated, restored);
|
|
236
|
+
lastBoundary = restored;
|
|
195
237
|
current = undefined;
|
|
196
238
|
};
|
|
197
239
|
|
|
198
|
-
//
|
|
199
|
-
//
|
|
200
|
-
//
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
240
|
+
// The framework repository's files, on a shared worker, start from THEIR graph's policy
|
|
241
|
+
// declarations (`registry-environment.ts`), put in place before the body runs. An app keeps the
|
|
242
|
+
// union: its tests reach app modules through `loadApp()`, which no static graph shows.
|
|
243
|
+
const narrowed = (
|
|
244
|
+
live: ProcessRegistrySnapshot,
|
|
245
|
+
inherited: ProcessRegistrySnapshot,
|
|
246
|
+
): ProcessRegistrySnapshot => {
|
|
247
|
+
if (inApp || graph === undefined) return inherited;
|
|
248
|
+
const fresh = (names: readonly string[], before: readonly string[]): Set<string> =>
|
|
249
|
+
new Set(names.filter((name) => !before.includes(name)));
|
|
250
|
+
const kept = {
|
|
251
|
+
permissions: new Set([
|
|
252
|
+
...preloadNames.permissions,
|
|
253
|
+
...fresh(live.permissions, lastBoundary.permissions),
|
|
254
|
+
]),
|
|
255
|
+
roles: new Set([
|
|
256
|
+
...preloadNames.roles,
|
|
257
|
+
...fresh(Object.keys(live.roles), Object.keys(lastBoundary.roles)),
|
|
258
|
+
]),
|
|
259
|
+
};
|
|
260
|
+
// The locale config likewise: an earlier file's import that narrowed it (an app's
|
|
261
|
+
// `defineCatalogs()`) is no environment of this one — unless THIS load moved it.
|
|
262
|
+
const movedNow = JSON.stringify(live.locales) !== JSON.stringify(lastBoundary.locales);
|
|
263
|
+
const locales = movedNow ? live.locales : atPreload.locales;
|
|
264
|
+
const own = { ...inherited, ...ownEnvironment(inherited, graph, kept), locales };
|
|
265
|
+
restorePolicyRegistries(own);
|
|
266
|
+
configureLocales(locales);
|
|
267
|
+
return own;
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
// Both called from the file's own source, once per test file. At the body's START everything
|
|
271
|
+
// the file's IMPORT graph registered is its environment, and is what the boundary restores to.
|
|
272
|
+
// At the body's END everything the module scope registered is the TAG baseline — importing an
|
|
273
|
+
// app module is how an app declares its tags — and everything after it is the file's to undo.
|
|
274
|
+
hookHost[BODY_START_HOOK] = () => {
|
|
275
|
+
reruns.bodyStart();
|
|
204
276
|
if (pending === undefined) return;
|
|
205
|
-
|
|
206
|
-
|
|
277
|
+
const live = captureProcessRegistries();
|
|
278
|
+
accumulated = mergeSnapshots(accumulated, live);
|
|
279
|
+
current = {
|
|
280
|
+
file: pending,
|
|
281
|
+
before: undefined,
|
|
282
|
+
snapshot: narrowed(live, accumulated),
|
|
283
|
+
admins: captureAdminMounts(),
|
|
284
|
+
};
|
|
207
285
|
pending = undefined;
|
|
208
286
|
};
|
|
287
|
+
hookHost[BASELINE_HOOK] = () => {
|
|
288
|
+
reruns.bodyEnd();
|
|
289
|
+
if (current !== undefined && current.before === undefined) current.before = sampleRegistries();
|
|
290
|
+
};
|
|
209
291
|
|
|
210
292
|
// The only signal Bun gives a preload for "a new test file starts": its hooks carry no file. A
|
|
211
293
|
// load handler MUST answer with contents — one that answers `undefined` makes Bun load nothing
|
|
@@ -225,6 +307,8 @@ export function installRegistryLeakGuard(): void {
|
|
|
225
307
|
runFileBoundary();
|
|
226
308
|
close();
|
|
227
309
|
pending = repoRelative(args.path);
|
|
310
|
+
// Read before the file evaluates — a body-start hook is synchronous and this is not.
|
|
311
|
+
graph = inApp ? undefined : await graphOf(args.path);
|
|
228
312
|
// `loading` closes the previous file's window first (`fileEnd`).
|
|
229
313
|
reruns.loading(args.path);
|
|
230
314
|
return {
|
package/src/registry-snapshot.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// module declares at MODULE scope evaluates once per `bun test` process — a neighbour's clear is
|
|
4
4
|
// permanent and there is no second evaluation left to redo it.
|
|
5
5
|
//
|
|
6
|
-
//
|
|
6
|
+
// SEVEN registries, out of roughly nine that publish a `clear*`/`reset*`. The missing ones and what
|
|
7
7
|
// each still needs are tabulated in `registry-leak-guard.ts` beside `RegistrySample` — every one of
|
|
8
8
|
// them needs a RESTORE in its owning package first, the way `restorePermissions` / `restoreRoles`
|
|
9
9
|
// were added to `@ultimat3/policy` for the two rows below.
|
|
@@ -25,8 +25,8 @@ import {
|
|
|
25
25
|
registeredLocales,
|
|
26
26
|
resetCatalogs,
|
|
27
27
|
} from '@ultimat3/i18n';
|
|
28
|
-
import type { TaskHandle } from '@ultimat3/jobs';
|
|
29
|
-
import { registeredTasks, restoreTasks } from '@ultimat3/jobs';
|
|
28
|
+
import type { AnyJobHandle, TaskHandle } from '@ultimat3/jobs';
|
|
29
|
+
import { registeredJobs, registeredTasks, restoreJobs, restoreTasks } from '@ultimat3/jobs';
|
|
30
30
|
import type { RoleMap } from '@ultimat3/policy';
|
|
31
31
|
import {
|
|
32
32
|
knownPermissions,
|
|
@@ -57,6 +57,13 @@ export interface ProcessRegistrySnapshot {
|
|
|
57
57
|
* fired in every later file's `appManifest` round — 14 framework failures, measured.
|
|
58
58
|
*/
|
|
59
59
|
readonly tasks: readonly TaskHandle[];
|
|
60
|
+
/**
|
|
61
|
+
* Jobs, for the tasks' reason read the other way: `job()` runs at module scope (`sendMailJob`),
|
|
62
|
+
* and `job.test.ts` `resetJobs()` in every `beforeEach` — so on a shared worker every later file
|
|
63
|
+
* lost the jobs its cached imports had declared, and a fixture app with no module of its own
|
|
64
|
+
* read as X_APP_EMPTY (`@ultimat3/cli`'s `loadApp` counts the process's registries).
|
|
65
|
+
*/
|
|
66
|
+
readonly jobs: readonly AnyJobHandle[];
|
|
60
67
|
/** `defineCatalogs()` calls so far — see `@ultimat3/i18n`'s `catalogDeclarationCount`. */
|
|
61
68
|
readonly catalogDeclarations: number;
|
|
62
69
|
/**
|
|
@@ -77,6 +84,7 @@ export function captureProcessRegistries(): ProcessRegistrySnapshot {
|
|
|
77
84
|
roles: roleDefinitions(),
|
|
78
85
|
roleSites: roleDeclarationSites(),
|
|
79
86
|
tasks: registeredTasks(),
|
|
87
|
+
jobs: registeredJobs(),
|
|
80
88
|
catalogDeclarations: catalogDeclarationCount(),
|
|
81
89
|
measurementActor: declaredMeasurementActor(),
|
|
82
90
|
};
|
|
@@ -92,13 +100,24 @@ export function restoreProcessRegistries(snapshot: ProcessRegistrySnapshot): voi
|
|
|
92
100
|
// a partial call can never widen `supported` back.
|
|
93
101
|
configureLocales(snapshot.locales);
|
|
94
102
|
restoreCatalogs(snapshot.catalogs);
|
|
95
|
-
|
|
96
|
-
restoreRoles(snapshot.roles, snapshot.roleSites);
|
|
103
|
+
restorePolicyRegistries(snapshot);
|
|
97
104
|
restoreTasks(snapshot.tasks);
|
|
105
|
+
restoreJobs(snapshot.jobs);
|
|
98
106
|
if (snapshot.measurementActor === undefined) resetMeasurementActor();
|
|
99
107
|
else defineMeasurementActor(snapshot.measurementActor);
|
|
100
108
|
}
|
|
101
109
|
|
|
110
|
+
/** The permission set and the role map alone, each with its declaration sites. */
|
|
111
|
+
export function restorePolicyRegistries(
|
|
112
|
+
snapshot: Pick<
|
|
113
|
+
ProcessRegistrySnapshot,
|
|
114
|
+
'permissions' | 'permissionSites' | 'roles' | 'roleSites'
|
|
115
|
+
>,
|
|
116
|
+
): void {
|
|
117
|
+
restorePermissions(snapshot.permissions, snapshot.permissionSites);
|
|
118
|
+
restoreRoles(snapshot.roles, snapshot.roleSites);
|
|
119
|
+
}
|
|
120
|
+
|
|
102
121
|
/**
|
|
103
122
|
* Repair a clear; never undo a registration. The catalogs are the one registry here restored by
|
|
104
123
|
* MERGE rather than by replacement, and the module cache is why.
|
|
@@ -154,6 +173,8 @@ export function mergeSnapshots(
|
|
|
154
173
|
}
|
|
155
174
|
const tasks = new Map(older.tasks.map((handle) => [handle.name, handle] as const));
|
|
156
175
|
for (const handle of newer.tasks) tasks.set(handle.name, handle);
|
|
176
|
+
const jobs = new Map(older.jobs.map((handle) => [handle.name, handle] as const));
|
|
177
|
+
for (const handle of newer.jobs) jobs.set(handle.name, handle);
|
|
157
178
|
return {
|
|
158
179
|
locales: newer.locales,
|
|
159
180
|
catalogs: [...catalogs],
|
|
@@ -162,6 +183,7 @@ export function mergeSnapshots(
|
|
|
162
183
|
roles: { ...older.roles, ...newer.roles },
|
|
163
184
|
roleSites: { ...older.roleSites, ...newer.roleSites },
|
|
164
185
|
tasks: [...tasks.values()],
|
|
186
|
+
jobs: [...jobs.values()],
|
|
165
187
|
catalogDeclarations: Math.max(older.catalogDeclarations, newer.catalogDeclarations),
|
|
166
188
|
// Last declaration wins, as `defineMeasurementActor` itself has it; "none" never erases one.
|
|
167
189
|
measurementActor: newer.measurementActor ?? older.measurementActor,
|
package/src/sealed-network.ts
CHANGED
|
@@ -91,6 +91,33 @@ const isThisMachine = (hostname: string): boolean => {
|
|
|
91
91
|
return kind === 'loopback' || kind === 'unspecified';
|
|
92
92
|
};
|
|
93
93
|
|
|
94
|
+
/**
|
|
95
|
+
* The proxy a `fetch` init names (`string`, `URL` or `{ url }`, Bun's three forms), credentials
|
|
96
|
+
* stripped, or `undefined`: with one, the bytes leave this process at the PROXY, whatever the
|
|
97
|
+
* target says. An unparseable one is left to the real `fetch`, which refuses it itself.
|
|
98
|
+
*/
|
|
99
|
+
const proxyOf = (init: RequestInit | undefined): URL | undefined => {
|
|
100
|
+
const raw: unknown = init === undefined ? undefined : Reflect.get(init, 'proxy');
|
|
101
|
+
const value =
|
|
102
|
+
typeof raw === 'object' && raw !== null && !(raw instanceof URL)
|
|
103
|
+
? Reflect.get(raw, 'url')
|
|
104
|
+
: raw;
|
|
105
|
+
if (typeof value !== 'string' && !(value instanceof URL)) return undefined;
|
|
106
|
+
let url: URL;
|
|
107
|
+
try {
|
|
108
|
+
url = new URL(value);
|
|
109
|
+
} catch {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
url.username = '';
|
|
113
|
+
url.password = '';
|
|
114
|
+
return url;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
/** A proxy on this machine (or one this test allowed) is no egress; any other is a remote dial. */
|
|
118
|
+
const proxyPasses = (proxy: URL): boolean =>
|
|
119
|
+
isThisMachine(proxy.hostname) || isSelfOrigin(proxy.href) || state.allowed.has(proxy.host);
|
|
120
|
+
|
|
94
121
|
/** The socket dials' gate: the same allow-list, offline state and record as `fetch`. No mocks — a
|
|
95
122
|
* socket test injects its transport (`connect`, `client`), it does not intercept the dial. */
|
|
96
123
|
const socketRefusal = (url: string, method: string): Error | undefined => {
|
|
@@ -189,6 +216,18 @@ export function sealNetwork(): void {
|
|
|
189
216
|
const passes = isSelfOrigin(url) || (host !== undefined && state.allowed.has(host));
|
|
190
217
|
const allowed = [...state.allowed];
|
|
191
218
|
const original = state.original;
|
|
219
|
+
// Judged by the PROXY too: an allowed target reached through a remote proxy is a dial to the
|
|
220
|
+
// proxy. A socket dial, so the fix names a loopback listener as the way out.
|
|
221
|
+
const proxy = proxyOf(init);
|
|
222
|
+
if (passes && proxy !== undefined && !proxyPasses(proxy)) {
|
|
223
|
+
await logBody(probe);
|
|
224
|
+
throw new NetworkSealedError({
|
|
225
|
+
url: proxy.origin,
|
|
226
|
+
method: url.startsWith('https:') ? 'CONNECT' : method,
|
|
227
|
+
allowed,
|
|
228
|
+
transport: 'socket',
|
|
229
|
+
});
|
|
230
|
+
}
|
|
192
231
|
if (passes) {
|
|
193
232
|
if (original === undefined) throw new NetworkRaceError();
|
|
194
233
|
// `(input, init)` as handed: `tls`, `unix` and `proxy` are Bun's own and no Request holds them.
|
|
@@ -194,7 +194,6 @@ export const STORAGE_STREAM_CHECKS: readonly StorageCheck[] = [
|
|
|
194
194
|
{ checksum: 'abc' },
|
|
195
195
|
{ legalHold: true },
|
|
196
196
|
{ retention: { mode: 'GOVERNANCE', retainUntil: new Date(0) } },
|
|
197
|
-
{ serverSideEncryption: { algorithm: 'AES256' } },
|
|
198
197
|
]) {
|
|
199
198
|
const upFront = await refused({ maxBytes: 64, ...extra });
|
|
200
199
|
expect([upFront.code, names(upFront, 'fix', 'disk.put(')]).toEqual(['X_INVARIANT', true]);
|
package/src/tenant-proof.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// The tenant proof, one primitive at a time: tenant B calls with A's ids before A's own
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// The tenant proof, one primitive at a time: tenant B calls with A's ids before and after A's own
|
|
2
|
+
// call; crossed if anything of A's (a canary, an id B was not handed) comes back or one of A's rows
|
|
3
|
+
// changes. B, A, B: a deleting action would leave B nothing, the second B catches A's cache fill. A
|
|
4
|
+
// read touching only `entity({ global })` entities has no row of A's: `global`, not unproven.
|
|
5
5
|
|
|
6
6
|
import type { Actor } from '@ultimat3/core';
|
|
7
7
|
import type { Policy } from '@ultimat3/policy';
|
|
@@ -85,12 +85,76 @@ export interface TenantAttack {
|
|
|
85
85
|
* so the write half's premise, B choosing A's row, cannot hold: skipped (`tenantlessReason`).
|
|
86
86
|
*/
|
|
87
87
|
readonly tenantless: boolean;
|
|
88
|
+
/** Entity name → its `entity({ global })` reason, from `globalEntities`. Absent: none declared. */
|
|
89
|
+
readonly globals?: ReadonlyMap<string, string> | undefined;
|
|
88
90
|
attack(leg: TenantLeg): Promise<LegAnswer>;
|
|
89
|
-
/**
|
|
90
|
-
|
|
91
|
+
/**
|
|
92
|
+
* A's positive control: today's exercise of the primitive, and what A's last answer was. `reads`
|
|
93
|
+
* is every entity its calls' statements were attributed to (`readsOf`); `null`, one was not.
|
|
94
|
+
*/
|
|
95
|
+
control(): Promise<ControlAnswer>;
|
|
91
96
|
snapshot(rows: readonly SeedRow[]): Promise<readonly (string | null)[]>;
|
|
92
97
|
}
|
|
93
98
|
|
|
99
|
+
/** What A's control answered, and the entities its statements touched. */
|
|
100
|
+
export interface ControlAnswer {
|
|
101
|
+
readonly record: ExerciseRecord;
|
|
102
|
+
readonly output: unknown;
|
|
103
|
+
readonly reads?: readonly string[] | null | undefined;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
type Described = { readonly $name: string; $describe(): { readonly global?: string | undefined } };
|
|
107
|
+
|
|
108
|
+
/** One map per pass's entity list: the proof runs once per primitive, the list never changes. */
|
|
109
|
+
const globalsByList = new WeakMap<readonly Described[], ReadonlyMap<string, string>>();
|
|
110
|
+
|
|
111
|
+
/** Each entity's `entity({ global })` reason, by name; an entity without one is not in it. */
|
|
112
|
+
export function globalEntities(entities: readonly Described[]): ReadonlyMap<string, string> {
|
|
113
|
+
const known = globalsByList.get(entities);
|
|
114
|
+
if (known !== undefined) return known;
|
|
115
|
+
const globals = new Map<string, string>();
|
|
116
|
+
for (const entity of entities) {
|
|
117
|
+
const reason = entity.$describe().global;
|
|
118
|
+
if (reason !== undefined) globals.set(entity.$name, reason);
|
|
119
|
+
}
|
|
120
|
+
globalsByList.set(entities, globals);
|
|
121
|
+
return globals;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Every entity a primitive's calls touched, first seen first; `null` when any call sent a statement
|
|
126
|
+
* no repository attributed — hand-written SQL reads tables nobody can name, so nothing is global.
|
|
127
|
+
*/
|
|
128
|
+
export function readsOf(
|
|
129
|
+
calls: readonly { readonly reads?: readonly string[] | null | undefined }[],
|
|
130
|
+
): readonly string[] | null {
|
|
131
|
+
const seen = new Set<string>();
|
|
132
|
+
for (const call of calls) {
|
|
133
|
+
if (call.reads === null || call.reads === undefined) return null;
|
|
134
|
+
for (const entity of call.reads) seen.add(entity);
|
|
135
|
+
}
|
|
136
|
+
return [...seen];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Why a read is `global`, or `undefined`: it touched at least one entity and every one is declared
|
|
141
|
+
* global. One tenant entity — a policy's membership lookup included — or an unknown read is not.
|
|
142
|
+
*/
|
|
143
|
+
export function globalReason(
|
|
144
|
+
reads: readonly string[] | null | undefined,
|
|
145
|
+
globals: ReadonlyMap<string, string> | undefined,
|
|
146
|
+
): string | undefined {
|
|
147
|
+
if (reads === null || reads === undefined || reads.length === 0 || globals === undefined) {
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
const reasons = reads.map((entity) => {
|
|
151
|
+
const reason = globals.get(entity);
|
|
152
|
+
return reason === undefined ? undefined : `${entity}: ${reason}`;
|
|
153
|
+
});
|
|
154
|
+
if (reasons.some((reason) => reason === undefined)) return undefined;
|
|
155
|
+
return `every entity this read touched is declared global (${reasons.join('; ')}), so no row of A's can come back: the legs still searched, write half kept`;
|
|
156
|
+
}
|
|
157
|
+
|
|
94
158
|
/** A's rows whose digest moved across one B leg — changed, or gone. */
|
|
95
159
|
export function crossedWrites(
|
|
96
160
|
leg: TenantLeg,
|
|
@@ -153,7 +217,7 @@ export function tenantlessReason(
|
|
|
153
217
|
|
|
154
218
|
const verdictOf = (
|
|
155
219
|
plan: TenantAttack,
|
|
156
|
-
control:
|
|
220
|
+
control: ControlAnswer,
|
|
157
221
|
findings: readonly TenantFinding[],
|
|
158
222
|
skipped: readonly string[],
|
|
159
223
|
): TenantProof => {
|
|
@@ -167,6 +231,8 @@ const verdictOf = (
|
|
|
167
231
|
}
|
|
168
232
|
if (plan.public !== undefined) return { verdict: 'public', reason: plan.public };
|
|
169
233
|
if (skipped.length > 0) return { verdict: 'public', reason: skipped.join('; ') };
|
|
234
|
+
const global = plan.read ? globalReason(control.reads, plan.globals) : undefined;
|
|
235
|
+
if (global !== undefined) return { verdict: 'global', reason: global };
|
|
170
236
|
// Every mark of A's, handed ones included: A was handed its own ids, and reading them is the point.
|
|
171
237
|
if (plan.read && findTaint(control.output, 'output', plan.taint.marks).length === 0) {
|
|
172
238
|
return {
|