Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(registry): complete identity cache invalidation
Josué587fdb46a5a8
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex e274676d8..64b831807 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.399",+ "version": "0.1.400","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.399",+ "version": "0.1.400","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex 342e9df2e..377f347ea 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.399",+ "version": "0.1.400","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/services/orgApiKeyClient.ts b/control-api/src/services/orgApiKeyClient.tsindex e8428d15e..82cb745bb 100644--- a/control-api/src/services/orgApiKeyClient.ts+++ b/control-api/src/services/orgApiKeyClient.ts@@ -1,16 +1,21 @@import { config } from '../config.js'import { rootLogger } from '../observability/logger.js'import type { AdminUserRecord } from './adminAuthService.js'+import {+ isRegistryIdentityCacheGenerationCurrent,+ withCurrentRegistryIdentity,+} from './registryIdentityCache.js'import { mintIdentityVoucher } from './registryVoucher.js'const API_BASE = `${config.registryUrl}/api/v1`-/** Per-admin cache of the exchanged registry USER token. Keyed by admin.id;- * evicted only on a 401 from a gated call (authoritative invalidation).- * No TTL / no sessionVersion — see spec §3.3. */-const userTokenCache = new Map<string, string>()+/** Per-admin cache of the exchanged registry USER token. */+const userTokenCache = new Map<string, { generation: number; token: string }>()+const pendingUserTokenRequests = new Map<string, { generation: number; promise: Promise<string> }>()+export function __resetUserTokenCacheForTests(): void {userTokenCache.clear()+ pendingUserTokenRequests.clear()}/** Error carrying an HTTP status the route maps to a response. `.message` is a@@ -90,11 +95,31 @@ async function exchangeVoucher(admin: AdminUserRecord): Promise<string> {}async function getUserToken(admin: AdminUserRecord): Promise<string> {- const cached = userTokenCache.get(admin.id)- if (cached) return cached- const token = await exchangeVoucher(admin)- userTokenCache.set(admin.id, token)- return token+ return withCurrentRegistryIdentity(+ generation => {+ const cached = userTokenCache.get(admin.id)+ if (cached?.generation === generation) return Promise.resolve(cached.token)++ const pending = pendingUserTokenRequests.get(admin.id)+ if (pending?.generation === generation) return pending.promise++ const promise = exchangeVoucher(admin)+ .then(token => {+ if (isRegistryIdentityCacheGenerationCurrent(generation)) {+ userTokenCache.set(admin.id, { generation, token })+ }+ return token+ })+ .finally(() => {+ if (pendingUserTokenRequests.get(admin.id)?.promise === promise) {+ pendingUserTokenRequests.delete(admin.id)+ }+ })+ pendingUserTokenRequests.set(admin.id, { generation, promise })+ return promise+ },+ { staleError: () => new RegistryStatusError('registry_integration_error', 502) }+ )}/** Parse the registry { error } body into a bare-code RegistryStatusError.diff --git a/control-api/src/services/registryClient.ts b/control-api/src/services/registryClient.tsindex 7f34673e5..f07979b80 100644--- a/control-api/src/services/registryClient.ts+++ b/control-api/src/services/registryClient.ts@@ -7,7 +7,10 @@import { config } from '../config.js'import { rootLogger } from '../observability/logger.js'import { resolveMachineCreds } from './registryConnectionDb.js'-import { getRegistryIdentityCacheGeneration } from './registryIdentityCache.js'+import {+ isRegistryIdentityCacheGenerationCurrent,+ withCurrentRegistryIdentity,+} from './registryIdentityCache.js'export { invalidateRegistryIdentityCaches } from './registryIdentityCache.js'@@ -36,6 +39,26 @@ function isTransientFetchError(err: unknown): boolean {return err.name === 'AbortError' || err.name === 'TimeoutError'}+/**+ * Registry origin/gateway is unreachable (network refusal, timeout, or an+ * upstream HTTP 5xx). A clean, user-safe error the global handler forwards as a+ * 503 so the marketplace shows a clear message instead of a raw 500.+ */+export class RegistryUnavailableError extends Error {+ readonly status = 503+ readonly code = 'registry_unavailable'+ constructor(+ message = 'The registry is currently unavailable. Check the connection and try again.'+ ) {+ super(message)+ this.name = 'RegistryUnavailableError'+ }+}++function staleRegistryIdentityError(): RegistryUnavailableError {+ return new RegistryUnavailableError('The registry identity changed. Please try again.')+}+// ── OAuth2 client_credentials token cache ────────────────────────────────────// control-api is one-per-cluster; a single cached token serves the whole// process. Refreshed ~30s before expiry so we never hit 401 from expiry in@@ -64,19 +87,31 @@ const CATALOG_CACHE_KEYS = {interface CacheEntry<T> {value: Tts: number+ generation: number}const swrCache = new Map<string, CacheEntry<unknown>>()+const pendingSWRReads = new Map<string, { generation: number; promise: Promise<unknown> }>()export function __resetTokenCacheForTests(): void {cached = nullswrCache.clear()+ pendingSWRReads.clear()}export async function mintToken(envOverride?: NodeJS.ProcessEnv): Promise<string> {+ return withCurrentRegistryIdentity(+ generation => mintTokenForGeneration(generation, envOverride),+ { staleError: staleRegistryIdentityError }+ )+}++async function mintTokenForGeneration(+ cacheGeneration: number,+ envOverride?: NodeJS.ProcessEnv+): Promise<string> {const env = envOverride ?? process.envconst now = Date.now()- const cacheGeneration = getRegistryIdentityCacheGeneration()if (cached && cached.generation === cacheGeneration && now < cached.expiresAt - 30_000)return cached.token@@ -144,7 +179,7 @@ export async function mintToken(envOverride?: NodeJS.ProcessEnv): Promise<stringexpiresAt: now + json.expires_in * 1000,generation: cacheGeneration,}- if (getRegistryIdentityCacheGeneration() === cacheGeneration) cached = next+ if (isRegistryIdentityCacheGenerationCurrent(cacheGeneration)) cached = nextreturn next.token}@@ -254,22 +289,6 @@ async function authedFetch(return attempt(isGet)}-/**- * Registry origin/gateway is unreachable (network refusal, timeout, or an- * upstream HTTP 5xx). A clean, user-safe error the global handler forwards as a- * 503 so the marketplace shows a clear message instead of a raw 500.- */-export class RegistryUnavailableError extends Error {- readonly status = 503- readonly code = 'registry_unavailable'- constructor(- message = 'The registry is currently unavailable. Check the connection and try again.'- ) {- super(message)- this.name = 'RegistryUnavailableError'- }-}-async function registryFetch<T>(path: string, init?: RequestInit): Promise<T> {let res: Responsetry {@@ -360,32 +379,50 @@ function buildQuery(params: Record<string, string | number | undefined | null>):* caller 500s.*/async function withReadThroughCache<T>(key: string, fetcher: () => Promise<T>): Promise<T> {- const hit = swrCache.get(key) as CacheEntry<T> | undefined- if (hit && Date.now() - hit.ts <= CATALOG_CACHE_TTL_MS) {- return hit.value- }- try {- const value = await fetcher()- swrCache.set(key, { value, ts: Date.now() })- return value- } catch (err) {- const cachedEntry = swrCache.get(key) as CacheEntry<T> | undefined- if (cachedEntry) {- const ageMs = Date.now() - cachedEntry.ts- logger.warn(- {- event: 'registry_stale_while_error',- key,- ageMs,- fresh: ageMs <= STALE_WHILE_ERROR_TTL_MS,- err: err instanceof Error ? err.message : String(err),- },- 'registry read failed; serving last-good cached value'- )- return cachedEntry.value- }- throw err- }+ return withCurrentRegistryIdentity(+ generation => {+ const hit = swrCache.get(key) as CacheEntry<T> | undefined+ if (hit?.generation === generation && Date.now() - hit.ts <= CATALOG_CACHE_TTL_MS) {+ return Promise.resolve(hit.value)+ }+ const pending = pendingSWRReads.get(key)+ if (pending?.generation === generation) return pending.promise as Promise<T>++ const promise = fetcher()+ .then(value => {+ if (isRegistryIdentityCacheGenerationCurrent(generation)) {+ swrCache.set(key, { value, ts: Date.now(), generation })+ }+ return value+ })+ .catch(err => {+ if (!isRegistryIdentityCacheGenerationCurrent(generation)) throw err+ const cachedEntry = swrCache.get(key) as CacheEntry<T> | undefined+ if (cachedEntry?.generation === generation) {+ const ageMs = Date.now() - cachedEntry.ts+ logger.warn(+ {+ event: 'registry_stale_while_error',+ key,+ ageMs,+ fresh: ageMs <= STALE_WHILE_ERROR_TTL_MS,+ err: err instanceof Error ? err.message : String(err),+ },+ 'registry read failed; serving last-good cached value'+ )+ return cachedEntry.value+ }+ throw err+ })+ .finally(() => {+ if (pendingSWRReads.get(key)?.promise === promise) pendingSWRReads.delete(key)+ })++ pendingSWRReads.set(key, { generation, promise })+ return promise+ },+ { staleError: staleRegistryIdentityError }+ )}/**@@ -395,7 +432,10 @@ async function withReadThroughCache<T>(key: string, fetcher: () => Promise<T>):* peers still converge within CATALOG_CACHE_TTL_MS.*/function invalidateCatalogCaches(): void {- for (const key of Object.values(CATALOG_CACHE_KEYS)) swrCache.delete(key)+ for (const key of Object.values(CATALOG_CACHE_KEYS)) {+ swrCache.delete(key)+ pendingSWRReads.delete(key)+ }}/** True for the default marketplace catalog landing query (limit:200, no filters). */@@ -648,6 +688,7 @@ export interface PublishScope {}let _scopeCache: { generation: number; scope: PublishScope } | null = null+let _scopePending: { generation: number; promise: Promise<PublishScope> } | null = nullexport async function whoami(): Promise<{clientId?: string@@ -659,26 +700,45 @@ export async function whoami(): Promise<{}export async function resolvePublishScope(opts?: { force?: boolean }): Promise<PublishScope> {- const cacheGeneration = getRegistryIdentityCacheGeneration()- if (_scopeCache && _scopeCache.generation === cacheGeneration && !opts?.force)- return _scopeCache.scope- const w = await whoami()- const scope = {- curator: w.curator,- orgName: w.orgName,- // Curator publishes stay unscoped (the registry maps them to @clerum).- // Org-bound clients MUST scope to their own org or the registry 400s- // (scope_required), so we derive the @<org> prefix here.- scope: w.curator || !w.orgName ? null : `@${w.orgName}`,- }- if (getRegistryIdentityCacheGeneration() === cacheGeneration) {- _scopeCache = { generation: cacheGeneration, scope }- }- return scope+ return withCurrentRegistryIdentity(+ generation => {+ if (_scopeCache && _scopeCache.generation === generation && !opts?.force)+ return Promise.resolve(_scopeCache.scope)+ const pending =+ !opts?.force && _scopePending?.generation === generation ? _scopePending : null+ if (pending) return pending.promise++ const promise = whoami().then(w => {+ const scope = {+ curator: w.curator,+ orgName: w.orgName,+ // Curator publishes stay unscoped (the registry maps them to @clerum).+ // Org-bound clients MUST scope to their own org or the registry 400s+ // (scope_required), so we derive the @<org> prefix here.+ scope: w.curator || !w.orgName ? null : `@${w.orgName}`,+ }+ if (isRegistryIdentityCacheGenerationCurrent(generation)) {+ _scopeCache = { generation, scope }+ }+ return scope+ })+ if (!opts?.force) {+ _scopePending = { generation, promise }+ void promise+ .finally(() => {+ if (_scopePending?.promise === promise) _scopePending = null+ })+ .catch(() => undefined)+ }+ return promise+ },+ { staleError: staleRegistryIdentityError }+ )}export function __resetScopeCacheForTests(): void {_scopeCache = null+ _scopePending = null}/**diff --git a/control-api/src/services/registryIdentityCache.ts b/control-api/src/services/registryIdentityCache.tsindex 2da1e6dcd..e2671fc1a 100644--- a/control-api/src/services/registryIdentityCache.ts+++ b/control-api/src/services/registryIdentityCache.ts@@ -1,5 +1,12 @@let registryIdentityCacheGeneration = 0+export class RegistryIdentityChangedError extends Error {+ constructor() {+ super('registry_identity_changed')+ this.name = 'RegistryIdentityChangedError'+ }+}+export function invalidateRegistryIdentityCaches(): void {registryIdentityCacheGeneration += 1}@@ -8,6 +15,26 @@ export function getRegistryIdentityCacheGeneration(): number {return registryIdentityCacheGeneration}+export function isRegistryIdentityCacheGenerationCurrent(generation: number): boolean {+ return registryIdentityCacheGeneration === generation+}++export async function withCurrentRegistryIdentity<T>(+ read: (generation: number) => Promise<T>,+ opts: { staleError?: () => Error } = {}+): Promise<T> {+ for (let attempt = 0; attempt < 2; attempt += 1) {+ const generation = getRegistryIdentityCacheGeneration()+ try {+ const value = await read(generation)+ if (isRegistryIdentityCacheGenerationCurrent(generation)) return value+ } catch (err) {+ if (isRegistryIdentityCacheGenerationCurrent(generation)) throw err+ }+ }+ throw opts.staleError?.() ?? new RegistryIdentityChangedError()+}+export function __resetRegistryIdentityCacheGenerationForTests(): void {registryIdentityCacheGeneration = 0}diff --git a/control-api/test/registryClient.test.ts b/control-api/test/registryClient.test.tsindex 5b711418a..3938dd6b6 100644--- a/control-api/test/registryClient.test.ts+++ b/control-api/test/registryClient.test.ts@@ -649,7 +649,7 @@ describe('registryClient — resolvePublishScope', () => {})})- it('prevents an older pending publish-scope request from overwriting a newer identity', async () => {+ it('does not return an older pending publish-scope result after identity invalidation', async () => {const staleWhoami = deferred<Response>()let tokenCalls = 0let whoamiCalls = 0@@ -685,14 +685,14 @@ describe('registryClient — resolvePublishScope', () => {headers: { 'content-type': 'application/json' },}))- expect(await staleRequest).toEqual({ curator: false, orgName: 'alpha', scope: '@alpha' })+ expect(await staleRequest).toEqual(freshScope)expect(await resolvePublishScope()).toEqual(freshScope)expect(tokenCalls).toBe(2)expect(whoamiCalls).toBe(2)})- it('prevents an older pending token mint from overwriting a newer token', async () => {+ it('does not return an older pending token mint after identity invalidation', async () => {const staleToken = deferred<Response>()let tokenCalls = 0const fetchMock = vi.fn().mockImplementation((url: string) => {@@ -710,11 +710,41 @@ describe('registryClient — resolvePublishScope', () => {await expect(mintToken(ENV_OVERRIDE)).resolves.toBe('tok-bravo')staleToken.resolve(fakeTokenResponse('tok-alpha', 600))- await expect(staleRequest).resolves.toBe('tok-alpha')+ await expect(staleRequest).resolves.toBe('tok-bravo')await expect(mintToken(ENV_OVERRIDE)).resolves.toBe('tok-bravo')expect(tokenCalls).toBe(2)})++ it('fails closed when identity changes again during a stale token retry', async () => {+ const staleToken = deferred<Response>()+ const retryToken = deferred<Response>()+ let tokenCalls = 0+ const fetchMock = vi.fn().mockImplementation((url: string) => {+ if (!url.endsWith('/oauth/token')) throw new Error(`unexpected fetch: ${url}`)+ tokenCalls += 1+ if (tokenCalls === 1) return staleToken.promise+ if (tokenCalls === 2) return retryToken.promise+ return Promise.resolve(fakeTokenResponse('tok-charlie', 600))+ })+ vi.stubGlobal('fetch', fetchMock)++ const staleRequest = mintToken(ENV_OVERRIDE)+ await waitUntil(() => tokenCalls === 1, 'stale token request did not start')++ invalidateRegistryIdentityCaches()+ staleToken.resolve(fakeTokenResponse('tok-alpha', 600))+ await waitUntil(() => tokenCalls === 2, 'stale token retry did not start')++ invalidateRegistryIdentityCaches()+ retryToken.resolve(fakeTokenResponse('tok-bravo', 600))++ await expect(staleRequest).rejects.toMatchObject({+ code: 'registry_unavailable',+ status: 503,+ })+ expect(tokenCalls).toBe(2)+ })})describe('registryClient — applyPublishScope', () => {@@ -829,6 +859,26 @@ describe('registryClient — catalog read-through cache', () => {expect(entryGets.length).toBe(1)})+ it('does not serve cached default catalog across registry identity invalidation', async () => {+ let entryCalls = 0+ const fetchMock = vi.fn().mockImplementation((url: string) => {+ if (url.endsWith('/oauth/token')) return Promise.resolve(fakeTokenResponse('tok', 600))+ entryCalls += 1+ return Promise.resolve(okSearch(entryCalls === 1 ? 'alpha' : 'bravo'))+ })+ vi.stubGlobal('fetch', fetchMock)+ Object.assign(process.env, ENV_OVERRIDE)++ const first = await searchEntries({ limit: 200 })+ expect(first.data).toEqual([{ name: 'alpha' }])++ invalidateRegistryIdentityCaches()++ const second = await searchEntries({ limit: 200 })+ expect(second.data).toEqual([{ name: 'bravo' }])+ expect(entryCalls).toBe(2)+ })+it('revalidates after the TTL expires and serves the fresh value', async () => {vi.useFakeTimers()let n = 0@@ -872,6 +922,76 @@ describe('registryClient — catalog read-through cache', () => {expect(catGets.length).toBe(1)})+ it('does not serve cached categories across registry identity invalidation', async () => {+ let categoryCalls = 0+ const fetchMock = vi.fn().mockImplementation((url: string) => {+ if (url.endsWith('/oauth/token')) return Promise.resolve(fakeTokenResponse('tok', 600))+ categoryCalls += 1+ return Promise.resolve(+ new Response(JSON.stringify({ data: categoryCalls === 1 ? ['alpha'] : ['bravo'] }), {+ status: 200,+ })+ )+ })+ vi.stubGlobal('fetch', fetchMock)+ Object.assign(process.env, ENV_OVERRIDE)++ await expect(getCategories()).resolves.toEqual({ data: ['alpha'] })+ invalidateRegistryIdentityCaches()+ await expect(getCategories()).resolves.toEqual({ data: ['bravo'] })+ expect(categoryCalls).toBe(2)+ })++ it('does not serve stale-while-error catalog data across identity invalidation', async () => {+ const fetchMock = vi.fn().mockImplementation((url: string) => {+ if (url.endsWith('/oauth/token')) return Promise.resolve(fakeTokenResponse('tok', 600))+ const entryCalls = fetchMock.mock.calls.filter(+ (c: unknown[]) => typeof c[0] === 'string' && (c[0] as string).includes('/entries')+ ).length+ return Promise.resolve(+ entryCalls <= 1 ? okSearch('alpha') : new Response('down', { status: 503 })+ )+ })+ vi.stubGlobal('fetch', fetchMock)+ Object.assign(process.env, ENV_OVERRIDE)++ await expect(searchEntries({ limit: 200 })).resolves.toMatchObject({+ data: [{ name: 'alpha' }],+ })+ invalidateRegistryIdentityCaches()++ await expect(searchEntries({ limit: 200 })).rejects.toMatchObject({+ code: 'registry_unavailable',+ status: 503,+ })+ })++ it('does not return or cache an older pending default catalog after invalidation', async () => {+ const staleCatalog = deferred<Response>()+ let entryCalls = 0+ const fetchMock = vi.fn().mockImplementation((url: string) => {+ if (url.endsWith('/oauth/token')) return Promise.resolve(fakeTokenResponse('tok', 600))+ entryCalls += 1+ if (entryCalls === 1) return staleCatalog.promise+ return Promise.resolve(okSearch('bravo'))+ })+ vi.stubGlobal('fetch', fetchMock)+ Object.assign(process.env, ENV_OVERRIDE)++ const staleRequest = searchEntries({ limit: 200 })+ await waitUntil(() => entryCalls === 1, 'stale catalog request did not start')++ invalidateRegistryIdentityCaches()++ const fresh = await searchEntries({ limit: 200 })+ expect(fresh.data).toEqual([{ name: 'bravo' }])++ staleCatalog.resolve(okSearch('alpha'))+ await expect(staleRequest).resolves.toEqual(fresh)+ await expect(searchEntries({ limit: 200 })).resolves.toEqual(fresh)+ expect(entryCalls).toBe(2)+ })+it('invalidates the catalog cache after a publish so the next catalog load refetches', async () => {const fetchMock = vi.fn().mockImplementation((url: string, init?: RequestInit) => {if (url.endsWith('/oauth/token')) return Promise.resolve(fakeTokenResponse('tok', 600))diff --git a/control-api/test/services.orgApiKeyClient.test.ts b/control-api/test/services.orgApiKeyClient.test.tsindex 294b0db4c..e2e6c4aa6 100644--- a/control-api/test/services.orgApiKeyClient.test.ts+++ b/control-api/test/services.orgApiKeyClient.test.ts@@ -1,5 +1,16 @@// control-api/test/services.orgApiKeyClient.test.tsimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import {+ RegistryStatusError,+ __resetUserTokenCacheForTests,+ createKey,+ listKeys,+ revokeKey,+} from '../src/services/orgApiKeyClient.js'+import {+ __resetRegistryIdentityCacheGenerationForTests,+ invalidateRegistryIdentityCaches,+} from '../src/services/registryIdentityCache.js'const { cfg, log } = vi.hoisted(() => ({cfg: { registryUrl: 'https://registry.test' },@@ -11,14 +22,6 @@ vi.mock('../src/services/registryVoucher.js', () => ({mintIdentityVoucher: vi.fn(() => 'voucher-jwt'),}))-import {- RegistryStatusError,- __resetUserTokenCacheForTests,- createKey,- listKeys,- revokeKey,-} from '../src/services/orgApiKeyClient.js'-const admin = { id: 'admin-1', username: 'alice' } as neverfunction makeRes(status: number, body?: unknown): Response {@@ -30,8 +33,27 @@ function makeRes(status: number, body?: unknown): Response {} as unknown as Response}+function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise+ reject = rejectPromise+ })+ return { promise, reject, resolve }+}++async function waitUntil(predicate: () => boolean, message: string): Promise<void> {+ for (let attempt = 0; attempt < 20; attempt += 1) {+ if (predicate()) return+ await new Promise(resolve => setImmediate(resolve))+ }+ throw new Error(message)+}+let fetchMock: ReturnType<typeof vi.fn>beforeEach(() => {+ __resetRegistryIdentityCacheGenerationForTests()__resetUserTokenCacheForTests()fetchMock = vi.fn()vi.stubGlobal('fetch', fetchMock)@@ -54,6 +76,82 @@ describe('orgApiKeyClient', () => {expect((lastInit.headers as Record<string, string>).Authorization).toBe('Bearer user-tok')})+ it('does not reuse a cached user token after registry identity invalidates', async () => {+ fetchMock+ .mockResolvedValueOnce(makeRes(200, { token: 'tok-alpha' })) // /user/exchange+ .mockResolvedValueOnce(makeRes(200, { keys: [] })) // GET alpha keys+ .mockResolvedValueOnce(makeRes(200, { token: 'tok-bravo' })) // /user/exchange after identity change+ .mockResolvedValueOnce(makeRes(200, { keys: [] })) // GET bravo keys++ await listKeys(admin, 'alpha')+ invalidateRegistryIdentityCaches()+ await listKeys(admin, 'bravo')++ const exchangeCalls = fetchMock.mock.calls.filter(c => String(c[0]).endsWith('/user/exchange'))+ expect(exchangeCalls).toHaveLength(2)+ const keyCalls = fetchMock.mock.calls.filter(c => String(c[0]).includes('/keys'))+ expect((keyCalls[0]![1]!.headers as Record<string, string>).Authorization).toBe(+ 'Bearer tok-alpha'+ )+ expect((keyCalls[1]![1]!.headers as Record<string, string>).Authorization).toBe(+ 'Bearer tok-bravo'+ )+ })++ it('does not cache or return a stale pending user-token exchange after invalidation', async () => {+ const staleExchange = deferred<Response>()+ let exchangeCalls = 0+ fetchMock.mockImplementation((url: string) => {+ if (url.endsWith('/user/exchange')) {+ exchangeCalls += 1+ if (exchangeCalls === 1) return staleExchange.promise+ return Promise.resolve(makeRes(200, { token: 'tok-bravo' }))+ }+ return Promise.resolve(makeRes(200, { keys: [] }))+ })++ const staleRequest = listKeys(admin, 'alpha')+ await waitUntil(() => exchangeCalls === 1, 'stale user-token exchange did not start')++ invalidateRegistryIdentityCaches()++ await listKeys(admin, 'bravo')+ staleExchange.resolve(makeRes(200, { token: 'tok-alpha' }))+ await expect(staleRequest).resolves.toEqual({ keys: [] })++ await listKeys(admin, 'bravo')+ const exchangeRequests = fetchMock.mock.calls.filter(c =>+ String(c[0]).endsWith('/user/exchange')+ )+ const keyRequests = fetchMock.mock.calls.filter(c => String(c[0]).includes('/keys'))+ expect(exchangeRequests).toHaveLength(2)+ expect(+ keyRequests.map(c => (c[1]!.headers as Record<string, string>).Authorization)+ ).not.toContain('Bearer tok-alpha')+ expect(keyRequests.at(-1)![1]!.headers).toMatchObject({ Authorization: 'Bearer tok-bravo' })+ })++ it('deduplicates same-generation pending user-token exchanges per admin', async () => {+ const exchange = deferred<Response>()+ fetchMock.mockImplementation((url: string) => {+ if (url.endsWith('/user/exchange')) return exchange.promise+ return Promise.resolve(makeRes(200, { keys: [] }))+ })++ const first = listKeys(admin, 'acme')+ const second = listKeys(admin, 'acme')+ await waitUntil(+ () => fetchMock.mock.calls.filter(c => String(c[0]).endsWith('/user/exchange')).length === 1,+ 'user-token exchange was not deduplicated'+ )++ exchange.resolve(makeRes(200, { token: 'tok-shared' }))+ await expect(Promise.all([first, second])).resolves.toEqual([{ keys: [] }, { keys: [] }])++ const exchangeCalls = fetchMock.mock.calls.filter(c => String(c[0]).endsWith('/user/exchange'))+ expect(exchangeCalls).toHaveLength(1)+ })+it('on a gated-endpoint 401, evicts + re-exchanges once then retries', async () => {fetchMock.mockResolvedValueOnce(makeRes(200, { token: 'tok-1' })) // exchange #1@@ -92,7 +190,11 @@ describe('orgApiKeyClient', () => {message: 'registry_integration_error',})expect(log.error).toHaveBeenCalledWith(- expect.objectContaining({ event: 'registry_exchange_failed', status: 409, code: 'reserved_username' }),+ expect.objectContaining({+ event: 'registry_exchange_failed',+ status: 409,+ code: 'reserved_username',+ }),expect.any(String))})@@ -109,11 +211,15 @@ describe('orgApiKeyClient', () => {})it('createKey returns the one-time key payload verbatim', async () => {- fetchMock- .mockResolvedValueOnce(makeRes(200, { token: 'tok' }))- .mockResolvedValueOnce(- makeRes(201, { id: 'k1', key: 'efrk_secret', key_prefix: 'efrk_sec', scopes: [], expires_at: null })- )+ fetchMock.mockResolvedValueOnce(makeRes(200, { token: 'tok' })).mockResolvedValueOnce(+ makeRes(201, {+ id: 'k1',+ key: 'efrk_secret',+ key_prefix: 'efrk_sec',+ scopes: [],+ expires_at: null,+ })+ )const out = await createKey(admin, 'acme', { description: 'ci' })expect(out.key).toBe('efrk_secret')})