@ultimat3/testing 31.22.3 → 31.24.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/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.22.3",
3
+ "version": "31.24.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.22.3",
51
- "@ultimat3/ai": "31.22.3",
52
- "@ultimat3/auth": "31.22.3",
53
- "@ultimat3/cache": "31.22.3",
54
- "@ultimat3/core": "31.22.3",
55
- "@ultimat3/db": "31.22.3",
56
- "@ultimat3/entity": "31.22.3",
57
- "@ultimat3/http": "31.22.3",
58
- "@ultimat3/i18n": "31.22.3",
59
- "@ultimat3/jobs": "31.22.3",
60
- "@ultimat3/mail": "31.22.3",
61
- "@ultimat3/notify": "31.22.3",
62
- "@ultimat3/policy": "31.22.3",
63
- "@ultimat3/pwa": "31.22.3",
64
- "@ultimat3/query": "31.22.3",
65
- "@ultimat3/realtime": "31.22.3",
66
- "@ultimat3/render": "31.22.3",
67
- "@ultimat3/schema": "31.22.3",
68
- "@ultimat3/scraping": "31.22.3",
69
- "@ultimat3/seo": "31.22.3",
70
- "@ultimat3/time": "31.22.3"
50
+ "@ultimat3/action": "31.24.0",
51
+ "@ultimat3/ai": "31.24.0",
52
+ "@ultimat3/auth": "31.24.0",
53
+ "@ultimat3/cache": "31.24.0",
54
+ "@ultimat3/core": "31.24.0",
55
+ "@ultimat3/db": "31.24.0",
56
+ "@ultimat3/entity": "31.24.0",
57
+ "@ultimat3/http": "31.24.0",
58
+ "@ultimat3/i18n": "31.24.0",
59
+ "@ultimat3/jobs": "31.24.0",
60
+ "@ultimat3/mail": "31.24.0",
61
+ "@ultimat3/notify": "31.24.0",
62
+ "@ultimat3/policy": "31.24.0",
63
+ "@ultimat3/pwa": "31.24.0",
64
+ "@ultimat3/query": "31.24.0",
65
+ "@ultimat3/realtime": "31.24.0",
66
+ "@ultimat3/render": "31.24.0",
67
+ "@ultimat3/schema": "31.24.0",
68
+ "@ultimat3/scraping": "31.24.0",
69
+ "@ultimat3/seo": "31.24.0",
70
+ "@ultimat3/time": "31.24.0"
71
71
  }
72
72
  }
@@ -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
+ ];
@@ -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
- return { statements, effects, refusedHosts, payloads, shapes: tallies };
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 { proveTenant, publicReason, withoutCrossTenant } from './tenant-proof';
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);
@@ -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]);
@@ -1,7 +1,7 @@
1
- // The tenant proof, one primitive at a time: tenant B calls with A's ids before A's own call and
2
- // again after it, and the call is crossed if anything of A's — a canary, an id B was not handed —
3
- // came back in the output or an effect, or if one of A's rows changed. Order B, A, B: a deleting
4
- // action would leave B nothing to reach, and the second B catches a cache entry A filled.
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
- /** A's positive control: today's exercise of the primitive, and what A's last answer was. */
90
- control(): Promise<{ readonly record: ExerciseRecord; readonly output: unknown }>;
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: { readonly record: ExerciseRecord; readonly output: unknown },
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 {