@ultimat3/testing 30.7.0 → 30.9.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.
@@ -9,7 +9,7 @@ import { mockRoute, routeMatches, routeNamesHost } from './mock-route';
9
9
  import type { LoggedRequest } from './request-log';
10
10
  import { hasStreamBody, headersOf, isOpenEnded, readBody, requestProbe } from './request-log';
11
11
  import type { DnsVerdict } from './sealed-dns';
12
- import { installDnsSeal } from './sealed-dns';
12
+ import { ADDRESS_QUERIES, installDnsSeal } from './sealed-dns';
13
13
  import { installSocketSeal } from './sealed-sockets';
14
14
 
15
15
  export type FetchLike = typeof globalThis.fetch;
@@ -99,25 +99,26 @@ const isAllowedName = (hostname: string): boolean =>
99
99
 
100
100
  /**
101
101
  * The resolver's gate, in `fetch`'s order: offline refuses every name, this machine and an allowed
102
- * host resolve for real, a host a mock answers resolves to `MOCKED_HOST_ADDRESS`, the rest is
103
- * `X_TEST_NETWORK_SEALED` — the code `fetch` would have raised a moment later.
102
+ * host resolve for real, as does a `LOOKUP` of an address literal (no query leaves; a `REVERSE` of
103
+ * one does), a host a mock answers resolves to `MOCKED_HOST_ADDRESS` for an address query only,
104
+ * the rest is `X_TEST_NETWORK_SEALED` — the code `fetch` would have raised a moment later.
104
105
  */
