Skip to content

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

TypeScript

test(recovery): r10-l2 bound composed HTTP process cleanup

Josuéb7087d247b85
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.yml
index bd6816b7d..888e81bee 100644
--- a/.github/workflows/ci-public.yml
+++ b/.github/workflows/ci-public.yml
@@ -134,6 +134,11 @@ jobs:
working-directory: external-rest-api
run: npm ci
+ - name: Build External REST composed HTTP child
+ if: matrix.service == 'control-api'
+ working-directory: external-rest-api
+ run: npm run build
+
# External REST producer-contract tests import Control API route sources
# directly, so install the producer's dependencies in this isolated job.
- name: Install Control API producer dependencies
@@ -357,6 +362,10 @@ jobs:
working-directory: external-rest-api
run: npm ci
+ - name: Build External REST composed HTTP child
+ working-directory: external-rest-api
+ run: npm run build
+
- name: Run control-api real Postgres suites (migration + GFS)
working-directory: control-api
env:
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 9371cabc5..1eac31572 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.766",
+ "version": "0.1.767",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.766",
+ "version": "0.1.767",
"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.json
index 275a6a574..43c868b52 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.766",
+ "version": "0.1.767",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/test/bug192.passwordLogin.realPostgres.integration.test.ts b/control-api/test/bug192.passwordLogin.realPostgres.integration.test.ts
index 96e00c400..e7b6730ce 100644
--- a/control-api/test/bug192.passwordLogin.realPostgres.integration.test.ts
+++ b/control-api/test/bug192.passwordLogin.realPostgres.integration.test.ts
@@ -3,7 +3,6 @@ import express from 'express'
import bcrypt from 'bcryptjs'
import { createPublicKey, randomBytes } from 'node:crypto'
import { Pool } from 'pg'
-import request from 'supertest'
import { initDb } from '../src/db.js'
import { passwordAdmissionDenialsTotal } from '../src/observability/metrics.js'
import { createExternalAuthRouter } from '../src/routes/external/auth.js'
@@ -18,6 +17,11 @@ import {
} from '../src/services/directory/membership.js'
import { createPasswordResetInvitation } from '../src/services/directory/passwordResetInvitations.js'
import { verifyExternalSessionToken } from '../src/utils/auth/externalSessionAuthToken.js'
+import {
+ type ExternalRestHttpProcess,
+ boundedRequest as request,
+ startExternalRestHttpProcess,
+} from './helpers/externalRestHttpProcess.js'
import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.js'
const holder = vi.hoisted(() => ({
@@ -718,21 +722,17 @@ realPg('BUG-192 observable password-login regressions on real PostgreSQL', () =>
)
.export({ type: 'spki', format: 'pem' })
.toString()
- const { createAuthRouter } = await import('../../external-rest-api/src/routes/auth.js')
- const { config: externalConfig } = await import('../../external-rest-api/src/config.js')
- const { withExternalRequestContext } =
- await import('../../external-rest-api/src/requestContext.js')
const server = app.listen(0, '127.0.0.1')
await new Promise<void>(resolve => server.once('listening', resolve))
const address = server.address() as { port: number }
- const previous = externalConfig.controlApiBaseUrl
- externalConfig.controlApiBaseUrl = `http://127.0.0.1:${address.port}`
- const edge = express()
- edge.set('trust proxy', 1)
- edge.use(express.json())
- edge.use(withExternalRequestContext)
- edge.use('/api/v1', createAuthRouter())
+ let child: ExternalRestHttpProcess | undefined
try {
+ child = await startExternalRestHttpProcess({
+ controlApiBaseUrl: `http://127.0.0.1:${address.port}`,
+ controlApiServiceToken: 'synthetic-login-service-token',
+ jwtPrivateKey: process.env.CONTROL_API_SESSION_JWT_PRIVATE_KEY!,
+ })
+ const edge = child.baseUrl
await holder.pool.query("INSERT INTO users(email) VALUES ('[email protected]')")
for (const email of [
@@ -762,10 +762,14 @@ realPg('BUG-192 observable password-login regressions on real PostgreSQL', () =>
)
expect(keys).toContain('external_authentication_attempt:ip:192.0.2.123')
} finally {
- externalConfig.controlApiBaseUrl = previous
- await new Promise<void>((resolve, reject) =>
- server.close(error => (error ? reject(error) : resolve()))
- )
+ try {
+ await child?.stop()
+ } finally {
+ server.closeAllConnections()
+ await new Promise<void>((resolve, reject) =>
+ server.close(error => (error ? reject(error) : resolve()))
+ )
+ }
}
})
})
diff --git a/control-api/test/helpers.externalRestHttpProcess.test.ts b/control-api/test/helpers.externalRestHttpProcess.test.ts
new file mode 100644
index 000000000..6292446f1
--- /dev/null
+++ b/control-api/test/helpers.externalRestHttpProcess.test.ts
@@ -0,0 +1,130 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { EventEmitter } from 'node:events'
+import { PassThrough } from 'node:stream'
+import { boundedRequest, startExternalRestHttpProcess } from './helpers/externalRestHttpProcess.js'
+
+const seams = vi.hoisted(() => ({ spawn: vi.fn(), access: vi.fn() }))
+vi.mock('node:child_process', async original => {
+ const real = await original<typeof import('node:child_process')>()
+ seams.spawn.mockImplementation(real.spawn)
+ return { ...real, spawn: seams.spawn }
+})
+vi.mock('node:fs/promises', async original => {
+ const real = await original<typeof import('node:fs/promises')>()
+ seams.access.mockImplementation(real.access)
+ return { ...real, access: seams.access }
+})
+const config = {
+ controlApiBaseUrl: 'http://127.0.0.1:43121/api/v1',
+ controlApiServiceToken: 'synthetic-process-contract-token',
+}
+afterEach(() => {
+ vi.useRealTimers()
+ vi.clearAllMocks()
+})
+function fakeChild(output?: string, hang = false, exitEarly = false) {
+ const child = new EventEmitter() as EventEmitter & Record<string, any>
+ child.stdin = new PassThrough()
+ child.stdout = new PassThrough()
+ child.stderr = new PassThrough()
+ child.kill = vi.fn((signal: string) => {
+ if (!hang || signal === 'SIGKILL') child.emit('exit', signal === 'SIGKILL' ? 137 : 0)
+ return true
+ })
+ seams.spawn.mockImplementationOnce(() => {
+ queueMicrotask(() =>
+ exitEarly
+ ? child.emit('exit', 1)
+ : output === undefined
+ ? undefined
+ : child.stdout.write(output + '\n')
+ )
+ return child
+ })
+ return child
+}
+describe('bounded External REST HTTP process ownership', () => {
+ it('starts the real built app with allowlisted synthetic environment and closes it', async () => {
+ const child = await startExternalRestHttpProcess(config)
+ try {
+ expect(
+ (await boundedRequest(child.baseUrl).get('/api/v1/recovery-contract-missing')).status
+ ).toBe(404)
+ const env = seams.spawn.mock.calls[0][2].env
+ expect(Object.keys(env).sort()).toEqual(
+ [
+ 'NODE_ENV',
+ 'LOG_LEVEL',
+ 'EXTERNAL_REST_API_CORS_ORIGIN',
+ 'EXTERNAL_REST_API_GOOGLE_CLIENT_ID',
+ 'EXTERNAL_REST_API_CONTROL_API_BASE_URL',
+ 'EXTERNAL_REST_API_CONTROL_API_SERVICE_TOKEN',
+ 'EXTERNAL_REST_API_CONTROL_API_SERVICE_NAME',
+ 'EXTERNAL_REST_API_JWT_PUBLIC_KEY',
+ 'EXTERNAL_REST_API_JWT_ISSUER',
+ 'EXTERNAL_REST_API_JWT_AUDIENCE',
+ 'EXTERNAL_REST_API_PUBLIC_BASE_URL',
+ 'EXTERNAL_REST_API_DESKTOP_RPC_PROXY_BASE_URL',
+ ].sort()
+ )
+ expect(env.NODE_ENV).toBe('test')
+ } finally {
+ await child.stop()
+ }
+ await child.stop()
+ })
+ it.each([
+ 'https://127.0.0.1:43121/api/v1',
+ 'http://example.invalid:43121/api/v1',
+ 'http://127.0.0.1:43121/api/v1?next=x',
+ ])('rejects unowned destination %s before spawning', async controlApiBaseUrl => {
+ await expect(startExternalRestHttpProcess({ ...config, controlApiBaseUrl })).rejects.toThrow(
+ 'task-owned loopback'
+ )
+ expect(seams.spawn).not.toHaveBeenCalled()
+ })
+ it('fails before spawning when the service build is absent', async () => {
+ seams.access.mockRejectedValueOnce(new Error('ENOENT'))
+ await expect(startExternalRestHttpProcess(config)).rejects.toThrow('Build External REST')
+ expect(seams.spawn).not.toHaveBeenCalled()
+ })
+ it('fails and cleans up malformed readiness', async () => {
+ const child = fakeChild('http://example.invalid')
+ await expect(startExternalRestHttpProcess(config)).rejects.toThrow(
+ 'Invalid recovery HTTP readiness'
+ )
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM')
+ })
+ it('fails if the child exits before readiness', async () => {
+ fakeChild(undefined, false, true)
+ const pending = startExternalRestHttpProcess(config)
+ await expect(pending).rejects.toThrow('exited before readiness')
+ })
+ it('bounds absent readiness and terminates the child', async () => {
+ vi.useFakeTimers()
+ seams.access.mockResolvedValueOnce(undefined)
+ const child = fakeChild()
+ const pending = expect(startExternalRestHttpProcess(config)).rejects.toThrow(
+ 'readiness exceeded 10 seconds'
+ )
+ await vi.advanceTimersByTimeAsync(10_000)
+ await pending
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM')
+ })
+ it('does not accept an unsuccessfully exited ready child as successful cleanup', async () => {
+ const child = fakeChild('http://127.0.0.1:43122')
+ const running = await startExternalRestHttpProcess(config)
+ child.emit('exit', 1)
+ await expect(running.stop()).rejects.toThrow('exited unsuccessfully')
+ })
+ it('kills a hung child after the shutdown deadline and reports failure', async () => {
+ vi.useFakeTimers()
+ seams.access.mockResolvedValueOnce(undefined)
+ const child = fakeChild('http://127.0.0.1:43122', true)
+ const running = await startExternalRestHttpProcess(config)
+ const pending = expect(running.stop()).rejects.toThrow('shutdown exceeded 5 seconds')
+ await vi.advanceTimersByTimeAsync(5000)
+ await pending
+ expect(child.kill).toHaveBeenCalledWith('SIGKILL')
+ })
+})
diff --git a/control-api/test/helpers/externalRestHttpProcess.ts b/control-api/test/helpers/externalRestHttpProcess.ts
new file mode 100644
index 000000000..cd7b03d13
--- /dev/null
+++ b/control-api/test/helpers/externalRestHttpProcess.ts
@@ -0,0 +1,159 @@
+import { spawn } from 'node:child_process'
+import { createPublicKey, generateKeyPairSync } from 'node:crypto'
+import { access } from 'node:fs/promises'
+import { createInterface } from 'node:readline'
+import { fileURLToPath } from 'node:url'
+import request from 'supertest'
+
+export type ExternalRestHttpProcess = {
+ baseUrl: string
+ stop: () => Promise<void>
+}
+export type RecoveryHttpConfig = {
+ controlApiBaseUrl: string
+ controlApiServiceToken: string
+ jwtPublicKey?: string
+ jwtPrivateKey?: string
+ jwtIssuer?: string
+ jwtAudience?: string
+}
+
+// Every request in the composed lane has a finite deadline, including failure schedules.
+export function boundedRequest(target: Parameters<typeof request>[0]) {
+ const agent = request(target)
+ for (const method of ['get', 'post', 'put', 'patch', 'delete', 'head'] as const) {
+ const original = agent[method].bind(agent)
+ agent[method] = ((...args: Parameters<typeof original>) =>
+ original(...args).timeout({ response: 10_000, deadline: 15_000 })) as typeof original
+ }
+ return agent
+}
+
+export async function startExternalRestHttpProcess(
+ config: RecoveryHttpConfig
+): Promise<ExternalRestHttpProcess> {
+ const upstream = new URL(config.controlApiBaseUrl)
+ if (
+ upstream.protocol !== 'http:' ||
+ upstream.hostname !== '127.0.0.1' ||
+ !upstream.port ||
+ upstream.username ||
+ upstream.password ||
+ upstream.search ||
+ upstream.hash ||
+ !['', '/', '/api/v1'].includes(upstream.pathname)
+ )
+ throw new Error('Recovery HTTP producer must be task-owned loopback')
+ const entry = fileURLToPath(
+ new URL(
+ '../../../external-rest-api/test/helpers/passwordRecoveryHttpServer.mjs',
+ import.meta.url
+ )
+ )
+ const build = fileURLToPath(new URL('../../../external-rest-api/dist/app.js', import.meta.url))
+ await access(build).catch(() => {
+ throw new Error('Build External REST before composed HTTP tests')
+ })
+ const publicKey =
+ config.jwtPublicKey ||
+ createPublicKey(
+ config.jwtPrivateKey || generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey
+ )
+ .export({ type: 'spki', format: 'pem' })
+ .toString()
+ const child = spawn(process.execPath, [entry], {
+ stdio: ['pipe', 'pipe', 'pipe'],
+ env: {
+ NODE_ENV: 'test',
+ LOG_LEVEL: 'silent',
+ EXTERNAL_REST_API_CORS_ORIGIN: 'http://127.0.0.1',
+ EXTERNAL_REST_API_GOOGLE_CLIENT_ID: 'synthetic-recovery-client',
+ EXTERNAL_REST_API_CONTROL_API_BASE_URL: config.controlApiBaseUrl,
+ EXTERNAL_REST_API_CONTROL_API_SERVICE_TOKEN: config.controlApiServiceToken,
+ EXTERNAL_REST_API_CONTROL_API_SERVICE_NAME: 'external-rest-api',
+ EXTERNAL_REST_API_JWT_PUBLIC_KEY: publicKey,
+ EXTERNAL_REST_API_JWT_ISSUER: config.jwtIssuer || 'control-api',
+ EXTERNAL_REST_API_JWT_AUDIENCE: config.jwtAudience || 'profile-ui',
+ EXTERNAL_REST_API_PUBLIC_BASE_URL: 'http://127.0.0.1',
+ EXTERNAL_REST_API_DESKTOP_RPC_PROXY_BASE_URL: 'http://127.0.0.1',
+ },
+ })
+ // Do not forward child logs/configuration into assertion errors.
+ child.stderr.resume()
+ let exited = false
+ let exitCode: number | null = null
+ const completion = new Promise<void>((resolve, reject) => {
+ child.once('error', reject)
+ child.once('exit', code => {
+ exited = true
+ exitCode = code
+ resolve()
+ })
+ })
+ const lines = createInterface({ input: child.stdout })
+ let stopped: Promise<void> | undefined
+ const stop = () =>
+ (stopped ||= (async () => {
+ if (!exited) child.kill('SIGTERM')
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try {
+ try {
+ await Promise.race([
+ completion,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ reject(new Error('Recovery HTTP child shutdown exceeded 5 seconds'))
+ }, 5000)
+ }),
+ ])
+ } catch (error) {
+ clearTimeout(timer)
+ if (!exited) {
+ child.kill('SIGKILL')
+ await Promise.race([
+ completion,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error('Recovery HTTP child did not exit after SIGKILL')),
+ 2000
+ )
+ }),
+ ])
+ }
+ throw error
+ }
+ if (exitCode !== 0) throw new Error('Recovery HTTP child exited unsuccessfully')
+ } finally {
+ clearTimeout(timer)
+ lines.close()
+ child.stdin.destroy()
+ }
+ })())
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try {
+ const baseUrl = await Promise.race([
+ new Promise<string>((resolve, reject) => {
+ lines.once('line', line => {
+ if (!/^http:\/\/127\.0\.0\.1:[1-9][0-9]*$/.test(line)) {
+ reject(new Error('Invalid recovery HTTP readiness address'))
+ } else resolve(line)
+ })
+ }),
+ completion.then(() => {
+ throw new Error('Recovery HTTP child exited before readiness')
+ }),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error('Recovery HTTP readiness exceeded 10 seconds')),
+ 10_000
+ )
+ }),
+ ])
+ return { baseUrl, stop }
+ } catch (error) {
+ await stop().catch(() => undefined)
+ throw error
+ } finally {
+ clearTimeout(timer)
+ }
+}
diff --git a/control-api/test/r2m1.passwordAuthorityConsumer.realPostgres.integration.test.ts b/control-api/test/passwordRecovery.http.realPostgres.integration.test.ts
similarity index 92%
rename from control-api/test/r2m1.passwordAuthorityConsumer.realPostgres.integration.test.ts
rename to control-api/test/passwordRecovery.http.realPostgres.integration.test.ts
index 33623fd7b..b836607ba 100644
--- a/control-api/test/r2m1.passwordAuthorityConsumer.realPostgres.integration.test.ts
+++ b/control-api/test/passwordRecovery.http.realPostgres.integration.test.ts
@@ -3,7 +3,11 @@ import express from 'express'
import { generateKeyPairSync, randomBytes } from 'node:crypto'
import type { Server } from 'node:http'
import { Pool } from 'pg'
-import request from 'supertest'
+import {
+ type ExternalRestHttpProcess,
+ boundedRequest as request,
+ startExternalRestHttpProcess,
+} from './helpers/externalRestHttpProcess.js'
import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.js'
const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
@@ -19,11 +23,9 @@ realPg('R2-M1/R2-M2 public password authority contract on PostgreSQL 16', () =>
let db: typeof import('../src/db.js')
let controlApp: express.Express
let controlServer: Server
- let publicApp: express.Express
+ let publicApp: string
+ let publicProcess: ExternalRestHttpProcess
let bcrypt: typeof import('bcryptjs').default
- let externalConfig: (typeof import('../../external-rest-api/src/config.js'))['config']
- let previousBaseUrl: string
- let previousServiceToken: string
let sourceCounter = 1
beforeAll(async () => {
@@ -66,21 +68,18 @@ realPg('R2-M1/R2-M2 public password authority contract on PostgreSQL 16', () =>
controlServer = controlApp.listen(0, '127.0.0.1')
await new Promise<void>(resolve => controlServer.once('listening', resolve))
- externalConfig = (await import('../../external-rest-api/src/config.js')).config
- previousBaseUrl = externalConfig.controlApiBaseUrl
- previousServiceToken = externalConfig.controlApiServiceToken
- externalConfig.controlApiBaseUrl = `http://127.0.0.1:${(controlServer.address() as { port: number }).port}/api/v1`
- externalConfig.controlApiServiceToken = serviceToken
- const { createApp } = await import('../../external-rest-api/src/app.js')
- publicApp = createApp()
+ publicProcess = await startExternalRestHttpProcess({
+ controlApiBaseUrl: `http://127.0.0.1:${(controlServer.address() as { port: number }).port}/api/v1`,
+ controlApiServiceToken: serviceToken,
+ jwtPublicKey: publicKey.export({ type: 'spki', format: 'pem' }).toString(),
+ })
+ publicApp = publicProcess.baseUrl
}, 60_000)
afterAll(async () => {
+ let childCleanup: PromiseSettledResult<void | undefined> | undefined
try {
- if (externalConfig) {
- externalConfig.controlApiBaseUrl = previousBaseUrl
- externalConfig.controlApiServiceToken = previousServiceToken
- }
+ ;[childCleanup] = await Promise.allSettled([publicProcess?.stop()])
if (controlServer) {
await new Promise<void>((resolve, reject) =>
controlServer.close(error => (error ? reject(error) : resolve()))
@@ -95,6 +94,7 @@ realPg('R2-M1/R2-M2 public password authority contract on PostgreSQL 16', () =>
await admin?.end()
vi.unstubAllEnvs()
}
+ if (childCleanup?.status === 'rejected') throw childCleanup.reason
})
async function acceptedInvitationSession() {
@@ -102,7 +102,8 @@ realPg('R2-M1/R2-M2 public password authority contract on PostgreSQL 16', () =>
await import('../src/services/directory/membership.js')
const { signExternalSessionToken } =
await import('../src/utils/auth/externalSessionAuthToken.js')
- const { verifyToken } = await import('../../external-rest-api/src/authToken.js')
+ const { verifyExternalSessionToken: verifyToken } =
+ await import('../src/utils/auth/externalSessionAuthToken.js')
const email = `r2m1-${randomBytes(8).toString('hex')}@example.invalid`
const invitation = await createSilentInvitationForTeams({
inviteeName: 'Synthetic invited member',
diff --git a/control-api/test/r4l1.resetPasswordPayload.externalRest.realPostgres.integration.test.ts b/control-api/test/r4l1.resetPasswordPayload.externalRest.realPostgres.integration.test.ts
index b9e2af420..f702d0764 100644
--- a/control-api/test/r4l1.resetPasswordPayload.externalRest.realPostgres.integration.test.ts
+++ b/control-api/test/r4l1.resetPasswordPayload.externalRest.realPostgres.integration.test.ts
@@ -7,7 +7,6 @@ import { once } from 'node:events'
import { type Server, createServer, request as httpRequest } from 'node:http'
import path from 'node:path'
import { Pool } from 'pg'
-import request from 'supertest'
import { config as controlConfig } from '../src/config.js'
import { initDb } from '../src/db.js'
import { requireInternalToken } from '../src/middleware/internalServiceAuth.js'
@@ -16,6 +15,11 @@ import { createExternalInvitationsRouter } from '../src/routes/external/invitati
import { createSilentInvitationForTeams } from '../src/services/directory/membership.js'
import { createSilentPasswordResetInvitation } from '../src/services/directory/passwordResetInvitations.js'
import { registerAndSendInvitation } from '../src/services/invitationFlowRegistrationService.js'
+import {
+ type ExternalRestHttpProcess,
+ boundedRequest as request,
+ startExternalRestHttpProcess,
+} from './helpers/externalRestHttpProcess.js'
import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.js'
const holder = vi.hoisted(() => ({ pool: null as unknown as Pool }))
@@ -46,14 +50,8 @@ const internalToken = 'Synthetic-R4-L1-Internal-Token'
const tenantId = 'r4-l1-test-tenant'
const tenantKid = 'r4-l1-test-credential'
const tenantSecret = 'Synthetic-R4-L1-Member-Registration-Secret'
-type ExternalConfig = typeof import('../../external-rest-api/src/config.js').config
-type ExternalRouterFactory =
- typeof import('../../external-rest-api/src/routes/invitations.js').createInvitationsRouter
-type ExternalAuthoritySender =
- typeof import('../../external-rest-api/src/http/passwordAdmissionError.js').sendPasswordAuthorityError
-let externalConfig: ExternalConfig
-let createInvitationsRouter: ExternalRouterFactory
-let sendPasswordAuthorityError: ExternalAuthoritySender
+const externalConfig = { controlApiBaseUrl: '' }
+const publicChildren: ExternalRestHttpProcess[] = []
let originalExternalJwtKey: string | undefined
function listen(server: Server): Promise<number> {
@@ -194,10 +192,17 @@ realProducer('R4-L1 reset password payload through the public route and real pro
let controlApiPort = 0
let controlBaseUrl = ''
let producerBaseUrl = ''
- let publicApp: express.Express
+ async function publicApp() {
+ const child = await startExternalRestHttpProcess({
+ controlApiBaseUrl: externalConfig.controlApiBaseUrl,
+ controlApiServiceToken: internalToken,
+ jwtPrivateKey: controlConfig.sessionJwtPrivateKey,
+ })
+ publicChildren.push(child)
+ return child.baseUrl
+ }
let producerResponses: Array<{ status: number; error: string | null }> = []
let originalControlConfig: Record<string, unknown> = {}
- let originalExternalConfig: Record<string, unknown> = {}
beforeAll(async () => {
originalExternalJwtKey = process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY
@@ -208,13 +213,6 @@ realProducer('R4-L1 reset password payload through the public route and real pro
publicKeyEncoding: { type: 'spki', format: 'pem' },
}).publicKey
}
- externalConfig = (await import('../../external-rest-api/src/config.js')).config
- createInvitationsRouter = (await import('../../external-rest-api/src/routes/invitations.js'))
- .createInvitationsRouter
- sendPasswordAuthorityError = (
- await import('../../external-rest-api/src/http/passwordAdmissionError.js')
- ).sendPasswordAuthorityError
-
admin = new Pool({ connectionString: adminUrl })
await admin.query(`CREATE DATABASE "${controlDatabase}"`)
await admin.query(`CREATE DATABASE "${producerDatabase}"`)
@@ -240,12 +238,6 @@ realProducer('R4-L1 reset password payload through the public route and real pro
desktopAppName: controlConfig.desktopAppName,
internalServiceToken: controlConfig.internalServiceTokens['external-rest-api'],
}
- originalExternalConfig = {
- controlApiBaseUrl: externalConfig.controlApiBaseUrl,
- controlApiServiceToken: externalConfig.controlApiServiceToken,
- controlApiServiceName: externalConfig.controlApiServiceName,
- }
-
const producerPort = await freeLoopbackPort()
memberRegistrationProcess = spawn(
path.join(memberRegistrationRoot!, 'node_modules/.bin/tsx'),
@@ -314,21 +306,12 @@ realProducer('R4-L1 reset password payload through the public route and real pro
controlBaseUrl = `http://127.0.0.1:${controlApiPort}/api/v1`
externalConfig.controlApiBaseUrl = controlBaseUrl
- externalConfig.controlApiServiceToken = internalToken
- externalConfig.controlApiServiceName = 'external-rest-api'
- publicApp = express()
- publicApp.use(express.json())
- publicApp.use(createInvitationsRouter())
- publicApp.use(
- (error: unknown, _req: express.Request, res: express.Response, _next: unknown) => {
- if (sendPasswordAuthorityError(error, res)) return
- res.status(500).json({ error: 'Internal Server Error' })
- }
- )
}, 60_000)
afterAll(async () => {
+ let childCleanup: PromiseSettledResult<void>[] | undefined
try {
+ childCleanup = await Promise.allSettled(publicChildren.splice(0).map(child => child.stop()))
await ambiguousProxy?.close()
if (controlServer) {
await new Promise<void>(resolve => controlServer!.close(() => resolve()))
@@ -364,13 +347,14 @@ realProducer('R4-L1 reset password payload through the public route and real pro
originalControlConfig.internalServiceToken
)
}
- Object.assign(externalConfig, originalExternalConfig)
if (originalExternalJwtKey === undefined) {
delete process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY
} else {
process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY = originalExternalJwtKey
}
}
+ const failed = childCleanup?.find(result => result.status === 'rejected')
+ if (failed?.status === 'rejected') throw failed.reason
})
async function createReset(emailLabel: string) {
@@ -422,12 +406,14 @@ realProducer('R4-L1 reset password payload through the public route and real pro
it('returns sanitized 400 for the producer invalid-payload response and allows valid retry', async () => {
producerResponses = []
const reset = await createReset('empty')
- const empty = await request(publicApp).post('/invitations/password').send({
- token: reset.proof,
- email: reset.email,
- invitationId: reset.invitationId,
- password: '',
- })
+ const empty = await request(await publicApp())
+ .post('/api/v1/invitations/password')
+ .send({
+ token: reset.proof,
+ email: reset.email,
+ invitationId: reset.invitationId,
+ password: '',
+ })
expect(empty.status).toBe(400)
expect(empty.body).toEqual({ error: 'Password must be between 8 and 256 characters' })
@@ -451,12 +437,14 @@ realProducer('R4-L1 reset password payload through the public route and real pro
})
const replacementPassword = `Synthetic-R4-L1-Replacement-${randomUUID()}`
- const valid = await request(publicApp).post('/invitations/password').send({
- token: reset.proof,
- email: reset.email,
- invitationId: reset.invitationId,
- password: replacementPassword,
- })
+ const valid = await request(await publicApp())
+ .post('/api/v1/invitations/password')
+ .send({
+ token: reset.proof,
+ email: reset.email,
+ invitationId: reset.invitationId,
+ password: replacementPassword,
+ })
expect(valid.status).toBe(200)
expect(valid.headers['set-cookie']).toEqual(
expect.arrayContaining([expect.stringContaining('profile_session=')])
@@ -488,12 +476,14 @@ realProducer('R4-L1 reset password payload through the public route and real pro
const proxyBaseUrl = await ambiguousProxy.start()
externalConfig.controlApiBaseUrl = proxyBaseUrl
const replacementPassword = `Synthetic-R4-L1-Ambiguous-${randomUUID()}`
- const unknown = await request(publicApp).post('/invitations/password').send({
- token: reset.proof,
- email: reset.email,
- invitationId: reset.invitationId,
- password: replacementPassword,
- })
+ const unknown = await request(await publicApp())
+ .post('/api/v1/invitations/password')
+ .send({
+ token: reset.proof,
+ email: reset.email,
+ invitationId: reset.invitationId,
+ password: replacementPassword,
+ })
await ambiguousProxy.droppedResetResponse
expect(unknown.status).toBe(503)
expect(unknown.body).toEqual({ error: 'recovery_outcome_unknown', retryAfterSeconds: 2 })
@@ -523,12 +513,14 @@ realProducer('R4-L1 reset password payload through the public route and real pro
).toBe(true)
externalConfig.controlApiBaseUrl = controlBaseUrl
- const replay = await request(publicApp).post('/invitations/password').send({
- token: reset.proof,
- email: reset.email,
- invitationId: reset.invitationId,
- password: replacementPassword,
- })
+ const replay = await request(await publicApp())
+ .post('/api/v1/invitations/password')
+ .send({
+ token: reset.proof,
+ email: reset.email,
+ invitationId: reset.invitationId,
+ password: replacementPassword,
+ })
expect(replay.status).toBe(409)
expect(replay.headers['set-cookie']).toBeUndefined()
expect(ambiguousProxy.resetPostCount).toBe(1)
diff --git a/control-api/test/r6.credentialChangedRoute.realPostgres.integration.test.ts b/control-api/test/r6.credentialChangedRoute.realPostgres.integration.test.ts
index 2695ef9ea..af2d380f4 100644
--- a/control-api/test/r6.credentialChangedRoute.realPostgres.integration.test.ts
+++ b/control-api/test/r6.credentialChangedRoute.realPostgres.integration.test.ts
@@ -4,11 +4,15 @@ import bcrypt from 'bcryptjs'
import { createPublicKey, randomBytes, randomUUID } from 'node:crypto'
import { type Server } from 'node:http'
import { Pool } from 'pg'
-import request from 'supertest'
import { config as controlConfig } from '../src/config.js'
import { initDb } from '../src/db.js'
import { requireInternalToken } from '../src/middleware/internalServiceAuth.js'
import { createExternalUsersRouter } from '../src/routes/external/users.js'
+import {
+ type ExternalRestHttpProcess,
+ boundedRequest as request,
+ startExternalRestHttpProcess,
+} from './helpers/externalRestHttpProcess.js'
import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.js'
const holder = vi.hoisted(() => ({ pool: null as unknown as Pool }))
@@ -44,15 +48,11 @@ realPg('R6 credential-generation update fence (Control API + External REST, Post
const email = `r6-credential-${randomUUID()}@example.invalid`
let admin: Pool
let server: Server
- let publicApp: express.Express
+ let publicApp: string
+ let publicProcess: ExternalRestHttpProcess
let userId: string
let sessionToken: string
let initialHash: string
- let externalConfig: typeof import('../../external-rest-api/src/config.js').config
- let createMeRouter: typeof import('../../external-rest-api/src/routes/me.js').createMeRouter
- let oldExternalBaseUrl: string
- let oldExternalServiceToken: string
- let oldExternalServiceName: string
const oldExternalJwtPublicKey = process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY
const oldInternalToken = controlConfig.internalServiceTokens['external-rest-api']
@@ -96,32 +96,19 @@ realPg('R6 credential-generation update fence (Control API + External REST, Post
const address = server.address()
if (!address || typeof address === 'string') throw new Error('Control API did not bind TCP')
- vi.resetModules()
- externalConfig = (await import('../../external-rest-api/src/config.js')).config
- createMeRouter = (await import('../../external-rest-api/src/routes/me.js')).createMeRouter
- oldExternalBaseUrl = externalConfig.controlApiBaseUrl
- oldExternalServiceToken = externalConfig.controlApiServiceToken
- oldExternalServiceName = externalConfig.controlApiServiceName
- externalConfig.controlApiBaseUrl = `http://127.0.0.1:${address.port}/api/v1`
- externalConfig.controlApiServiceToken = internalToken
- externalConfig.controlApiServiceName = 'external-rest-api'
-
- publicApp = express()
- publicApp.use(express.json())
- publicApp.use(createMeRouter())
- publicApp.use((_error: unknown, _req: express.Request, res: express.Response) =>
- res.status(500).json({ error: 'Internal Server Error' })
- )
+ publicProcess = await startExternalRestHttpProcess({
+ controlApiBaseUrl: `http://127.0.0.1:${address.port}/api/v1`,
+ controlApiServiceToken: internalToken,
+ jwtPrivateKey: controlConfig.sessionJwtPrivateKey,
+ })
+ publicApp = publicProcess.baseUrl
}, 60_000)
afterAll(async () => {
+ let childCleanup: PromiseSettledResult<void | undefined> | undefined
try {
+ ;[childCleanup] = await Promise.allSettled([publicProcess?.stop()])
if (server) await new Promise<void>(resolve => server.close(() => resolve()))
- if (externalConfig) {
- externalConfig.controlApiBaseUrl = oldExternalBaseUrl
- externalConfig.controlApiServiceToken = oldExternalServiceToken
- externalConfig.controlApiServiceName = oldExternalServiceName
- }
if (oldExternalJwtPublicKey === undefined) {
delete process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY
} else {
@@ -133,6 +120,7 @@ realPg('R6 credential-generation update fence (Control API + External REST, Post
} finally {
await admin?.end()
}
+ if (childCleanup?.status === 'rejected') throw childCleanup.reason
})
it('returns 409 without overwriting the concurrent credential and preserves public guidance', async () => {
@@ -157,7 +145,7 @@ realPg('R6 credential-generation update fence (Control API + External REST, Post
})
const change = request(publicApp)
- .put('/me/password')
+ .put('/api/v1/me/password')
.set('authorization', `Bearer ${sessionToken}`)
.send({ currentPassword, newPassword: submittedPassword })
.then(response => response)
diff --git a/control-api/test/r6.retiredRecoveryRoute.realPostgres.integration.test.ts b/control-api/test/r6.retiredRecoveryRoute.realPostgres.integration.test.ts
index 1b4bfe903..a63c446e9 100644
--- a/control-api/test/r6.retiredRecoveryRoute.realPostgres.integration.test.ts
+++ b/control-api/test/r6.retiredRecoveryRoute.realPostgres.integration.test.ts
@@ -4,7 +4,6 @@ import bcrypt from 'bcryptjs'
import { createPublicKey, randomBytes, randomUUID } from 'node:crypto'
import { type Server } from 'node:http'
import { Pool } from 'pg'
-import request from 'supertest'
import { config as controlConfig } from '../src/config.js'
import { initDb } from '../src/db.js'
import { requireInternalToken } from '../src/middleware/internalServiceAuth.js'
@@ -12,6 +11,11 @@ import { createExternalInvitationsRouter } from '../src/routes/external/invitati
import { createSilentInvitationForTeams } from '../src/services/directory/membership.js'
import { createSilentPasswordResetInvitation } from '../src/services/directory/passwordResetInvitations.js'
import { retireDesktopUser } from '../src/services/directory/users.js'
+import {
+ type ExternalRestHttpProcess,
+ boundedRequest as request,
+ startExternalRestHttpProcess,
+} from './helpers/externalRestHttpProcess.js'
import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.js'
const holder = vi.hoisted(() => ({ pool: null as unknown as Pool }))
@@ -54,18 +58,14 @@ realPg('R6 retired-user password reset route and public mapping (PostgreSQL)', (
let admin: Pool
let server: Server
let producerApp: express.Express
- let app: express.Express
+ let app: string
+ let publicProcess: ExternalRestHttpProcess
let userId: string
let invitationId: string
let invitationToken: string
let initialHash: string
- let externalConfig: typeof import('../../external-rest-api/src/config.js').config
- let createPublicInvitationsRouter: typeof import('../../external-rest-api/src/routes/invitations.js').createInvitationsRouter
let publicAddress: string
const oldInternalToken = controlConfig.internalServiceTokens['external-rest-api']
- let oldExternalBaseUrl: string
- let oldExternalServiceToken: string
- let oldExternalServiceName: string
const oldExternalJwtPublicKey = process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY
beforeAll(async () => {
@@ -125,34 +125,19 @@ realPg('R6 retired-user password reset route and public mapping (PostgreSQL)', (
)
.export({ type: 'spki', format: 'pem' })
.toString()
- vi.resetModules()
- externalConfig = (await import('../../external-rest-api/src/config.js')).config
- createPublicInvitationsRouter = (
- await import('../../external-rest-api/src/routes/invitations.js')
- ).createInvitationsRouter
- oldExternalBaseUrl = externalConfig.controlApiBaseUrl
- oldExternalServiceToken = externalConfig.controlApiServiceToken
- oldExternalServiceName = externalConfig.controlApiServiceName
- externalConfig.controlApiBaseUrl = `${publicAddress}/api/v1`
- externalConfig.controlApiServiceToken = internalToken
- externalConfig.controlApiServiceName = 'external-rest-api'
-
- app = express()
- app.use(express.json())
- app.use(createPublicInvitationsRouter())
- app.use((_error: unknown, _req: express.Request, res: express.Response, _next: unknown) =>
- res.status(500).json({ error: 'Internal Server Error' })
- )
+ publicProcess = await startExternalRestHttpProcess({
+ controlApiBaseUrl: `${publicAddress}/api/v1`,
+ controlApiServiceToken: internalToken,
+ jwtPrivateKey: controlConfig.sessionJwtPrivateKey,
+ })
+ app = publicProcess.baseUrl
}, 60_000)
afterAll(async () => {
+ let childCleanup: PromiseSettledResult<void | undefined> | undefined
try {
+ ;[childCleanup] = await Promise.allSettled([publicProcess?.stop()])
if (server) await new Promise<void>(resolve => server.close(() => resolve()))
- if (externalConfig) {
- externalConfig.controlApiBaseUrl = oldExternalBaseUrl
- externalConfig.controlApiServiceToken = oldExternalServiceToken
- externalConfig.controlApiServiceName = oldExternalServiceName
- }
if (oldExternalJwtPublicKey === undefined) {
delete process.env.EXTERNAL_REST_API_JWT_PUBLIC_KEY
} else {
@@ -164,11 +149,12 @@ realPg('R6 retired-user password reset route and public mapping (PostgreSQL)', (
} finally {
await admin?.end()
}
+ if (childCleanup?.status === 'rejected') throw childCleanup.reason
})
it('emits user_retired at Control API and maps it to a non-enumerating public result', async () => {
const preview = await request(app)
- .get('/invitations/token/r6-synthetic-retired-reset-proof')
+ .get('/api/v1/invitations/token/r6-synthetic-retired-reset-proof')
.expect(200)
expect(preview.body).toMatchObject({
id: invitationId,
@@ -190,7 +176,7 @@ realPg('R6 retired-user password reset route and public mapping (PostgreSQL)', (
.expect(401, { error: 'user_retired' })
const response = await request(app)
- .post('/invitations/password')
+ .post('/api/v1/invitations/password')
.send({
token: 'r6-synthetic-retired-reset-proof',
email,
diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.json
index c51288961..5ddb6259f 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.120",
+ "version": "0.1.121",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-external-rest-api",
- "version": "0.1.120",
+ "version": "0.1.121",
"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 55a99996c..a960fd9ef 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.120",
+ "version": "0.1.121",
"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.ts
index b846ffdf1..d394abb7b 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.120',
+ externalRestApiVersion: '0.1.121',
rpcProxyVersion: '0.1.126',
desktopVersion: '0.11.0',
minimumDesktopVersion: '0.1.252',
diff --git a/external-rest-api/test/helpers/passwordRecoveryHttpServer.mjs b/external-rest-api/test/helpers/passwordRecoveryHttpServer.mjs
new file mode 100644
index 000000000..163b05524
--- /dev/null
+++ b/external-rest-api/test/helpers/passwordRecoveryHttpServer.mjs
@@ -0,0 +1,24 @@
+// This service owns the app import; the parent supplies synthetic configuration only.
+import { createApp } from '../../dist/app.js'
+
+const server = createApp().listen(0, '127.0.0.1', () => {
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('No loopback address')
+ process.stdout.write(`http://127.0.0.1:${address.port}\n`)
+})
+let stopping = false
+function stop() {
+ if (stopping) return
+ stopping = true
+ const deadline = setTimeout(() => process.exit(1), 3000)
+ server.closeAllConnections()
+ server.close(error => {
+ clearTimeout(deadline)
+ process.exit(error ? 1 : 0)
+ })
+}
+process.once('SIGTERM', stop)
+process.once('SIGINT', stop)
+process.stdin.resume()
+process.stdin.once('end', stop)
+server.once('error', () => process.exit(1))