Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(external-rest-api): classify credential transport outcomes (R13-8)

Josué04a08f64e2c5
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index 4030250c5..057ddd9a3 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.126",
+ "version": "0.1.127",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.126",
+ "version": "0.1.127",
"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.json
index 0909094f9..e313914d5 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.126",
+ "version": "0.1.127",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --git a/external-rest-api/src/controlApiClient.ts b/external-rest-api/src/controlApiClient.ts
index f843923f2..edc359423 100644
--- a/external-rest-api/src/controlApiClient.ts
+++ b/external-rest-api/src/controlApiClient.ts
@@ -52,6 +52,26 @@ export class ControlApiError extends Error {
}
}
+export type ControlApiTransportOperation = 'read' | 'mutation'
+export type ControlApiTransportPhase = 'dispatch' | 'response'
+
+export class ControlApiTransportError extends Error {
+ constructor(
+ readonly operation: ControlApiTransportOperation,
+ readonly phase: ControlApiTransportPhase
+ ) {
+ super('Control API transport failed')
+ this.name = 'ControlApiTransportError'
+ }
+}
+
+export class ControlApiUnexpectedResponseError extends Error {
+ constructor() {
+ super('Control API returned an unsupported response')
+ this.name = 'ControlApiUnexpectedResponseError'
+ }
+}
+
function forwardableResponseHeaders(response: Response): Record<string, string> {
const headers: Record<string, string> = {}
for (const name of FORWARDABLE_RESPONSE_HEADERS) {
@@ -113,13 +133,23 @@ export async function controlApiRequestWithStatus<T>(
Object.assign(headers, options.extraHeaders)
}
- const response = await fetch(buildUrl(path, options?.query), {
- method,
- headers,
- body: options?.body !== undefined ? JSON.stringify(options.body) : undefined,
- })
+ const url = buildUrl(path, options?.query)
+ const body = options?.body !== undefined ? JSON.stringify(options.body) : undefined
+ const operation: ControlApiTransportOperation =
+ method === 'GET' || method === 'HEAD' ? 'read' : 'mutation'
+ let response: Response
+ try {
+ response = await fetch(url, { method, headers, body })
+ } catch {
+ throw new ControlApiTransportError(operation, 'dispatch')
+ }
- const raw = await response.text()
+ let raw: string
+ try {
+ raw = await response.text()
+ } catch {
+ throw new ControlApiTransportError(operation, 'response')
+ }
let parsed: unknown = null
let parseError = false
if (raw) {
diff --git a/external-rest-api/src/http/passwordAdmissionError.ts b/external-rest-api/src/http/passwordAdmissionError.ts
index 638cdb3ec..7a3bc1d9f 100644
--- a/external-rest-api/src/http/passwordAdmissionError.ts
+++ b/external-rest-api/src/http/passwordAdmissionError.ts
@@ -1,5 +1,9 @@
import type { ErrorRequestHandler, Response } from 'express'
-import { ControlApiError } from '../controlApiClient.js'
+import {
+ ControlApiError,
+ ControlApiTransportError,
+ ControlApiUnexpectedResponseError,
+} from '../controlApiClient.js'
function sendPublicPasswordAuthorityError(
res: Response,
@@ -28,7 +32,19 @@ function sendPublicPasswordAuthorityError(
/** Only the bounded public authority contract crosses this credential seam. */
export function sendPasswordAuthorityError(error: unknown, res: Response): boolean {
- if (!(error instanceof ControlApiError)) return false
+ if (error instanceof ControlApiTransportError) {
+ sendPublicPasswordAuthorityError(res, 503, 'authority_unavailable')
+ return true
+ }
+ if (error instanceof ControlApiUnexpectedResponseError) {
+ res.status(502).json({ error: 'Password recovery service returned an invalid response' })
+ return true
+ }
+ if (!(error instanceof ControlApiError)) {
+ if (!(error instanceof Error)) return false
+ res.status(500).json({ error: 'Internal Server Error' })
+ return true
+ }
if (error.status === 429) {
sendPublicPasswordAuthorityError(res, 429, 'rate_limited', error.headers['retry-after'])
return true
@@ -57,14 +73,14 @@ export function sendPasswordAuthorityError(error: unknown, res: Response): boole
export const invitationPasswordErrorHandler: ErrorRequestHandler = (error, _req, res, next) => {
if (sendPasswordAuthorityError(error, res)) return
- if (error instanceof TypeError) {
- sendPasswordAuthorityUnavailable(res)
- return
- }
if (error instanceof ControlApiError) {
res.status(error.status).json({ error: 'Invitation is invalid or unavailable' })
return
}
+ if (error instanceof Error) {
+ res.status(500).json({ error: 'Internal Server Error' })
+ return
+ }
next(error)
}
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index cd50a6b45..3fde82d9d 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.11.0',
- externalRestApiVersion: '0.1.126',
+ externalRestApiVersion: '0.1.127',
rpcProxyVersion: '0.1.126',
desktopVersion: '0.11.0',
minimumDesktopVersion: '0.1.252',
diff --git a/external-rest-api/src/services/invitationPasswordService.ts b/external-rest-api/src/services/invitationPasswordService.ts
index fa2621b78..0f64ec5f0 100644
--- a/external-rest-api/src/services/invitationPasswordService.ts
+++ b/external-rest-api/src/services/invitationPasswordService.ts
@@ -1,4 +1,9 @@
-import { ControlApiError, controlApiRequest } from '../controlApiClient.js'
+import {
+ ControlApiError,
+ ControlApiTransportError,
+ ControlApiUnexpectedResponseError,
+ controlApiRequest,
+} from '../controlApiClient.js'
import type { InvitationPreview } from './invitationsService.js'
type AuthContext = {
@@ -101,12 +106,15 @@ export async function setupInvitationPassword(
)
return { data }
} catch (error) {
+ if (error instanceof ControlApiTransportError) throw passwordAuthorityUnavailable()
if (error instanceof ControlApiError && [429, 503].includes(error.status)) throw error
if (error instanceof ControlApiError) {
const domainError = invitationPasswordDomainError(error)
if (domainError) return { error: domainError }
+ if (error.status >= 500) throw passwordAuthorityUnavailable()
+ throw new ControlApiUnexpectedResponseError()
}
- throw passwordAuthorityUnavailable()
+ throw error
}
}
@@ -134,12 +142,20 @@ export async function setupInvitationPasswordWithToken(
})
return { data }
} catch (error) {
- if (error instanceof ControlApiError && [429, 503].includes(error.status)) throw error
+ if (error instanceof ControlApiTransportError) throw unknownRecoveryOutcome()
+ if (error instanceof ControlApiError && error.status === 429) throw error
if (error instanceof ControlApiError) {
+ if (
+ error.status === 503 &&
+ (error.code === 'authority_unavailable' || error.code === 'recovery_outcome_unknown')
+ ) {
+ throw error
+ }
const domainError = resetPasswordDomainError(error)
if (domainError) return { error: domainError }
- if (error.status < 500) throw passwordAuthorityUnavailable()
+ if (error.status >= 500) throw unknownRecoveryOutcome()
+ throw new ControlApiUnexpectedResponseError()
}
- throw unknownRecoveryOutcome()
+ throw error
}
}
diff --git a/external-rest-api/test/controlApiClient.test.ts b/external-rest-api/test/controlApiClient.test.ts
index b60794edf..dc330eddf 100644
--- a/external-rest-api/test/controlApiClient.test.ts
+++ b/external-rest-api/test/controlApiClient.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
ControlApiError,
+ ControlApiTransportError,
controlApiBinaryRequestWithStatus,
controlApiRequest,
controlApiRequestWithStatus,
@@ -38,6 +39,18 @@ async function captureError(work: () => Promise<unknown>): Promise<ControlApiErr
throw new Error('expected control-api request to reject')
}
+async function captureTransportError(
+ work: () => Promise<unknown>
+): Promise<ControlApiTransportError> {
+ try {
+ await work()
+ } catch (error) {
+ expect(error).toBeInstanceOf(ControlApiTransportError)
+ return error as ControlApiTransportError
+ }
+ throw new Error('expected control-api transport request to reject')
+}
+
describe('controlApiClient error headers', () => {
afterEach(() => vi.unstubAllGlobals())
@@ -74,6 +87,44 @@ describe('ControlApiError.code', () => {
})
})
+describe('controlApiClient transport classification', () => {
+ afterEach(() => vi.unstubAllGlobals())
+
+ it('classifies rejected GET dispatch as a read without exposing the transport error', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('private URL and token')))
+
+ const error = await captureTransportError(() =>
+ controlApiRequestWithStatus('GET', '/external/invitations/token/proof')
+ )
+
+ expect(error.operation).toBe('read')
+ expect(error.phase).toBe('dispatch')
+ expect(error.message).not.toContain('private URL')
+ expect(error.message).not.toContain('token')
+ })
+
+ it('classifies a rejected mutation response read without exposing its body error', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ text: vi.fn().mockRejectedValue(new Error('private proof body')),
+ })
+ )
+
+ const error = await captureTransportError(() =>
+ controlApiRequestWithStatus('POST', '/external/invitations/password-token', {
+ body: { token: 'synthetic-proof' },
+ })
+ )
+
+ expect(error.operation).toBe('mutation')
+ expect(error.phase).toBe('response')
+ expect(error.message).not.toContain('private proof')
+ })
+})
+
describe('controlApiClient request identity', () => {
afterEach(() => vi.unstubAllGlobals())
diff --git a/external-rest-api/test/invitations.passwordRecovery.public.test.ts b/external-rest-api/test/invitations.passwordRecovery.public.test.ts
index 61c7ad4da..3c262ae10 100644
--- a/external-rest-api/test/invitations.passwordRecovery.public.test.ts
+++ b/external-rest-api/test/invitations.passwordRecovery.public.test.ts
@@ -22,6 +22,7 @@ describe('password reset preview authority failures', () => {
afterEach(async () => {
config.controlApiBaseUrl = previousControlApiBaseUrl
config.controlApiServiceToken = previousControlApiServiceToken
+ vi.unstubAllGlobals()
if (upstream?.listening) {
await new Promise<void>((resolve, reject) =>
upstream!.close(error => (error ? reject(error) : resolve()))
@@ -49,6 +50,15 @@ describe('password reset preview authority failures', () => {
})
}
+ async function submitDedicatedReset() {
+ return request(createApp()).post('/api/v1/invitations/password-reset').send({
+ token: recoveryProof,
+ email: '[email protected]',
+ invitationId: '00000000-0000-4000-8000-000000000001',
+ password: 'Synthetic-Replacement-Password-123',
+ })
+ }
+
async function lookupInvitation() {
return request(createApp()).get(`/api/v1/invitations/token/${recoveryProof}`)
}
@@ -116,6 +126,78 @@ describe('password reset preview authority failures', () => {
expect(response.headers['retry-after']).toBe('2')
expect(requestedPath).toContain(encodeURIComponent(recoveryProof))
})
+
+ it('keeps a reset dispatch failure unknown and never retries the one-use proof', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockRejectedValue(new TypeError('private producer URL and signed proof'))
+ vi.stubGlobal('fetch', fetchMock)
+ config.controlApiBaseUrl = 'http://control-api.example.invalid/api/v1'
+
+ const response = await submitDedicatedReset()
+
+ expect(response.status).toBe(503)
+ expect(response.body).toEqual({ error: 'recovery_outcome_unknown', retryAfterSeconds: 2 })
+ expect(response.headers['retry-after']).toBe('2')
+ expect(response.headers['set-cookie']).toBeUndefined()
+ expect(response.text).not.toContain('private producer URL')
+ expect(response.text).not.toContain(recoveryProof)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps an unread reset response unknown without replaying the mutation', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ text: vi.fn().mockRejectedValue(new Error('private response proof')),
+ })
+ vi.stubGlobal('fetch', fetchMock)
+ config.controlApiBaseUrl = 'http://control-api.example.invalid/api/v1'
+
+ const response = await submitDedicatedReset()
+
+ expect(response.status).toBe(503)
+ expect(response.body).toEqual({ error: 'recovery_outcome_unknown', retryAfterSeconds: 2 })
+ expect(response.headers['retry-after']).toBe('2')
+ expect(response.headers['set-cookie']).toBeUndefined()
+ expect(response.text).not.toContain('private response proof')
+ expect(response.text).not.toContain(recoveryProof)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('sanitizes an unrecognized producer client response without a retry hint', async () => {
+ await startUpstream((_req, res) => {
+ res.writeHead(400, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ error: 'invalid payload', detail: 'private producer data' }))
+ })
+
+ const response = await submitDedicatedReset()
+
+ expect(response.status).toBe(502)
+ expect(response.body).toEqual({
+ error: 'Password recovery service returned an invalid response',
+ })
+ expect(response.headers['retry-after']).toBeUndefined()
+ expect(response.headers['set-cookie']).toBeUndefined()
+ expect(response.text).not.toContain('private producer data')
+ expect(response.text).not.toContain(recoveryProof)
+ })
+
+ it('returns a sanitized nonretryable error when request construction fails before dispatch', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ config.controlApiBaseUrl = 'not a valid URL'
+
+ const response = await submitDedicatedReset()
+
+ expect(response.status).toBe(500)
+ expect(response.body).toEqual({ error: 'Internal Server Error' })
+ expect(response.headers['retry-after']).toBeUndefined()
+ expect(response.headers['set-cookie']).toBeUndefined()
+ expect(response.text).not.toContain('not a valid URL')
+ expect(response.text).not.toContain(recoveryProof)
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
})
const fetchMock = vi.fn()
@@ -158,7 +240,7 @@ describe('setupInvitationPasswordWithToken', () => {
).resolves.toEqual({ error: 'invalid_password' })
})
- it('keeps invalid-payload outside the allowlist when a password was supplied', async () => {
+ it('rejects an unrecognized producer error instead of treating it as a password error', async () => {
fetchMock.mockResolvedValue(
new Response(JSON.stringify({ error: 'invalid payload' }), { status: 400 })
)
@@ -170,9 +252,6 @@ describe('setupInvitationPasswordWithToken', () => {
'synthetic-row-id',
'Synthetic-Valid-Password-123'
)
- ).rejects.toMatchObject({
- status: 503,
- body: { error: 'authority_unavailable' },
- })
+ ).rejects.toMatchObject({ name: 'ControlApiUnexpectedResponseError' })
})
})
diff --git a/external-rest-api/test/routes.auth.test.ts b/external-rest-api/test/routes.auth.test.ts
index d32f780c9..6af49e23a 100644
--- a/external-rest-api/test/routes.auth.test.ts
+++ b/external-rest-api/test/routes.auth.test.ts
@@ -46,6 +46,22 @@ describe('routes/auth password-login', () => {
expect(res.body).toEqual({ error: 'invalid_credentials' })
})
+ it('sanitizes password-operation programming errors without marking them retryable', async () => {
+ authServiceMock.loginWithPassword.mockRejectedValueOnce(
+ new TypeError('private URL and credential detail')
+ )
+
+ const res = await request(buildApp())
+ .post('/api/v1/auth/password-login')
+ .send({ email: '[email protected]', password: 'synthetic-password' })
+
+ expect(res.status).toBe(500)
+ expect(res.body).toEqual({ error: 'Internal Server Error' })
+ expect(res.headers['retry-after']).toBeUndefined()
+ expect(res.text).not.toContain('private URL')
+ expect(res.text).not.toContain('credential detail')
+ })
+
it('sets an HttpOnly profile session cookie and omits bearer token body for browser login', async () => {
authServiceMock.loginWithPassword.mockResolvedValueOnce({
token: 'profile-session-jwt',