Skip to content

Commit 415ea42

Browse files
committed
fix(rest, objectql): register the backfill door in the rest censuses; a refused row reads the hook's sentence
The new `POST /meta/_migrate-record-currency-codes` write door joins the censuses that enumerate every REST write door and registrar module: - the `/meta` write-door enumeration (a DATA door, gated on `setup.write`, with its own refusal and control cases), the #8497 record-echo tripwire (no record echo), the #22694 hook-refusal ledger (driven per row), the registrar file lists, the objectQLProvider consumer census (7 sites), the query-slot census (no slot) and the docblock floors. Driving it through the hook-refusal ledger found a real leak: a row whose code write a sandboxed hook refused reported the `hook '<name>' threw:` debug wrapper as its failure text, and a crashed hook's row its native error. The backfill now reads the throw as the import row does: the hook's own sentence for a refusal, the `/data` door's withheld sentence for a 5xx. The operator's log line keeps the whole text. Measured by ablation: without the objectql change, 12 rows of the ledger go red. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cyrhYJgbkZHbbqud3F
1 parent f229b66 commit 415ea42

10 files changed

Lines changed: 208 additions & 11 deletions

‎.changeset/30675-record-currency-backfill-rest-door.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,4 @@ An organization admin with no shell on the deployment can now run the record-cur
2020
- The 409 `destructive_change` finding `currency_mode_to_record` now names this route beside the CLI command.
2121
- `@objectstack/objectql` now exports `RecordCurrencyBackfillOrganization` and `RecordCurrencyBackfillOrganizationsRefusal` from its entry.
2222
- A backfill walk stopped by `--max-records` no longer prints "nothing to backfill" for rows it did not examine. It says the walk is incomplete, and an unscoped run says its organization check saw only the rows examined.
23+
- A backfill row whose write a sandboxed hook refused now reports the hook's own sentence, not the `hook '<name>' threw:` debug wrapper, and a crashed hook's row reports the write doors' withheld fault sentence. The operator's log line keeps the whole text.

‎packages/objectql/src/record-currency-backfill.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,3 +435,57 @@ describe('backfillRecordCurrencyCodes — one organization at a time', () => {
435435
expect(formatRecordCurrencyBackfillReport(report).some((l) => l.includes('organization'))).toBe(false);
436436
});
437437
});
438+
439+
/**
440+
* [#30675] The report is also a REST answer (`POST /meta/_migrate-record-currency-codes`),
441+
* so a failed row's entry reads a sandboxed hook's throw as the write doors read
442+
* it: the hook's own sentence for a refusal, the door's withheld sentence for a
443+
* crash, never the `hook '<name>' threw:` debug wrapper. The operator's log line
444+
* keeps the whole text.
445+
*/
446+
describe('a failed row reads a sandboxed hook as the write doors do', () => {
447+
const SENTENCE = 'Locked rows cannot be changed here.';
448+
const sandboxed = (inner: string) => Object.assign(
449+
Object.assign(new Error(`hook 'guard' threw: Error: ${inner}`), { name: 'SandboxError' }),
450+
{ innerMessage: inner },
451+
);
452+
const run = async (thrown: () => Error) => {
453+
const warned: string[] = [];
454+
const stub = {
455+
getObject: () => ({
456+
fields: {
457+
amount: { type: 'currency', currencyConfig: { currencyMode: 'record', currencyField: 'currency_code' } },
458+
currency_code: { type: 'text', valueDomain: 'iso_4217_currency' },
459+
},
460+
}),
461+
find: async () => [{ id: 'r1', amount: 5 }],
462+
update: async () => { throw thrown(); },
463+
};
464+
const report = await backfillRecordCurrencyCodes(stub, { info: () => {}, warn: (m: string) => warned.push(m) }, {
465+
object: 'deal', field: 'amount', code: 'USD', apply: true, retry: { maxRetries: 1 },
466+
});
467+
return { report, warned };
468+
};
469+
470+
it("a refusal: the hook's own sentence, the wrapper only in the log", async () => {
471+
const { report, warned } = await run(() => sandboxed(SENTENCE));
472+
expect(report.failures).toEqual([{ recordId: 'r1', error: SENTENCE }]);
473+
expect(warned.join('\n')).toContain(`hook 'guard' threw: Error: ${SENTENCE}`);
474+
});
475+
476+
it("a crash and the sandbox's own fault: the door's withheld sentence, no native text", async () => {
477+
for (const thrown of [
478+
() => sandboxed('TypeError: __crash_words__'),
479+
() => Object.assign(new Error("hook 'guard' exceeded CPU budget of 50ms"), { name: 'SandboxError' }),
480+
]) {
481+
const { report } = await run(thrown);
482+
expect(report.failures).toHaveLength(1);
483+
expect(report.failures[0]!.error).not.toMatch(/__crash_words__|budget|threw:/);
484+
}
485+
});
486+
487+
it('CONTROL: any other throw keeps its message, as before', async () => {
488+
const { report } = await run(() => new Error('driver refused this row'));
489+
expect(report.failures).toEqual([{ recordId: 'r1', error: 'driver refused this row' }]);
490+
});
491+
});

