@ultimat3/testing 31.2.0 → 31.3.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 +53 -2
- package/package.json +22 -22
- package/src/e2e-preload.ts +20 -2
- package/src/entity-conformance-checks.ts +2 -0
- package/src/entity-conformance-history.ts +70 -0
- package/src/entity-conformance-locks.ts +17 -5
- package/src/entity-driver-conformance.ts +23 -1
- package/src/fake-saml-identity-provider.ts +110 -0
- package/src/index.ts +8 -0
- package/src/seed-graph-partition.ts +69 -0
- package/src/seed-graph-pass.ts +13 -0
- package/src/seed-graph-plan.ts +6 -0
- package/src/seed-graph.ts +21 -8
- package/src/seed-writer.ts +25 -9
- package/src/upload-scanner-conformance.ts +28 -3
package/README.md
CHANGED
|
@@ -30,7 +30,7 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
|
|
|
30
30
|
| `sealed-sockets.ts` | the `WebSocket` and `Bun.connect` patches, behind `sealed-network.ts`'s one gate |
|
|
31
31
|
| `factories.ts` | `defineFactory` — seeded rows, traits, associations, `build` vs `create` |
|
|
32
32
|
| `factory-registry.ts` | `factoriesFor(registry)` — one factory per entity, each value read off its column's declaration (default, enum, kind, money, nullability) through `$parse`, never off its name |
|
|
33
|
-
| `seed-graph.ts` | `seedGraph(entities, { tenants, perTable, seed, factories, beside })` — rows for every table with no factory written: parents first, same-tenant keys, every declared rule kept. Pure, same seed same bytes |
|
|
33
|
+
| `seed-graph.ts` | `seedGraph(entities, { tenants, perTable, seed, factories, beside, now })` — rows for every table with no factory written: parents first, same-tenant keys, every declared rule kept. A `partitionBy` column lands in the UTC bucket holding `now` (default `systemClock.now()`; under a frozen test clock pass the database's `now()`) — the partition the migration always makes (`seed-graph-partition.ts`). Pure, same seed and `now`, same bytes |
|
|
34
34
|
| `repro.ts` | `reproduce(bundle, { driver })` and `reproJob(runJobs, failure)` — what a test `x repro --write` generated calls: captured reads seeded, clock frozen at the failure, the same actor and input (masked fields stood in from the schema); a dead job's completed steps replayed from storage |
|
|
35
35
|
| `seed-graph-plan.ts` | the plan's types and `insertSeedGraph(graph, writer)` — every insert, then every deferred key, sequentially |
|
|
36
36
|
| `seed-graph-values.ts` | one column's candidate values, off its declaration, kept only where `$parse` accepts them — `factoriesFor`'s source too |
|
|
@@ -518,7 +518,7 @@ is meant to FAIL it. The subject is called once per test.
|
|
|
518
518
|
| `AuthServerStore` (auth) | `behavesLike(authServerStoreConformance, () => store)` |
|
|
519
519
|
| `BudgetStore` (ai) | `behavesLike(budgetStoreConformance, () => store)` |
|
|
520
520
|
| `CacheTier` (cache) | `behavesLike(cacheTierConformance, () => tier)` — each check runs inside a request |
|
|
521
|
-
| entity `Driver` (entity) | `behavesLike(entityDriverConformance, () => ({ open: (entities) => driver, capabilities, foreignKeys }))` — `open` hands a driver over EMPTY tables for `entities`; an undeclared capability is asserted REFUSED |
|
|
521
|
+
| entity `Driver` (entity) | `behavesLike(entityDriverConformance, () => ({ open: (entities) => driver, capabilities, foreignKeys }))` — `open` hands a driver over EMPTY tables for `entities`; an undeclared capability is asserted REFUSED. `history: true` when the store records `entity({ history: true })` (memory, Postgres): the history check runs `history(table, id)` against it; absent, as for a `defineDriver` store with no lifecycle hook, that check is skipped |
|
|
522
522
|
| `ErrorGroupsStore` (admin) | `behavesLike(errorGroupsStoreConformance, () => store)` |
|
|
523
523
|
| `ErrorReporter` (core) | `behavesLike(errorReporterConformance, () => ({ reporter, delivered }))` — `delivered()` is the text each report left as; only a `localErrorSink`-marked reporter may carry a secret |
|
|
524
524
|
| `EventBus` (jobs) | `behavesLike(eventBusConformance, () => ({ bus, elapse }))` |
|
|
@@ -807,6 +807,57 @@ Each tamper is refused by `@ultimat3/auth`'s real `verifyIdToken` with the code
|
|
|
807
807
|
broken token gets (`packages/testing/src/fake-identity-provider.test.ts`). An unknown `sub` and an
|
|
808
808
|
empty `users` are `X_INVARIANT`.
|
|
809
809
|
|
|
810
|
+
### SAML
|
|
811
|
+
|
|
812
|
+
`As of 31.3`. `fakeSamlIdentityProvider({ audience, users, clock? })` is the SAML twin: metadata
|
|
813
|
+
for `samlIdentityProvider`, and a signed answer to the AuthnRequest an SP's redirect carries — no
|
|
814
|
+
socket, no browser. `audience` is the SP's `spEntityId`; a user is `{ nameId, email?, name? }`.
|
|
815
|
+
|
|
816
|
+
```ts
|
|
817
|
+
import { memoryTotpReplayGuard, parseSamlMetadata, samlIdentityProvider } from '@ultimat3/auth';
|
|
818
|
+
import { frozenClock } from '@ultimat3/core';
|
|
819
|
+
import { expect, fakeSamlIdentityProvider, unitTest } from '@ultimat3/testing';
|
|
820
|
+
|
|
821
|
+
unitTest('a SAML sign-in completes as the IdP user', async () => {
|
|
822
|
+
const clock = frozenClock('2026-11-10T09:00:00.000Z');
|
|
823
|
+
const spEntityId = 'https://app.example.test/saml/metadata';
|
|
824
|
+
const callbackUrl = 'https://app.example.test/auth/sso/corp/callback';
|
|
825
|
+
const idp = await fakeSamlIdentityProvider({
|
|
826
|
+
audience: spEntityId,
|
|
827
|
+
clock,
|
|
828
|
+
users: [{ nameId: 'u-ada', email: 'ada@corp.example' }],
|
|
829
|
+
});
|
|
830
|
+
const provider = samlIdentityProvider({
|
|
831
|
+
id: 'corp',
|
|
832
|
+
idp: parseSamlMetadata(idp.metadataXml),
|
|
833
|
+
spEntityId,
|
|
834
|
+
trustEmail: true,
|
|
835
|
+
emailDomains: ['corp.example'],
|
|
836
|
+
});
|
|
837
|
+
const redirect = await provider.begin({ callbackUrl, clock });
|
|
838
|
+
const identity = await provider.complete({
|
|
839
|
+
state: redirect.state,
|
|
840
|
+
params: await idp.answer(redirect.location), // { SAMLResponse, RelayState }
|
|
841
|
+
callbackUrl,
|
|
842
|
+
clock,
|
|
843
|
+
replay: memoryTotpReplayGuard(),
|
|
844
|
+
});
|
|
845
|
+
expect(identity.profile.providerAccountId).toBe('u-ada');
|
|
846
|
+
});
|
|
847
|
+
```
|
|
848
|
+
|
|
849
|
+
| Member | Does |
|
|
850
|
+
|---|---|
|
|
851
|
+
| `entityId` · `metadataXml` | the IdP's identity; `parseSamlMetadata(metadataXml)` is the provider's `idp` |
|
|
852
|
+
| `signInAs(nameId)` | who the next answer signs in as; the first user until called |
|
|
853
|
+
| `tamper({ wrongAudience?, expired?, unsigned?, wrongKey? })` | every answer after it is broken that way; `tamper({})` restores honesty |
|
|
854
|
+
| `readAuthnRequest(location)` | the inflated AuthnRequest: `id`, `relayState`, `acsUrl`, `xml` |
|
|
855
|
+
| `answer(location)` | the ACS form body for that request: `{ SAMLResponse, RelayState }` |
|
|
856
|
+
|
|
857
|
+
The signer is `@ultimat3/auth/saml-test-idp`'s, the one auth's own SAML suites sign with —
|
|
858
|
+
loaded on first call, so this barrel stays auth-free. Each tamper is refused by the real verifier
|
|
859
|
+
with an `X_SAML_*` code (`fake-saml-identity-provider.test.ts`).
|
|
860
|
+
|
|
810
861
|
## Testing a passkey ceremony
|
|
811
862
|
|
|
812
863
|
`As of 2026-11`. `softAuthenticator({ origin, algorithm?, counter? })` is a passkey on no device:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/testing",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.3.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.3.0",
|
|
51
|
+
"@ultimat3/ai": "31.3.0",
|
|
52
|
+
"@ultimat3/auth": "31.3.0",
|
|
53
|
+
"@ultimat3/cache": "31.3.0",
|
|
54
|
+
"@ultimat3/core": "31.3.0",
|
|
55
|
+
"@ultimat3/db": "31.3.0",
|
|
56
|
+
"@ultimat3/entity": "31.3.0",
|
|
57
|
+
"@ultimat3/http": "31.3.0",
|
|
58
|
+
"@ultimat3/i18n": "31.3.0",
|
|
59
|
+
"@ultimat3/jobs": "31.3.0",
|
|
60
|
+
"@ultimat3/mail": "31.3.0",
|
|
61
|
+
"@ultimat3/notify": "31.3.0",
|
|
62
|
+
"@ultimat3/policy": "31.3.0",
|
|
63
|
+
"@ultimat3/pwa": "31.3.0",
|
|
64
|
+
"@ultimat3/query": "31.3.0",
|
|
65
|
+
"@ultimat3/realtime": "31.3.0",
|
|
66
|
+
"@ultimat3/render": "31.3.0",
|
|
67
|
+
"@ultimat3/schema": "31.3.0",
|
|
68
|
+
"@ultimat3/scraping": "31.3.0",
|
|
69
|
+
"@ultimat3/seo": "31.3.0",
|
|
70
|
+
"@ultimat3/time": "31.3.0"
|
|
71
71
|
}
|
|
72
72
|
}
|
package/src/e2e-preload.ts
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
// (`e2e-run.ts`) with Bun's own hooks and a real browser. With no root named it is INERT.
|
|
4
4
|
|
|
5
5
|
import { afterAll, beforeEach } from 'bun:test';
|
|
6
|
+
import { DETECTED_ZONE_COOKIE } from '@ultimat3/render';
|
|
7
|
+
import type { E2eBrowser } from './cdp-browser';
|
|
6
8
|
import { openE2eBrowser } from './cdp-browser';
|
|
7
9
|
import { startE2eApp } from './e2e-app';
|
|
8
10
|
import { E2E_ROOT_ENV } from './e2e-browser-handle';
|
|
@@ -10,15 +12,31 @@ import { installE2eDriver } from './e2e-driver';
|
|
|
10
12
|
import { e2eDefaultLocale } from './e2e-locale';
|
|
11
13
|
import { startE2eRun } from './e2e-run';
|
|
12
14
|
|
|
15
|
+
/** Seed the same device zone a rendered document would report before the browser can navigate. */
|
|
16
|
+
export async function seedDetectedZone(
|
|
17
|
+
browser: E2eBrowser,
|
|
18
|
+
origin: string,
|
|
19
|
+
timeZone: string,
|
|
20
|
+
): Promise<E2eBrowser> {
|
|
21
|
+
await browser.session.setCookie(origin, DETECTED_ZONE_COOKIE, timeZone);
|
|
22
|
+
return browser;
|
|
23
|
+
}
|
|
24
|
+
|
|
13
25
|
const root = Bun.env[E2E_ROOT_ENV];
|
|
14
26
|
if (root !== undefined && root !== '') {
|
|
15
27
|
// Read once, before the app boots: every browser this run opens — the first and every relaunch —
|
|
16
28
|
// asks for the app's default locale, so a page's language never depends on the runner's Chrome.
|
|
17
29
|
const acceptLanguage = await e2eDefaultLocale(root);
|
|
30
|
+
const app = await startE2eApp({ root });
|
|
31
|
+
const timeZone = Bun.env['TZ'] ?? 'UTC';
|
|
32
|
+
const openBrowser = async (): Promise<E2eBrowser> => {
|
|
33
|
+
const browser = await openE2eBrowser(acceptLanguage === undefined ? {} : { acceptLanguage });
|
|
34
|
+
return seedDetectedZone(browser, app.base, timeZone);
|
|
35
|
+
};
|
|
18
36
|
await startE2eRun({
|
|
19
|
-
app
|
|
37
|
+
app,
|
|
20
38
|
// `openE2eBrowser`, never the `IfAvailable` door: the step only names a root after finding one.
|
|
21
|
-
openBrowser
|
|
39
|
+
openBrowser,
|
|
22
40
|
install: installE2eDriver,
|
|
23
41
|
beforeEach,
|
|
24
42
|
afterAll,
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import { AGGREGATE_CHECKS } from './entity-conformance-aggregates';
|
|
5
5
|
import { BATCH_CHECKS } from './entity-conformance-batches';
|
|
6
6
|
import { BULK_CHECKS } from './entity-conformance-bulk';
|
|
7
|
+
import { HISTORY_CHECKS } from './entity-conformance-history';
|
|
7
8
|
import { LOCK_CHECKS } from './entity-conformance-locks';
|
|
8
9
|
import { MATRIX_CHECKS } from './entity-conformance-matrix';
|
|
9
10
|
import { READ_CHECKS } from './entity-conformance-reads';
|
|
@@ -24,4 +25,5 @@ export const ENTITY_DRIVER_CHECKS: readonly EntityDriverCheck[] = [
|
|
|
24
25
|
...LOCK_CHECKS,
|
|
25
26
|
...MATRIX_CHECKS,
|
|
26
27
|
...VERSION_CHECKS,
|
|
28
|
+
...HISTORY_CHECKS,
|
|
27
29
|
];
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Entity conformance · HISTORY: `entity({ history: true })` read back through `history(table, id)`.
|
|
2
|
+
// One transaction's versions tie on `now()` and still read back in write order, numbered from 1; a
|
|
3
|
+
// transaction that fails writes no version; another tenant reads none. Run only where the subject
|
|
4
|
+
// declares `history` — a `defineDriver` store has no lifecycle hook (`EntityDriverSubject.history`).
|
|
5
|
+
|
|
6
|
+
import { expect } from 'bun:test';
|
|
7
|
+
import { entity, history, text, uuid } from '@ultimat3/entity';
|
|
8
|
+
import { remember } from './entity-conformance-entities';
|
|
9
|
+
import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
|
|
10
|
+
import type { EntityDriverCheck } from './entity-driver-conformance';
|
|
11
|
+
|
|
12
|
+
const notes = remember(
|
|
13
|
+
entity('ec_h_notes', {
|
|
14
|
+
columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), title: text({ max: 40 }) },
|
|
15
|
+
history: true,
|
|
16
|
+
}),
|
|
17
|
+
);
|
|
18
|
+
const notesHistory = remember(
|
|
19
|
+
notes.$history ?? expect.unreachable('history: true declares a history entity'),
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
const ORG = idAt('b1');
|
|
23
|
+
const OTHER_ORG = idAt('b2');
|
|
24
|
+
const NOTE = idAt('b11');
|
|
25
|
+
const FAILED = idAt('b12');
|
|
26
|
+
const TITLES = ['b', 'c', 'd'];
|
|
27
|
+
|
|
28
|
+
export const HISTORY_CHECKS: readonly EntityDriverCheck[] = [
|
|
29
|
+
checkOver(
|
|
30
|
+
{ notes, notesHistory },
|
|
31
|
+
'history: one transaction reads back in order, a failed one writes none, no other tenant reads it',
|
|
32
|
+
async (db, raw) => {
|
|
33
|
+
// A `defineDriver` store has no lifecycle hook: it records no history and refuses nothing, so
|
|
34
|
+
// there is no answer to hold it to. Skipped, not asserted refused, as a capability would be.
|
|
35
|
+
if (!raw.history) return;
|
|
36
|
+
const tx = () => raw.driver.transactor();
|
|
37
|
+
const own = await inOrg(ORG, async () => {
|
|
38
|
+
await tx().run(async () => {
|
|
39
|
+
await db.notes.insert({ id: NOTE, orgId: ORG, title: 'a' });
|
|
40
|
+
for (const title of TITLES) await db.notes.update(NOTE, { title });
|
|
41
|
+
await db.notes.delete(NOTE);
|
|
42
|
+
});
|
|
43
|
+
const failed = await codeOf(() =>
|
|
44
|
+
tx().run(async () => {
|
|
45
|
+
await db.notes.insert({ id: FAILED, orgId: ORG, title: 'a' });
|
|
46
|
+
await db.notes.insert({ id: FAILED, orgId: ORG, title: 'again' });
|
|
47
|
+
}),
|
|
48
|
+
);
|
|
49
|
+
return {
|
|
50
|
+
versions: await history(db.notesHistory, NOTE),
|
|
51
|
+
failed,
|
|
52
|
+
failedVersions: await history(db.notesHistory, FAILED),
|
|
53
|
+
};
|
|
54
|
+
});
|
|
55
|
+
const title = (image: unknown): string | null =>
|
|
56
|
+
(image as { title?: string } | null)?.title ?? null;
|
|
57
|
+
expect(own.versions.map((v) => [v.version, v.op, title(v.before), title(v.after)])).toEqual([
|
|
58
|
+
[1, 'insert', null, 'a'],
|
|
59
|
+
[2, 'update', 'a', 'b'],
|
|
60
|
+
[3, 'update', 'b', 'c'],
|
|
61
|
+
[4, 'update', 'c', 'd'],
|
|
62
|
+
[5, 'delete', 'd', null],
|
|
63
|
+
]);
|
|
64
|
+
expect(own.failed).toBe('X_DB_UNIQUE_VIOLATION');
|
|
65
|
+
expect(own.failedVersions).toEqual([]);
|
|
66
|
+
expect(await inOrg(OTHER_ORG, () => history(db.notesHistory, NOTE))).toEqual([]);
|
|
67
|
+
},
|
|
68
|
+
['transactions'],
|
|
69
|
+
),
|
|
70
|
+
];
|
|
@@ -147,22 +147,34 @@ const lockChecks: readonly EntityDriverCheck[] = [
|
|
|
147
147
|
checkOver(
|
|
148
148
|
SET,
|
|
149
149
|
'a nested lock is held to the outer end, not released with its own',
|
|
150
|
-
async (db) => {
|
|
150
|
+
async (db, raw) => {
|
|
151
|
+
// Sequenced on what the driver REPORTS, never on a clock: the outer ends once the contender is
|
|
152
|
+
// queued behind c4 (a held lock) or has run (a released one) — whichever the driver does. A
|
|
153
|
+
// wall-clock window let a broken driver pass whenever its contender was slow.
|
|
154
|
+
const waiters = raw.lockWaiters;
|
|
155
|
+
if (waiters === undefined) return;
|
|
151
156
|
await counter(db, idAt('c3'));
|
|
152
157
|
await counter(db, idAt('c4'));
|
|
153
158
|
const order: string[] = [];
|
|
159
|
+
const nestedHeld = Promise.withResolvers<void>();
|
|
160
|
+
let secondRan = false;
|
|
161
|
+
const queuedOrRan = async (): Promise<void> => {
|
|
162
|
+
while (!secondRan && (await waiters()) < 1) {
|
|
163
|
+
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
164
|
+
}
|
|
165
|
+
};
|
|
154
166
|
await inOrg(ORG_A, () =>
|
|
155
167
|
Promise.all([
|
|
156
168
|
db.counters.lock(idAt('c3'), async () => {
|
|
157
|
-
await db.counters.lock(idAt('c4'), () =>
|
|
158
|
-
await
|
|
159
|
-
await yieldNow();
|
|
169
|
+
await db.counters.lock(idAt('c4'), () => nestedHeld.resolve());
|
|
170
|
+
await queuedOrRan();
|
|
160
171
|
order.push('outer ending');
|
|
161
172
|
}),
|
|
162
173
|
(async () => {
|
|
163
|
-
await
|
|
174
|
+
await nestedHeld.promise;
|
|
164
175
|
await db.counters.lock(idAt('c4'), () => {
|
|
165
176
|
order.push('second ran');
|
|
177
|
+
secondRan = true;
|
|
166
178
|
});
|
|
167
179
|
})(),
|
|
168
180
|
]),
|
|
@@ -24,12 +24,29 @@ export interface EntityDriverSubject {
|
|
|
24
24
|
readonly capabilities: readonly DriverCapability[];
|
|
25
25
|
/** Whether a reference to a row that does not exist is refused (`X_DB_FOREIGN_KEY_VIOLATION`). */
|
|
26
26
|
readonly foreignKeys: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Whether the store records `entity({ history: true })` — Postgres by trigger, memory in its
|
|
29
|
+
* repository. A `defineDriver` store has no lifecycle hook, so it records nothing and refuses
|
|
30
|
+
* nothing: absent here, the history check is not run against it (there is no refusal to assert).
|
|
31
|
+
*/
|
|
32
|
+
readonly history?: boolean;
|
|
33
|
+
/**
|
|
34
|
+
* How many lock requests are blocked behind a holder right now — `memoryLockWaiters` from
|
|
35
|
+
* `@ultimat3/entity/adapter`, or `pg_stat_activity`'s `wait_event_type = 'Lock'` on a pool. What
|
|
36
|
+
* the hold check waits on to know a contender REACHED the lock, never a clock. Absent (PGlite:
|
|
37
|
+
* one connection, so a contender waits on the client where no query sees it): that check skips.
|
|
38
|
+
*/
|
|
39
|
+
readonly lockWaiters?: (() => number | Promise<number>) | undefined;
|
|
27
40
|
}
|
|
28
41
|
|
|
29
42
|
/** What one check sees: the opened driver, and the subject's declared traits. */
|
|
30
43
|
export interface EntityDriverRun {
|
|
31
44
|
readonly driver: Driver;
|
|
32
45
|
readonly foreignKeys: boolean;
|
|
46
|
+
/** The subject's `history`, `false` when it declared none. */
|
|
47
|
+
readonly history: boolean;
|
|
48
|
+
/** The subject's `lockWaiters`, when it can see one. */
|
|
49
|
+
readonly lockWaiters: (() => number | Promise<number>) | undefined;
|
|
33
50
|
}
|
|
34
51
|
|
|
35
52
|
export interface EntityDriverCheck {
|
|
@@ -82,7 +99,12 @@ export const runEntityDriverCheck = async (
|
|
|
82
99
|
for (const capability of missing) await assertRefused(driver, capability);
|
|
83
100
|
return;
|
|
84
101
|
}
|
|
85
|
-
await check.run({
|
|
102
|
+
await check.run({
|
|
103
|
+
driver,
|
|
104
|
+
foreignKeys: subject.foreignKeys,
|
|
105
|
+
history: subject.history === true,
|
|
106
|
+
lockWaiters: subject.lockWaiters,
|
|
107
|
+
});
|
|
86
108
|
};
|
|
87
109
|
|
|
88
110
|
/** Generous: a SQL subject re-creates its tables per check, and one check writes 40,000 rows. */
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// A fake SAML IdP for an app's sign-in tests, the SAML twin of `fakeIdentityProvider`: metadata to
|
|
2
|
+
// hand `samlIdentityProvider`, and a signed answer to the AuthnRequest an SP's redirect carries, as a
|
|
3
|
+
// chosen user. `tamper()` mints the refusals that matter. The signer is `@ultimat3/auth/saml-test-idp`'s
|
|
4
|
+
// — the one auth's own suites sign with — loaded on first use, so this barrel stays auth-free.
|
|
5
|
+
|
|
6
|
+
import type { Clock } from '@ultimat3/core';
|
|
7
|
+
import { assert, systemClock } from '@ultimat3/core';
|
|
8
|
+
|
|
9
|
+
export interface FakeSamlUser {
|
|
10
|
+
/** The `NameID`: what `profile.providerAccountId` reads. */
|
|
11
|
+
readonly nameId: string;
|
|
12
|
+
/** The `email` attribute; `null` omits it. Defaults to none. */
|
|
13
|
+
readonly email?: string | null | undefined;
|
|
14
|
+
/** The `displayName` attribute; absent omits it. */
|
|
15
|
+
readonly name?: string | undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface FakeSamlTamper {
|
|
19
|
+
/** The audience names another SP. */
|
|
20
|
+
readonly wrongAudience?: boolean | undefined;
|
|
21
|
+
/** The assertion's window closed an hour ago. */
|
|
22
|
+
readonly expired?: boolean | undefined;
|
|
23
|
+
/** No signature at either level. */
|
|
24
|
+
readonly unsigned?: boolean | undefined;
|
|
25
|
+
/** Signed by a key the metadata does not publish. */
|
|
26
|
+
readonly wrongKey?: boolean | undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface FakeSamlIdentityProviderInput {
|
|
30
|
+
/** The SP's entity id — `samlIdentityProvider({ spEntityId })` — that each response is for. */
|
|
31
|
+
readonly audience: string;
|
|
32
|
+
readonly users: readonly FakeSamlUser[];
|
|
33
|
+
readonly clock?: Clock | undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface FakeSamlAuthnRequest {
|
|
37
|
+
readonly id: string;
|
|
38
|
+
readonly relayState: string;
|
|
39
|
+
/** Where the SP asked the answer posted: its `AssertionConsumerServiceURL`. */
|
|
40
|
+
readonly acsUrl: string;
|
|
41
|
+
readonly xml: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface FakeSamlIdentityProvider {
|
|
45
|
+
readonly entityId: string;
|
|
46
|
+
/** `parseSamlMetadata(metadataXml)` is `samlIdentityProvider`'s `idp`. */
|
|
47
|
+
readonly metadataXml: string;
|
|
48
|
+
/** Who the next answer signs in as. Defaults to the first user. */
|
|
49
|
+
signInAs(nameId: string): void;
|
|
50
|
+
/** Applies to every answer after it; `tamper({})` restores honesty. */
|
|
51
|
+
tamper(flags: FakeSamlTamper): void;
|
|
52
|
+
/** The AuthnRequest on an SP's redirect `location`, inflated. */
|
|
53
|
+
readAuthnRequest(location: string): FakeSamlAuthnRequest;
|
|
54
|
+
/** The browser's POST back for the request on `location`: the ACS's form body. */
|
|
55
|
+
answer(location: string): Promise<{ readonly SAMLResponse: string; readonly RelayState: string }>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const HOUR_MS = 3_600_000;
|
|
59
|
+
|
|
60
|
+
export async function fakeSamlIdentityProvider(
|
|
61
|
+
input: FakeSamlIdentityProviderInput,
|
|
62
|
+
): Promise<FakeSamlIdentityProvider> {
|
|
63
|
+
assert(
|
|
64
|
+
input.users.length > 0,
|
|
65
|
+
'fakeSamlIdentityProvider was given no users',
|
|
66
|
+
'pass users: [{ nameId, email }]',
|
|
67
|
+
);
|
|
68
|
+
const saml = await import('@ultimat3/auth/saml-test-idp');
|
|
69
|
+
const [idp, rogue] = await Promise.all([saml.samlTestIdp(), saml.testRsaSigner()]);
|
|
70
|
+
const users = new Map(input.users.map((user) => [user.nameId, user]));
|
|
71
|
+
const clock = input.clock ?? systemClock;
|
|
72
|
+
let current = input.users[0]?.nameId ?? '';
|
|
73
|
+
let flags: FakeSamlTamper = {};
|
|
74
|
+
|
|
75
|
+
const readAuthnRequest = (location: string): FakeSamlAuthnRequest => {
|
|
76
|
+
const request = saml.readAuthnRequest(location);
|
|
77
|
+
const acsUrl = /\bAssertionConsumerServiceURL="([^"]+)"/.exec(request.xml)?.[1] ?? '';
|
|
78
|
+
return { ...request, acsUrl };
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
entityId: saml.TEST_IDP_ENTITY_ID,
|
|
83
|
+
metadataXml: idp.metadataXml,
|
|
84
|
+
signInAs(nameId) {
|
|
85
|
+
assert(users.has(nameId), `fake SAML IdP has no user ${nameId}`, 'add it to users: [...]');
|
|
86
|
+
current = nameId;
|
|
87
|
+
},
|
|
88
|
+
tamper(next) {
|
|
89
|
+
flags = next;
|
|
90
|
+
},
|
|
91
|
+
readAuthnRequest,
|
|
92
|
+
async answer(location) {
|
|
93
|
+
const request = readAuthnRequest(location);
|
|
94
|
+
const user = users.get(current);
|
|
95
|
+
const now = clock.now();
|
|
96
|
+
const xml = await idp.responseXml({
|
|
97
|
+
requestId: request.id,
|
|
98
|
+
acsUrl: request.acsUrl,
|
|
99
|
+
audience: flags.wrongAudience === true ? `${input.audience}#other` : input.audience,
|
|
100
|
+
now: flags.expired === true ? new Date(now.getTime() - HOUR_MS) : now,
|
|
101
|
+
nameId: current,
|
|
102
|
+
email: user?.email ?? null,
|
|
103
|
+
name: user?.name ?? null,
|
|
104
|
+
signAssertion: flags.unsigned !== true,
|
|
105
|
+
...(flags.wrongKey === true ? { signer: rogue } : {}),
|
|
106
|
+
});
|
|
107
|
+
return { SAMLResponse: saml.encodeResponse(xml), RelayState: request.relayState };
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -199,6 +199,14 @@ export type {
|
|
|
199
199
|
FakeIdpUser,
|
|
200
200
|
} from './fake-identity-provider';
|
|
201
201
|
export { fakeIdentityProvider } from './fake-identity-provider';
|
|
202
|
+
export type {
|
|
203
|
+
FakeSamlAuthnRequest,
|
|
204
|
+
FakeSamlIdentityProvider,
|
|
205
|
+
FakeSamlIdentityProviderInput,
|
|
206
|
+
FakeSamlTamper,
|
|
207
|
+
FakeSamlUser,
|
|
208
|
+
} from './fake-saml-identity-provider';
|
|
209
|
+
export { fakeSamlIdentityProvider } from './fake-saml-identity-provider';
|
|
202
210
|
export type { FaultMode, FaultProxy, FaultProxyCounts } from './fault-proxy';
|
|
203
211
|
export { faultProxy } from './fault-proxy';
|
|
204
212
|
export type { TestClock, TestDuration } from './fixture-clock';
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Single responsibility: where a seeded `partitionBy` column's values may land: the UTC bucket
|
|
2
|
+
// holding the anchor (`date_trunc(unit, … at time zone 'UTC')`, as `ultimate_partitions` cuts it),
|
|
3
|
+
// read off the entity's own `$describe().partition` — never a date of ours.
|
|
4
|
+
//
|
|
5
|
+
// Storable while the database's partitions cover the anchor: the migration makes them around its
|
|
6
|
+
// APPLY time and only the app's `partitions()` job keeps them ahead; past that, the seed pass
|
|
7
|
+
// refuses naming that job.
|
|
8
|
+
|
|
9
|
+
import type { PartitionDescription } from '@ultimat3/entity';
|
|
10
|
+
|
|
11
|
+
/** One UTC bucket: `[startMs, startMs + spanMs)`. */
|
|
12
|
+
export interface PartitionWindow {
|
|
13
|
+
readonly startMs: number;
|
|
14
|
+
readonly spanMs: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const DAY = 86_400_000;
|
|
18
|
+
|
|
19
|
+
/** `date_trunc(unit, anchor at time zone 'UTC')` and the bucket's length, as Postgres reads both. */
|
|
20
|
+
export function partitionWindow(
|
|
21
|
+
partition: PartitionDescription | null | undefined,
|
|
22
|
+
anchor: Date,
|
|
23
|
+
): PartitionWindow | null {
|
|
24
|
+
if (partition === null || partition === undefined) return null;
|
|
25
|
+
const y = anchor.getUTCFullYear();
|
|
26
|
+
const m = anchor.getUTCMonth();
|
|
27
|
+
const today = Date.UTC(y, m, anchor.getUTCDate());
|
|
28
|
+
switch (partition.interval) {
|
|
29
|
+
case 'day':
|
|
30
|
+
return { startMs: today, spanMs: DAY };
|
|
31
|
+
case 'week':
|
|
32
|
+
// ISO: a week starts on a Monday, as `date_trunc('week', …)` does. getUTCDay(): Sunday is 0.
|
|
33
|
+
return { startMs: today - ((anchor.getUTCDay() + 6) % 7) * DAY, spanMs: 7 * DAY };
|
|
34
|
+
case 'month':
|
|
35
|
+
return { startMs: Date.UTC(y, m, 1), spanMs: Date.UTC(y, m + 1, 1) - Date.UTC(y, m, 1) };
|
|
36
|
+
case 'year':
|
|
37
|
+
return { startMs: Date.UTC(y, 0, 1), spanMs: Date.UTC(y + 1, 0, 1) - Date.UTC(y, 0, 1) };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** How many distinct values one row is offered: enough for the row solver to step past a unique. */
|
|
42
|
+
const OFFERED = 8;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Candidates for one row's partition column, every one inside `window`: instants for a
|
|
46
|
+
* `timestamptz`, `YYYY-MM-DD` for a `date`, rotated by the row's ordinal so rows spread over the
|
|
47
|
+
* bucket. Any other kind is no partition bound this reads — none of its own, the kind's own apply.
|
|
48
|
+
*/
|
|
49
|
+
export function valuesInWindow(
|
|
50
|
+
kind: string,
|
|
51
|
+
window: PartitionWindow,
|
|
52
|
+
ordinal: number,
|
|
53
|
+
position: number,
|
|
54
|
+
): readonly unknown[] {
|
|
55
|
+
if (kind === 'date') {
|
|
56
|
+
const days = Math.max(1, Math.floor(window.spanMs / DAY));
|
|
57
|
+
return Array.from({ length: Math.min(OFFERED, days) }, (_, i) =>
|
|
58
|
+
new Date(window.startMs + ((ordinal + i) % days) * DAY).toISOString().slice(0, 10),
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
if (kind === 'timestamptz') {
|
|
62
|
+
const minutes = Math.floor(window.spanMs / 60_000);
|
|
63
|
+
return Array.from(
|
|
64
|
+
{ length: OFFERED },
|
|
65
|
+
(_, i) => new Date(window.startMs + ((ordinal * 7 + position + i) % minutes) * 60_000),
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
return [];
|
|
69
|
+
}
|
package/src/seed-graph-pass.ts
CHANGED
|
@@ -31,9 +31,22 @@ const ROW_REFUSALS: ReadonlySet<string> = new Set([
|
|
|
31
31
|
'X_DB_STATEMENT_FAILED',
|
|
32
32
|
]);
|
|
33
33
|
|
|
34
|
+
/** Postgres' 23514 for a row whose partition key no partition covers, in its own words. */
|
|
35
|
+
const NO_PARTITION = 'no partition of relation';
|
|
36
|
+
|
|
34
37
|
const refused = (write: SeedRow | SeedUpdate, error: unknown): unknown => {
|
|
35
38
|
if (isUltimateError(error) && !ROW_REFUSALS.has(error.code)) return error;
|
|
36
39
|
const why = isUltimateError(error) ? `${error.code}: ${error.cause}` : renderThrowable(error);
|
|
40
|
+
if (why.includes(NO_PARTITION)) {
|
|
41
|
+
// No factory repairs this: the database's partitions stop short of the seed's anchor — made
|
|
42
|
+
// around a migrate long past (or a clock other than the seed's) and never kept ahead since.
|
|
43
|
+
return seedGraphUnsatisfied({
|
|
44
|
+
entity: write.entity,
|
|
45
|
+
what: `the database holds no partition for a generated row — ${why}. The seed anchors a partitionBy column on its clock's now; the partitions were made around the migration's apply time and are kept ahead only by the app's partitions() job`,
|
|
46
|
+
columns: [],
|
|
47
|
+
fix: "await maintainPartitions.enqueue({}); // the app's partitions() job: every partition up to now and its ahead — or pass seedGraph(entities, { now }) the database's select now()",
|
|
48
|
+
});
|
|
49
|
+
}
|
|
37
50
|
return seedGraphUnsatisfied({
|
|
38
51
|
entity: write.entity,
|
|
39
52
|
what: `the database refused a generated row — ${why}`,
|
package/src/seed-graph-plan.ts
CHANGED
|
@@ -29,6 +29,12 @@ export interface SeedGraphOptions {
|
|
|
29
29
|
* from a position (`code: \`c${index}\``) never repeats one of its rows on a unique column.
|
|
30
30
|
*/
|
|
31
31
|
readonly beside?: SeedGraph;
|
|
32
|
+
/**
|
|
33
|
+
* The instant the database's partitions were made around — the migration's apply time. A
|
|
34
|
+
* `partitionBy` column's values land in the bucket holding it, which the migration always makes.
|
|
35
|
+
* Default `systemClock.now()`: in a test under a frozen clock, pass the database's `now()`.
|
|
36
|
+
*/
|
|
37
|
+
readonly now?: Date | undefined;
|
|
32
38
|
}
|
|
33
39
|
|
|
34
40
|
export interface SeedRow {
|
package/src/seed-graph.ts
CHANGED
|
@@ -2,11 +2,12 @@
|
|
|
2
2
|
// key accepts, each child pointing at a parent of its OWN tenant, every value storable and every
|
|
3
3
|
// declared rule kept. Pure: it returns the plan, `insertSeedGraph` writes it. Same seed, same bytes.
|
|
4
4
|
|
|
5
|
-
import { finiteCount, finiteOption, fnv1a } from '@ultimat3/core';
|
|
5
|
+
import { finiteCount, finiteOption, fnv1a, systemClock } from '@ultimat3/core';
|
|
6
6
|
import type { ReferenceDescription } from '@ultimat3/entity';
|
|
7
7
|
import { DEFAULT_SEED, seededUuid } from './determinism';
|
|
8
8
|
import { seedGraphUnsatisfied } from './seed-graph-error';
|
|
9
9
|
import { edgeKey, insertOrder } from './seed-graph-order';
|
|
10
|
+
import { partitionWindow, valuesInWindow } from './seed-graph-partition';
|
|
10
11
|
import { declaredPatterns } from './seed-graph-patterns';
|
|
11
12
|
import type {
|
|
12
13
|
SeedCanary,
|
|
@@ -97,6 +98,7 @@ export function seedGraph(
|
|
|
97
98
|
const seed = finiteOption('seedGraph', 'seed', options.seed ?? DEFAULT_SEED);
|
|
98
99
|
const tenantCount = finiteCount('seedGraph', 'tenants', options.tenants ?? 2, 1);
|
|
99
100
|
const perTable = finiteCount('seedGraph', 'perTable', options.perTable ?? 3, 1);
|
|
101
|
+
const anchor = options.now ?? systemClock.now();
|
|
100
102
|
// A view entity is a relation Postgres derives: no row is ever written to it, so it is no part of
|
|
101
103
|
// the graph (`X_ENTITY_VIEW_READ_ONLY` otherwise) — the tables it reads from carry the rows. A
|
|
102
104
|
// history table is the same from this side: its trigger writes every row, from the parent's.
|
|
@@ -197,6 +199,12 @@ export function seedGraph(
|
|
|
197
199
|
const rootProperty = roots.get(name);
|
|
198
200
|
// Read once per table: each `matches(/…/)` an invariant holds a column to, sampled from.
|
|
199
201
|
const patterns = declaredPatterns(entity);
|
|
202
|
+
// A `partitionBy` column takes values from the bucket the migration made first (`anchor`'s).
|
|
203
|
+
const description = entity.$describe();
|
|
204
|
+
const window = partitionWindow(description.partition, anchor);
|
|
205
|
+
const partitioned = description.columns.find(
|
|
206
|
+
(column) => column.column === description.partition?.column,
|
|
207
|
+
);
|
|
200
208
|
const buckets: readonly (string | null)[] = scoped(name) ? tenants : [null];
|
|
201
209
|
// Positions continue past the graph written before this one: a reset factory rebuilt that
|
|
202
210
|
// graph's first values, and a unique column refused the second copy.
|
|
@@ -231,13 +239,18 @@ export function seedGraph(
|
|
|
231
239
|
: parentValues(reference, tenant, index)
|
|
232
240
|
: Object.hasOwn(built, property)
|
|
233
241
|
? storable(column, [built[property]])
|
|
234
|
-
:
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
242
|
+
: window !== null && property === partitioned?.property
|
|
243
|
+
? storable(
|
|
244
|
+
column,
|
|
245
|
+
valuesInWindow(partitioned.kind, window, ordinal, position),
|
|
246
|
+
)
|
|
247
|
+
: candidatesFor(property, column, {
|
|
248
|
+
ordinal,
|
|
249
|
+
canary,
|
|
250
|
+
position,
|
|
251
|
+
patterns: patterns.get(property),
|
|
252
|
+
uuid: stream,
|
|
253
|
+
});
|
|
241
254
|
return [
|
|
242
255
|
property,
|
|
243
256
|
candidates.length === 0 ? refuseEmpty(shape, property, tenant) : candidates,
|
package/src/seed-writer.ts
CHANGED
|
@@ -23,14 +23,29 @@ type SeedRepo = Repo<Record<string, unknown>>;
|
|
|
23
23
|
*/
|
|
24
24
|
export const digestRow = (row: unknown): string => fingerprint(row);
|
|
25
25
|
|
|
26
|
-
/** The physical columns of an entity's primary key, in key order. */
|
|
27
|
-
const keyColumns = (entity: EntityCore): readonly string[] => {
|
|
26
|
+
/** The physical columns of an entity's primary key, in key order, with each one's kind. */
|
|
27
|
+
const keyColumns = (entity: EntityCore): readonly { name: string; kind: string }[] => {
|
|
28
28
|
const columns = entity.$describe().columns;
|
|
29
|
-
return entity.$primaryKey.map(
|
|
30
|
-
|
|
31
|
-
|
|
29
|
+
return entity.$primaryKey.map((property) => {
|
|
30
|
+
const found = columns.find((column) => column.property === property);
|
|
31
|
+
return { name: found?.column ?? property, kind: found?.kind ?? 'text' };
|
|
32
|
+
});
|
|
32
33
|
};
|
|
33
34
|
|
|
35
|
+
/**
|
|
36
|
+
* One key part as text, the same on both sides of the match: a `Date` as its ISO instant — never
|
|
37
|
+
* `String(date)`, the process zone's `… GMT-0500 (…)` that no server parses — which is also what
|
|
38
|
+
* `instantText` below spells a stored `timestamptz` as, whatever the session's zone.
|
|
39
|
+
*/
|
|
40
|
+
const keyText = (value: unknown): string =>
|
|
41
|
+
value instanceof Date ? value.toISOString() : String(value);
|
|
42
|
+
|
|
43
|
+
/** A key column as text: a `timestamptz` in UTC ISO to the millisecond, as `toISOString` is. */
|
|
44
|
+
const columnText = (column: { name: string; kind: string }): SqlFragment =>
|
|
45
|
+
column.kind === 'timestamptz'
|
|
46
|
+
? sql`to_char(${identifier(column.name)} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`
|
|
47
|
+
: sql`${identifier(column.name)}::text`;
|
|
48
|
+
|
|
34
49
|
/** Joins a composite key's parts, in Postgres and here alike: no seeded key holds a unit separator. */
|
|
35
50
|
const KEY_SEPARATOR = '\u001f';
|
|
36
51
|
|
|
@@ -53,17 +68,18 @@ async function snapshotOnClient(
|
|
|
53
68
|
else indexes.push(i);
|
|
54
69
|
});
|
|
55
70
|
const keyOf = (entity: EntityCore, i: number): string =>
|
|
56
|
-
entity.$primaryKey.map((property) =>
|
|
71
|
+
entity.$primaryKey.map((property) => keyText(rows[i]?.row[property])).join(KEY_SEPARATOR);
|
|
57
72
|
const branches = [...byEntity].map(([entity, indexes], at): SqlFragment => {
|
|
58
|
-
const
|
|
73
|
+
const keys = keyColumns(entity);
|
|
74
|
+
const columns = keys.map((column) => identifier(column.name));
|
|
59
75
|
// Each key column against its values, the parameter UNTYPED so Postgres types it as the
|
|
60
76
|
// column: `id::text = any(…)` read every row of a table that grows with the primitives. A
|
|
61
77
|
// composite key matches a superset here; the full key is matched below.
|
|
62
78
|
const matched = entity.$primaryKey.map(
|
|
63
79
|
(property, part) =>
|
|
64
|
-
sql`${columns[part] as SqlFragment} = any(${[...new Set(indexes.map((i) =>
|
|
80
|
+
sql`${columns[part] as SqlFragment} = any(${[...new Set(indexes.map((i) => keyText(rows[i]?.row[property])))]})`,
|
|
65
81
|
);
|
|
66
|
-
const texts =
|
|
82
|
+
const texts = keys.map(columnText);
|
|
67
83
|
return sql`select ${at}::int as e, concat_ws(${KEY_SEPARATOR}, ${join(texts)}) as k, md5(t::text) as h from ${identifier(entity.$table)} t where ${join(matched, ' and ')}`;
|
|
68
84
|
});
|
|
69
85
|
if (branches.length === 0) return [];
|
|
@@ -19,6 +19,8 @@ export interface UploadScannerLike {
|
|
|
19
19
|
scan(input: {
|
|
20
20
|
readonly key: string;
|
|
21
21
|
readonly pendingKey: string;
|
|
22
|
+
/** Which bytes under `pendingKey`: a held decision is keyed by `(pendingKey, revision)`. */
|
|
23
|
+
readonly revision?: string | undefined;
|
|
22
24
|
readonly size: number;
|
|
23
25
|
readonly contentType: string;
|
|
24
26
|
readonly body: ReadableStream<Uint8Array>;
|
|
@@ -47,14 +49,25 @@ function streamOf(bytes: Uint8Array, size: number): ReadableStream<Uint8Array> {
|
|
|
47
49
|
});
|
|
48
50
|
}
|
|
49
51
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
52
|
+
/**
|
|
53
|
+
* The revision `promoteAttachment` would hand over for these bytes: one identity per content. A true
|
|
54
|
+
* retry of the same bytes keeps it; different bytes never share it — so a scanner caching by
|
|
55
|
+
* `(pendingKey, revision)`, as a held decision must, is judged on what it was actually sent.
|
|
56
|
+
*/
|
|
57
|
+
const revisionOf = (bytes: Uint8Array): string =>
|
|
58
|
+
`sha256:${new Bun.CryptoHasher('sha256').update(bytes).digest('hex')}`;
|
|
59
|
+
|
|
60
|
+
const scan = (scanner: UploadScannerLike, bytes: Uint8Array, chunk = 64 * 1024) => {
|
|
61
|
+
const revision = revisionOf(bytes);
|
|
62
|
+
return scanner.scan({
|
|
63
|
+
key: `org/conformance/pending/scan/${revision.slice(7, 19)}-u-1.txt`,
|
|
53
64
|
pendingKey: 'org/conformance/pending/u-1.txt',
|
|
65
|
+
revision,
|
|
54
66
|
size: bytes.byteLength,
|
|
55
67
|
contentType: 'text/plain',
|
|
56
68
|
body: streamOf(bytes, chunk),
|
|
57
69
|
});
|
|
70
|
+
};
|
|
58
71
|
|
|
59
72
|
const PLAIN = encode('A plain note: nothing in here is a virus.\n');
|
|
60
73
|
|
|
@@ -98,6 +111,18 @@ export const UPLOAD_SCANNER_CHECKS: readonly UploadScannerCheck[] = [
|
|
|
98
111
|
expect(await scan(scanner, PLAIN)).toEqual({ verdict: 'clean' });
|
|
99
112
|
},
|
|
100
113
|
},
|
|
114
|
+
{
|
|
115
|
+
// The upload URL stays valid after the sniff: the bytes under one pending key can be rewritten
|
|
116
|
+
// between two confirms. A scanner (or the review behind it) keyed by `pendingKey` alone clears
|
|
117
|
+
// the rewrite with the original's verdict — EICAR attached unscanned.
|
|
118
|
+
name: 'a new revision of one upload is judged on its own bytes: clean, then EICAR is never clean',
|
|
119
|
+
async run(scanner) {
|
|
120
|
+
const first = await scan(scanner, PLAIN);
|
|
121
|
+
expect(first.verdict === 'infected').toBe(false);
|
|
122
|
+
const second = await scan(scanner, encode(UPLOAD_SCANNER_EICAR));
|
|
123
|
+
expect(second.verdict).not.toBe('clean');
|
|
124
|
+
},
|
|
125
|
+
},
|
|
101
126
|
];
|
|
102
127
|
|
|
103
128
|
export const uploadScannerConformance: SharedExamples<UploadScannerLike> = sharedExamples(
|