105
- const dnsVerdict = (hostname: string): DnsVerdict => {
106
+ const dnsVerdict = (hostname: string, query: string): DnsVerdict => {
106
107
  const name = hostname.toLowerCase().replace(/^\[|\]$/g, '');
107
108
  const url = `dns://${name}`;
109
+ const method = query === 'LOOKUP' || query === 'REVERSE' ? query : `RESOLVE ${query}`;
108
110
  if (state.network !== 'online') {
109
- return { refused: new NetworkOfflineError({ url, method: 'LOOKUP', mode: state.network }) };
111
+ return { refused: new NetworkOfflineError({ url, method, mode: state.network }) };
110
112
  }
111
- if (isThisMachine(name) || peerAddressClass(name) !== undefined || isAllowedName(name)) {
112
- return { real: true };
113
- }
114
- if (state.mocks.some((route) => routeNamesHost(route, name))) {
113
+ const literal = query === 'LOOKUP' && peerAddressClass(name) !== undefined;
114
+ if (isThisMachine(name) || literal || isAllowedName(name)) return { real: true };
115
+ if (ADDRESS_QUERIES.has(query) && state.mocks.some((route) => routeNamesHost(route, name))) {
115
116
  return { answer: [MOCKED_HOST_ADDRESS] };
116
117
  }
117
118
  const allowed = [...state.allowed];
118
- return {
119
- refused: new NetworkSealedError({ url, method: 'LOOKUP', allowed, transport: 'dns' }),
120
- };
119
+ // A record no mock answers (MX, TXT, a reverse) is lifted by `allowHost` alone: say that first.
120
+ const transport = ADDRESS_QUERIES.has(query) ? 'dns' : 'dns-record';
121
+ return { refused: new NetworkSealedError({ url, method, allowed, transport }) };
121
122
  };
122
123
 
123
124
  /** Replace global fetch, `WebSocket`, `Bun.connect` and the resolvers. Idempotent: sealing twice
@@ -0,0 +1,63 @@
1
+ // The `node:*` half of the socket seal: `net`, `tls`, `http(s)` and `http2` all dial through
2
+ // `net.Socket#connect` (measured; none reaches `Bun.connect` or `fetch`), so that one prototype is
3
+ // the root. WHETHER a dial may leave is `sealed-network.ts`'s socket gate, handed in.
4
+
5
+ // why: `net.Socket` is the class every node:* client socket is, and the only place they all meet.
6
+ import net from 'node:net';
7
+ import type { SocketGate } from './sealed-sockets';
8
+
9
+ /** A dial target as a URL, so the gate parses one shape. IPv6 literals need their brackets. */
10
+ export const dialUrl = (hostname: string, port: unknown, scheme: 'tcp' | 'udp' = 'tcp'): string => {
11
+ const host = hostname.includes(':') && !hostname.startsWith('[') ? `[${hostname}]` : hostname;
12
+ return `${scheme}://${host}:${typeof port === 'number' || typeof port === 'string' ? port : 0}`;
13
+ };
14
+
15
+ interface Target {
16
+ readonly host?: unknown;
17
+ readonly hostname?: unknown;
18
+ readonly port?: unknown;
19
+ readonly path?: unknown;
20
+ }
21
+
22
+ const isRecord = (value: unknown): value is Target => typeof value === 'object' && value !== null;
23
+
24
+ /**
25
+ * The TCP dial `connect`'s arguments name, or `undefined` for a unix socket — a path on this
26
+ * machine, never egress. Node's three shapes: `[options, cb]` (what `net.connect`, `tls`, `http`
27
+ * hand it), `(options, cb)` and `(port, host?, cb)`. No host is Node's `localhost`.
28
+ */
29
+ const tcpTarget = (args: readonly unknown[]): string | undefined => {
30
+ const first = Array.isArray(args[0]) ? args[0][0] : args[0];
31
+ if (isRecord(first)) {
32
+ const host = first.host ?? first.hostname;
33
+ if (typeof host !== 'string')
34
+ return typeof first.path === 'string' ? undefined : 'tcp://localhost:0';
35
+ return dialUrl(host, first.port);
36
+ }
37
+ if (typeof first === 'string' && !/^\d+$/.test(first)) return undefined;
38
+ return dialUrl(typeof args[1] === 'string' ? args[1] : 'localhost', first);
39
+ };
40
+
41
+ type Connect = (this: net.Socket, ...args: unknown[]) => net.Socket;
42
+
43
+ /**
44
+ * Patch `net.Socket#connect` and return the uninstaller. A refusal is a dial in flight that fails:
45
+ * `connecting` as the real one sets it, so `http`'s first write queues instead of failing
46
+ * `ERR_SOCKET_CLOSED` (measured), then the `error` event a macrotask later, once every client has
47
+ * its listener on. A throw from inside `http.get` would bypass every `error` handler the app wrote.
48
+ */
49
+ export function installNodeSocketSeal(gate: SocketGate): () => void {
50
+ const original = Reflect.get(net.Socket.prototype, 'connect') as Connect;
51
+ const sealed: Connect = function sealedConnect(this: net.Socket, ...args) {
52
+ const target = tcpTarget(args);
53
+ const refusal = target === undefined ? undefined : gate(target, 'CONNECT');
54
+ if (refusal === undefined) return Reflect.apply(original, this, args);
55
+ Reflect.set(this, 'connecting', true);
56
+ setImmediate(() => this.destroy(refusal));
57
+ return this;
58
+ };
59
+ Reflect.set(net.Socket.prototype, 'connect', sealed);
60
+ return () => {
61
+ Reflect.set(net.Socket.prototype, 'connect', original);
62
+ };
63
+ }
@@ -1,9 +1,16 @@
1
1
  // The socket half of the sealed network: `WebSocket` and `Bun.connect`, the two dials that are not
2
2
  // `fetch`. Only the patching lives here; WHETHER a dial may leave is `sealed-network.ts`'s one
3
3
  // gate, handed in, so fetch and sockets cannot disagree about the allow-list or the offline state.
4
+ // `node:*` TCP is `sealed-node-sockets.ts`, UDP `sealed-udp.ts`: installed and undone from here.
5
+
6
+ import { dialUrl, installNodeSocketSeal } from './sealed-node-sockets';
7
+ import { installUdpSeal } from './sealed-udp';
4
8
 
5
9
  /** A dial's verdict: the error to raise, or `undefined` to let it through to the real one. */
6
- export type SocketGate = (url: string, method: 'WEBSOCKET' | 'CONNECT') => Error | undefined;
10
+ export type SocketGate = (
11
+ url: string,
12
+ method: 'WEBSOCKET' | 'CONNECT' | 'SEND',
13
+ ) => Error | undefined;
7
14
 
8
15
  /** `Bun.connect`'s two option shapes, read structurally: TCP names a host, a unix socket a path. */
9
16
  interface ConnectOptions {
@@ -14,12 +21,6 @@ interface ConnectOptions {
14
21
 
15
22
  type Connect = (options: ConnectOptions) => Promise<unknown>;
16
23
 
17
- /** A dial target as a URL, so the gate parses one shape. IPv6 literals need their brackets. */
18
- const tcpUrl = (hostname: string, port: number | undefined): string => {
19
- const host = hostname.includes(':') && !hostname.startsWith('[') ? `[${hostname}]` : hostname;
20
- return `tcp://${host}:${port ?? 0}`;
21
- };
22
-
23
24
  /**
24
25
  * Patch both dials and return the uninstaller, which puts back exactly what was there — the same
25
26
  * originals, so `globalThis.WebSocket === original` holds again. Assigned through `Reflect.set`:
@@ -44,7 +45,7 @@ export function installSocketSeal(gate: SocketGate): () => void {
44
45
  // a path on this machine and is never egress.
45
46
  const sealedConnect: Connect = (options) => {
46
47
  if (options.unix === undefined && options.hostname !== undefined) {
47
- const refusal = gate(tcpUrl(options.hostname, options.port), 'CONNECT');
48
+ const refusal = gate(dialUrl(options.hostname, options.port), 'CONNECT');
48
49
  if (refusal !== undefined) return Promise.reject(refusal);
49
50
  }
50
51
  return originalConnect(options);
@@ -52,8 +53,12 @@ export function installSocketSeal(gate: SocketGate): () => void {
52
53
 
53
54
  Reflect.set(globalThis, 'WebSocket', SealedWebSocket);
54
55
  Reflect.set(Bun, 'connect', sealedConnect);
56
+ const restoreNode = installNodeSocketSeal(gate);
57
+ const restoreUdp = installUdpSeal(gate);
55
58
  return () => {
56
59
  Reflect.set(globalThis, 'WebSocket', OriginalWebSocket);
57
60
  Reflect.set(Bun, 'connect', originalConnect);
61
+ restoreNode();
62
+ restoreUdp();
58
63
  };
59
64
  }
@@ -0,0 +1,118 @@
1
+ // The UDP half of the socket seal: `Bun.udpSocket`, which `node:dgram` sends through too (measured).
2
+ // A connected socket is gated at `connect` and every send after; an unconnected one per datagram.
3
+ // A refusal surfaces as Bun's own UDP failures do: `send` throws, a `connect` rejects.
4
+
5
+ // why: Bun's `dgram.Socket#send` drops a throw when no callback is given (measured); patched below.
6
+ import dgram from 'node:dgram';
7
+ import { dialUrl } from './sealed-node-sockets';
8
+ import type { SocketGate } from './sealed-sockets';
9
+
10
+ type UdpSocketFactory = (options: unknown) => Promise<unknown>;
11
+ type Method = (...args: unknown[]) => unknown;
12
+
13
+ interface ConnectTarget {
14
+ readonly hostname?: unknown;
15
+ readonly port?: unknown;
16
+ }
17
+
18
+ /** The refusals this seal raised: the only errors the `dgram` patch re-emits. */
19
+ const refusals = new WeakSet<Error>();
20
+
21
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
22
+ typeof value === 'object' && value !== null;
23
+
24
+ /** The peer a `connect` option names, as the gate's URL; `undefined` for an unconnected socket. */
25
+ const peerOf = (options: unknown): string | undefined => {
26
+ const connect: unknown = isRecord(options) ? options['connect'] : undefined;
27
+ if (!isRecord(connect)) return undefined;
28
+ const target: ConnectTarget = connect;
29
+ return typeof target.hostname === 'string'
30
+ ? dialUrl(target.hostname, target.port, 'udp')
31
+ : undefined;
32
+ };
33
+
34
+ /**
35
+ * The peer a connected socket sends to, read off the socket at send time: `node:dgram`'s
36
+ * `connect()` re-points the native socket without `Bun.udpSocket` (measured), so a peer remembered
37
+ * from the options would miss it.
38
+ */
39
+ const remoteOf = (socket: object): string | undefined => {
40
+ const remote: unknown = Reflect.get(socket, 'remoteAddress');
41
+ if (!isRecord(remote) || typeof remote['address'] !== 'string') return undefined;
42
+ return dialUrl(remote['address'], remote['port'], 'udp');
43
+ };
44
+
45
+ /**
46
+ * Wrap one socket's two senders. Every datagram of a `sendMany` is judged before any leaves, so a
47
+ * refused batch sends nothing. A connected socket is judged per send: offline may have begun since.
48
+ */
49
+ const sealSends = (socket: object, gate: SocketGate): void => {
50
+ const send = Reflect.get(socket, 'send') as Method;
51
+ const sendMany = Reflect.get(socket, 'sendMany') as Method;
52
+ const judge = (target: string | undefined): void => {
53
+ // No target: an unconnected send without an address, which Bun refuses itself.
54
+ const refusal = target === undefined ? undefined : gate(target, 'SEND');
55
+ if (refusal === undefined) return;
56
+ refusals.add(refusal);
57
+ throw refusal;
58
+ };
59
+ Reflect.set(socket, 'send', (...args: unknown[]): unknown => {
60
+ judge(typeof args[2] === 'string' ? dialUrl(args[2], args[1], 'udp') : remoteOf(socket));
61
+ return Reflect.apply(send, socket, args);
62
+ });
63
+ Reflect.set(socket, 'sendMany', (packets: Iterable<unknown>): unknown => {
64
+ const list = [...packets];
65
+ const remote = remoteOf(socket);
66
+ if (remote !== undefined) judge(remote);
67
+ else {
68
+ for (let at = 0; at + 2 < list.length; at += 3) {
69
+ const address = list[at + 2];
70
+ if (typeof address === 'string') judge(dialUrl(address, list[at + 1], 'udp'));
71
+ }
72
+ }
73
+ return Reflect.apply(sendMany, socket, [list]);
74
+ });
75
+ };
76
+
77
+ /**
78
+ * Bun's `dgram` hands a failed send to the callback and DROPS it without one; Node emits `error`
79
+ * then. Without a callback, a refusal of ours is emitted as Node would, so it fails the test loudly.
80
+ */
81
+ const sealDgramSend = (): (() => void) => {
82
+ const send = Reflect.get(dgram.Socket.prototype, 'send') as Method;
83
+ Reflect.set(
84
+ dgram.Socket.prototype,
85
+ 'send',
86
+ function sealedSend(this: dgram.Socket, ...args: unknown[]) {
87
+ if (typeof args.at(-1) === 'function') return Reflect.apply(send, this, args);
88
+ const reemit = (error: unknown): void => {
89
+ if (error instanceof Error && refusals.has(error)) this.emit('error', error);
90
+ };
91
+ return Reflect.apply(send, this, [...args, reemit]);
92
+ },
93
+ );
94
+ return () => {
95
+ Reflect.set(dgram.Socket.prototype, 'send', send);
96
+ };
97
+ };
98
+
99
+ /** Patch `Bun.udpSocket` and return the uninstaller, which puts back exactly what was there. */
100
+ export function installUdpSeal(gate: SocketGate): () => void {
101
+ const restoreDgram = sealDgramSend();
102
+ const original = Reflect.get(Bun, 'udpSocket') as UdpSocketFactory;
103
+ const sealed: UdpSocketFactory = async (options) => {
104
+ const peer = peerOf(options);
105
+ if (peer !== undefined) {
106
+ const refusal = gate(peer, 'CONNECT');
107
+ if (refusal !== undefined) throw refusal;
108
+ }
109
+ const socket = await original(options);
110
+ if (isRecord(socket)) sealSends(socket, gate);
111
+ return socket;
112
+ };
113
+ Reflect.set(Bun, 'udpSocket', sealed);
114
+ return () => {
115
+ Reflect.set(Bun, 'udpSocket', original);
116
+ restoreDgram();
117
+ };
118
+ }
@@ -23,6 +23,12 @@ export interface SeedGraphOptions {
23
23
  readonly seed?: number;
24
24
  /** By entity name. A column the factory builds takes its value; keys stay the graph's. */
25
25
  readonly factories?: Readonly<Record<string, SeedFactory>>;
26
+ /**
27
+ * A graph already written to the same database. Each table's row positions — the ordinal a
28
+ * generated value is built from, a factory's `index` — continue past its `next`, so a value built
29
+ * from a position (`code: \`c${index}\``) never repeats one of its rows on a unique column.
30
+ */
31
+ readonly beside?: SeedGraph;
26
32
  }
27
33
 
28
34
  export interface SeedRow {
@@ -67,6 +73,11 @@ export interface SeedGraph {
67
73
  readonly updates: readonly SeedUpdate[];
68
74
  /** One per insert, in the same order: `canaries[i]` is `inserts[i]`'s. */
69
75
  readonly canaries: readonly SeedCanary[];
76
+ /**
77
+ * Per table, the row position a graph written `beside` this one starts at: its own `beside`'s
78
+ * plus every row this graph built. Absent on a hand-written graph: positions then start at 0.
79
+ */
80
+ readonly next?: Readonly<Record<string, number>>;
70
81
  }
71
82
 
72
83
  /** Where `insertSeedGraph` writes. One insert per row, in order, then one update per deferred key. */
package/src/seed-graph.ts CHANGED
@@ -137,6 +137,8 @@ export function seedGraph(
137
137
  const scoped = (name: string): boolean => owned.has(name);
138
138
  const fanned = fannedOut(shapes, scoped);
139
139
  for (const factory of Object.values(options.factories ?? {})) factory.reset();
140
+ const besideNext = options.beside?.next ?? {};
141
+ const next: Record<string, number> = { ...besideNext };
140
142
 
141
143
  const placed = new Map<string, Placed[]>();
142
144
  // The same rows by tenant: a pool read per row was a filter of the whole parent table, so a pass
@@ -196,12 +198,17 @@ export function seedGraph(
196
198
  // Read once per table: each `matches(/…/)` an invariant holds a column to, sampled from.
197
199
  const patterns = declaredPatterns(entity);
198
200
  const buckets: readonly (string | null)[] = scoped(name) ? tenants : [null];
199
- let ordinal = 0;
201
+ // Positions continue past the graph written before this one: a reset factory rebuilt that
202
+ // graph's first values, and a unique column refused the second copy.
203
+ const start = besideNext[name] ?? 0;
204
+ for (let skipped = 0; factory !== undefined && skipped < start; skipped += 1) factory.build();
205
+ let ordinal = start;
200
206
  for (const [bucket, tenant] of buckets.entries()) {
201
207
  const size =
202
208
  rootProperty !== undefined ? 1 : fanned.has(name) ? perTable * tenantCount : perTable;
203
209
  for (let index = 0; index < size; index += 1) {
204
210
  ordinal += 1;
211
+ next[name] = ordinal;
205
212
  const canary = stream().replace(/-/g, '').slice(0, 10);
206
213
  const built: Readonly<Record<string, unknown>> =
207
214
  factory === undefined ? {} : { ...factory.build() };
@@ -320,5 +327,5 @@ export function seedGraph(
320
327
  updates.push({ entity: name, tenant, key: keyOf(shape.entity, row), patch });
321
328
  }
322
329
  }
323
- return { seed, tenants, order, inserts, updates, canaries };
330
+ return { seed, tenants, order, inserts, updates, canaries, next };
324
331
  }
@@ -25,6 +25,11 @@ export interface SubjectProofOptions {
25
25
  readonly seed?: number;
26
26
  /** `defineExercise`'s factories: a table only they satisfy is built by them for the proof too. */
27
27
  readonly factories?: Readonly<Record<string, SeedFactory>> | undefined;
28
+ /**
29
+ * The graph already written to this database — the previous subject's `graph`. Row positions
30
+ * continue past it, so a factory value built from the index never repeats one on a unique column.
31
+ */
32
+ readonly beside?: SeedGraph | undefined;
28
33
  }
29
34
 
30
35
  export interface SubjectProofResult {
@@ -32,6 +37,8 @@ export interface SubjectProofResult {
32
37
  /** The person erased, by key; absent when the plan refused before a row was seeded. */
33
38
  readonly key?: string;
34
39
  readonly problems: readonly UltimateError[];
40
+ /** What it wrote: the next proof on the same database is seeded `beside` it. */
41
+ readonly graph?: SeedGraph;
35
42
  }
36
43
 
37
44
  interface Reached {
@@ -111,6 +118,7 @@ export async function subjectProof<I>(
111
118
  seed: finiteOption('subjectProof', 'seed', options.seed ?? 1),
112
119
  tenants: 2,
113
120
  ...(options.factories === undefined ? {} : { factories: options.factories }),
121
+ ...(options.beside === undefined ? {} : { beside: options.beside }),
114
122
  });
115
123
  // The pass's rule: a nullable cycle key the database refuses to set stays null.
116
124
  await insertSeedGraph(graph, deferredMayStayNull(options.writer));
@@ -119,7 +127,9 @@ export async function subjectProof<I>(
119
127
  (i) => i.entity === subject.entity && (i.tenant === tenant || i.tenant === null),
120
128
  );
121
129
  const root = entities.get(subject.entity);
122
- if (person === undefined || root === undefined) return { subject: subject.entity, problems: [] };
130
+ if (person === undefined || root === undefined) {
131
+ return { subject: subject.entity, problems: [], graph };
132
+ }
123
133
  const key = String(person.row[plan.key]);
124
134
  const reached = reachedRows(graph, plan, entities, person.row);
125
135
 
@@ -181,5 +191,5 @@ export async function subjectProof<I>(
181
191
  }
182
192
  }
183
193
  }
184
- return { subject: subject.entity, key, problems: found };
194
+ return { subject: subject.entity, key, problems: found, graph };
185
195
  }
@@ -1,6 +1,6 @@
1
- // The tenant proof, as `x exercise` reports it: one line per finding — primitive, leg, and the path
2
- // of A's canary in B's answer or the table and id of A's changed row — and one coded finding each
3
- // for the gate to fail on. Only paths, tables and seeded ids are printed: never a bound value.
1
+ // The tenant proof, as `x exercise` reports it: one line per leg and code — primitive, leg, and the
2
+ // paths of A's canaries in B's answer or the tables and ids of A's changed rows — and one coded
3
+ // finding each for the gate to fail on. Only paths, tables and seeded ids: never a bound value.
4
4
 
5
5
  import { renderFixShellArg } from '@ultimat3/core';
6
6
  import type { ExerciseRecord, TenantFinding } from './exercise-report';
@@ -16,21 +16,66 @@ export interface TenantProofFinding {
16
16
 
17
17
  const LEG = { before: 'before A ran', after: 'after A ran' } as const;
18
18
 
19
- /** `B with A's ids, before A ran: output.items[0].url` — where, never what. */
20
- const where = (finding: TenantFinding): string =>
19
+ /** Every finding of one leg and one code: one statement's leak, however many fields it carried. */
20
+ interface Group {
21
+ readonly code: TenantFinding['code'];
22
+ readonly leg: TenantFinding['leg'];
23
+ readonly sweep: boolean;
24
+ readonly where: string;
25
+ }
26
+
27
+ /** `output.items[0].url` — where, never what. */
28
+ const whereOne = (finding: TenantFinding): string =>
21
29
  finding.code === 'X_TENANT_LEAK'
22
30
  ? `${finding.path ?? 'output'}`
23
31
  : `${finding.table ?? '?'} row ${finding.id ?? '?'}`;
24
32
 
25
- /** Every finding of every crossed record, one line each: `action readPost · before · output.url`. */
33
+ /**
34
+ * Each distinct place once. Places differing only in a list index — three enqueues carrying the same
35
+ * three fields — collapse to `[*]` with their count; a lone one keeps its index.
36
+ */
37
+ const whereAll = (findings: readonly TenantFinding[]): string => {
38
+ const counts = new Map<string, { readonly first: string; count: number }>();
39
+ for (const finding of findings) {
40
+ const place = whereOne(finding);
41
+ const shape = place.replace(/\[\d+\]/g, '[*]');
42
+ const seen = counts.get(shape);
43
+ if (seen === undefined) counts.set(shape, { first: place, count: 1 });
44
+ else seen.count += 1;
45
+ }
46
+ const entries = [...counts.entries()];
47
+ const each = entries[0]?.[1].count ?? 1;
48
+ if (each > 1 && entries.every(([, { count }]) => count === each)) {
49
+ return `${entries.map(([shape]) => shape).join(', ')} (${each} each)`;
50
+ }
51
+ return entries
52
+ .map(([shape, { first, count }]) => (count === 1 ? first : `${shape} (×${count})`))
53
+ .join(', ');
54
+ };
55
+
56
+ const groupsOf = (findings: readonly TenantFinding[]): readonly Group[] => {
57
+ const byKey = new Map<string, TenantFinding[]>();
58
+ for (const finding of findings) {
59
+ const key = `${finding.leg}\u0000${finding.code}\u0000${finding.sweep === true}`;
60
+ const list = byKey.get(key);
61
+ if (list === undefined) byKey.set(key, [finding]);
62
+ else list.push(finding);
63
+ }
64
+ return [...byKey.values()].map((list) => {
65
+ const head = list[0] as TenantFinding;
66
+ return { code: head.code, leg: head.leg, sweep: head.sweep === true, where: whereAll(list) };
67
+ });
68
+ };
69
+
70
+ const crossedGroups = (record: ExerciseRecord): readonly Group[] =>
71
+ record.tenant?.verdict === 'crossed' ? groupsOf(record.tenant.findings) : [];
72
+
73
+ /** One line per leg and code of every crossed record: `action readPost · before · …`. */
26
74
  export function tenantFindingLines(records: readonly ExerciseRecord[]): readonly string[] {
27
75
  return records.flatMap((record) =>
28
- record.tenant?.verdict === 'crossed'
29
- ? record.tenant.findings.map(
30
- (finding) =>
31
- `${record.kind} ${record.name} · ${finding.leg} · ${finding.code} ${where(finding)}`,
32
- )
33
- : [],
76
+ crossedGroups(record).map(
77
+ (group) => `${record.kind} ${record.name} · ${group.leg} · ${group.code} ${group.where}`,
78
+ ),
34
79
  );
35
80
  }
36
81
 
@@ -38,32 +83,37 @@ export function tenantFindingLines(records: readonly ExerciseRecord[]): readonly
38
83
  * B sends A's own first input, A's ids bound in only where it takes any: `{ occurrenceMs }` carries
39
84
  * none, and B still crosses when a statement it ran names no tenant. Both readings, always.
40
85
  */
41
- const causeOf = (record: ExerciseRecord, finding: TenantFinding): string =>
42
- finding.code === 'X_TENANT_LEAK'
43
- ? `${record.kind} ${record.name}, called by tenant B with A's own input ${LEG[finding.leg]}, handed back A's seeded data at ${where(finding)}: a read reached A's row past the tenant guard — by an id the caller chose, or by a statement no tenant predicate scopes`
44
- : `${record.kind} ${record.name}, called by tenant B with A's own input ${LEG[finding.leg]}, changed A's ${where(finding)}: a write reached A's row past the tenant guard — by an id the caller chose, or by a statement no tenant predicate scopes`;
86
+ const causeOf = (record: ExerciseRecord, group: Group): string =>
87
+ group.code === 'X_TENANT_LEAK'
88
+ ? `${record.kind} ${record.name}, called by tenant B with A's own input ${LEG[group.leg]}, handed back A's seeded data at ${group.where}: a read reached A's row past the tenant guard — by an id the caller chose, or by a statement no tenant predicate scopes`
89
+ : `${record.kind} ${record.name}, called by tenant B with A's own input ${LEG[group.leg]}, changed A's ${group.where}: a write reached A's row past the tenant guard — by an id the caller chose, or by a statement no tenant predicate scopes`;
45
90
 
46
- const fixOf = (name: string, finding: TenantFinding): string =>
47
- finding.code === 'X_TENANT_LEAK'
48
- ? `x exercise ${name} --json — then read the row behind ${where(finding)} through the repository scoped to ctx.actor, never by the input id alone, nor by an unscoped statement`
49
- : `x exercise ${name} --json — then write ${where(finding)} through the repository scoped to ctx.actor, never by the input id alone, nor by an unscoped statement`;
91
+ /**
92
+ * A `tenant: 'none'` job has no actor's org to scope a read to: reading every org is its job, and
93
+ * the one declaration the proof credits for that is a `crossTenant()` scope (`sweepReason`).
94
+ */
95
+ const fixOf = (name: string, group: Group): string =>
96
+ group.code === 'X_TENANT_WRITE_CROSSED'
97
+ ? `x exercise ${name} --json — then write ${group.where} through the repository scoped to ctx.actor, never by the input id alone, nor by an unscoped statement`
98
+ : group.sweep
99
+ ? `x exercise ${name} --json — then wrap the read behind ${group.where} in ${name}'s run in crossTenant('<why ${name} reads every org>', async () => …) from @ultimat3/entity; the job's actor must hold tenancy:cross`
100
+ : `x exercise ${name} --json — then read the row behind ${group.where} through the repository scoped to ctx.actor, never by the input id alone, nor by an unscoped statement`;
50
101
 
51
102
  /**
52
- * One coded finding per tenant finding. The fix reruns the one primitive: what it reads or writes
53
- * by input id goes through the repository scoped to `ctx.actor` (or `crossTenant()` with a public
54
- * policy, when it truly spans tenants) — which read, only the handler shows.
103
+ * One coded finding per leg and code. The fix reruns the one primitive: what it reads or writes by
104
+ * input id goes through the repository scoped to `ctx.actor` — or, for a `tenant: 'none'` job's
105
+ * read across every org, a `crossTenant()` scope. Which statement, only the handler shows.
55
106
  */
56
107
  export function tenantProofFindings(
57
108
  records: readonly ExerciseRecord[],
58
109
  ): readonly TenantProofFinding[] {
59
110
  return records.flatMap((record) => {
60
- if (record.tenant?.verdict !== 'crossed') return [];
61
111
  const name = renderFixShellArg(record.name, '<primitive>');
62
- return record.tenant.findings.map(
63
- (finding): TenantProofFinding => ({
64
- code: finding.code,
65
- cause: causeOf(record, finding),
66
- fix: fixOf(name, finding),
112
+ return crossedGroups(record).map(
113
+ (group): TenantProofFinding => ({
114
+ code: group.code,
115
+ cause: causeOf(record, group),
116
+ fix: fixOf(name, group),
67
117
  at: `${record.kind} ${record.name}`,
68
118
  }),
69
119
  );
@@ -118,6 +118,8 @@ export function leaksIn(
118
118
  return paths.map((path): TenantFinding => ({ code: 'X_TENANT_LEAK', leg, path }));
119
119
  }
120
120
 
121
+ const asSweep = (finding: TenantFinding): TenantFinding => ({ ...finding, sweep: true });
122
+
121
123
  /**
122
124
  * The reason a leg's read half is skipped as a declared sweep, or `undefined`: a job, a scope the
123
125
  * leg opened, and an input carrying nothing of A's — so no id B chose pointed at A, and what came
@@ -181,6 +183,8 @@ export async function proveTenant(plan: TenantAttack): Promise<ExerciseRecord> {
181
183
  const findings: TenantFinding[] = [];
182
184
  const unwritten = tenantlessReason(plan, marks);
183
185
  let swept: string | undefined;
186
+ // What `sweepReason` would credit, had the leg opened a scope: the leak's fix is that scope.
187
+ const undeclared = plan.sweep && plan.tenantless && marks.length === plan.taint.marks.length;
184
188
  /** B's call, between two snapshots unless the write half is skipped: then none is read. */
185
189
  const watched = async (name: TenantLeg): Promise<LegAnswer> => {
186
190
  if (unwritten !== undefined) return plan.attack(name);
@@ -194,8 +198,9 @@ export async function proveTenant(plan: TenantAttack): Promise<ExerciseRecord> {
194
198
  const answer = await watched(name);
195
199
  if (plan.public !== undefined) return;
196
200
  const sweep = sweepReason(plan, answer, marks);
197
- if (sweep === undefined) findings.push(...leaksIn(name, answer, marks));
198
- else swept = sweep;
201
+ if (sweep !== undefined) swept = sweep;
202
+ else if (undeclared) findings.push(...leaksIn(name, answer, marks).map(asSweep));
203
+ else findings.push(...leaksIn(name, answer, marks));
199
204
  };
200
205
  await leg('before');
201
206
  const control = await plan.control();