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): r2-m3 sanitize invitation preview failures

Josuéb5d282960bdb
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index cef5abb10..a18c48b56 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.107",
+ "version": "0.1.108",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.107",
+ "version": "0.1.108",
"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 d37226f24..994f8bf49 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.107",
+ "version": "0.1.108",
"description": "External REST API for profile, team management, and RPC token brokerage",
"main": "dist/main.js",
"engines": {
diff --git a/external-rest-api/src/app.ts b/external-rest-api/src/app.ts
index 43af58971..33827ccb1 100644
--- a/external-rest-api/src/app.ts
+++ b/external-rest-api/src/app.ts
@@ -1,6 +1,7 @@
import express, { NextFunction, Request, Response } from 'express'
import cors from 'cors'
import { config } from './config.js'
+import { invitationPasswordErrorHandler } from './http/passwordAdmissionError.js'
import { withExternalRequestContext } from './requestContext.js'
import { createAuthRouter } from './routes/auth.js'
import { createContextSharedFilesystemsRouter } from './routes/contextSharedFilesystems.js'
@@ -68,7 +69,9 @@ export function createApp() {
api.use(createContextSharedFilesystemsRouter())
api.use(createGfsRouter())
api.use(createTeamRouter())
- api.use(createInvitationsRouter())
+ const invitationsRouter = createInvitationsRouter()
+ invitationsRouter.use(invitationPasswordErrorHandler)
+ api.use(invitationsRouter)
api.use(createDirectoryRouter())
api.use(createRpcRouter())
api.use(createNotificationsRouter())
diff --git a/external-rest-api/src/http/passwordAdmissionError.ts b/external-rest-api/src/http/passwordAdmissionError.ts
index 0edc1e37b..14749291b 100644
--- a/external-rest-api/src/http/passwordAdmissionError.ts
+++ b/external-rest-api/src/http/passwordAdmissionError.ts
@@ -1,16 +1,13 @@
-import type { Response } from 'express'
+import type { ErrorRequestHandler, Response } from 'express'
import { ControlApiError } from '../controlApiClient.js'
-/** Only the bounded public authority contract crosses this credential seam. */
-export function sendPasswordAuthorityError(error: unknown, res: Response): boolean {
- if (!(error instanceof ControlApiError) || ![429, 503].includes(error.status)) return false
- const recoveryOutcomeUnknown =
- error.status === 503 &&
- error.body !== null &&
- typeof error.body === 'object' &&
- 'error' in error.body &&
- error.body.error === 'recovery_outcome_unknown'
- const retry = Number(error.headers['retry-after'])
+function sendPublicPasswordAuthorityError(
+ res: Response,
+ status: 429 | 503,
+ error: 'rate_limited' | 'authority_unavailable' | 'recovery_outcome_unknown',
+ retryHeader?: string
+): void {
+ const retry = Number(retryHeader)
const retryAfterSeconds =
Number.isFinite(retry) && retry > 0 ? Math.min(900, Math.max(1, Math.ceil(retry))) : 2
for (const name of [
@@ -26,14 +23,56 @@ export function sendPasswordAuthorityError(error: unknown, res: Response): boole
res.removeHeader(name)
res.setHeader('Retry-After', String(retryAfterSeconds))
res.setHeader('Cache-Control', 'no-store')
- res.status(error.status).json({
- error:
- error.status === 429
- ? 'rate_limited'
- : recoveryOutcomeUnknown
- ? 'recovery_outcome_unknown'
- : 'authority_unavailable',
- retryAfterSeconds,
- })
- return true
+ res.status(status).json({ error, retryAfterSeconds })
+}
+
+/** 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.status === 429) {
+ sendPublicPasswordAuthorityError(res, 429, 'rate_limited', error.headers['retry-after'])
+ return true
+ }
+ if (error.status === 503) {
+ const recoveryOutcomeUnknown =
+ error.body !== null &&
+ typeof error.body === 'object' &&
+ 'error' in error.body &&
+ error.body.error === 'recovery_outcome_unknown'
+ sendPublicPasswordAuthorityError(
+ res,
+ 503,
+ recoveryOutcomeUnknown ? 'recovery_outcome_unknown' : 'authority_unavailable',
+ error.headers['retry-after']
+ )
+ return true
+ }
+ if (error.status >= 500) {
+ sendPublicPasswordAuthorityError(
+ res,
+ 503,
+ 'authority_unavailable',
+ error.headers['retry-after']
+ )
+ return true
+ }
+ return false
+}
+
+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
+ }
+ next(error)
+}
+
+/** Sends a generic authority failure when an invitation Control API call cannot be verified. */
+export function sendPasswordAuthorityUnavailable(res: Response): void {
+ sendPublicPasswordAuthorityError(res, 503, 'authority_unavailable')
}
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index 622b7a430..2d5928b4b 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.107',
+ externalRestApiVersion: '0.1.108',
rpcProxyVersion: '0.1.126',
desktopVersion: '0.10.0',
minimumDesktopVersion: '0.1.252',
diff --git a/external-rest-api/test/r2m3.resetPreviewFailure.public.test.ts b/external-rest-api/test/r2m3.resetPreviewFailure.public.test.ts
new file mode 100644
index 000000000..6ae3ad19a
--- /dev/null
+++ b/external-rest-api/test/r2m3.resetPreviewFailure.public.test.ts
@@ -0,0 +1,118 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { type Server, createServer } from 'node:http'
+import { type AddressInfo } from 'node:net'
+import request from 'supertest'
+import { createApp } from '../src/app.js'
+import { config } from '../src/config.js'
+
+const recoveryProof = 'synthetic-one-use-recovery-proof'
+
+describe('password reset preview authority failures', () => {
+ let previousControlApiBaseUrl: string
+ let previousControlApiServiceToken: string
+ let upstream: Server | undefined
+
+ beforeEach(() => {
+ previousControlApiBaseUrl = config.controlApiBaseUrl
+ previousControlApiServiceToken = config.controlApiServiceToken
+ config.controlApiServiceToken = 'synthetic-internal-service-token'
+ })
+
+ afterEach(async () => {
+ config.controlApiBaseUrl = previousControlApiBaseUrl
+ config.controlApiServiceToken = previousControlApiServiceToken
+ if (upstream?.listening) {
+ await new Promise<void>((resolve, reject) =>
+ upstream!.close(error => (error ? reject(error) : resolve()))
+ )
+ }
+ upstream = undefined
+ })
+
+ async function startUpstream(handler: Parameters<typeof createServer>[0]): Promise<void> {
+ upstream = createServer(handler)
+ await new Promise<void>((resolve, reject) => {
+ upstream!.once('error', reject)
+ upstream!.listen(0, '127.0.0.1', resolve)
+ })
+ const address = upstream.address() as AddressInfo
+ config.controlApiBaseUrl = `http://127.0.0.1:${address.port}/api/v1`
+ }
+
+ async function submitReset() {
+ return request(createApp()).post('/api/v1/invitations/password').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}`)
+ }
+
+ it('sanitizes a non-JSON preview failure before any one-use reset POST', async () => {
+ let previewRequests = 0
+ let resetPosts = 0
+ let requestedPath = ''
+ await startUpstream((req, res) => {
+ if (req.method === 'POST') resetPosts += 1
+ previewRequests += 1
+ requestedPath = req.url || ''
+ res.writeHead(502, { 'content-type': 'text/html' })
+ res.end('<html>gateway unavailable</html>')
+ })
+
+ const response = await submitReset()
+
+ expect(response.text).not.toContain(recoveryProof)
+ expect(JSON.stringify(response.body)).not.toContain(recoveryProof)
+ expect(response.status).toBe(503)
+ expect(response.body).toEqual({ error: 'authority_unavailable', retryAfterSeconds: 2 })
+ expect(response.headers['retry-after']).toBe('2')
+ expect(response.headers['cache-control']).toContain('no-store')
+ expect(requestedPath).toContain(encodeURIComponent(recoveryProof))
+ expect(previewRequests).toBe(1)
+ expect(resetPosts).toBe(0)
+ })
+
+ it('sanitizes a rejected preview transport and never submits the one-use reset POST', async () => {
+ let previewRequests = 0
+ let resetPosts = 0
+ await startUpstream((req, res) => {
+ if (req.method === 'POST') resetPosts += 1
+ previewRequests += 1
+ req.socket.destroy()
+ res.destroy()
+ })
+
+ const response = await submitReset()
+
+ expect(response.text).not.toContain(recoveryProof)
+ expect(JSON.stringify(response.body)).not.toContain(recoveryProof)
+ expect(response.status).toBe(503)
+ expect(response.body).toEqual({ error: 'authority_unavailable', retryAfterSeconds: 2 })
+ expect(response.headers['retry-after']).toBe('2')
+ expect(previewRequests).toBe(1)
+ expect(resetPosts).toBe(0)
+ })
+
+ it('sanitizes failures from the public invitation-preview route too', async () => {
+ let requestedPath = ''
+ await startUpstream((req, res) => {
+ requestedPath = req.url || ''
+ res.writeHead(502, { 'content-type': 'text/html' })
+ res.end('<html>gateway unavailable</html>')
+ })
+
+ const response = await lookupInvitation()
+
+ expect(response.text).not.toContain(recoveryProof)
+ expect(JSON.stringify(response.body)).not.toContain(recoveryProof)
+ expect(response.status).toBe(503)
+ expect(response.body).toEqual({ error: 'authority_unavailable', retryAfterSeconds: 2 })
+ expect(response.headers['retry-after']).toBe('2')
+ expect(requestedPath).toContain(encodeURIComponent(recoveryProof))
+ })
+})