Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): close negative-cache bypass paths and boot-enrollment liveness risk
Jose Ramireza6d694b40806
diff --git a/control-api/src/main.ts b/control-api/src/main.tsindex 32e11335c..a7e3341b0 100644--- a/control-api/src/main.ts+++ b/control-api/src/main.ts@@ -51,10 +51,6 @@ async function main(): Promise<void> {// self-hosted deployment that has no registry_connection identity row.await assertRegistryConnectionReady()- // Hosted member-registration self-enrollment (spec §8.4): degrade, never- // block — runBootEnrollment never rejects; failures log and retry on demand.- await runBootEnrollment()-startExpiryCron(config.userApprovalRequestExpiryIntervalMs)startPluginWorkloadSdkMaintenanceCron()startRateLimiterCleanup(config.approvalRlCleanupIntervalMs)@@ -128,6 +124,16 @@ async function main(): Promise<void> {await server.start()console.log('[ControlAPI] Running')++ // Hosted member-registration self-enrollment (spec §8.4): degrade, never+ // block. Fire-and-forget, and only AFTER the listener is up — the liveness+ // probe has no startupProbe grace (control-api.yaml: initialDelaySeconds=8,+ // periodSeconds=12, failureThreshold=3 ≈ 32s), and a silently dropped hub+ // (egress firewall / default-deny NetworkPolicy) can burn up to 20s of that+ // budget on its own. Nothing is gained by awaiting it here: the hook never+ // rejects, every send re-attempts enrollment on demand via ensureEnrollment,+ // and the in-flight map dedupes any request that races this boot call.+ void runBootEnrollment()}main().catch(error => {diff --git a/control-api/src/routes/external/invitations.ts b/control-api/src/routes/external/invitations.tsindex d16d21e56..078b41cf0 100644--- a/control-api/src/routes/external/invitations.ts+++ b/control-api/src/routes/external/invitations.ts@@ -207,6 +207,7 @@ export function createExternalInvitationsRouter(): Router {try {await storeDesktopAuthorizationToken(email, authorizationToken)} catch (error) {+ if (memberRegistrationErrorResponse(error)) throw errorconst message = error instanceof Error ? error.message : ''if (message.includes('(404)')) {return res.status(404).json({ error: 'not_found' })diff --git a/control-api/src/services/memberRegistrationEnrollment.ts b/control-api/src/services/memberRegistrationEnrollment.tsindex ab35ac15f..06f9ed4a1 100644--- a/control-api/src/services/memberRegistrationEnrollment.ts+++ b/control-api/src/services/memberRegistrationEnrollment.ts@@ -110,7 +110,15 @@ async function enroll(domain: string): Promise<MemberRegistrationCredential> {throw transientFailure(domain, `member-registration hub error (${response.status})`)}- const minted = (await response.json()) as { tenantId?: unknown; kid?: unknown; secret?: unknown }+ let minted: { tenantId?: unknown; kid?: unknown; secret?: unknown }+ try {+ minted = (await response.json()) as { tenantId?: unknown; kid?: unknown; secret?: unknown }+ } catch {+ // Log hygiene: fixed message only — never fold the caught parse error's+ // text in here, since a JSON.parse SyntaxError can echo body content and+ // the mint body carries the secret.+ throw transientFailure(domain, 'member-registration hub returned an unparseable mint response')+ }if (typeof minted.tenantId !== 'string' ||typeof minted.kid !== 'string' ||@@ -124,13 +132,22 @@ async function enroll(domain: string): Promise<MemberRegistrationCredential> {// forever instead of escalating toward BACKOFF_CAP_MS.consecutiveTransientFailures.delete(domain)- const { inserted } = await insertMemberRegistrationCredential({- boundDomain: domain,- tenantId: minted.tenantId,- kid: minted.kid,- secret: minted.secret,- })- const winner = await getActiveMemberRegistrationCredential(domain)+ let inserted: boolean+ let winner: MemberRegistrationCredential | null+ try {+ ;({ inserted } = await insertMemberRegistrationCredential({+ boundDomain: domain,+ tenantId: minted.tenantId,+ kid: minted.kid,+ secret: minted.secret,+ }))+ winner = await getActiveMemberRegistrationCredential(domain)+ } catch {+ // Same bypass risk as the parse failure above: a persistence throw here+ // (e.g. Postgres unreachable) must not escape untyped, or every+ // subsequent request re-mints a fresh hub credential (an orphan storm).+ throw transientFailure(domain, 'failed to persist the minted credential')+ }if (!winner) {throw transientFailure(domain, 'credential row missing after insert')}diff --git a/control-api/test/routes.externalInvitations.unavailable.test.ts b/control-api/test/routes.externalInvitations.unavailable.test.tsindex 2d4a35371..2ea8607e8 100644--- a/control-api/test/routes.externalInvitations.unavailable.test.ts+++ b/control-api/test/routes.externalInvitations.unavailable.test.ts@@ -89,4 +89,35 @@ describe('external invitation routes when the hub is unavailable', () => {expect(res.status).toBe(400)expect(res.body.error).toBe('invalid_invitation')})++ it('POST desktop-authorization returns 503, NOT 404, when the hub-rejection message shape collides with the "(404)" not_found string match', async () => {+ // enroll() builds messages like `...rejected enrollment for '<domain>'+ // (${response.status})`. A hub 404 during boot/on-demand enrollment+ // therefore produces a MemberRegistrationUnavailableError whose message+ // contains the literal substring "(404)" — the same substring this+ // route's catch used to key off of to detect an invitation 404. Without+ // the memberRegistrationErrorResponse guard, this typed 503 gets+ // misclassified as a 404 invitation lookup failure.+ directory.verifyUserPassword.mockResolvedValue(true)+ flow.storeDesktopAuthorizationToken.mockRejectedValue(+ new MemberRegistrationUnavailableError(+ "member-registration hub rejected enrollment for 'x.acme.com' (404)"+ )+ )+ const res = await request(app())+ .post('/external/invitations/desktop-authorization')+ .send({ userId: 'u1', email: '[email protected]', password: 'pw' })+ expect(res.status).toBe(503)+ expect(res.body.error).toBe('member_registration_unavailable')+ })++ it('REGRESSION: POST desktop-authorization still maps a generic upstream 404 message to 404 not_found', async () => {+ directory.verifyUserPassword.mockResolvedValue(true)+ flow.storeDesktopAuthorizationToken.mockRejectedValue(new Error('upstream responded (404)'))+ const res = await request(app())+ .post('/external/invitations/desktop-authorization')+ .send({ userId: 'u1', email: '[email protected]', password: 'pw' })+ expect(res.status).toBe(404)+ expect(res.body.error).toBe('not_found')+ })})diff --git a/control-api/test/services.memberRegistrationEnrollment.test.ts b/control-api/test/services.memberRegistrationEnrollment.test.tsindex ce8445ce1..a278635cf 100644--- a/control-api/test/services.memberRegistrationEnrollment.test.ts+++ b/control-api/test/services.memberRegistrationEnrollment.test.ts@@ -243,6 +243,47 @@ describe('memberRegistrationEnrollment', () => {expect(fetchMock).toHaveBeenCalledTimes(3)})+ it('negative-caches a 200 response with an unparseable body (proxy/WAF page) instead of re-minting every request', async () => {+ // response.json() throws SyntaxError on a non-JSON 200 body. Before the+ // fix this escaped enroll() untyped and unguarded — no negative-cache+ // entry, so every subsequent request re-minted (the exact amplifier the+ // cache exists to prevent).+ const fetchMock = vi+ .fn()+ .mockResolvedValue(new Response('<html>proxy error</html>', { status: 200 }))+ vi.stubGlobal('fetch', fetchMock)+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(+ MemberRegistrationUnavailableError+ )+ expect(fetchMock).toHaveBeenCalledTimes(1)+ // Second immediate call must be served from the negative cache, not re-fetch.+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(+ MemberRegistrationUnavailableError+ )+ expect(fetchMock).toHaveBeenCalledTimes(1)+ // Log hygiene: the parse error must never echo the raw body.+ expect(logSink.lines.join('\n')).not.toContain('<html>')+ expect(logSink.lines.join('\n')).not.toContain('proxy error')+ })++ it('negative-caches a persistence failure after a successful mint instead of re-minting a fresh hub credential every request', async () => {+ // insertMemberRegistrationCredential throwing (e.g. Postgres unreachable)+ // after a successful mint was unguarded before the fix — every subsequent+ // request would mint a brand-new hub credential (an orphan mint storm).+ const fetchMock = vi.fn().mockResolvedValue(mintResponse())+ vi.stubGlobal('fetch', fetchMock)+ store.insertMemberRegistrationCredential.mockRejectedValue(new Error('pg down'))+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(+ MemberRegistrationUnavailableError+ )+ expect(fetchMock).toHaveBeenCalledTimes(1)+ // Second immediate call must be served from the negative cache, not re-mint.+ await expect(ensureEnrollment('profile.acme.com')).rejects.toBeInstanceOf(+ MemberRegistrationUnavailableError+ )+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })+it('rejects localhost / IP-literal / dotless hosts with the misconfiguration error, never fetching', async () => {const fetchMock = vi.fn()vi.stubGlobal('fetch', fetchMock)