Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(external-rest-api): classify upstream credential errors
Josué5012e9ab7755
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 39ae925e3..3d59738d0 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.747",+ "version": "0.1.748","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.747",+ "version": "0.1.748","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex a945ea8ab..5536d5d8b 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.747",+ "version": "0.1.748","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/external/invitations.ts b/control-api/src/routes/external/invitations.tsindex 996af8185..cfa94ff0b 100644--- a/control-api/src/routes/external/invitations.ts+++ b/control-api/src/routes/external/invitations.ts@@ -135,7 +135,7 @@ export function createExternalInvitationsRouter(): Router {return res.status(410).json({ error: 'expired' })}if (result.error === 'user_retired') {- return res.status(401).json({ error: 'Unauthorized' })+ return res.status(401).json({ error: 'user_retired' })}return res.status(400).json({ error: 'invalid_password' })}@@ -203,7 +203,7 @@ export function createExternalInvitationsRouter(): Router {return res.status(410).json({ error: 'expired' })}if (result.error === 'user_retired') {- return res.status(401).json({ error: 'Unauthorized' })+ return res.status(401).json({ error: 'user_retired' })}return res.status(400).json({ error: 'invalid_password' })}diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.jsonindex a18c48b56..086e1bbec 100644--- a/external-rest-api/package-lock.json+++ b/external-rest-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-external-rest-api",- "version": "0.1.108",+ "version": "0.1.109","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-external-rest-api",- "version": "0.1.108",+ "version": "0.1.109","dependencies": {"@clerum/jwt-key-policy": "file:../packages/jwt-key-policy","cors": "^2.8.5",diff --git a/external-rest-api/package.json b/external-rest-api/package.jsonindex 994f8bf49..7b8618c75 100644--- a/external-rest-api/package.json+++ b/external-rest-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-external-rest-api",- "version": "0.1.108",+ "version": "0.1.109","description": "External REST API for profile, team management, and RPC token brokerage","main": "dist/main.js","engines": {diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.tsindex 2d5928b4b..49132fa20 100644--- a/external-rest-api/src/releaseManifest.ts+++ b/external-rest-api/src/releaseManifest.ts@@ -8,7 +8,7 @@ export type ReleaseManifest = {export const releaseManifest: ReleaseManifest = {releaseId: 'v0.10.0',- externalRestApiVersion: '0.1.108',+ externalRestApiVersion: '0.1.109',rpcProxyVersion: '0.1.126',desktopVersion: '0.10.0',minimumDesktopVersion: '0.1.252',diff --git a/external-rest-api/src/services/invitationsService.ts b/external-rest-api/src/services/invitationsService.tsindex dca50f485..eb6af9468 100644--- a/external-rest-api/src/services/invitationsService.ts+++ b/external-rest-api/src/services/invitationsService.ts@@ -14,6 +14,27 @@ type ResetPasswordDomainError =| 'invalid_invitation'| 'invalid_password'+function invitationPasswordDomainError(+ error: ControlApiError+):+ | 'not_found'+ | 'forbidden'+ | 'not_accepted'+ | 'not_pending'+ | 'expired'+ | 'invalid_password'+ | null {+ const code = controlApiErrorCode(error)+ if (error.status === 400 && code === 'invalid_password') return 'invalid_password'+ if (error.status === 401 && code === 'user_retired') return 'not_found'+ if (error.status === 403 && code === 'forbidden') return 'forbidden'+ if (error.status === 404 && code === 'not_found') return 'not_found'+ if (error.status === 409 && code === 'invitation_not_accepted') return 'not_accepted'+ if (error.status === 409 && code === 'invitation_not_pending') return 'not_pending'+ if (error.status === 410 && code === 'expired') return 'expired'+ return null+}+function controlApiErrorCode(error: ControlApiError): string | null {if (error.body !== null &&@@ -30,6 +51,7 @@ function resetPasswordDomainError(error: ControlApiError): ResetPasswordDomainErconst code = controlApiErrorCode(error)if (error.status === 400 && code === 'invalid_password') return 'invalid_password'if (error.status === 400 && code === 'invalid_invitation') return 'invalid_invitation'+ if (error.status === 401 && code === 'user_retired') return 'invalid_invitation'if (error.status === 403 && code === 'forbidden') return 'forbidden'if (error.status === 404 && code === 'not_found') return 'not_found'if (@@ -51,6 +73,15 @@ function unknownRecoveryOutcome(): ControlApiError {)}+function passwordAuthorityUnavailable(): ControlApiError {+ return new ControlApiError(+ 'Password recovery authority unavailable',+ 503,+ { error: 'authority_unavailable' },+ { 'retry-after': '2' }+ )+}+export type InvitationPreview = {id: stringteamId: string | null@@ -146,9 +177,15 @@ export async function createDesktopAuthorization(return { data }} catch (error) {if (error instanceof ControlApiError && [429, 503].includes(error.status)) throw error- const message = error instanceof Error ? error.message : ''- if (message.includes('(404)')) return { error: 'not_found' }- return { error: 'invalid_password' }+ if (error instanceof ControlApiError) {+ if (error.status === 404 && controlApiErrorCode(error) === 'not_found') {+ return { error: 'not_found' }+ }+ if (error.status === 401 && controlApiErrorCode(error) === 'invalid_password') {+ return { error: 'invalid_password' }+ }+ }+ throw passwordAuthorityUnavailable()}}@@ -196,12 +233,11 @@ export async function setupInvitationPassword(return { data }} catch (error) {if (error instanceof ControlApiError && [429, 503].includes(error.status)) throw error- const message = error instanceof Error ? error.message : ''- if (message.includes('(404)')) return { error: 'not_found' }- if (message.includes('(403)')) return { error: 'forbidden' }- if (message.includes('(409)')) return { error: 'not_accepted' }- if (message.includes('(410)')) return { error: 'expired' }- return { error: 'invalid_password' }+ if (error instanceof ControlApiError) {+ const domainError = invitationPasswordDomainError(error)+ if (domainError) return { error: domainError }+ }+ throw passwordAuthorityUnavailable()}}@@ -233,7 +269,7 @@ export async function setupInvitationPasswordWithToken(if (error instanceof ControlApiError) {const domainError = resetPasswordDomainError(error)if (domainError) return { error: domainError }- if (error.status < 500) return { error: 'invalid_invitation' }+ if (error.status < 500) throw passwordAuthorityUnavailable()}throw unknownRecoveryOutcome()}diff --git a/external-rest-api/test/r2m6.resetUnknownControlApi4xx.contract.test.ts b/external-rest-api/test/r2m6.resetUnknownControlApi4xx.contract.test.tsnew file mode 100644index 000000000..de4ca936d--- /dev/null+++ b/external-rest-api/test/r2m6.resetUnknownControlApi4xx.contract.test.ts@@ -0,0 +1,121 @@+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import express from 'express'+import { generateKeyPairSync } from 'node:crypto'+import type { Server } from 'node:http'+import { config as externalConfig } from '../src/config.js'+import {+ createDesktopAuthorization,+ setupInvitationPassword,+ setupInvitationPasswordWithToken,+} from '../src/services/invitationsService.js'++describe('reset consumer handling of unexpected Control API 4xx responses', () => {+ const controlServiceToken = `synthetic-control-service-${'x'.repeat(24)}`+ let server: Server+ let previousBaseUrl: string+ let previousServiceToken: string+ let controlConfig: (typeof import('../../control-api/src/config.js'))['config']+ let previousInternalServiceTokens: Record<string, string>++ beforeAll(async () => {+ previousBaseUrl = externalConfig.controlApiBaseUrl+ previousServiceToken = externalConfig.controlApiServiceToken+ const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 })+ const privateKeyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString()+ vi.stubEnv('CONTROL_API_RPC_JWT_PRIVATE_KEY', privateKeyPem)+ vi.stubEnv('CONTROL_API_SESSION_JWT_PRIVATE_KEY', privateKeyPem)+ vi.stubEnv('CONTROL_API_ADMIN_JWT_PRIVATE_KEY', privateKeyPem)+ vi.resetModules()+ controlConfig = (await import('../../control-api/src/config.js')).config+ const { requireInternalToken } =+ await import('../../control-api/src/middleware/internalServiceAuth.js')+ previousInternalServiceTokens = controlConfig.internalServiceTokens+ controlConfig.internalServiceTokens = {}++ const controlApp = express()+ controlApp.use(express.json())+ controlApp.use(requireInternalToken)+ controlApp.post('/api/v1/external/invitations/password-token', (_req, res) => {+ res.status(200).json({ passwordUpdated: true })+ })+ server = controlApp.listen(0, '127.0.0.1')+ await new Promise<void>(resolve => server.once('listening', resolve))++ externalConfig.controlApiBaseUrl = `http://127.0.0.1:${(server.address() as { port: number }).port}/api/v1`+ externalConfig.controlApiServiceToken = controlServiceToken+ })++ afterAll(async () => {+ externalConfig.controlApiBaseUrl = previousBaseUrl+ externalConfig.controlApiServiceToken = previousServiceToken+ controlConfig.internalServiceTokens = previousInternalServiceTokens+ if (server) {+ await new Promise<void>((resolve, reject) =>+ server.close(error => (error ? reject(error) : resolve()))+ )+ }+ vi.unstubAllEnvs()+ })++ it('treats a real internal-service 401 as a sanitized authority outage', async () => {+ const outcome = await setupInvitationPasswordWithToken(+ 'Synthetic-Recovery-Proof',+ '[email protected]',+ 'synthetic-reset-row',+ 'Synthetic-New-Password-123'+ ).then(+ value => ({ value }),+ error => ({ error })+ )++ expect(outcome).toMatchObject({+ error: {+ status: 503,+ body: { error: 'authority_unavailable' },+ headers: { 'retry-after': '2' },+ },+ })+ if ('error' in outcome) {+ expect(outcome.error.message).not.toMatch(/Unauthorized|api\/v1|Synthetic-Recovery-Proof/)+ expect(JSON.stringify(outcome.error.body)).not.toMatch(+ /Unauthorized|member@example|synthetic/+ )+ }+ })++ it('applies the same operational fallback to the other password consumers', async () => {+ const auth = {+ userId: 'synthetic-user-id',+ email: '[email protected]',+ sessionToken: 'synthetic-session-token',+ }+ const acceptedInvitation = await setupInvitationPassword(+ auth,+ 'synthetic-invitation-row',+ 'Synthetic-New-Password-123'+ ).then(+ value => ({ value }),+ error => ({ error })+ )+ const desktopAuthorization = await createDesktopAuthorization(+ auth,+ 'Synthetic-Current-Password-123'+ ).then(+ value => ({ value }),+ error => ({ error })+ )++ for (const outcome of [acceptedInvitation, desktopAuthorization]) {+ expect(outcome).toMatchObject({+ error: {+ status: 503,+ body: { error: 'authority_unavailable' },+ headers: { 'retry-after': '2' },+ },+ })+ if ('error' in outcome) {+ expect(outcome.error.message).not.toMatch(/Unauthorized|api\/v1|synthetic/i)+ }+ }+ })+})