‎packages/objectql/src/record-currency-backfill.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@
8686
* `sys_migration` flag (the `summary-nulls` reasoning: a flag nothing reads).
8787
*/
8888

89-
import { keysetWalk, type KeysetPageQuery } from '@objectstack/types';
89+
import { isSandboxOrigin, isSandboxOwnFault, keysetWalk, mapDataError, sandboxBusinessMessage, type KeysetPageQuery } from '@objectstack/types';
9090
import { objectNotFoundError, withTransientRetry, type RetryOptions } from '@objectstack/core';
9191
import { isValueDomainMember } from '@objectstack/spec/shared';
9292

@@ -430,7 +430,7 @@ async function walkCodelessRows(
430430
// what is still codeless.
431431
const message = (err as any)?.message ?? String(err);
432432
logger.warn(`[record-currency-backfill] ${object} record ${String(id)}: ${message}`);
433-
report.failures.push({ recordId: String(id), error: message });
433+
report.failures.push({ recordId: String(id), error: rowFailureSentence(err, object, message) });
434434
}
435435
}
436436
}
@@ -441,6 +441,25 @@ async function walkCodelessRows(
441441
return report;
442442
}
443443

444+
/**
445+
* [#30675] The sentence a failed row's report entry carries. The report is now
446+
* also a REST answer (`POST /meta/_migrate-record-currency-codes`), so a
447+
* sandboxed hook's throw is read as the write doors read it — the import row's
448+
* rule (`toFailedResult`, `@objectstack/core`'s import runner): a sandboxed
449+
* error the `/data` door answers with a 5xx (a crash, a declared 5xx, the
450+
* sandbox's own fault) takes that door's withheld sentence, and a sandboxed
451+
* refusal takes the hook's own sentence, never the `hook '<name>' threw:`
452+
* debug wrapper. Any other throw keeps its message, as before. The operator's
453+
* log line above keeps the whole text.
454+
*/
455+
function rowFailureSentence(err: unknown, object: string, message: string): string {
456+
if (isSandboxOrigin(err) || isSandboxOwnFault(err)) {
457+
const door = mapDataError(err, object);
458+
if (door.status >= 500) return String(door.body.error);
459+
}
460+
return sandboxBusinessMessage(err) ?? message;
461+
}
462+
444463
/** Human-readable report body, shared by the CLI's dry-run and apply output. */
445464
export function formatRecordCurrencyBackfillReport(report: RecordCurrencyBackfillReport): string[] {
446465
const lines: string[] = [];

‎packages/rest/src/meta-write-door-capability-enumeration.test.ts‎

Lines changed: 82 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,31 @@ const DOORS: readonly Door[] = [
162162
// capability gate, so the door set loses a spelling, not a capability.
163163
];
164164

165+
/**
166+
* [#30675] The `/meta` write doors that write a DATA object's rows, not
167+
* metadata, and so are not `manage_metadata` doors: they reach no protocol
168+
* method, and their gate is a tenant Setup capability resolved for the
169+
* caller's current organization. Enumerated in the same closed set (the
170+
* comparison below derives from both tables), with their own refusal cases in
171+
* the `#30675` describe at the end of this file.
172+
*/
173+
interface DataDoor {
174+
readonly label: string;
175+
readonly method: 'POST';
176+
readonly path: string;
177+
readonly capability: string;
178+
readonly body: unknown;
179+
}
180+
181+
const DATA_DOORS: readonly DataDoor[] = [
182+
{
183+
label: 'POST /meta/_migrate-record-currency-codes — record-currency code backfill [#30675]',
184+
method: 'POST', path: `${META}/_migrate-record-currency-codes`,
185+
capability: 'setup.write',
186+
body: { object: 'deal', field: 'currency_code', code: 'USD' },
187+
},
188+
];
189+
165190
/** Every protocol method any door reaches — all present, so 501 is never the answer. */
166191
const PROTOCOL_METHODS = [...new Set(DOORS.map((d) => d.protocolMethod))];
167192

@@ -190,14 +215,14 @@ const META_SEGMENT = /(?:^|\/)meta(?:\/|$)/;
190215
* The same door, addressed on another mount base
191216
* (`/api/v1/meta/...` → `/api/v1/environments/:environmentId/meta/...`).
192217
*/
193-
function onBase(door: Door, base: string): string {
218+
function onBase(door: Pick<Door, 'path'>, base: string): string {
194219
return `${base}${door.path.slice(UNSCOPED_BASE.length)}`;
195220
}
196221

197222
/** Every door, on every base the composition under test mounts. */
198223
function expectedDoors(bases: readonly string[]): string[] {
199224
return bases
200-
.flatMap((base) => DOORS.map((d) => `${d.method} ${onBase(d, base)}`))
225+
.flatMap((base) => [...DOORS, ...DATA_DOORS].map((d) => `${d.method} ${onBase(d, base)}`))
201226
.sort();
202227
}
203228

@@ -320,7 +345,7 @@ describe('#11473 — "CLOSED, enumerated set" holds for EVERY base, not just the
320345
expect(doors).toEqual(expectedDoors([UNSCOPED_BASE, SCOPED_BASE]));
321346
// Stated as a count too, because the number is the part that regressed:
322347
// the pre-#11473 prefix filter saw 5 of these 10.
323-
expect(doors).toHaveLength(DOORS.length * 2);
348+
expect(doors).toHaveLength((DOORS.length + DATA_DOORS.length) * 2);
324349
});
325350

326351
it("'required' mounts ONLY the scoped base — the case a `/api/v1/meta` prefix filter enumerated as empty", () => {
@@ -335,7 +360,7 @@ describe('#11473 — "CLOSED, enumerated set" holds for EVERY base, not just the
335360
);
336361
const doors = stack.registeredWriteDoors();
337362
expect(doors).toEqual(expectedDoors([SCOPED_BASE]));
338-
expect(doors).toHaveLength(DOORS.length);
363+
expect(doors).toHaveLength(DOORS.length + DATA_DOORS.length);
339364
expect(doors.every((d: string) => d.includes(SCOPED_BASE))).toBe(true);
340365
// And nothing is left on the unscoped base to fall back to.
341366
expect(doors.some((d: string) => d.includes(`${META}/`))).toBe(false);
@@ -609,3 +634,56 @@ describe('ADR-0131 D6 — `manage_org_presentation` is refused, and no door thre
609634
expect(stack.calls[MIGRATE_DOOR.protocolMethod]).toBe(0);
610635
});
611636
});
637+
638+
/**
639+
* [#30675] The data doors' own refusal cases. Booted with NO data engine, so a
640+
* caller the gate admits gets `501 NOT_IMPLEMENTED` — the answer that tells the
641+
* gate's verdict apart from the refusal, the role the protocol call count plays
642+
* for the metadata doors above. No case here reaches a row (the route's own
643+
* test file drives the walk and the writes on a real engine).
644+
*/
645+
describe('#30675 — the data doors refuse on their own capability, not `manage_metadata`', () => {
646+
const knockData = async (door: DataDoor, context: Record<string, unknown> | undefined, base = UNSCOPED_BASE) => {
647+
const stack = boot(context, base === UNSCOPED_BASE ? {} : { enableProjectScoping: true, projectResolution: 'auto' });
648+
const path = onBase(door, base);
649+
const route = (stack.rest as any).getRoutes().find((r: any) => r.method === door.method && r.path === path);
650+
if (!route) throw new Error(`route not registered: ${door.method} ${path}`);
651+
const res = mockRes();
652+
await route.handler({
653+
method: door.method, path, params: base === UNSCOPED_BASE ? {} : { environmentId: 'env_probe' },
654+
query: {}, headers: {}, body: door.body,
655+
}, res);
656+
return { status: res.statusCode, body: res.json.mock.calls.at(-1)?.[0] };
657+
};
658+
659+
it.each(DATA_DOORS.map((d) => [d.label, d] as const))('%s → anonymous gets 401 from the /meta umbrella', async (_l, door) => {
660+
expect((await knockData(door, undefined)).status).toBe(401);
661+
});
662+
663+
it.each(DATA_DOORS.map((d) => [d.label, d] as const))(
664+
'%s → refuses a capability-less caller, a `manage_metadata` holder and `setup.access` alone (403)',
665+
async (_l, door) => {
666+
for (const systemPermissions of [[], ['manage_metadata'], ['setup.access', 'studio.access']]) {
667+
const out = await knockData(door, { userId: 'u', tenantId: 'org_a', systemPermissions });
668+
expect(out.status).toBe(403);
669+
expect(out.body).toMatchObject({ error: { code: 'FORBIDDEN' } });
670+
}
671+
},
672+
);
673+
674+
it.each(DATA_DOORS.map((d) => [d.label, d] as const))(
675+
'%s → the control: its own capability (and `isSystem`) passes the gate, on both bases',
676+
async (_l, door) => {
677+
for (const base of [UNSCOPED_BASE, SCOPED_BASE]) {
678+
for (const ctx of [
679+
{ userId: 'u', tenantId: 'org_a', systemPermissions: [door.capability] },
680+
{ isSystem: true, tenantId: 'org_a' },
681+
]) {
682+
const out = await knockData(door, ctx, base);
683+
expect(out.status).toBe(501);
684+
expect(out.body).toMatchObject({ error: { code: 'NOT_IMPLEMENTED' } });
685+
}
686+
}
687+
},
688+
);
689+
});

