From 81c7346f37f11395b41d199a2e7c0d603b148122 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 10:39:50 +0000 Subject: [PATCH 1/3] refactor(core)!: ResolveLocalizationInput takes organizationId, not tenantId The key always meant the organization id; the old name let an environment id type-check. Renamed with no alias; the four in-repo callers and the localization tests are migrated, and a pin holds both the type refusal and the runtime absence of any alias. Claude-Session: https://claude.ai/code/session_014xf92fjdDKjycyVbyxMKm8 Co-authored-by: Claude --- .../src/security/request-execution-context.ts | 2 +- .../security/resolve-authz-context.test.ts | 64 +++++----- .../src/security/resolve-authz-context.ts | 34 +++-- .../resolve-localization-cache.test.ts | 120 +++++++++--------- ...lization-fallback-organization.pin.test.ts | 14 +- ...ocalization-fallback-row-reach.pin.test.ts | 4 +- ...e-localization-organization-id.pin.test.ts | 96 ++++++++++++++ packages/mcp/src/plugin.ts | 2 +- .../plugins/plugin-audit/src/audit-plugin.ts | 2 +- .../src/current-user-endpoints.ts | 2 +- 10 files changed, 224 insertions(+), 116 deletions(-) create mode 100644 packages/core/src/security/resolve-localization-organization-id.pin.test.ts diff --git a/packages/core/src/security/request-execution-context.ts b/packages/core/src/security/request-execution-context.ts index 3c5556bf5c1..910e52e9c16 100644 --- a/packages/core/src/security/request-execution-context.ts +++ b/packages/core/src/security/request-execution-context.ts @@ -271,7 +271,7 @@ export async function resolveRequestExecutionContext( if (authz.userId) { if (input.localization !== 'withhold') { const settings = await Promise.resolve(input.localization.settings()).catch(() => undefined); - localization = await resolveLocalizationContext({ ql, settings, tenantId: authz.tenantId, userId: authz.userId }); + localization = await resolveLocalizationContext({ ql, settings, organizationId: authz.tenantId, userId: authz.userId }); } authGate = await decideAuthGate(input, authz, sessionApi); } diff --git a/packages/core/src/security/resolve-authz-context.test.ts b/packages/core/src/security/resolve-authz-context.test.ts index 15f1409d109..67543e2136d 100644 --- a/packages/core/src/security/resolve-authz-context.test.ts +++ b/packages/core/src/security/resolve-authz-context.test.ts @@ -224,7 +224,7 @@ describe('resolveLocalizationContext — batched fallback read (#2409)', () => { { namespace: 'localization', key: 'currency', scope: 'tenant', organization_id: 'o1', value: 'JPY' }, ], }); - const loc = await resolveLocalizationContext({ ql, tenantId: 'o1' }); + const loc = await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(loc).toEqual({ timezone: 'Asia/Tokyo', locale: 'ja-JP', currency: 'JPY' }); expect(ql.counts.sys_setting).toBe(1); }); @@ -256,7 +256,7 @@ describe('resolveLocalizationContext — batched fallback read (#2409)', () => { }, }; const ql = makeCountingQl({ sys_setting: [] }); - const loc = await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + const loc = await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(loc).toEqual({ timezone: 'Asia/Tokyo', locale: 'ja-JP', currency: 'JPY' }); expect(getMany.calls).toBe(1); expect(ql.counts.sys_setting ?? 0).toBe(0); // service answered — no direct read @@ -271,7 +271,7 @@ describe('resolveLocalizationContext — batched fallback read (#2409)', () => { }, }; const ql = makeCountingQl({ sys_setting: [] }); - const loc = await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + const loc = await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(loc).toEqual({ timezone: 'Asia/Tokyo', locale: 'ja-JP', currency: 'JPY' }); expect(gets).toBe(3); }); @@ -286,7 +286,7 @@ describe('resolveLocalizationContext — batched fallback read (#2409)', () => { { namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'Europe/Paris' }, ], }); - const loc = await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + const loc = await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(loc.timezone).toBe('Europe/Paris'); expect(ql.counts.sys_setting).toBe(1); // the batched $in fallback ran once }); @@ -372,7 +372,7 @@ describe('resolveLocalizationContext — batched fallback read (#2409)', () => { it('a per-key occupant issues three namespace reads in ONE leg (the pre-#10826 cost)', async () => { const settings = makeSettingsRig(VALUES, { batched: false }); const ql = makeCountingQl({ sys_setting: [] }); - const loc = await resolveLocalizationContext({ ql, settings, tenantId: 'o1', userId: 'u1' }); + const loc = await resolveLocalizationContext({ ql, settings, organizationId: 'o1', userId: 'u1' }); expect(loc).toEqual(EXPECTED); expect(settings.stats).toEqual({ queries: 3, legs: 1 }); // The settings path answered, so the direct `sys_setting` fallback is not @@ -383,7 +383,7 @@ describe('resolveLocalizationContext — batched fallback read (#2409)', () => { it('the batched occupant issues ONE namespace read, in the same ONE leg', async () => { const settings = makeSettingsRig(VALUES, { batched: true }); const ql = makeCountingQl({ sys_setting: [] }); - const loc = await resolveLocalizationContext({ ql, settings, tenantId: 'o1', userId: 'u1' }); + const loc = await resolveLocalizationContext({ ql, settings, organizationId: 'o1', userId: 'u1' }); expect(loc).toEqual(EXPECTED); // queries 3 -> 1, legs 1 -> 1. #10826 was correctly scheduled as a // query-count fix; the `legs` half is what a sequential-loop regression @@ -397,7 +397,7 @@ describe('resolveLocalizationContext — batched fallback read (#2409)', () => { await resolveLocalizationContext({ ql: makeCountingQl({ sys_setting: [] }), settings, - tenantId: 'o1', + organizationId: 'o1', userId: 'u1', }); expect(settings.calls).toEqual([ @@ -451,8 +451,8 @@ describe('resolveLocalizationContext — failure-only cross-request cache (#1022 it('does not re-query on a second call within the TTL window when the read fails (same tenant)', async () => { const ql = makeMissingTableQl(); - const first = await resolveLocalizationContext({ ql, tenantId: 'o1' }); - const second = await resolveLocalizationContext({ ql, tenantId: 'o1' }); + const first = await resolveLocalizationContext({ ql, organizationId: 'o1' }); + const second = await resolveLocalizationContext({ ql, organizationId: 'o1' }); // Functional behavior is unchanged — still the built-in defaults — the // second call just doesn't repeat the failing query (and its log line). expect(first).toEqual({ timezone: 'UTC', locale: 'en-US', currency: undefined }); @@ -462,32 +462,32 @@ describe('resolveLocalizationContext — failure-only cross-request cache (#1022 it('re-queries once the TTL expires, so the cache self-heals once the table/migration lands', async () => { const ql = makeMissingTableQl(); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(ql.counts.sys_setting).toBe(1); await vi.advanceTimersByTimeAsync(30_001); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(ql.counts.sys_setting).toBe(2); }); it('keys the failure cache per tenant, so a lookup for one tenant never reuses another tenant\'s entry', async () => { const qlA = makeMissingTableQl(); // Reuse the SAME underlying table state across two tenant-scoped calls by - // routing both through one `ql`, distinguished only by `tenantId` in the + // routing both through one `ql`, distinguished only by `organizationId` in the // cache key (the direct-read fallback query itself is not tenant-scoped // in its `where`, matching the real resolver's existing behavior). - await resolveLocalizationContext({ ql: qlA, tenantId: 'tenant-a' }); - await resolveLocalizationContext({ ql: qlA, tenantId: 'tenant-b' }); + await resolveLocalizationContext({ ql: qlA, organizationId: 'tenant-a' }); + await resolveLocalizationContext({ ql: qlA, organizationId: 'tenant-b' }); expect(qlA.counts.sys_setting).toBe(2); // A repeat for the first tenant hits its own cache entry, not tenant-b's. - await resolveLocalizationContext({ ql: qlA, tenantId: 'tenant-a' }); + await resolveLocalizationContext({ ql: qlA, organizationId: 'tenant-a' }); expect(qlA.counts.sys_setting).toBe(2); }); it('keys the failure cache per `ql` instance, so two environments in one process never share a cached outcome', async () => { const qlA = makeMissingTableQl(); const qlB = makeMissingTableQl(); - await resolveLocalizationContext({ ql: qlA, tenantId: 'o1' }); - await resolveLocalizationContext({ ql: qlB, tenantId: 'o1' }); + await resolveLocalizationContext({ ql: qlA, organizationId: 'o1' }); + await resolveLocalizationContext({ ql: qlB, organizationId: 'o1' }); expect(qlA.counts.sys_setting).toBe(1); expect(qlB.counts.sys_setting).toBe(1); }); @@ -507,12 +507,12 @@ describe('resolveLocalizationContext — failure-only cross-request cache (#1022 it('without an engine write-epoch seam, a successful read is never cached: a value change between two calls is visible on the very next call', async () => { const rows = [{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'UTC' }]; const ql = makeCountingQl({ sys_setting: rows }); - const first = await resolveLocalizationContext({ ql, tenantId: 'o1' }); + const first = await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(first.timezone).toBe('UTC'); // Simulate a settings write landing between the two calls — no TTL // advance, so a cache would still be "fresh" if one existed. rows[0].value = 'America/Los_Angeles'; - const second = await resolveLocalizationContext({ ql, tenantId: 'o1' }); + const second = await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(second.timezone).toBe('America/Los_Angeles'); expect(ql.counts.sys_setting).toBe(2); }); @@ -525,10 +525,10 @@ describe('resolveLocalizationContext — failure-only cross-request cache (#1022 it('without a seam, a legitimate empty result is not cached either: the first write for a previously-unconfigured tenant is visible immediately', async () => { const rows: Array<{ namespace: string; key: string; scope: string; organization_id: string; value: string }> = []; const ql = makeCountingQl({ sys_setting: rows }); - const first = await resolveLocalizationContext({ ql, tenantId: 'o1' }); + const first = await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(first).toEqual({ timezone: 'UTC', locale: 'en-US', currency: undefined }); rows.push({ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'Asia/Tokyo' }); - const second = await resolveLocalizationContext({ ql, tenantId: 'o1' }); + const second = await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(second.timezone).toBe('Asia/Tokyo'); expect(ql.counts.sys_setting).toBe(2); }); @@ -608,14 +608,14 @@ describe('resolveLocalizationContext — only a backend fault populates the memo const settings = makeBindWindowSettings(); const ql = makeCountingQl({ sys_setting: [] }); - const preBind = await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + const preBind = await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(preBind).toEqual({ timezone: 'UTC', locale: 'en-US', currency: undefined }); expect(settings.state.getManyCalls).toBe(1); settings.state.bound = true; // the settings engine binds await vi.advanceTimersByTimeAsync(1_000); // still deep inside the 30s window - const postBind = await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + const postBind = await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); // The re-read must REACH the service (a memo hit would never call it) and // must carry the configured values, which exist only behind the bind. expect(settings.state.getManyCalls).toBe(2); @@ -630,11 +630,11 @@ describe('resolveLocalizationContext — only a backend fault populates the memo const rows = [{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'UTC' }]; const ql = makeCountingQl({ sys_setting: rows }); - const first = await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + const first = await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(first.timezone).toBe('UTC'); rows[0].value = 'America/Los_Angeles'; // a settings write lands, no TTL advance - const second = await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + const second = await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(second.timezone).toBe('America/Los_Angeles'); expect(ql.counts.sys_setting).toBe(2); }); @@ -652,7 +652,7 @@ describe('resolveLocalizationContext — only a backend fault populates the memo }; const ql = makeCountingQl({ sys_setting: [] }); - expect(await resolveLocalizationContext({ ql, settings, tenantId: 'o1' })).toEqual({ + expect(await resolveLocalizationContext({ ql, settings, organizationId: 'o1' })).toEqual({ timezone: 'UTC', locale: 'en-US', currency: undefined, @@ -661,7 +661,7 @@ describe('resolveLocalizationContext — only a backend fault populates the memo state.bound = true; await vi.advanceTimersByTimeAsync(1_000); - expect(await resolveLocalizationContext({ ql, settings, tenantId: 'o1' })).toEqual({ + expect(await resolveLocalizationContext({ ql, settings, organizationId: 'o1' })).toEqual({ timezone: 'Asia/Shanghai', locale: 'zh-CN', currency: 'CNY', @@ -684,7 +684,7 @@ describe('resolveLocalizationContext — only a backend fault populates the memo }; const ql = makeCountingQl({ sys_setting: [] }); - expect(await resolveLocalizationContext({ ql, settings, tenantId: 'o1' })).toEqual({ + expect(await resolveLocalizationContext({ ql, settings, organizationId: 'o1' })).toEqual({ timezone: 'UTC', locale: 'en-US', currency: undefined, @@ -692,7 +692,7 @@ describe('resolveLocalizationContext — only a backend fault populates the memo state.bound = true; await vi.advanceTimersByTimeAsync(1_000); - expect((await resolveLocalizationContext({ ql, settings, tenantId: 'o1' })).timezone).toBe('Asia/Shanghai'); + expect((await resolveLocalizationContext({ ql, settings, organizationId: 'o1' })).timezone).toBe('Asia/Shanghai'); }); // ── the half that must be PRESERVED (#10221) ──────────────────────────── @@ -705,18 +705,18 @@ describe('resolveLocalizationContext — only a backend fault populates the memo const settings = makeBindWindowSettings(); // unbound → refuses const ql = makeMissingTableQl(); // and the direct read throws - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(ql.counts.sys_setting).toBe(1); await vi.advanceTimersByTimeAsync(1_000); - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); // Memo hit: the failing query — and the driver's log line for it — did not // repeat. The settings refusal is re-attempted (it is free), but that is // not what #10221 was protecting. expect(ql.counts.sys_setting).toBe(1); await vi.advanceTimersByTimeAsync(30_001); - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(ql.counts.sys_setting).toBe(2); // and it still self-heals on expiry }); }); diff --git a/packages/core/src/security/resolve-authz-context.ts b/packages/core/src/security/resolve-authz-context.ts index 69d10904a18..9ceabebcf6b 100644 --- a/packages/core/src/security/resolve-authz-context.ts +++ b/packages/core/src/security/resolve-authz-context.ts @@ -2178,7 +2178,17 @@ export interface ResolveLocalizationInput { * and `rest-server.ts` widens the provider's return to a bare promise. */ settings?: any; - tenantId?: string; + /** + * The caller's ORGANIZATION id — the tenant rung the settings service stores + * and reads `localization` under (ADR-0131 D8), and the organization the + * direct `sys_setting` fallback may draw on. Never an environment id: an + * environment is not a settings scope, so one passed here matches no + * organization's row and every non-UTC organization silently resolves `UTC`. + * The key used to be spelled `tenantId`, which said none of this and let + * exactly that mistake type-check; it was renamed, with no alias, so the old + * spelling is now an excess-property error at every object-literal call. + */ + organizationId?: string; userId?: string; } @@ -2249,7 +2259,7 @@ type LocalizationResult = { timezone: string; locale: string; currency?: string * * Keyed on the `ql` instance (one entry-set per environment engine, so two * environments/tenants sharing a process never see each other's cached - * outcome) and then `tenantId|userId` beneath it, matching the audit writer's + * outcome) and then `organizationId|userId` beneath it, matching the audit writer's * key shape. A `ql` that isn't cacheable (missing/non-object) skips the cache * entirely — there is no query to dedupe in that case. */ @@ -2539,7 +2549,7 @@ function localizationSettingsState(settings: unknown): LocalizationSettingsState } /** - * One entry per `ql` → `tenantId|userId`. ONE table, two lifecycles — the two + * One entry per `ql` → `organizationId|userId`. ONE table, two lifecycles — the two * docblocks above are why they must not collapse into a single rule: * * `failure` — #10221/#11877. TTL only; no invalidation ever retires it. @@ -2598,7 +2608,7 @@ function putLocalizationEntry(ql: object, key: string, entry: LocalizationCacheE * * The DIRECT `sys_setting` read failing outright (backend fault — table * missing, connection refused, etc.) is memoized for - * {@link LOCALIZATION_FAILURE_CACHE_TTL_MS} per `(ql, tenantId, userId)` so + * {@link LOCALIZATION_FAILURE_CACHE_TTL_MS} per `(ql, organizationId, userId)` so * the failing query — and the driver's log line for it — does not repeat * every request (#10221). A settings-service refusal is not a backend fault * and never populates that memo (#11877). @@ -2615,8 +2625,8 @@ function putLocalizationEntry(ql: object, key: string, entry: LocalizationCacheE * a `ql` with no seam declines to cache rather than falling back to the TTL. */ export async function resolveLocalizationContext(input: ResolveLocalizationInput): Promise { - const { ql, settings, tenantId, userId } = input; - const cacheKey = `${tenantId ?? ''}|${userId ?? ''}`; + const { ql, settings, organizationId, userId } = input; + const cacheKey = `${organizationId ?? ''}|${userId ?? ''}`; const cacheable = Boolean(ql) && typeof ql === 'object'; // ⭐ Both invalidation readings are taken BEFORE the resolve, and it is these @@ -2693,10 +2703,10 @@ export async function resolveLocalizationContext(input: ResolveLocalizationInput * the one in force, and a failed derivation degraded where the service * propagates it — both make this fallback the stricter reader. */ -async function localizationFallbackReach(ql: any, tenantId: string | undefined): Promise { +async function localizationFallbackReach(ql: any, organizationId: string | undefined): Promise { try { return await resolveOrganizationReach({ - callerOrganizationId: tenantId, + callerOrganizationId: organizationId, wallStands: () => postureEnforcesWall(resolveTenancyPosture()), deriveOrganization: () => resolveGuestOrganization(ql, resolveTenancyPosture()), }); @@ -2711,13 +2721,15 @@ async function localizationFallbackReach(ql: any, tenantId: string | undefined): async function resolveLocalizationContextUncached( input: ResolveLocalizationInput, ): Promise<{ value: LocalizationResult; backendFailed: boolean }> { - const { ql, settings, tenantId, userId } = input; + const { ql, settings, organizationId, userId } = input; // ONLY the direct `sys_setting` read below sets this. The settings-service // legs deliberately do not — see the cache doc above (#11877). let backendFailed = false; try { if (settings && typeof settings.get === 'function') { - const sctx = { tenantId, userId } as any; + // The settings service's own scope still spells the organization + // `tenantId`; that rename is its own surface, not this input's. + const sctx = { tenantId: organizationId, userId } as any; // [#10826] ONE grouped namespace read instead of three: `getMany` // resolves all three keys over at most two `loadRows` calls (queries // 16–18 of 24 on the measured rig collapse to one). Same per-key @@ -2775,7 +2787,7 @@ async function resolveLocalizationContextUncached( // [ADR-0131 D8] The organization this read may draw on — the reach the // settings service itself reads with (#25226): never another organization's // row, and a row with no organization only where no organization can exist. - const reach = await localizationFallbackReach(ql, tenantId); + const reach = await localizationFallbackReach(ql, organizationId); // One read for all three keys instead of a query per key (`$in` on `key`). // Inlined (rather than the shared `tryFind`) so a genuine backend fault — // as opposed to a legitimate empty result — is visible to the caller above, diff --git a/packages/core/src/security/resolve-localization-cache.test.ts b/packages/core/src/security/resolve-localization-cache.test.ts index 21a42c1cac5..a985c7a9a03 100644 --- a/packages/core/src/security/resolve-localization-cache.test.ts +++ b/packages/core/src/security/resolve-localization-cache.test.ts @@ -154,8 +154,8 @@ describe('resolveLocalizationContext — success cache identity (#11633 §7 pin { namespace: 'localization', key: 'locale', scope: 'tenant', organization_id: 'o1', value: 'ja-JP' }, { namespace: 'localization', key: 'currency', scope: 'tenant', organization_id: 'o1', value: 'JPY' }, ]); - const first = await resolveLocalizationContext({ ql, tenantId: 'o1' }); - const second = await resolveLocalizationContext({ ql, tenantId: 'o1' }); + const first = await resolveLocalizationContext({ ql, organizationId: 'o1' }); + const second = await resolveLocalizationContext({ ql, organizationId: 'o1' }); // Both halves are load-bearing: equality alone passes on a cache that never // caches, and a zero-read count alone passes on a cache that returns junk. expect(second).toEqual(first); @@ -167,11 +167,11 @@ describe('resolveLocalizationContext — success cache identity (#11633 §7 pin const rows = [{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'Asia/Tokyo' }]; const qlA = makeQl(rows); const qlB = makeQl(rows); - await resolveLocalizationContext({ ql: qlA, tenantId: 't1' }); - await resolveLocalizationContext({ ql: qlA, tenantId: 't2' }); - await resolveLocalizationContext({ ql: qlA, tenantId: 't1' }); + await resolveLocalizationContext({ ql: qlA, organizationId: 't1' }); + await resolveLocalizationContext({ ql: qlA, organizationId: 't2' }); + await resolveLocalizationContext({ ql: qlA, organizationId: 't1' }); expect(qlA.counts.sys_setting).toBe(2); - await resolveLocalizationContext({ ql: qlB, tenantId: 't1' }); + await resolveLocalizationContext({ ql: qlB, organizationId: 't1' }); expect(qlB.counts.sys_setting).toBe(1); }); }); @@ -180,10 +180,10 @@ describe('resolveLocalizationContext — the settings seam invalidates synchrono it('a `localization` write is observed by the very next resolve, with NO clock advance', async () => { const ql = makeQl([]); const settings = makeSettings({ timezone: 'UTC' }); - const first = await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + const first = await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(first.timezone).toBe('UTC'); // Cached: a repeat issues no read at all. - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(settings.counts.reads).toBe(1); settings.write('timezone', 'America/Los_Angeles'); @@ -191,7 +191,7 @@ describe('resolveLocalizationContext — the settings seam invalidates synchrono // ⭐ Assert the END of the chain — the new VALUE — never "the cache was // cleared". A clear-then-repopulate-from-a-stale-read implementation // passes the second and fails this one (#11633 §7 pin 2's discipline). - const after = await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + const after = await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(after.timezone).toBe('America/Los_Angeles'); expect(settings.counts.reads).toBe(2); }); @@ -201,14 +201,14 @@ describe('resolveLocalizationContext — the settings seam invalidates synchrono const full = makeSettings({ timezone: 'UTC' }); const { subscribe: _drop, ...seamless } = full; const settings = seamless as unknown as typeof full; - const first = await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + const first = await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(first.timezone).toBe('UTC'); // Still cached — the engine-side backstop and the TTL are the remaining bounds. - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(settings.counts.reads).toBe(1); // ...and the backstop still retires it. await ql.write('sys_setting'); - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(settings.counts.reads).toBe(2); }); @@ -216,8 +216,8 @@ describe('resolveLocalizationContext — the settings seam invalidates synchrono const ql = makeQl([]); const a = makeSettings({ timezone: 'Asia/Tokyo' }); const b = makeSettings({ timezone: 'Europe/Paris' }); - expect((await resolveLocalizationContext({ ql, settings: a, tenantId: 'o1' })).timezone).toBe('Asia/Tokyo'); - expect((await resolveLocalizationContext({ ql, settings: b, tenantId: 'o1' })).timezone).toBe('Europe/Paris'); + expect((await resolveLocalizationContext({ ql, settings: a, organizationId: 'o1' })).timezone).toBe('Asia/Tokyo'); + expect((await resolveLocalizationContext({ ql, settings: b, organizationId: 'o1' })).timezone).toBe('Europe/Paris'); }); }); @@ -227,27 +227,27 @@ describe('resolveLocalizationContext — a write to a table the answer is read f // engine, so no settings event is ever emitted. const rows = [{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'UTC' }]; const ql = makeQl(rows); - expect((await resolveLocalizationContext({ ql, tenantId: 'o1' })).timezone).toBe('UTC'); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + expect((await resolveLocalizationContext({ ql, organizationId: 'o1' })).timezone).toBe('UTC'); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(ql.counts.sys_setting).toBe(1); await ql.write('sys_setting', () => { rows[0].value = 'America/Los_Angeles'; }); - expect((await resolveLocalizationContext({ ql, tenantId: 'o1' })).timezone).toBe('America/Los_Angeles'); + expect((await resolveLocalizationContext({ ql, organizationId: 'o1' })).timezone).toBe('America/Los_Angeles'); expect(ql.counts.sys_setting).toBe(2); }); it('a `sys_platform_setting` write — the global rung `getMany` reads — retires it too', async () => { const ql = makeQl([]); const settings = makeSettings({ timezone: 'UTC' }); - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(settings.counts.reads).toBe(1); // A direct engine write of the global row: no settings event is emitted. await ql.write('sys_platform_setting', () => {}, 'insert'); - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(settings.counts.reads).toBe(2); }); @@ -256,7 +256,7 @@ describe('resolveLocalizationContext — a write to a table the answer is read f // driver step is still running when the resolve reads the old row. const rows = [{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'UTC' }]; const ql = makeQl(rows); - await resolveLocalizationContext({ ql, tenantId: 'other' }); // first sight: wires the seam + await resolveLocalizationContext({ ql, organizationId: 'other' }); // first sight: wires the seam let land!: () => void; const landed = new Promise((r) => { land = r; @@ -265,10 +265,10 @@ describe('resolveLocalizationContext — a write to a table the answer is read f await landed; rows[0].value = 'Asia/Tokyo'; }); - expect((await resolveLocalizationContext({ ql, tenantId: 'o1' })).timezone).toBe('UTC'); + expect((await resolveLocalizationContext({ ql, organizationId: 'o1' })).timezone).toBe('UTC'); land(); await inFlight; - expect((await resolveLocalizationContext({ ql, tenantId: 'o1' })).timezone).toBe('Asia/Tokyo'); + expect((await resolveLocalizationContext({ ql, organizationId: 'o1' })).timezone).toBe('Asia/Tokyo'); }); it('a peer node\'s hint (`remote`) retires the entry the same way a local write does', async () => { @@ -276,19 +276,19 @@ describe('resolveLocalizationContext — a write to a table the answer is read f // local bump — so cross-node convergence rides the same backstop. const rows = [{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'UTC' }]; const ql = makeQl(rows); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); rows[0].value = 'Asia/Tokyo'; ql.writeEpoch.bump('remote'); - expect((await resolveLocalizationContext({ ql, tenantId: 'o1' })).timezone).toBe('Asia/Tokyo'); + expect((await resolveLocalizationContext({ ql, organizationId: 'o1' })).timezone).toBe('Asia/Tokyo'); }); it('a `metadata` bump — no object to judge — retires it as well', async () => { const rows = [{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'UTC' }]; const ql = makeQl(rows); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); rows[0].value = 'Asia/Tokyo'; ql.writeEpoch.bump('metadata'); - expect((await resolveLocalizationContext({ ql, tenantId: 'o1' })).timezone).toBe('Asia/Tokyo'); + expect((await resolveLocalizationContext({ ql, organizationId: 'o1' })).timezone).toBe('Asia/Tokyo'); }); }); @@ -303,11 +303,11 @@ describe('resolveLocalizationContext — a write to any OTHER object does not re async (object) => { const ql = makeQl([{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'UTC' }]); const settings = makeSettings({ timezone: 'Asia/Tokyo' }); - expect((await resolveLocalizationContext({ ql, settings, tenantId: 'o1' })).timezone).toBe('Asia/Tokyo'); + expect((await resolveLocalizationContext({ ql, settings, organizationId: 'o1' })).timezone).toBe('Asia/Tokyo'); await ql.write(object); await ql.write(object, () => {}, 'insert'); await ql.write(object, () => {}, 'delete'); - expect((await resolveLocalizationContext({ ql, settings, tenantId: 'o1' })).timezone).toBe('Asia/Tokyo'); + expect((await resolveLocalizationContext({ ql, settings, organizationId: 'o1' })).timezone).toBe('Asia/Tokyo'); expect(settings.counts.reads).toBe(1); expect(ql.counts.sys_setting).toBe(0); }, @@ -316,18 +316,18 @@ describe('resolveLocalizationContext — a write to any OTHER object does not re it('a READ of a watched table retires nothing', async () => { const ql = makeQl([]); const settings = makeSettings({ timezone: 'UTC' }); - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); await ql.write('sys_setting', () => {}, 'find'); - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(settings.counts.reads).toBe(1); }); it('a bare `write` epoch bump is the middleware\'s to judge, and on its own retires nothing', async () => { const ql = makeQl([]); const settings = makeSettings({ timezone: 'UTC' }); - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); ql.writeEpoch.bump('write'); - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); expect(settings.counts.reads).toBe(1); }); @@ -339,9 +339,9 @@ describe('resolveLocalizationContext — a write to any OTHER object does not re seen.push(opts); register(fn, opts); }; - await resolveLocalizationContext({ ql, tenantId: 'o1' }); - await resolveLocalizationContext({ ql, tenantId: 'o2' }); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o2' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(seen).toEqual([undefined]); }); }); @@ -350,9 +350,9 @@ describe('resolveLocalizationContext — no seam, no success cache', () => { it('a `ql` without a write epoch never caches a success (the pre-#11966 multiset, exactly)', async () => { const rows = [{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'UTC' }]; const ql = makeQl(rows, { epoch: false }); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); rows[0].value = 'Asia/Tokyo'; - const second = await resolveLocalizationContext({ ql, tenantId: 'o1' }); + const second = await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(second.timezone).toBe('Asia/Tokyo'); expect(ql.counts.sys_setting).toBe(2); }); @@ -360,9 +360,9 @@ describe('resolveLocalizationContext — no seam, no success cache', () => { it('a `ql` with the epoch but no middleware seam never caches a success either', async () => { const rows = [{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'UTC' }]; const ql = makeQl(rows, { middleware: false }); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); rows[0].value = 'Asia/Tokyo'; - expect((await resolveLocalizationContext({ ql, tenantId: 'o1' })).timezone).toBe('Asia/Tokyo'); + expect((await resolveLocalizationContext({ ql, organizationId: 'o1' })).timezone).toBe('Asia/Tokyo'); expect(ql.counts.sys_setting).toBe(2); }); @@ -372,9 +372,9 @@ describe('resolveLocalizationContext — no seam, no success cache', () => { const rows = [{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'UTC' }]; const ql = makeQl(rows, { epoch: false }); (ql as Record).writeEpoch = { current: 0 }; - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); rows[0].value = 'Asia/Tokyo'; - expect((await resolveLocalizationContext({ ql, tenantId: 'o1' })).timezone).toBe('Asia/Tokyo'); + expect((await resolveLocalizationContext({ ql, organizationId: 'o1' })).timezone).toBe('Asia/Tokyo'); expect(ql.counts.sys_setting).toBe(2); }); }); @@ -396,9 +396,9 @@ describe('resolveLocalizationContext — the TTL is the residual bound (#11633 registered.push(fn); register(fn); }; - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); rows[0].value = 'Asia/Tokyo'; - const second = await resolveLocalizationContext({ ql, tenantId: 'o1' }); + const second = await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(second.timezone).toBe('Asia/Tokyo'); expect(ql.counts.sys_setting).toBe(2); // OFF leaves no footprint on the engine: nothing is registered. @@ -411,9 +411,9 @@ describe('resolveLocalizationContext — the TTL is the residual bound (#11633 process.env[TTL_ENV] = '3OOO'; const rows = [{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'UTC' }]; const ql = makeQl(rows); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); rows[0].value = 'Asia/Tokyo'; - expect((await resolveLocalizationContext({ ql, tenantId: 'o1' })).timezone).toBe('Asia/Tokyo'); + expect((await resolveLocalizationContext({ ql, organizationId: 'o1' })).timezone).toBe('Asia/Tokyo'); expect(ql.counts.sys_setting).toBe(2); }); @@ -421,11 +421,11 @@ describe('resolveLocalizationContext — the TTL is the residual bound (#11633 vi.useFakeTimers(); try { const ql = makeQl([{ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'UTC' }]); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(ql.counts.sys_setting).toBe(1); await vi.advanceTimersByTimeAsync(30_001); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(ql.counts.sys_setting).toBe(2); } finally { vi.useRealTimers(); @@ -459,7 +459,7 @@ describe('resolveLocalizationContext — the failure memo survives what retires it('an engine write does NOT retire a failure entry (#10221 log spam stays fixed)', async () => { const ql = makeFailingQl(); const settings = makeSettings({}); - expect(await resolveLocalizationContext({ ql, settings, tenantId: 'o1' })).toEqual({ + expect(await resolveLocalizationContext({ ql, settings, organizationId: 'o1' })).toEqual({ timezone: 'UTC', locale: 'en-US', currency: undefined, @@ -470,7 +470,7 @@ describe('resolveLocalizationContext — the failure memo survives what retires ql.writeEpoch.bump('remote'); settings.write('timezone', 'Asia/Tokyo'); - await resolveLocalizationContext({ ql, settings, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, settings, organizationId: 'o1' }); // Still ONE failing query: the memo is TTL-bound only, exactly as shipped. expect(ql.counts.sys_setting).toBe(1); }); @@ -479,10 +479,10 @@ describe('resolveLocalizationContext — the failure memo survives what retires vi.useFakeTimers(); try { const ql = makeFailingQl(); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(ql.counts.sys_setting).toBe(1); await vi.advanceTimersByTimeAsync(30_001); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(ql.counts.sys_setting).toBe(2); } finally { vi.useRealTimers(); @@ -506,22 +506,22 @@ describe('resolveLocalizationContext — the failure memo survives what retires return rows; }, }; - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(counts.sys_setting).toBe(1); // Migration lands; the memo is still standing, so nothing changes yet. broken = false; rows.push({ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id: 'o1', value: 'Asia/Tokyo' }); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(counts.sys_setting).toBe(1); // The memo expires, a SUCCESS is recorded in its place... vi.useFakeTimers(); try { await vi.advanceTimersByTimeAsync(30_001); - expect((await resolveLocalizationContext({ ql, tenantId: 'o1' })).timezone).toBe('Asia/Tokyo'); + expect((await resolveLocalizationContext({ ql, organizationId: 'o1' })).timezone).toBe('Asia/Tokyo'); expect(counts.sys_setting).toBe(2); - await resolveLocalizationContext({ ql, tenantId: 'o1' }); + await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(counts.sys_setting).toBe(2); } finally { vi.useRealTimers(); @@ -531,7 +531,7 @@ describe('resolveLocalizationContext — the failure memo survives what retires await seams.write('sys_setting', () => { rows[0].value = 'Europe/Paris'; }); - expect((await resolveLocalizationContext({ ql, tenantId: 'o1' })).timezone).toBe('Europe/Paris'); + expect((await resolveLocalizationContext({ ql, organizationId: 'o1' })).timezone).toBe('Europe/Paris'); }); }); @@ -563,10 +563,10 @@ describe('resolveLocalizationContext — a write DURING the read must not be swa return snapshot; }, }; - const first = await resolveLocalizationContext({ ql, tenantId: 'o1' }); + const first = await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(first.timezone).toBe('UTC'); // The stale answer must NOT be reusable — the next call re-reads. - const second = await resolveLocalizationContext({ ql, tenantId: 'o1' }); + const second = await resolveLocalizationContext({ ql, organizationId: 'o1' }); expect(second.timezone).toBe('Asia/Tokyo'); expect(counts.sys_setting).toBe(2); }); diff --git a/packages/core/src/security/resolve-localization-fallback-organization.pin.test.ts b/packages/core/src/security/resolve-localization-fallback-organization.pin.test.ts index d65a8cf5143..422bb8c3940 100644 --- a/packages/core/src/security/resolve-localization-fallback-organization.pin.test.ts +++ b/packages/core/src/security/resolve-localization-fallback-organization.pin.test.ts @@ -90,8 +90,8 @@ afterEach(() => { describe('the direct localization fallback reads the caller organization only (ADR-0131 D8)', () => { it('settings service absent: each organization reads its own row, never the first row of another', async () => { const ql = makeQl(TWO_ORGS); - expect((await resolveLocalizationContext({ ql, tenantId: 'org_a' })).timezone).toBe('Europe/Paris'); - expect((await resolveLocalizationContext({ ql, tenantId: 'org_b' })).timezone).toBe('Asia/Tokyo'); + expect((await resolveLocalizationContext({ ql, organizationId: 'org_a' })).timezone).toBe('Europe/Paris'); + expect((await resolveLocalizationContext({ ql, organizationId: 'org_b' })).timezone).toBe('Asia/Tokyo'); // The organization is in the query itself, not only compared afterwards. expect(ql.settingQueries.map((w) => w?.organization_id)).toEqual(['org_a', 'org_b']); }); @@ -99,12 +99,12 @@ describe('the direct localization fallback reads the caller organization only (A it('settings service throwing (the organization source\'s AuthzStoreUnavailableError) reads the same way', async () => { const settings = throwingSettings(new AuthzStoreUnavailableError('sys_organization', new Error('down'))); const ql = makeQl(TWO_ORGS); - expect((await resolveLocalizationContext({ ql, settings, tenantId: 'org_a' })).timezone).toBe('Europe/Paris'); + expect((await resolveLocalizationContext({ ql, settings, organizationId: 'org_a' })).timezone).toBe('Europe/Paris'); }); it('an organization with no row of its own gets the built-in default, not another organization\'s row', async () => { const ql = makeQl({ sys_organization: [{ id: 'org_a' }, { id: 'org_c' }], sys_setting: [tz('org_a', 'Europe/Paris')] }); - expect((await resolveLocalizationContext({ ql, tenantId: 'org_c' })).timezone).toBe('UTC'); + expect((await resolveLocalizationContext({ ql, organizationId: 'org_c' })).timezone).toBe('UTC'); }); it('the organization is compared in memory too — an engine that drops the filter still cannot leak', async () => { @@ -114,12 +114,12 @@ describe('the direct localization fallback reads the caller organization only (A const { organization_id: _dropped, ...where } = options?.where ?? {}; return base.find(object, { ...options, where }); } }; - expect((await resolveLocalizationContext({ ql, tenantId: 'org_a' })).timezone).toBe('Europe/Paris'); + expect((await resolveLocalizationContext({ ql, organizationId: 'org_a' })).timezone).toBe('Europe/Paris'); }); it('a row with no organization is not an organization\'s fallback', async () => { const ql = makeQl({ sys_organization: [{ id: 'org_a' }], sys_setting: [tz(null, 'America/New_York')] }); - expect((await resolveLocalizationContext({ ql, tenantId: 'org_a' })).timezone).toBe('UTC'); + expect((await resolveLocalizationContext({ ql, organizationId: 'org_a' })).timezone).toBe('UTC'); }); }); @@ -158,7 +158,7 @@ describe('a caller that names no organization (ADR-0131 D9)', () => { it(`behind a wall (\`${posture}\`), a caller that names its organization still reads its own row`, async () => { vi.stubEnv('OS_TENANCY_POSTURE', posture); const ql = makeQl(TWO_ORGS); - expect((await resolveLocalizationContext({ ql, tenantId: 'org_b' })).timezone).toBe('Asia/Tokyo'); + expect((await resolveLocalizationContext({ ql, organizationId: 'org_b' })).timezone).toBe('Asia/Tokyo'); }); } diff --git a/packages/core/src/security/resolve-localization-fallback-row-reach.pin.test.ts b/packages/core/src/security/resolve-localization-fallback-row-reach.pin.test.ts index f8e0f374559..16fcb1c10f5 100644 --- a/packages/core/src/security/resolve-localization-fallback-row-reach.pin.test.ts +++ b/packages/core/src/security/resolve-localization-fallback-row-reach.pin.test.ts @@ -49,7 +49,7 @@ describe('[ADR-0131 D8] the fallback judges each row it is handed, not only the sys_organization: [{ id: 'org_a' }, { id: 'org_b' }], sys_setting: [tz(null, 'America/New_York'), tz('org_b', 'Asia/Tokyo'), tz('org_a', 'Europe/Paris')], }); - expect((await resolveLocalizationContext({ ql, tenantId: 'org_a' })).timezone).toBe('Europe/Paris'); + expect((await resolveLocalizationContext({ ql, organizationId: 'org_a' })).timezone).toBe('Europe/Paris'); }); it('with no row of its own, that caller gets the built-in default — neither foreign row', async () => { @@ -57,7 +57,7 @@ describe('[ADR-0131 D8] the fallback judges each row it is handed, not only the sys_organization: [{ id: 'org_a' }, { id: 'org_c' }], sys_setting: [tz(null, 'America/New_York'), tz('org_a', 'Europe/Paris')], }); - expect((await resolveLocalizationContext({ ql, tenantId: 'org_c' })).timezone).toBe('UTC'); + expect((await resolveLocalizationContext({ ql, organizationId: 'org_c' })).timezone).toBe('UTC'); }); it('the lean embedding takes only the row with no organization, behind another organization\'s', async () => { diff --git a/packages/core/src/security/resolve-localization-organization-id.pin.test.ts b/packages/core/src/security/resolve-localization-organization-id.pin.test.ts new file mode 100644 index 00000000000..c0a5b78462d --- /dev/null +++ b/packages/core/src/security/resolve-localization-organization-id.pin.test.ts @@ -0,0 +1,96 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `ResolveLocalizationInput` names the organization it localizes for + * `organizationId`, and nothing else. + * + * The key used to be spelled `tenantId`. It always meant the ORGANIZATION id — + * the tenant rung the settings service stores `localization` under (ADR-0131 + * D8) — but the name did not say so, and an integrator passed the ENVIRONMENT + * id there from three AI entry points: every hosted environment then resolved + * its organization's timezone as `UTC`, and nothing failed. The rename makes + * the mistake unspellable: the old key is an excess-property error at every + * object-literal call, and the resolver reads no alias for it at run time. + * + * Two halves, both needed: + * + * 1. the TYPE — `tenantId` is refused by the compiler (the `@ts-expect-error` + * below is read by `tsconfig.test.json`, which compiles this file); + * 2. the RUNTIME — the organization's timezone resolves through + * `organizationId` on both legs (the settings service and the direct + * `sys_setting` fallback), and a `tenantId` smuggled past the compiler + * reaches neither. + */ +import { describe, expect, it } from 'vitest'; +import { resolveLocalizationContext, type ResolveLocalizationInput } from './resolve-authz-context.js'; + +type Row = Record; + +/** A settings service double answering `localization.timezone` per organization, recording each scope. */ +function makeSettings(timezoneByOrganization: Record) { + const scopes: Array> = []; + return { + scopes, + get: async () => undefined, + getMany: async (_namespace: string, _keys: string[], scope: Record) => { + scopes.push(scope); + const tz = timezoneByOrganization[String(scope.tenantId)]; + return { timezone: tz ? { value: tz } : undefined, locale: undefined, currency: undefined }; + }, + }; +} + +/** An engine double holding one tenant `sys_setting` row per organization. */ +function makeQl(timezoneByOrganization: Record) { + const rows: Row[] = Object.entries(timezoneByOrganization).map(([organization_id, value]) => ({ + namespace: 'localization', + key: 'timezone', + scope: 'tenant', + organization_id, + value, + })); + return { + registry: { getObject: (name: string) => ({ name }) }, + find: async (object: string, options: any) => { + if (object !== 'sys_setting') return []; + const where = options?.where ?? {}; + return rows.filter((r) => r.organization_id === where.organization_id); + }, + }; +} + +const ORGANIZATIONS = { org_sh: 'Asia/Shanghai', org_paris: 'Europe/Paris' }; + +describe('ResolveLocalizationInput.organizationId — the type', () => { + it('refuses the retired `tenantId` key at compile time', () => { + const input: ResolveLocalizationInput = { + ql: undefined, + // @ts-expect-error -- `tenantId` was renamed `organizationId`, with no alias. + tenantId: 'org_sh', + }; + expect(input).toBeDefined(); + }); +}); + +describe('ResolveLocalizationInput.organizationId — the runtime', () => { + it('resolves the organization timezone through the settings service, scoped by organizationId', async () => { + const settings = makeSettings(ORGANIZATIONS); + const loc = await resolveLocalizationContext({ ql: undefined, settings, organizationId: 'org_sh', userId: 'u1' }); + expect(loc.timezone).toBe('Asia/Shanghai'); + // The settings service's own scope keeps its `tenantId` spelling; the value is the organization id. + expect(settings.scopes).toEqual([{ tenantId: 'org_sh', userId: 'u1' }]); + }); + + it('resolves the organization timezone through the direct sys_setting fallback, scoped by organizationId', async () => { + const loc = await resolveLocalizationContext({ ql: makeQl(ORGANIZATIONS), organizationId: 'org_paris' }); + expect(loc.timezone).toBe('Europe/Paris'); + }); + + it('reads no `tenantId` alias: a value smuggled past the compiler reaches neither leg', async () => { + const settings = makeSettings(ORGANIZATIONS); + const smuggled = { ql: undefined, settings, tenantId: 'org_sh', userId: 'u1' } as unknown as ResolveLocalizationInput; + const loc = await resolveLocalizationContext(smuggled); + expect(settings.scopes).toEqual([{ tenantId: undefined, userId: 'u1' }]); + expect(loc.timezone).toBe('UTC'); + }); +}); diff --git a/packages/mcp/src/plugin.ts b/packages/mcp/src/plugin.ts index 45cf8fd92be..f1e2e0a80db 100644 --- a/packages/mcp/src/plugin.ts +++ b/packages/mcp/src/plugin.ts @@ -669,7 +669,7 @@ export class MCPServerPlugin implements Plugin { return resolveLocalizationContext({ ql: scopedQl, settings: settingsService, - tenantId: initial.tenantId, + organizationId: initial.tenantId, userId: initial.userId, }); }; diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 285b99a984c..b03abf01094 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -384,7 +384,7 @@ export class AuditPlugin implements Plugin { } catch { settings = undefined; } - const { locale } = await resolveLocalizationContext({ ql: engine, settings, tenantId, userId }); + const { locale } = await resolveLocalizationContext({ ql: engine, settings, organizationId: tenantId, userId }); return locale; }; // [ADR-0131 D9] The organization an activity row about an org-less record diff --git a/packages/plugins/plugin-hono-server/src/current-user-endpoints.ts b/packages/plugins/plugin-hono-server/src/current-user-endpoints.ts index 73b98f516ce..f0be04d68e3 100644 --- a/packages/plugins/plugin-hono-server/src/current-user-endpoints.ts +++ b/packages/plugins/plugin-hono-server/src/current-user-endpoints.ts @@ -740,7 +740,7 @@ async function resolveCurrentUserLocalization( })(); const [stored, deployment] = await Promise.all([ storedSignedInUserLocale(ql, userId, ctx.logger), - resolveLocalizationContext({ ql, settings, tenantId, userId }), + resolveLocalizationContext({ ql, settings, organizationId: tenantId, userId }), ]); return { currency: deployment.currency, From 4c667539338603df49c89e372ace7a17a81368f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 10:40:59 +0000 Subject: [PATCH 2/3] chore(changeset): retire ResolveLocalizationInput.tenantId (runtime-export-retired) Claude-Session: https://claude.ai/code/session_014xf92fjdDKjycyVbyxMKm8 Co-authored-by: Claude --- ...5555-localization-input-organization-id.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 .changeset/25555-localization-input-organization-id.md diff --git a/.changeset/25555-localization-input-organization-id.md b/.changeset/25555-localization-input-organization-id.md new file mode 100644 index 00000000000..c667997af77 --- /dev/null +++ b/.changeset/25555-localization-input-organization-id.md @@ -0,0 +1,23 @@ +--- +'@objectstack/core': patch +'@objectstack/mcp': patch +'@objectstack/plugin-audit': patch +'@objectstack/plugin-hono-server': patch +--- + +refactor(core)!: `resolveLocalizationContext` takes the organization as `organizationId`; the `tenantId` key is retired + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a TypeScript caller of `resolveLocalizationContext` from `@objectstack/core`. The key that names the organization to localize for is renamed. There is no alias and no deprecation window. + +`ResolveLocalizationInput.tenantId` always meant the **organization** id: the settings service stores and reads `localization` under the organization (ADR-0131 D8), and the direct `sys_setting` fallback reads that organization's rows. The name did not say so, and an environment id passed there type-checked. It matched no organization's settings, so every non-UTC organization silently resolved its timezone as `UTC`, and the date boundaries cut from it moved with it. The key is now `organizationId`, and the resolver reads no other spelling at run time. + +- FROM `ResolveLocalizationInput.tenantId` TO `ResolveLocalizationInput.organizationId`: pass the caller's organization id under the new key, `resolveLocalizationContext({ ql, settings, organizationId, userId })`. Never pass an environment id. + +**Who moves.** A caller that builds the input as an object literal with `tenantId` gets a compile error (excess property) and makes the one-key fix above. A caller that builds it some other way, such as spreading an object that holds `tenantId` or passing a variable typed wider than the input, does not get that error: its `tenantId` is ignored and the resolver localizes as for a caller with no organization, so grep for `tenantId` beside `resolveLocalizationContext`. In this repository the four callers (`@objectstack/core`'s request execution context, `@objectstack/mcp`, `@objectstack/plugin-audit` and `@objectstack/plugin-hono-server`) are migrated here and behave as before. + +**Not moved.** The settings service's own scope argument, `{ tenantId, userId }` on `get` / `getMany`, keeps its spelling. It is a separate surface with its own callers. The resolver passes the organization id there as before. From bcf5c8adf3dbb2b06f5bab2c0f566d26fc8fd810 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 11:14:26 +0000 Subject: [PATCH 3/3] test(core): the organizationId pin's engine double applies the where it is handed and holds the caller's bound Claude-Session: https://claude.ai/code/session_014xf92fjdDKjycyVbyxMKm8 Co-authored-by: Claude --- ...e-localization-organization-id.pin.test.ts | 34 +++++++++++++++---- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/packages/core/src/security/resolve-localization-organization-id.pin.test.ts b/packages/core/src/security/resolve-localization-organization-id.pin.test.ts index c0a5b78462d..9e13b84e4bf 100644 --- a/packages/core/src/security/resolve-localization-organization-id.pin.test.ts +++ b/packages/core/src/security/resolve-localization-organization-id.pin.test.ts @@ -40,21 +40,41 @@ function makeSettings(timezoneByOrganization: Record) { }; } -/** An engine double holding one tenant `sys_setting` row per organization. */ -function makeQl(timezoneByOrganization: Record) { - const rows: Row[] = Object.entries(timezoneByOrganization).map(([organization_id, value]) => ({ +/** One tenant `sys_setting` timezone row per organization. */ +function timezoneRows(timezoneByOrganization: Record): Row[] { + return Object.entries(timezoneByOrganization).map(([organization_id, value]) => ({ namespace: 'localization', key: 'timezone', scope: 'tenant', organization_id, value, })); +} + +/** Equality and `$in` per field; any other operator or combinator throws rather than matching on a guess. */ +function matches(row: Row, where: Record | undefined): boolean { + if (!where) return true; + return Object.entries(where).every(([field, cond]) => { + if (field.startsWith('$')) throw new Error(`this double does not implement the where combinator ${field}`); + const value = row[field] ?? null; + if (cond !== null && typeof cond === 'object') { + const operators = Object.keys(cond); + if (operators.length !== 1 || operators[0] !== '$in') { + throw new Error(`this double does not implement the where operator(s) ${operators.join(', ')} on ${field}`); + } + return (cond as any).$in.includes(value); + } + return value === (cond ?? null); + }); +} + +/** An engine double that applies the `where` it is handed and holds the caller's bound. */ +function makeQl(tables: Record) { return { registry: { getObject: (name: string) => ({ name }) }, find: async (object: string, options: any) => { - if (object !== 'sys_setting') return []; - const where = options?.where ?? {}; - return rows.filter((r) => r.organization_id === where.organization_id); + const rows = (tables[object] ?? []).filter((r) => matches(r, options?.where)); + return typeof options?.limit === 'number' ? rows.slice(0, options.limit) : rows; }, }; } @@ -82,7 +102,7 @@ describe('ResolveLocalizationInput.organizationId — the runtime', () => { }); it('resolves the organization timezone through the direct sys_setting fallback, scoped by organizationId', async () => { - const loc = await resolveLocalizationContext({ ql: makeQl(ORGANIZATIONS), organizationId: 'org_paris' }); + const loc = await resolveLocalizationContext({ ql: makeQl({ sys_setting: timezoneRows(ORGANIZATIONS) }), organizationId: 'org_paris' }); expect(loc.timezone).toBe('Europe/Paris'); });