‎packages/rest/src/objectql-slot-consumer-census.test.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ const SLOT_FILES = [
155155
'meta-item-history-routes.ts',
156156
// [#30205] A user's assigned work: the counts and the hand-over (the SIXTH consumer).
157157
'user-work-routes.ts',
158+
// [#30675] The record-currency code backfill door (the SEVENTH consumer).
159+
'meta-record-currency-backfill-route.ts',
158160
] as const;
159161
const SOURCES = new Map<string, string>(SLOT_FILES.map((file) => [
160162
file, file === 'rest-server.ts' ? SOURCE : readFileSync(resolve(HERE, file), 'utf8'),
@@ -232,11 +234,13 @@ describe('[#18546] §1 the `objectQLProvider` consumer census is mechanical', ()
232234
// `meta-object-state-routes.ts` and `/published`'s 1 in
233235
// `meta-item-history-routes.ts`. [#30205] 6: a user's assigned work, its
234236
// one site in `user-work-routes.ts`, shared by both of its routes.
237+
// [#30675] 7: the record-currency code backfill door, its one site in
238+
// `meta-record-currency-backfill-route.ts`.
235239
const sites = censusInvocationSites('objectQLProvider');
236240
// The message carries the sites, so a failure here hands the next
237241
// reader the new census instead of a bare number.
238242
expect(sites.map((s) => `${s.file}:${s.line}: ${s.text}`).join('\n')).toBeTruthy();
239-
expect(sites).toHaveLength(6);
243+
expect(sites).toHaveLength(7);
240244
});
241245

242246
it('⭐ [#18559] ALL FIVE consumers reach the slot through `wiredEngineOrLoud` — none reads it directly', () => {
@@ -252,7 +256,7 @@ describe('[#18546] §1 the `objectQLProvider` consumer census is mechanical', ()
252256
// the site rather than a bare number.
253257
expect(direct.map((s) => `${s.file}:${s.line}: ${s.text}`).join('\n')).toBe('');
254258
expect(direct).toHaveLength(0);
255-
expect(viaSeam).toHaveLength(6);
259+
expect(viaSeam).toHaveLength(7);
256260

257261
// ⭐ CONTROL for the window predicate itself, on BOTH axes. It reads a
258262
// WINDOW of source text, so "3 of 3" is only a reading if the same

‎packages/rest/src/rest-server-canonical-query-ast.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,9 @@ const REGISTRAR_QUERY_SLOT_FLOORS: Readonly<Record<RestServerRegistrarFile, numb
238238
'record-page-routes.ts': 2,
239239
'meta-app-bundle-routes.ts': 0,
240240
'user-work-routes.ts': 0,
241+
// [#30675] The record-currency code backfill door: no slot (the walk's
242+
// queries are `@objectstack/objectql`'s, built inside the function it calls).
243+
'meta-record-currency-backfill-route.ts': 0,
241244
};
242245

243246
const CENSUS: CensusEntry[] = [
@@ -449,6 +452,7 @@ describe('[#16638] §1 CONTROLS on the census instrument itself', () => {
449452
// [#27627] The sum 4 → 5: the record page's related list read.
450453
// [#27627] The sum unchanged by the app metadata bundle (no slot).
451454
// [#28470] The sum 5 → 6: the record page's stream reads (`readStream`).
455+
// [#30675] The sum unchanged by the record-currency code backfill (no slot).
452456
expect(Object.keys(REGISTRAR_QUERY_SLOT_FLOORS).sort()).toEqual([...REST_SERVER_REGISTRAR_FILES].sort());
453457
expect(CENSUS.filter(({ file }) => REGISTRAR_SOURCES.has(file)).map(({ file }) => file))
454458
.toEqual([...REST_SERVER_REGISTRAR_FILES]);

‎packages/rest/src/rest-server-docblock-position.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,9 @@ const MOVED_FILE_FLOORS: Readonly<Record<Exclude<RestServerRegistrarFile, typeof
251251
'record-page-routes.ts': 10,
252252
'meta-app-bundle-routes.ts': 15,
253253
'user-work-routes.ts': 6,
254+
// [#30675] The module header, the capability's, the body keys', the host
255+
// interface's, the two body helpers' and the function's.
256+
'meta-record-currency-backfill-route.ts': 7,
254257
};
255258
const MOVED_FILES: ReadonlyArray<{ file: string; minBlocks: number }> = REST_SERVER_REGISTRAR_FILES
256259
.filter((file): file is Exclude<RestServerRegistrarFile, typeof FILE> => file !== FILE)
@@ -313,6 +316,6 @@ describe('[#23050 slice 3] the registrar list this pin reads', () => {
313316
// keys, the function's, and the engine resolver's inside it).
314317
expect(Object.keys(MOVED_FILE_FLOORS).sort())
315318
.toEqual(REST_SERVER_REGISTRAR_FILES.filter((file) => file !== FILE).sort());
316-
expect(MOVED_FILES.reduce((n, { minBlocks }) => n + minBlocks, 0)).toBe(101);
319+
expect(MOVED_FILES.reduce((n, { minBlocks }) => n + minBlocks, 0)).toBe(108);
317320
});
318321
});

‎packages/rest/src/rest-server-registrar-files.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,10 @@ export const REST_SERVER_REGISTRAR_FILES = [
7878
// [#30205] `registerUserWorkEndpoints`' body, a user's assigned work: the counts and
7979
// the hand-over. New, not a moved slice.
8080
'user-work-routes.ts',
81+
// [#30675] `registerMetaRecordCurrencyBackfillRoute`' body, the record-currency code
82+
// backfill door. New, not a moved slice, and a `/meta` group — see
83+
// {@link REST_SERVER_META_ROUTE_FILES}.
84+
'meta-record-currency-backfill-route.ts',
8185
] as const;
8286

8387
/** One file on {@link REST_SERVER_REGISTRAR_FILES}. */
@@ -126,6 +130,10 @@ export const REST_SERVER_META_ROUTE_FILES: readonly RestServerRegistrarFile[] =
126130
// moved slice; like the per-item writes it goes through the inner method's per-item
127131
// registrar, handed over in its scope.
128132
'meta-app-bundle-routes.ts',
133+
// [#30675] The record-currency code backfill, `POST {metaPath}/_migrate-record-currency-codes`.
134+
// New, not a moved slice; like the state-machine read it registers on the route
135+
// manager itself, by value from a host literal built inside the inner method.
136+
'meta-record-currency-backfill-route.ts',
129137
];
130138

131139
/**

‎packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,12 @@ const DISPOSITIONS: Record<string, Disposition> = {
361361
// Metadata plane: bodies carry metadata ITEMS. `internal: true` is a field
362362
// flag on a data object's field, and a metadata item is not a data record.
363363
'POST /api/v1/meta/_migrate-stored': { kind: 'no-record-echo', why: 'Metadata plane: migration receipt.' },
364+
// [#30675] Writes a data object's rows, but answers only the run's report:
365+
// counts, a few record ids, and per-row failure sentences — no stored value.
366+
'POST /api/v1/meta/_migrate-record-currency-codes': {
367+
kind: 'no-record-echo',
368+
why: 'Backfill report: counts, sample record ids and failure sentences, never a stored field value.',
369+
},
364370
'PUT /api/v1/meta/:type/:name': { kind: 'no-record-echo', why: 'Metadata plane: metadata item, not a data record.' },
365371
'DELETE /api/v1/meta/:type/:name': { kind: 'no-record-echo', why: 'Metadata plane: delete receipt.' },
366372
'POST /api/v1/meta/:type/:name/publish': { kind: 'no-record-echo', why: 'Metadata plane: publish receipt.' },

0 commit comments

Comments
 (0)