Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(recovery): r10-m2 verify producer contracts through composed HTTP
Josuéc03bb2f4f6cf
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.ymlindex 888e81bee..71ea9b96a 100644--- a/.github/workflows/ci-public.yml+++ b/.github/workflows/ci-public.yml@@ -83,8 +83,10 @@ jobs:pinned_suites: gfsClient.retry429.test.ts logPayloadKeys.test.ts taskExecutor.test.tspinned_cases: ../scripts/ci/pinned-vitest-cases/mcp-host.json- service: control-api- pinned_suites: helpers.realPostgresTeardown.test.ts routes.mcp-host.llmProviderAttempts.test.ts+ pinned_suites: helpers.realPostgresTeardown.test.ts routes.mcp-host.llmProviderAttempts.test.ts passwordRecovery.http.contract.test.tspinned_cases: ../scripts/ci/pinned-vitest-cases/control-api.json+ - service: external-rest-api+ pinned_suites: invitations.passwordRecovery.public.test.ts- service: codex-llm-proxypinned_suites: originPolicy.test.ts server.security.test.tspinned_cases: ../scripts/ci/pinned-vitest-cases/codex-llm-proxy.json@@ -139,7 +141,7 @@ jobs:working-directory: external-rest-apirun: npm run build- # External REST producer-contract tests import Control API route sources+ # Inherited entity-change contracts still import Control API sources.# directly, so install the producer's dependencies in this isolated job.- name: Install Control API producer dependenciesif: matrix.service == 'external-rest-api'@@ -366,6 +368,9 @@ jobs:working-directory: external-rest-apirun: npm run build+ - name: Validate recovery suite selection contract+ run: node --test scripts/tests/password-recovery-suite-contract.test.mjs+- name: Run control-api real Postgres suites (migration + GFS)working-directory: control-apienv:@@ -388,18 +393,12 @@ jobs:# producer and its database, neither of which is available to public CI.# They run with the real producer and PostgreSQL in the dedicated local# integration lane; do not replace them with a test-only token producer.- for suite in \- test/bug192.passwordRecovery.memberRegistration.realPostgres.integration.test.ts \- test/r4l1.resetPasswordPayload.externalRest.realPostgres.integration.test.ts; do- test -s "$suite" || {- echo "excluded private recovery suite is missing or empty: $suite" >&2- exit 1- }- done+ node ../scripts/ci/password-recovery-suite-contract.mjs verifyFORCE_COLOR=0 NO_COLOR=1 npm test -- --run realPostgres \--exclude 'test/bug192.passwordRecovery.memberRegistration.realPostgres.integration.test.ts' \--exclude 'test/r4l1.resetPasswordPayload.externalRest.realPostgres.integration.test.ts' \--reporter=default --reporter=json --outputFile="$report" 2>&1 | tee "$log_file"+ node ../scripts/ci/password-recovery-suite-contract.mjs report publicPostgres "$report"sed $'s/\033\\[[0-9;]*m//g' "$log_file" > "$normalized_log"grep -Eq 'Test Files[[:space:]]+[1-9][0-9]* passed' "$normalized_log" || {echo 'real-Postgres control-api lane executed zero passing test files' >&2diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 1eac31572..a2a46f472 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.767",+ "version": "0.1.768","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.767",+ "version": "0.1.768","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 43c868b52..28ecce306 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.767",+ "version": "0.1.768","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/test/helpers/passwordRecoveryResponseProxy.ts b/control-api/test/helpers/passwordRecoveryResponseProxy.tsnew file mode 100644index 000000000..8b1115370--- /dev/null+++ b/control-api/test/helpers/passwordRecoveryResponseProxy.ts@@ -0,0 +1,121 @@+import express from 'express'++const internalServiceToken = 'Synthetic-R6-Producer-Contract-Token'++export function responseDropProxyApp(+ producerBaseUrl: string,+ onDroppedReset: () => void,+ options: {+ dropResetResponse?: boolean+ resetFault?:+ | 'html'+ | 'missing_session'+ | 'empty_session'+ | 'invalid_payload'+ | 'legacy_busy'+ | 'legacy_unavailable'+ } = {}+) {+ const producerBase = new URL(producerBaseUrl)+ const expectedProducerBaseUrl = `http://127.0.0.1:${producerBase.port}/api/v1`+ if (+ producerBase.protocol !== 'http:' ||+ producerBase.hostname !== '127.0.0.1' ||+ !producerBase.port ||+ producerBase.username ||+ producerBase.password ||+ producerBase.pathname !== '/api/v1' ||+ producerBase.search ||+ producerBase.hash ||+ producerBaseUrl !== expectedProducerBaseUrl+ ) {+ throw new Error('response-drop proxy requires the task-owned loopback Control API producer')+ }++ const previewRequestPath = '/api/v1/external/invitations/token/r6-synthetic-reset-proof'+ const resetRequestPath = '/api/v1/external/invitations/password-token'+ const previewProducerUrl = new URL(previewRequestPath, producerBase.origin)+ const resetProducerUrl = new URL(resetRequestPath, producerBase.origin)+ const dropResetResponse = options.dropResetResponse ?? true+ const app = express()+ app.use(express.json())+ const forwardProducerResponse = async (+ req: express.Request,+ res: express.Response,+ method: 'GET' | 'POST',+ producerUrl: URL,+ dropResponse: boolean+ ) => {+ const requestPath = method === 'GET' ? previewRequestPath : resetRequestPath+ if (req.originalUrl !== requestPath) {+ res.sendStatus(404)+ return+ }+ if (+ req.headers.authorization !== `Bearer ${internalServiceToken}` ||+ req.headers['x-service-token'] !== 'external-rest-api'+ ) {+ res.sendStatus(404)+ return+ }++ const headers: Record<string, string> = {+ authorization: `Bearer ${internalServiceToken}`,+ 'x-service-token': 'external-rest-api',+ 'content-type': 'application/json',+ }+ const clientIp = req.headers['x-external-client-ip']+ if (typeof clientIp === 'string') headers['x-external-client-ip'] = clientIp+ const upstream = await fetch(producerUrl, {+ method,+ headers,+ body: method === 'POST' ? JSON.stringify(req.body) : undefined,+ redirect: 'manual',+ signal: AbortSignal.timeout(15_000),+ })+ const body = await upstream.text()+ if (method === 'POST' && options.resetFault) {+ onDroppedReset()+ if (options.resetFault === 'html') {+ res.status(502).type('text/html').send('<html>synthetic gateway failure</html>')+ } else if (+ options.resetFault === 'legacy_busy' ||+ options.resetFault === 'legacy_unavailable'+ ) {+ const busy = options.resetFault === 'legacy_busy'+ res.setHeader('retry-after', busy ? '9' : '1200')+ res.setHeader('x-ratelimit-remaining', '0')+ res.status(busy ? 429 : 503).json({+ error: busy ? 'verification_busy' : 'authority_failure',+ diagnostic: 'private Control API detail',+ })+ } else if (options.resetFault === 'invalid_payload') {+ res.status(400).json({ error: 'invalid payload' })+ } else {+ const payload = JSON.parse(body)+ if (options.resetFault === 'missing_session') delete payload.token+ else payload.token = ''+ res.status(upstream.status).json(payload)+ }+ return+ }+ if (dropResponse) {+ onDroppedReset()+ req.socket.destroy()+ return+ }+ res.status(upstream.status).type('application/json').send(body)+ }+ app.get(previewRequestPath, async (req, res) => {+ if (req.method !== 'GET') {+ res.sendStatus(404)+ return+ }+ await forwardProducerResponse(req, res, 'GET', previewProducerUrl, false)+ })+ app.post(resetRequestPath, async (req, res) =>+ forwardProducerResponse(req, res, 'POST', resetProducerUrl, dropResetResponse)+ )+ app.use((_req, res) => res.sendStatus(404))+ return app+}diff --git a/external-rest-api/test/r6.invitationProducerMappings.contract.test.ts b/control-api/test/passwordRecovery.http.contract.test.tssimilarity index 72%rename from external-rest-api/test/r6.invitationProducerMappings.contract.test.tsrename to control-api/test/passwordRecovery.http.contract.test.tsindex 7f1f6b13c..b7e5de22c 100644--- a/external-rest-api/test/r6.invitationProducerMappings.contract.test.ts+++ b/control-api/test/passwordRecovery.http.contract.test.ts@@ -1,17 +1,36 @@-import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'import express from 'express'import { request as httpRequest } from 'node:http'import type { IncomingHttpHeaders, Server } from 'node:http'-import request from 'supertest'-import { requireInternalToken } from '../../control-api/src/middleware/internalServiceAuth.js'-import { createExternalInvitationsRouter } from '../../control-api/src/routes/external/invitations.js'-import { PasswordAdmissionError } from '../../control-api/src/services/auth/passwordCredentialVerification.js'-import { config as externalConfig } from '../src/config.js'-import { createInvitationsRouter } from '../src/routes/invitations.js'+import { requireInternalToken } from '../src/middleware/internalServiceAuth.js'+import { createExternalInvitationsRouter } from '../src/routes/external/invitations.js'+import { createExternalUsersRouter } from '../src/routes/external/users.js'+import { PasswordAdmissionError } from '../src/services/auth/passwordCredentialVerification.js'+import {+ signExternalSessionToken,+ verifyExternalSessionToken,+} from '../src/utils/auth/externalSessionAuthToken.js'+import {+ type ExternalRestHttpProcess,+ boundedRequest as request,+ startExternalRestHttpProcess,+} from './helpers/externalRestHttpProcess.js'+import { responseDropProxyApp } from './helpers/passwordRecoveryResponseProxy.js'++const externalConfig = {+ controlApiBaseUrl: '',+ controlApiServiceToken: '',+ controlApiServiceName: 'external-rest-api',+}+const children: ExternalRestHttpProcess[] = []+let sessionToken: stringconst internalServiceToken = 'Synthetic-R6-Producer-Contract-Token'const producerConfig = vi.hoisted(() => ({internalServiceTokens: { 'external-rest-api': 'Synthetic-R6-Producer-Contract-Token' },+ sessionJwtPrivateKey: process.env.CONTROL_API_SESSION_JWT_PRIVATE_KEY!,+ jwtIssuer: 'control-api',+ jwtAudience: 'profile-ui',approvalRlExternalClientIpPerMin: 100,approvalRlExternalEdgePerMin: 100,}))@@ -23,21 +42,18 @@ const directory = vi.hoisted(() => ({setInvitationPasswordForEmail: vi.fn(),setInvitationPasswordForUser: vi.fn(),verifyUserPassword: vi.fn(),+ updateUserPassword: vi.fn(),}))const desktopFlow = vi.hoisted(() => ({ storeDesktopAuthorizationToken: vi.fn() }))-vi.mock('../../control-api/src/config.js', () => ({ config: producerConfig }))-vi.mock('../../control-api/src/utils/auth/externalSessionAuthToken.js', () => ({- signExternalSessionToken: () => 'synthetic-producer-session',-}))-vi.mock('../../control-api/src/services/directory/index.js', () => directory)-vi.mock('../../control-api/src/services/invitationFlowRegistrationService.js', () => ({+vi.mock('../src/config.js', () => ({ config: producerConfig }))+vi.mock('../src/services/directory/index.js', () => directory)+vi.mock('../src/services/invitationFlowRegistrationService.js', () => ({...flow,...desktopFlow,}))-vi.mock('../../control-api/src/middleware/rateLimitMiddleware.js', async importOriginal => {- const real =- await importOriginal<typeof import('../../control-api/src/middleware/rateLimitMiddleware.js')>()+vi.mock('../src/middleware/rateLimitMiddleware.js', async importOriginal => {+ const real = await importOriginal<typeof import('../src/middleware/rateLimitMiddleware.js')>()return {...real,rateLimitMiddleware:@@ -45,7 +61,8 @@ vi.mock('../../control-api/src/middleware/rateLimitMiddleware.js', async importOnext(),}})-vi.mock('../../control-api/src/middleware/externalSessionAuth.js', () => ({+vi.mock('../src/middleware/externalSessionAuth.js', () => ({+ requireExternalUserParamMatch: () => (_req: unknown, _res: unknown, next: () => void) => next(),rejectBodyUserTeamMismatch: (_req: express.Request,_res: express.Response,@@ -66,16 +83,6 @@ vi.mock('../../control-api/src/middleware/externalSessionAuth.js', () => ({next()},}))-vi.mock('../src/authToken.js', () => ({- verifyToken: () => ({- userId: 'r6-user',- email: '[email protected]',- teamId: '',- role: 'member',- exp: 4_102_444_800,- }),-}))-const preview = {id: 'r6-reset-row',email: '[email protected]',@@ -362,109 +369,37 @@ describe('response-drop proxy outbound boundary', () => {})})-function publicApp() {- const app = express()- app.set('trust proxy', 1)- app.use(express.json())- app.use(createInvitationsRouter())- app.use((error: unknown, _req: express.Request, res: express.Response, _next: unknown) => {- res.status(500).json({ error: 'Internal Server Error' })+async function publicApp() {+ const child = await startExternalRestHttpProcess({+ controlApiBaseUrl: externalConfig.controlApiBaseUrl,+ controlApiServiceToken: externalConfig.controlApiServiceToken,+ jwtPrivateKey: producerConfig.sessionJwtPrivateKey,})- return app+ children.push(child)+ return child.baseUrl}function producerResponseApp() {const app = express()app.use(express.json())- app.use('/api/v1', requireInternalToken, createExternalInvitationsRouter())- return app-}--function responseDropProxyApp(- producerBaseUrl: string,- onDroppedReset: () => void,- options: { dropResetResponse?: boolean } = {}-) {- const producerBase = new URL(producerBaseUrl)- const expectedProducerBaseUrl = `http://127.0.0.1:${producerBase.port}/api/v1`- if (- producerBase.protocol !== 'http:' ||- producerBase.hostname !== '127.0.0.1' ||- !producerBase.port ||- producerBase.username ||- producerBase.password ||- producerBase.pathname !== '/api/v1' ||- producerBase.search ||- producerBase.hash ||- producerBaseUrl !== expectedProducerBaseUrl- ) {- throw new Error('response-drop proxy requires the task-owned loopback Control API producer')- }-- const previewRequestPath = '/api/v1/external/invitations/token/r6-synthetic-reset-proof'- const resetRequestPath = '/api/v1/external/invitations/password-token'- const previewProducerUrl = new URL(previewRequestPath, producerBase.origin)- const resetProducerUrl = new URL(resetRequestPath, producerBase.origin)- const dropResetResponse = options.dropResetResponse ?? true- const app = express()- app.use(express.json())- const forwardProducerResponse = async (- req: express.Request,- res: express.Response,- method: 'GET' | 'POST',- producerUrl: URL,- dropResponse: boolean- ) => {- const requestPath = method === 'GET' ? previewRequestPath : resetRequestPath- if (req.originalUrl !== requestPath) {- res.sendStatus(404)- return- }- if (- req.headers.authorization !== `Bearer ${internalServiceToken}` ||- req.headers['x-service-token'] !== 'external-rest-api'- ) {- res.sendStatus(404)- return- }-- const headers: Record<string, string> = {- authorization: `Bearer ${internalServiceToken}`,- 'x-service-token': 'external-rest-api',- 'content-type': 'application/json',- }- const clientIp = req.headers['x-external-client-ip']- if (typeof clientIp === 'string') headers['x-external-client-ip'] = clientIp- const upstream = await fetch(producerUrl, {- method,- headers,- body: method === 'POST' ? JSON.stringify(req.body) : undefined,- redirect: 'manual',- })- const body = await upstream.text()- if (dropResponse) {- onDroppedReset()- req.socket.destroy()- return- }- res.status(upstream.status).type('application/json').send(body)- }- app.get(previewRequestPath, async (req, res) => {- if (req.method !== 'GET') {- res.sendStatus(404)- return- }- await forwardProducerResponse(req, res, 'GET', previewProducerUrl, false)- })- app.post(resetRequestPath, async (req, res) =>- forwardProducerResponse(req, res, 'POST', resetProducerUrl, dropResetResponse)+ app.use(+ '/api/v1',+ requireInternalToken,+ createExternalInvitationsRouter(),+ createExternalUsersRouter({} as never))- app.use((_req, res) => res.sendStatus(404))return app}describe('invitation/password producer response mappings', () => {beforeAll(async () => {+ sessionToken = signExternalSessionToken({+ userId: preview.userId,+ email: preview.email,+ teamId: null,+ role: 'member',+ authGeneration: 1,+ })previousControlApiBaseUrl = externalConfig.controlApiBaseUrlpreviousControlApiServiceToken = externalConfig.controlApiServiceTokenpreviousControlApiServiceName = externalConfig.controlApiServiceName@@ -496,6 +431,12 @@ describe('invitation/password producer response mappings', () => {droppedResetResponsesForTest = () => droppedResetResponses})+ afterEach(async () => {+ const results = await Promise.allSettled(children.splice(0).map(child => child.stop()))+ const failed = results.find(result => result.status === 'rejected')+ if (failed?.status === 'rejected') throw failed.reason+ })+afterAll(async () => {externalConfig.controlApiBaseUrl = previousControlApiBaseUrlexternalConfig.controlApiServiceToken = previousControlApiServiceToken@@ -560,12 +501,14 @@ describe('invitation/password producer response mappings', () => {directory.setInvitationPasswordForEmail.mockResolvedValue(result)}- const response = await request(publicApp()).post('/invitations/password').send({- token: 'r6-synthetic-reset-proof',- email: preview.email,- invitationId: preview.id,- password: 'R6-synthetic-valid-password',- })+ const response = await request(await publicApp())+ .post('/api/v1/invitations/password')+ .send({+ token: 'r6-synthetic-reset-proof',+ email: preview.email,+ invitationId: preview.id,+ password: 'R6-synthetic-valid-password',+ })expect(response.status).toBe(status)expect(response.body).toEqual(body)@@ -586,12 +529,14 @@ describe('invitation/password producer response mappings', () => {new PasswordAdmissionError(429, 17, 'verification_busy'))- const response = await request(publicApp()).post('/invitations/password').send({- token: 'r6-synthetic-reset-proof',- email: preview.email,- invitationId: preview.id,- password: 'R6-synthetic-valid-password',- })+ const response = await request(await publicApp())+ .post('/api/v1/invitations/password')+ .send({+ token: 'r6-synthetic-reset-proof',+ email: preview.email,+ invitationId: preview.id,+ password: 'R6-synthetic-valid-password',+ })expect(response.status).toBe(429)expect(response.body).toEqual({ error: 'rate_limited', retryAfterSeconds: 17 })@@ -616,8 +561,8 @@ describe('invitation/password producer response mappings', () => {expect(producerResponse.body).toEqual({ error: 'invalid payload' })expect(directory.setInvitationPasswordForEmail).not.toHaveBeenCalled()- const response = await request(publicApp())- .post('/invitations/password')+ const response = await request(await publicApp())+ .post('/api/v1/invitations/password').set('x-forwarded-for', '198.51.100.41').send({token: 'r6-synthetic-reset-proof',@@ -730,9 +675,9 @@ describe('invitation/password producer response mappings', () => {expect(producerResponse.headers['retry-after']).toBeUndefined()expect(producerResponse.headers['set-cookie']).toBeUndefined()- const response = await request(publicApp())- .post('/invitations/password')- .set('authorization', 'Bearer r6-synthetic-session')+ const response = await request(await publicApp())+ .post('/api/v1/invitations/password')+ .set('authorization', `Bearer ${sessionToken}`).set('x-forwarded-for', invitationContractClientIp()).send({ invitationId: scenario.invitationId, password: scenario.password })@@ -793,9 +738,9 @@ describe('invitation/password producer response mappings', () => {expect(producerResponse.body).toEqual(scenario.producerBody)expect(producerResponse.headers['retry-after']).toBe(String(scenario.error.retryAfterSeconds))- const response = await request(publicApp())- .post('/invitations/password')- .set('authorization', 'Bearer r6-synthetic-session')+ const response = await request(await publicApp())+ .post('/api/v1/invitations/password')+ .set('authorization', `Bearer ${sessionToken}`).set('x-forwarded-for', invitationContractClientIp()).send({ invitationId: payload.invitationId, password: payload.password })@@ -835,8 +780,8 @@ describe('invitation/password producer response mappings', () => {},})- const response = await request(publicApp())- .post('/invitations/password')+ const response = await request(await publicApp())+ .post('/api/v1/invitations/password').set('x-forwarded-for', '198.51.100.42').send({token: 'r6-synthetic-reset-proof',@@ -855,10 +800,20 @@ describe('invitation/password producer response mappings', () => {passwordUpdated: true,})expect(response.body).not.toHaveProperty('token')- expect(String(response.headers['set-cookie'])).toContain(- 'profile_session=synthetic-producer-session'- )+ expect(String(response.headers['set-cookie'])).toContain('profile_session=')expect(String(response.headers['set-cookie'])).toContain('HttpOnly')+ const cookie = String(response.headers['set-cookie']).match(/profile_session=([^;]+)/)?.[1]+ expect(cookie).toBeTruthy()+ const claims = verifyExternalSessionToken(decodeURIComponent(cookie!))+ expect(claims).toMatchObject({+ userId: preview.userId,+ email: preview.email,+ teamId: null,+ role: 'member',+ authGeneration: 7,+ })+ expect(claims!.exp).toBeGreaterThan(Math.floor(Date.now() / 1000))+expect(directory.setInvitationPasswordForEmail).toHaveBeenCalledWith(preview.email,preview.id,@@ -894,8 +849,8 @@ describe('invitation/password producer response mappings', () => {const response = await (async () => {try {- return await request(publicApp())- .post('/invitations/password')+ return await request(await publicApp())+ .post('/api/v1/invitations/password').set('x-forwarded-for', '198.51.100.43').send({token: 'r6-synthetic-reset-proof',@@ -920,9 +875,9 @@ describe('invitation/password producer response mappings', () => {it('maps a real producer password mismatch for desktop authorization', async () => {directory.verifyUserPassword.mockResolvedValueOnce(false)- const response = await request(publicApp())- .post('/invitations/desktop-authorization')- .set('authorization', 'Bearer r6-synthetic-session')+ const response = await request(await publicApp())+ .post('/api/v1/invitations/desktop-authorization')+ .set('authorization', `Bearer ${sessionToken}`).send({ password: 'R6-synthetic-current-password' })expect(response.status).toBe(401)@@ -942,9 +897,9 @@ describe('invitation/password producer response mappings', () => {new PasswordAdmissionError(503, 23, 'authority_failure'))- const response = await request(publicApp())- .post('/invitations/desktop-authorization')- .set('authorization', 'Bearer r6-synthetic-session')+ const response = await request(await publicApp())+ .post('/api/v1/invitations/desktop-authorization')+ .set('authorization', `Bearer ${sessionToken}`).send({ password: 'R6-synthetic-current-password' })expect(response.status).toBe(503)@@ -963,9 +918,9 @@ describe('invitation/password producer response mappings', () => {))- const response = await request(publicApp())- .post('/invitations/desktop-authorization')- .set('authorization', 'Bearer r6-synthetic-session')+ const response = await request(await publicApp())+ .post('/api/v1/invitations/desktop-authorization')+ .set('authorization', `Bearer ${sessionToken}`).send({ password: 'R6-synthetic-current-password' })expect(response.status).toBe(404)@@ -976,4 +931,181 @@ describe('invitation/password producer response mappings', () => {)expect(desktopFlow.storeDesktopAuthorizationToken).toHaveBeenCalledOnce()})+ it.each(['reset', 'accepted', 'desktop'] as const)(+ 'maps actual internal-service authentication rejection for %s to sanitized outage',+ async operation => {+ const saved = producerConfig.internalServiceTokens['external-rest-api']+ if (operation === 'reset') {+ directory.getInvitationByToken.mockImplementationOnce(async () => {+ delete producerConfig.internalServiceTokens['external-rest-api']+ return preview+ })+ } else delete producerConfig.internalServiceTokens['external-rest-api']+ try {+ const endpoint = operation === 'desktop' ? 'desktop-authorization' : 'password'+ const payload =+ operation === 'reset'+ ? {+ token: 'r6-synthetic-reset-proof',+ email: preview.email,+ invitationId: preview.id,+ password: 'R6-synthetic-valid-password',+ }+ : operation === 'accepted'+ ? {+ invitationId: 'r6-accepted-member-row',+ password: 'R6-synthetic-valid-password',+ }+ : { password: 'R6-synthetic-valid-password' }+ const response = await request(await publicApp())+ .post(`/api/v1/invitations/${endpoint}`)+ .set('authorization', `Bearer ${sessionToken}`)+ .send(payload)+ expect(response.status).toBe(503)+ expect(response.body).toEqual({ error: 'authority_unavailable', retryAfterSeconds: 2 })+ expect(response.headers['retry-after']).toBe('2')+ expect(response.headers['set-cookie']).toBeUndefined()+ expect(JSON.stringify(response.body)).not.toMatch(+ /Unauthorized|api\/v1|r6-|example\.invalid/i+ )+ expect(directory.setInvitationPasswordForEmail).not.toHaveBeenCalled()+ expect(directory.setInvitationPasswordForUser).not.toHaveBeenCalled()+ expect(directory.verifyUserPassword).not.toHaveBeenCalled()+ } finally {+ producerConfig.internalServiceTokens['external-rest-api'] = saved+ }+ }+ )++ it.each([+ [+ 'credential_changed',+ 'Your password changed during this request. Sign in again with your new password.',+ ],+ ['password_not_set', 'Password is not set'],+ ])('preserves the real producer %s password-change guidance', async (error, message) => {+ directory.updateUserPassword.mockResolvedValue({ error })+ const response = await request(await publicApp())+ .put('/api/v1/me/password')+ .set('authorization', `Bearer ${sessionToken}`)+ .send({ currentPassword: 'synthetic-current', newPassword: 'synthetic-next-password' })+ expect(response.status).toBe(409)+ expect(response.body).toEqual({ error: message })+ expect(response.headers['set-cookie']).toBeUndefined()+ expect(directory.updateUserPassword).toHaveBeenCalledOnce()+ })++ it.each([+ [429, 9, 'rate_limited', 9],+ [503, 1200, 'authority_unavailable', 900],+ ])(+ 'preserves producer authority %s retry bounds after real preview',+ async (status, retry, code, bounded) => {+ directory.setInvitationPasswordForEmail.mockRejectedValue(+ new PasswordAdmissionError(+ status as 429 | 503,+ retry,+ status === 429 ? 'verification_busy' : 'authority_failure'+ )+ )+ const response = await request(await publicApp())+ .post('/api/v1/invitations/password')+ .send({+ token: 'r6-synthetic-reset-proof',+ email: preview.email,+ invitationId: preview.id,+ password: 'R6-synthetic-valid-password',+ })+ expect(response.status).toBe(status)+ expect(response.body).toEqual({ error: code, retryAfterSeconds: bounded })+ expect(response.headers['retry-after']).toBe(String(bounded))+ expect(response.headers['set-cookie']).toBeUndefined()+ expect(JSON.stringify(response.body)).not.toMatch(+ /diagnostic|verification_busy|authority_failure/i+ )+ expect(directory.getInvitationByToken).toHaveBeenCalledTimes(2)+ expect(directory.setInvitationPasswordForEmail).toHaveBeenCalledOnce()+ }+ )++ it.each([+ 'html',+ 'missing_session',+ 'empty_session',+ 'invalid_payload',+ 'legacy_busy',+ 'legacy_unavailable',+ ] as const)(+ 'alters only %s after real preview and serialized successful producer completion',+ async resetFault => {+ directory.setInvitationPasswordForEmail.mockResolvedValue({+ data: {+ ...preview,+ status: 'accepted',+ role: 'member',+ passwordUpdated: true,+ sessionContext: {+ userId: preview.userId,+ email: preview.email,+ teamId: null,+ role: 'member',+ authGeneration: 7,+ },+ },+ })+ let writes = 0+ const producerBaseUrl = externalConfig.controlApiBaseUrl+ const proxy = await listenOnLoopback(+ responseDropProxyApp(+ producerBaseUrl,+ () => {+ writes+++ },+ { resetFault }+ )+ )+ try {+ externalConfig.controlApiBaseUrl = `http://127.0.0.1:${listeningPort(proxy)}/api/v1`+ const response = await request(await publicApp())+ .post('/api/v1/invitations/password')+ .send({+ token: 'r6-synthetic-reset-proof',+ email: preview.email,+ invitationId: preview.id,+ password: 'R6-synthetic-valid-password',+ })+ if (resetFault === 'missing_session' || resetFault === 'empty_session') {+ expect(response.status).toBe(502)+ expect(response.body).toEqual({ error: 'Failed to restore account session' })+ } else if (resetFault === 'legacy_busy' || resetFault === 'legacy_unavailable') {+ const busy = resetFault === 'legacy_busy'+ expect(response.status).toBe(busy ? 429 : 503)+ expect(response.body).toEqual({+ error: busy ? 'rate_limited' : 'authority_unavailable',+ retryAfterSeconds: busy ? 9 : 900,+ })+ expect(response.headers['retry-after']).toBe(busy ? '9' : '900')+ expect(response.headers['x-ratelimit-remaining']).toBeUndefined()+ expect(JSON.stringify(response.body)).not.toMatch(+ /diagnostic|private Control API detail|verification_busy|authority_failure/i+ )+ } else {+ expect(response.status).toBe(503)+ expect(response.body).toEqual({+ error: resetFault === 'html' ? 'recovery_outcome_unknown' : 'authority_unavailable',+ retryAfterSeconds: 2,+ })+ expect(response.headers['retry-after']).toBe('2')+ }+ expect(response.headers['set-cookie']).toBeUndefined()+ expect(JSON.stringify(response.body)).not.toMatch(/r6-|gateway|sql|stack|connection reset/i)+ expect(writes).toBe(1)+ expect(directory.getInvitationByToken).toHaveBeenCalledTimes(2)+ expect(directory.setInvitationPasswordForEmail).toHaveBeenCalledOnce()+ } finally {+ externalConfig.controlApiBaseUrl = producerBaseUrl+ await closeLoopbackServer(proxy)+ }+ }+ )})diff --git a/control-api/test/r2h1.invitationAdmission.realPostgres.integration.test.ts b/control-api/test/r2h1.invitationAdmission.realPostgres.integration.test.tsindex 3b8ad8e3c..8cb074f47 100644--- a/control-api/test/r2h1.invitationAdmission.realPostgres.integration.test.ts+++ b/control-api/test/r2h1.invitationAdmission.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 flow = vi.hoisted(() => ({@@ -22,10 +26,13 @@ realPg('R2-H1 invitation admission identity on PostgreSQL', () => {let db: typeof import('../src/db.js')let controlApp: express.Expresslet controlServer: Server- let edge: express.Express- let externalConfig: (typeof import('../../external-rest-api/src/config.js'))['config']- let previousBaseUrl: string- let previousServiceToken: string+ let edge: string+ let publicProcess: ExternalRestHttpProcess+ let completionPosts = 0+ let invitationId: string+ let invitationToken: string+ const email = '[email protected]'+ const completionProof = 'synthetic-owned-completion-proof'beforeAll(async () => {admin = new Pool({ connectionString: adminUrl })@@ -45,6 +52,15 @@ realPg('R2-H1 invitation admission identity on PostgreSQL', () => {db = await import('../src/db.js')await db.initDb()+ await db.pool.query('INSERT INTO users(email) VALUES ($1)', [email])+ const { createSilentPasswordResetInvitation } =+ await import('../src/services/directory/passwordResetInvitations.js')+ const invitation = await createSilentPasswordResetInvitation({+ email,+ inviteeName: 'Synthetic admission principal',+ })+ invitationId = invitation.id+ invitationToken = invitation.tokenconst { requireInternalService, requireInternalToken } =await import('../src/middleware/internalServiceAuth.js')const { createExternalInvitationsRouter } =@@ -52,6 +68,11 @@ realPg('R2-H1 invitation admission identity on PostgreSQL', () => {controlApp = express()controlApp.use(express.json())controlApp.use(requireInternalToken)+ controlApp.use((req, _res, next) => {+ if (req.method === 'POST' && req.path === '/api/v1/external/invitations/password-token')+ completionPosts+++ next()+ })const api = express.Router()api.use('/external', requireInternalService('external-rest-api'))api.use(createExternalInvitationsRouter())@@ -59,64 +80,31 @@ realPg('R2-H1 invitation admission identity on PostgreSQL', () => {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 { ControlApiError, controlApiRequest } =- await import('../../external-rest-api/src/controlApiClient.js')- const { withExternalRequestContext } =- await import('../../external-rest-api/src/requestContext.js')-- // This test edge uses the production request-context middleware and- // Control API client. The client, rather than the test, produces the- // authenticated x-external-client-ip header consumed by Control API.- edge = express()- edge.set('trust proxy', 1)- edge.use(express.json())- edge.use(withExternalRequestContext)- edge.get('/probe/preview/:token', async (req, res, next) => {- try {- res- .status(200)- .json(await controlApiRequest('GET', `/external/invitations/token/${req.params.token}`))- } catch (error) {- if (error instanceof ControlApiError) {- res.status(error.status).json(error.body)- return- }- next(error)- }- })- edge.post('/probe/complete', async (req, res, next) => {- try {- res.status(200).json(- await controlApiRequest('POST', '/external/invitations/password-token', {- body: req.body,- })- )- } catch (error) {- if (error instanceof ControlApiError) {- res.status(error.status).json(error.body)- return- }- next(error)- }+ 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(),})+ edge = publicProcess.baseUrl}, 60_000)beforeEach(async () => {- flow.validateInvitationFlowToken.mockReset().mockRejectedValue(new Error('invalid proof'))+ completionPosts = 0+ flow.validateInvitationFlowToken+ .mockReset()+ .mockImplementation(async (token: string, claimedEmail?: string) => {+ if (token === completionProof && claimedEmail === undefined) {+ return { email, invitationUuid: invitationToken }+ }+ throw new Error('invalid proof')+ })await db.pool.query('TRUNCATE rate_limit_buckets')})afterAll(async () => {+ let childCleanup: PromiseSettledResult<void | undefined> | undefinedtry {- 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()))@@ -131,19 +119,20 @@ realPg('R2-H1 invitation admission identity on PostgreSQL', () => {await admin?.end()vi.unstubAllEnvs()}+ if (childCleanup?.status === 'rejected') throw childCleanup.reason})async function preview(source: string) {return request(edge)- .get('/probe/preview/not-a-signed-flow-token')+ .get('/api/v1/invitations/token/not-a-signed-flow-token').set('X-Forwarded-For', source)}async function complete(source: string) {- return request(edge).post('/probe/complete').set('X-Forwarded-For', source).send({- email: '[email protected]',- token: 'invalid',- invitationId: '00000000-0000-4000-8000-000000000001',+ return request(edge).post('/api/v1/invitations/password').set('X-Forwarded-For', source).send({+ email,+ token: completionProof,+ invitationId,password: 'Synthetic-Password-12',})}@@ -158,7 +147,13 @@ realPg('R2-H1 invitation admission identity on PostgreSQL', () => {const response = await complete('198.51.100.11')expect(response.status).toBe(400)expect(response.body).toEqual({ error: 'invalid_invitation' })- expect(flow.validateInvitationFlowToken).toHaveBeenCalledTimes(11)+ expect(completionPosts).toBe(1)+ const buckets = (await db.pool.query('SELECT bucket_key FROM rate_limit_buckets')).rows.map(+ row => row.bucket_key+ )+ expect(buckets).toContain('invite-token:password-token:external-client-ip:198.51.100.11')+ expect(buckets).toContain('invite-token:preview:external-client-ip:198.51.100.11')+ expect(flow.validateInvitationFlowToken).toHaveBeenCalledTimes(12)})it('isolates completion budgets by the trusted external client identity', async () => {@@ -171,7 +166,13 @@ realPg('R2-H1 invitation admission identity on PostgreSQL', () => {const response = await complete('198.51.100.22')expect(response.status).toBe(400)expect(response.body).toEqual({ error: 'invalid_invitation' })- expect(flow.validateInvitationFlowToken).toHaveBeenCalledTimes(11)+ expect(completionPosts).toBe(11)+ const buckets = (await db.pool.query('SELECT bucket_key FROM rate_limit_buckets')).rows.map(+ row => row.bucket_key+ )+ expect(buckets).toContain('invite-token:password-token:external-client-ip:198.51.100.21')+ expect(buckets).toContain('invite-token:password-token:external-client-ip:198.51.100.22')+ expect(flow.validateInvitationFlowToken).toHaveBeenCalledTimes(22)})it('does not trust an asserted source when the internal service gate rejects the caller', async () => {diff --git a/external-rest-api/package-lock.json b/external-rest-api/package-lock.jsonindex 5ddb6259f..5d324feaa 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.121",+ "version": "0.1.122","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-external-rest-api",- "version": "0.1.121",+ "version": "0.1.122","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 a960fd9ef..680b480ff 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.121",+ "version": "0.1.122","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 d394abb7b..0e3f064db 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.121',+ externalRestApiVersion: '0.1.122',rpcProxyVersion: '0.1.126',desktopVersion: '0.11.0',minimumDesktopVersion: '0.1.252',diff --git a/external-rest-api/test/r2m3.resetPreviewFailure.public.test.ts b/external-rest-api/test/invitations.passwordRecovery.public.test.tssimilarity index 70%rename from external-rest-api/test/r2m3.resetPreviewFailure.public.test.tsrename to external-rest-api/test/invitations.passwordRecovery.public.test.tsindex 6ae3ad19a..5024db735 100644--- a/external-rest-api/test/r2m3.resetPreviewFailure.public.test.ts+++ b/external-rest-api/test/invitations.passwordRecovery.public.test.ts@@ -1,9 +1,10 @@-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } 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'+import { setupInvitationPasswordWithToken } from '../src/services/invitationsService.js'const recoveryProof = 'synthetic-one-use-recovery-proof'@@ -116,3 +117,62 @@ describe('password reset preview authority failures', () => {expect(requestedPath).toContain(encodeURIComponent(recoveryProof))})})++const fetchMock = vi.fn()++describe('setupInvitationPasswordWithToken', () => {+ beforeEach(() => {+ fetchMock.mockReset()+ vi.stubGlobal('fetch', fetchMock)+ })++ afterEach(() => vi.unstubAllGlobals())++ it('preserves invalid recovery proof as a safe link error', async () => {+ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ error: 'invalid_invitation' }), { status: 400 })+ )++ await expect(+ setupInvitationPasswordWithToken(+ 'synthetic-proof',+ '[email protected]',+ 'synthetic-row-id',+ 'synthetic-password'+ )+ ).resolves.toEqual({ error: 'invalid_invitation' })+ })++ it('continues to identify password-policy rejections as invalid passwords', async () => {+ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ error: 'invalid_password' }), { status: 400 })+ )++ await expect(+ setupInvitationPasswordWithToken(+ 'synthetic-proof',+ '[email protected]',+ 'synthetic-row-id',+ 'short'+ )+ ).resolves.toEqual({ error: 'invalid_password' })+ })++ it('keeps invalid-payload outside the allowlist when a password was supplied', async () => {+ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ error: 'invalid payload' }), { status: 400 })+ )++ await expect(+ setupInvitationPasswordWithToken(+ 'synthetic-proof',+ '[email protected]',+ 'synthetic-row-id',+ 'Synthetic-Valid-Password-123'+ )+ ).rejects.toMatchObject({+ status: 503,+ body: { error: 'authority_unavailable' },+ })+ })+})diff --git a/external-rest-api/test/r2m3.resetTransport.public.test.ts b/external-rest-api/test/r2m3.resetTransport.public.test.tsdeleted file mode 100644index 09241f14d..000000000--- a/external-rest-api/test/r2m3.resetTransport.public.test.ts+++ /dev/null@@ -1,174 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import express from 'express'-import request from 'supertest'-import { config } from '../src/config.js'-import { createInvitationsRouter } from '../src/routes/invitations.js'--const fetchMock = vi.fn<typeof fetch>()--const preview = {- id: 'synthetic-reset-row',- email: '[email protected]',- purpose: 'password_reset' as const,- status: 'pending',- expiresAt: '2030-01-01T00:00:00.000Z',- acceptedAt: null,- userId: 'synthetic-member-id',- passwordPending: true,- teamId: null,- teamName: null,- role: 'member',-}--function jsonResponse(status: number, body: unknown, headers: Record<string, string> = {}) {- return new Response(JSON.stringify(body), {- status,- headers: { 'content-type': 'application/json', ...headers },- })-}--function makeApp() {- const app = express()- app.use(express.json())- app.use(createInvitationsRouter())- return app-}--describe('password reset transport outcomes', () => {- let previousControlApiBaseUrl: string- let previousControlApiServiceToken: string-- beforeEach(() => {- previousControlApiBaseUrl = config.controlApiBaseUrl- previousControlApiServiceToken = config.controlApiServiceToken- config.controlApiBaseUrl = 'http://control-api.synthetic.test/api/v1'- config.controlApiServiceToken = 'synthetic-internal-service-token'- fetchMock.mockReset()- vi.stubGlobal('fetch', fetchMock)- })-- afterEach(() => {- config.controlApiBaseUrl = previousControlApiBaseUrl- config.controlApiServiceToken = previousControlApiServiceToken- vi.unstubAllGlobals()- })-- function previewRequest() {- return jsonResponse(200, preview)- }-- async function submitReset() {- return request(makeApp()).post('/invitations/password').send({- token: 'synthetic-one-use-recovery-proof',- email: preview.email,- invitationId: preview.id,- password: 'Synthetic-Replacement-Password-123',- })- }-- it('reports an unknown outcome after a potentially committed reset without replaying the proof', async () => {- let passwordChanged = false- let resetProofConsumed = false- fetchMock.mockImplementation(async (input, init) => {- const url = String(input)- if (init?.method === 'GET') return previewRequest()- if (url.endsWith('/external/invitations/password-token')) {- passwordChanged = true- resetProofConsumed = true- return new Response('<html>upstream gateway failure</html>', {- status: 502,- headers: { 'content-type': 'text/html' },- })- }- throw new Error('Unexpected Control API request')- })-- const response = await submitReset()-- 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(JSON.stringify(response.body)).not.toContain('synthetic-one-use-recovery-proof')- expect(passwordChanged).toBe(true)- expect(resetProofConsumed).toBe(true)- expect(fetchMock).toHaveBeenCalledTimes(2)- })-- it('sanitizes a rejected reset transport as an unknown outcome and never retries', async () => {- fetchMock.mockImplementation(async (_input, init) => {- if (init?.method === 'GET') return previewRequest()- throw new TypeError('connection reset after request dispatch')- })-- const response = await submitReset()-- expect(response.status).toBe(503)- expect(response.body).toEqual({ error: 'recovery_outcome_unknown', retryAfterSeconds: 2 })- expect(response.headers['retry-after']).toBe('2')- expect(JSON.stringify(response.body)).not.toContain('connection reset')- expect(response.headers['set-cookie']).toBeUndefined()- expect(fetchMock).toHaveBeenCalledTimes(2)- })-- it.each([- {- status: 429,- upstreamError: 'verification_busy',- retryAfter: '9',- publicError: 'rate_limited',- retryAfterSeconds: 9,- },- {- status: 503,- upstreamError: 'authority_failure',- retryAfter: '1200',- publicError: 'authority_unavailable',- retryAfterSeconds: 900,- },- ])('preserves typed $status admission outcomes with bounded public retry guidance', async row => {- fetchMock- .mockResolvedValueOnce(previewRequest())- .mockResolvedValueOnce(- jsonResponse(- row.status,- { error: row.upstreamError, diagnostic: 'private Control API detail' },- { 'retry-after': row.retryAfter }- )- )-- const response = await submitReset()-- expect(response.status).toBe(row.status)- expect(response.body).toEqual({- error: row.publicError,- retryAfterSeconds: row.retryAfterSeconds,- })- expect(response.headers['retry-after']).toBe(String(row.retryAfterSeconds))- expect(response.headers['set-cookie']).toBeUndefined()- expect(JSON.stringify(response.body)).not.toContain('diagnostic')- expect(fetchMock).toHaveBeenCalledTimes(2)- })-- it('reports only explicit password and recovery domain rejections', async () => {- fetchMock- .mockResolvedValueOnce(previewRequest())- .mockResolvedValueOnce(jsonResponse(400, { error: 'invalid_password' }))-- const invalidPassword = await submitReset()- expect(invalidPassword.status).toBe(400)- expect(invalidPassword.body).toEqual({- error: 'Password must be between 8 and 256 characters',- })-- fetchMock- .mockResolvedValueOnce(previewRequest())- .mockResolvedValueOnce(- jsonResponse(410, { error: 'expired', detail: 'private expired-link detail' })- )- const expiredProof = await submitReset()- expect(expiredProof.status).toBe(410)- expect(expiredProof.body).toEqual({ error: 'Invitation has expired' })- expect(JSON.stringify(expiredProof.body)).not.toContain('private')- })-})diff --git a/external-rest-api/test/r2m6.resetUnknownControlApi4xx.contract.test.ts b/external-rest-api/test/r2m6.resetUnknownControlApi4xx.contract.test.tsdeleted file mode 100644index 4f0b91bba..000000000--- a/external-rest-api/test/r2m6.resetUnknownControlApi4xx.contract.test.ts+++ /dev/null@@ -1,116 +0,0 @@-import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'-import express from 'express'-import type { Server } from 'node:http'-import { config as externalConfig } from '../src/config.js'-import {- createDesktopAuthorization,- setupInvitationPassword,- setupInvitationPasswordWithToken,-} from '../src/services/invitationsService.js'--const controlApiProducerConfig = vi.hoisted(() => ({- internalServiceTokens: {} as Record<string, string>,-}))--// Keep the Control API producer middleware real while controlling only its-// allowlist input; this consumer contract test does not boot Control API config.-vi.mock('../../control-api/src/config.js', () => ({ config: controlApiProducerConfig }))--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-- beforeAll(async () => {- previousBaseUrl = externalConfig.controlApiBaseUrl- previousServiceToken = externalConfig.controlApiServiceToken- vi.resetModules()- const { requireInternalToken } =- await import('../../control-api/src/middleware/internalServiceAuth.js')-- 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- if (server) {- await new Promise<void>((resolve, reject) =>- server.close(error => (error ? reject(error) : resolve()))- )- }- })-- 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)- }- }- })-})diff --git a/external-rest-api/test/r6.resetMissingSessionToken.public.test.ts b/external-rest-api/test/r6.resetMissingSessionToken.public.test.tsdeleted file mode 100644index f772ef7fc..000000000--- a/external-rest-api/test/r6.resetMissingSessionToken.public.test.ts+++ /dev/null@@ -1,61 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest'-import express from 'express'-import request from 'supertest'-import { createInvitationsRouter } from '../src/routes/invitations.js'--const invitationService = vi.hoisted(() => ({- acceptInvitation: vi.fn(),- createDesktopAuthorization: vi.fn(),- getInvitationByToken: vi.fn(),- listPendingInvitations: vi.fn(),- setupInvitationPassword: vi.fn(),- setupInvitationPasswordWithToken: vi.fn(),-}))--vi.mock('../src/services/invitationsService.js', () => invitationService)-vi.mock('../src/authToken.js', () => ({ verifyToken: vi.fn(() => null) }))--const resetPreview = {- id: 'r6-reset-row',- email: '[email protected]',- purpose: 'password_reset',- status: 'pending',- userId: 'r6-member-id',-}--function makeApp() {- const app = express()- app.use(express.json())- app.use(createInvitationsRouter())- return app-}--beforeEach(() => {- vi.clearAllMocks()- invitationService.getInvitationByToken.mockResolvedValue(resetPreview)-})--describe('R6 reset completion session-token fail-closed contract', () => {- it.each([- ['missing', { ...resetPreview, passwordUpdated: true }],- ['empty', { ...resetPreview, token: '', passwordUpdated: true }],- ])(- 'does not authenticate a completion response with an %s session token',- async (_label, body) => {- invitationService.setupInvitationPasswordWithToken.mockResolvedValue(body)-- const response = await request(makeApp()).post('/invitations/password').send({- token: 'r6-synthetic-one-use-reset-proof',- email: resetPreview.email,- invitationId: resetPreview.id,- password: 'R6-synthetic-new-password',- })-- expect(response.status).toBe(502)- expect(response.body).toEqual({ error: 'Failed to restore account session' })- expect(response.headers['set-cookie']).toBeUndefined()- expect(JSON.stringify(response.body)).not.toContain('r6-synthetic-one-use-reset-proof')- expect(invitationService.setupInvitationPasswordWithToken).toHaveBeenCalledOnce()- }- )-})diff --git a/external-rest-api/test/routes.accessForwarding.test.ts b/external-rest-api/test/routes.accessForwarding.test.tsindex bc9d83972..cb6399fe2 100644--- a/external-rest-api/test/routes.accessForwarding.test.ts+++ b/external-rest-api/test/routes.accessForwarding.test.ts@@ -1,10 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest'import express from 'express'import request from 'supertest'-import {- PASSWORD_CREDENTIAL_CHANGED_RESPONSE,- PASSWORD_NOT_SET_RESPONSE,-} from '../../control-api/src/routes/external/passwordErrorResponses.js'import { createMeRouter } from '../src/routes/me.js'import { createTeamRouter } from '../src/routes/team.js'@@ -171,42 +167,6 @@ describe('routes/access forwarding', () => {expect(meServiceMock.getMyTeamDirectory).toHaveBeenCalledWith('user-1', 'good-token')})- it('maps the Control API credential-changed response to actionable password guidance', async () => {- const upstreamFetch = await preparePasswordApiError(PASSWORD_CREDENTIAL_CHANGED_RESPONSE)- const app = appWith(createMeRouter)-- try {- await request(app)- .put('/me/password')- .set('authorization', 'Bearer good-token')- .send({ currentPassword: 'synthetic-current', newPassword: 'synthetic-next-password' })- .expect(409)- .expect({- error: 'Your password changed during this request. Sign in again with your new password.',- })- expect(upstreamFetch).toHaveBeenCalledTimes(1)- } finally {- upstreamFetch.mockRestore()- }- })-- it('preserves the password-not-set message for the existing Control API 409 response', async () => {- const upstreamFetch = await preparePasswordApiError(PASSWORD_NOT_SET_RESPONSE)- const app = appWith(createMeRouter)-- try {- await request(app)- .put('/me/password')- .set('authorization', 'Bearer good-token')- .send({ currentPassword: 'synthetic-current', newPassword: 'synthetic-next-password' })- .expect(409)- .expect({ error: 'Password is not set' })- expect(upstreamFetch).toHaveBeenCalledTimes(1)- } finally {- upstreamFetch.mockRestore()- }- })-it('maps password-work contention to a sanitized 429 and permits a later retry', async () => {const upstreamFetch = await preparePasswordApiError({status: 429,diff --git a/external-rest-api/test/services.invitationsService.recovery.test.ts b/external-rest-api/test/services.invitationsService.recovery.test.tsdeleted file mode 100644index b7f2446e2..000000000--- a/external-rest-api/test/services.invitationsService.recovery.test.ts+++ /dev/null@@ -1,61 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { setupInvitationPasswordWithToken } from '../src/services/invitationsService.js'--const fetchMock = vi.fn()--describe('setupInvitationPasswordWithToken', () => {- beforeEach(() => {- fetchMock.mockReset()- vi.stubGlobal('fetch', fetchMock)- })-- afterEach(() => vi.unstubAllGlobals())-- it('preserves invalid recovery proof as a safe link error', async () => {- fetchMock.mockResolvedValue(- new Response(JSON.stringify({ error: 'invalid_invitation' }), { status: 400 })- )-- await expect(- setupInvitationPasswordWithToken(- 'synthetic-proof',- '[email protected]',- 'synthetic-row-id',- 'synthetic-password'- )- ).resolves.toEqual({ error: 'invalid_invitation' })- })-- it('continues to identify password-policy rejections as invalid passwords', async () => {- fetchMock.mockResolvedValue(- new Response(JSON.stringify({ error: 'invalid_password' }), { status: 400 })- )-- await expect(- setupInvitationPasswordWithToken(- 'synthetic-proof',- '[email protected]',- 'synthetic-row-id',- 'short'- )- ).resolves.toEqual({ error: 'invalid_password' })- })-- it('keeps invalid-payload outside the allowlist when a password was supplied', async () => {- fetchMock.mockResolvedValue(- new Response(JSON.stringify({ error: 'invalid payload' }), { status: 400 })- )-- await expect(- setupInvitationPasswordWithToken(- 'synthetic-proof',- '[email protected]',- 'synthetic-row-id',- 'Synthetic-Valid-Password-123'- )- ).rejects.toMatchObject({- status: 503,- body: { error: 'authority_unavailable' },- })- })-})diff --git a/scripts/ci/password-recovery-suite-contract.mjs b/scripts/ci/password-recovery-suite-contract.mjsnew file mode 100644index 000000000..ee5a6f548--- /dev/null+++ b/scripts/ci/password-recovery-suite-contract.mjs@@ -0,0 +1,114 @@+#!/usr/bin/env node+import { readFileSync, readdirSync, statSync } from 'node:fs'+import { dirname, relative, resolve } from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url'+import { pinnedSuiteViolations } from './assert-pinned-vitest-suites.mjs'++export function verifySuiteManifest(root, manifest) {+ const keys = ['version', 'publicPostgres', 'privatePostgres', 'composedContract', 'consumer']+ if (+ !manifest ||+ Object.keys(manifest).sort().join() !== keys.sort().join() ||+ manifest.version !== 1+ )+ throw new Error('Unknown recovery suite manifest schema')+ if (+ !manifest.privatePostgres ||+ Object.keys(manifest.privatePostgres).sort().join() !== 'configured,local'+ )+ throw new Error('Both exact private producer exclusions are required')+ const groups = [+ manifest.publicPostgres,+ Object.values(manifest.privatePostgres),+ manifest.composedContract,+ manifest.consumer,+ ]+ if (groups.some(group => !Array.isArray(group) || !group.length))+ throw new Error('Empty recovery suite lane')+ const entries = groups.flat()+ if (new Set(entries).size !== entries.length) throw new Error('Duplicate recovery suite')+ for (const entry of entries) {+ if (+ typeof entry !== 'string' ||+ !/^(control-api|external-rest-api)\/test\/[A-Za-z0-9./_-]+\.test\.ts$/.test(entry) ||+ entry.includes('..')+ )+ throw new Error('Invalid recovery suite path')+ const path = resolve(root, entry)+ if (!statSync(path).isFile() || !readFileSync(path, 'utf8').trim())+ throw new Error(`Missing or empty recovery suite: ${entry}`)+ }+ function collect(directory) {+ return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {+ const path = resolve(directory, entry.name)+ return entry.isDirectory()+ ? collect(path)+ : entry.name.includes('realPostgres') && entry.name.endsWith('.test.ts')+ ? [relative(root, path)]+ : []+ })+ }+ const census = collect(resolve(root, 'control-api/test')).sort()+ const expected = [...manifest.publicPostgres, ...Object.values(manifest.privatePostgres)].sort()+ if (census.join('\n') !== expected.join('\n'))+ throw new Error('PostgreSQL suite census differs from exact manifest')+ if (manifest.publicPostgres.some(entry => !entry.includes('realPostgres')))+ throw new Error('Non-PostgreSQL public selection')+ return manifest+}++export function reportViolations(root, manifest, lane, report) {+ if (!['publicPostgres', 'composedContract', 'consumer'].includes(lane))+ return ['Unknown recovery report lane']+ const expected = manifest[lane]+ const violations = pinnedSuiteViolations(+ report,+ expected.map(entry => entry.split('/').slice(1).join('/'))+ )+ if (!report?.success || report.numFailedTests !== 0 || report.numFailedTestSuites !== 0)+ violations.push('Incomplete or failed recovery report')+ if (lane === 'publicPostgres') {+ const actual = (report.testResults || []).map(file => relative(root, file.name)).sort()+ if (actual.join('\n') !== [...expected].sort().join('\n'))+ violations.push('Report physical selection differs from exact public PostgreSQL manifest')+ if (report.numPendingTests !== 0 || report.numTodoTests !== 0)+ violations.push('Required PostgreSQL report contains skipped/todo tests')+ const collected = (report.testResults || []).reduce(+ (sum, file) => sum + (file.assertionResults || []).length,+ 0+ )+ if (!collected || report.numTotalTests !== collected || report.numPassedTests !== collected)+ violations.push('Recovery reporter totals are incomplete')+ }+ return violations+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..')+ try {+ const manifest = verifySuiteManifest(+ root,+ JSON.parse(+ readFileSync(resolve(root, 'tests/contracts/password-recovery-suites.json'), 'utf8')+ )+ )+ const [command, lane, path] = process.argv.slice(2)+ if (command === 'verify' && !lane)+ console.log(+ `Recovery suite contract: ${manifest.publicPostgres.length} public PostgreSQL suites; 2 private exclusions`+ )+ else if (command === 'private' && ['local', 'configured'].includes(lane) && !path)+ console.log(manifest.privatePostgres[lane].replace(/^control-api\//, ''))+ else if (command === 'report' && path) {+ const errors = reportViolations(root, manifest, lane, JSON.parse(readFileSync(path, 'utf8')))+ if (errors.length) throw new Error(errors.join('\n'))+ console.log(`Recovery ${lane} report: complete and passing`)+ } else+ throw new Error(+ 'Usage: password-recovery-suite-contract.mjs verify | private local/configured | report lane report.json'+ )+ } catch (error) {+ console.error(error.message)+ process.exitCode = 1+ }+}diff --git a/scripts/ci/run-pr1056-private-recovery-postgres.sh b/scripts/ci/run-pr1056-private-recovery-postgres.shindex 2468edcb0..9b07357c0 100755--- a/scripts/ci/run-pr1056-private-recovery-postgres.sh+++ b/scripts/ci/run-pr1056-private-recovery-postgres.sh@@ -53,7 +53,11 @@ run_local_producer_suite() {printf 'Member Registration dependencies are missing under EVENFIRE_MEMBER_REGISTRATION_ROOT\n' >&2return 1fi- run_suite test/r4l1.resetPasswordPayload.externalRest.realPostgres.integration.test.ts+ test -s "$REPO_ROOT/external-rest-api/dist/app.js" || {+ printf 'Build External REST before the local composed producer suite\n' >&2+ return 1+ }+ run_suite "$(node "$REPO_ROOT/scripts/ci/password-recovery-suite-contract.mjs" private local)"}run_configured_producer_suite() {@@ -62,7 +66,7 @@ run_configured_producer_suite() {CONTROL_API_REAL_MEMBER_REGISTRATION_PG_URL \CONTROL_API_MEMBER_REGISTRATION_SERVICE_BASE_URL \CONTROL_API_MEMBER_REGISTRATION_HMAC_SECRET- run_suite test/bug192.passwordRecovery.memberRegistration.realPostgres.integration.test.ts+ run_suite "$(node "$REPO_ROOT/scripts/ci/password-recovery-suite-contract.mjs" private configured)"}case "$MODE" indiff --git a/scripts/tests/password-recovery-suite-contract.test.mjs b/scripts/tests/password-recovery-suite-contract.test.mjsnew file mode 100644index 000000000..c44e0057a--- /dev/null+++ b/scripts/tests/password-recovery-suite-contract.test.mjs@@ -0,0 +1,126 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import test from 'node:test'+import { fileURLToPath } from 'node:url'+import { reportViolations, verifySuiteManifest } from '../ci/password-recovery-suite-contract.mjs'++const root = fileURLToPath(new URL('../../', import.meta.url)).replace(/\/$/, '')+const manifest = JSON.parse(+ readFileSync(new URL('../../tests/contracts/password-recovery-suites.json', import.meta.url))+)+const green = () => ({+ success: true,+ numFailedTests: 0,+ numFailedTestSuites: 0,+ numPendingTests: 0,+ numTodoTests: 0,+ numTotalTests: manifest.publicPostgres.length,+ numPassedTests: manifest.publicPostgres.length,+ testResults: manifest.publicPostgres.map(name => ({+ name: `${root}/${name}`,+ status: 'passed',+ assertionResults: [{ status: 'passed' }],+ })),+})+test('exact checked-in census and full reporter pass', () => {+ assert.equal(verifySuiteManifest(root, manifest), manifest)+ assert.deepEqual(reportViolations(root, manifest, 'publicPostgres', green()), [])+})+for (const [label, mutate] of [+ [+ 'unknown schema',+ m => {+ m.extra = []+ },+ ],+ [+ 'missing private lane',+ m => {+ delete m.privatePostgres.local+ },+ ],+ [+ 'unknown physical suite',+ m => {+ m.publicPostgres.push('control-api/test/missing.realPostgres.test.ts')+ },+ ],+ [+ 'duplicate selection',+ m => {+ m.publicPostgres.push(m.publicPostgres[0])+ },+ ],+ [+ 'empty required lane',+ m => {+ m.composedContract = []+ },+ ],+ [+ 'removed public suite',+ m => {+ m.publicPostgres.pop()+ },+ ],+])+ test(label + ' fails closed', () => {+ const m = structuredClone(manifest)+ mutate(m)+ assert.throws(() => verifySuiteManifest(root, m))+ })+for (const [label, mutate] of [+ [+ 'missing suite',+ r => {+ r.testResults.pop()+ },+ ],+ [+ 'unexpected suite',+ r => {+ r.testResults.push({+ name: `${root}/control-api/test/unexpected.test.ts`,+ status: 'passed',+ assertionResults: [{ status: 'passed' }],+ })+ },+ ],+ [+ 'zero collection',+ r => {+ r.testResults[0].assertionResults = []+ },+ ],+ [+ 'skipped case',+ r => {+ r.testResults[0].assertionResults[0].status = 'pending'+ },+ ],+ [+ 'partial report',+ r => {+ r.success = false+ },+ ],+ [+ 'worker failure',+ r => {+ r.numFailedTestSuites = 1+ },+ ],+ [+ 'incorrect totals',+ r => {+ r.numPassedTests--+ },+ ],+])+ test(label + ' rejects reporter', () => {+ const r = green()+ mutate(r)+ assert.notDeepEqual(reportViolations(root, manifest, 'publicPostgres', r), [])+ })+test('unknown report lane rejects', () =>+ assert.notDeepEqual(reportViolations(root, manifest, 'unknown', green()), []))diff --git a/tests/contracts/password-recovery-suites.json b/tests/contracts/password-recovery-suites.jsonnew file mode 100644index 000000000..e997cd07b--- /dev/null+++ b/tests/contracts/password-recovery-suites.json@@ -0,0 +1,100 @@+{+ "version": 1,+ "publicPostgres": [+ "control-api/test/bug192.passwordLogin.realPostgres.integration.test.ts",+ "control-api/test/bug192.passwordPersistence.realPostgres.integration.test.ts",+ "control-api/test/db.codexSubscriptionConnection.realPostgres.integration.test.ts",+ "control-api/test/db.listGrantsReferencingModel.realPostgres.integration.test.ts",+ "control-api/test/db.llmProviderAttemptConnectionIntegrity.realPostgres.integration.test.ts",+ "control-api/test/db.pluginWorkloadSdkRuntimeContract.realPostgres.integration.test.ts",+ "control-api/test/db.realPostgresMigration.integration.test.ts",+ "control-api/test/entityChangeFeed.realPostgres.integration.test.ts",+ "control-api/test/gfsAuditDecisionEvidence.realPostgres.integration.test.ts",+ "control-api/test/gfsBlobMigration.realPostgres.integration.test.ts",+ "control-api/test/gfsBlobReconciliation.realPostgres.integration.test.ts",+ "control-api/test/gfsCopy.realPostgres.integration.test.ts",+ "control-api/test/gfsReaderRole.realPostgres.integration.test.ts",+ "control-api/test/gfsReadiness.realPostgres.integration.test.ts",+ "control-api/test/gfsStructuralIntegrity.realPostgres.integration.test.ts",+ "control-api/test/gfsUploadFinalizer.realPostgres.integration.test.ts",+ "control-api/test/gfsUploadSession.realPostgres.integration.test.ts",+ "control-api/test/helpers.realPostgresCancellation.test.ts",+ "control-api/test/helpers.realPostgresTeardown.test.ts",+ "control-api/test/llmProviderAttemptAuthorizer.cancellation.realPostgres.integration.test.ts",+ "control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts",+ "control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts",+ "control-api/test/oauth.dynamicClientStore.installIdentity.realPostgres.integration.test.ts",+ "control-api/test/oauth.legacyGrantLaneFence.realPostgres.integration.test.ts",+ "control-api/test/oauth.mcpDisconnect.realPostgres.integration.test.ts",+ "control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts",+ "control-api/test/oauth.perServerCallback.realPostgres.integration.test.ts",+ "control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.ts",+ "control-api/test/oauth.reactiveRefresh.installIdentity.realPostgres.integration.test.ts",+ "control-api/test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts",+ "control-api/test/oauth.store.installIdentityFence.realPostgres.integration.test.ts",+ "control-api/test/oauth.store.sharedGrants.realPostgres.integration.test.ts",+ "control-api/test/oauth.store.userGrantsListing.realPostgres.integration.test.ts",+ "control-api/test/passwordRecovery.http.realPostgres.integration.test.ts",+ "control-api/test/passwordResetInvitations.realPostgres.integration.test.ts",+ "control-api/test/passwordWorkOwnership.operation.realPostgres.integration.test.ts",+ "control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts",+ "control-api/test/pluginWorkloadSdkGrantUpdateNotify.realPostgres.integration.test.ts",+ "control-api/test/pluginWorkloadSdkGrokDualLedger.realPostgres.integration.test.ts",+ "control-api/test/pluginWorkloadSdkPolicyReview.realPostgres.integration.test.ts",+ "control-api/test/pluginWorkloadSdkSteplessQuota.realPostgres.integration.test.ts",+ "control-api/test/r2h1.invitationAdmission.realPostgres.integration.test.ts",+ "control-api/test/r2h2.passwordResetLostCommit.realPostgres.integration.test.ts",+ "control-api/test/r2m5.passwordResetLocking.realPostgres.integration.test.ts",+ "control-api/test/r4m2.passwordResetFatalCommit.realPostgres.integration.test.ts",+ "control-api/test/r6.credentialChangedRoute.realPostgres.integration.test.ts",+ "control-api/test/r6.retiredRecoveryRoute.realPostgres.integration.test.ts",+ "control-api/test/realPostgresAdminCleanup.guard.test.ts",+ "control-api/test/realPostgresCleanup.contract.test.ts",+ "control-api/test/realPostgresTeardown.guard.test.ts",+ "control-api/test/routes.externalGfsRateLimitFailClosed.realPostgres.integration.test.ts",+ "control-api/test/routes.externalGfsRateLimitStress.realPostgres.integration.test.ts",+ "control-api/test/routes.llmModelGrantRace.realPostgres.integration.test.ts",+ "control-api/test/routes.llmModelHostRace.realPostgres.integration.test.ts",+ "control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts",+ "control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts",+ "control-api/test/routes.mcpServerUninstall.repairRequired.realPostgres.integration.test.ts",+ "control-api/test/routes.rateLimitProcessMemory.realPostgres.integration.test.ts",+ "control-api/test/routes.registryUninstall.realPostgres.integration.test.ts",+ "control-api/test/rp001.passwordPool.realPostgres.integration.test.ts",+ "control-api/test/rp002.passwordCapture.realPostgres.integration.test.ts",+ "control-api/test/rp003.passwordHeaders.realPostgres.integration.test.ts",+ "control-api/test/rp004.passwordWork.realPostgres.integration.test.ts",+ "control-api/test/rp005.passwordPrincipal.realPostgres.integration.test.ts",+ "control-api/test/services.access.mcpConnectors.realPostgres.integration.test.ts",+ "control-api/test/services.access.mcpInvocable.grantGate.realPostgres.integration.test.ts",+ "control-api/test/services.adminAuthDelete.realPostgres.integration.test.ts",+ "control-api/test/services.adminSubscriptionRateLimitMigration.realPostgres.integration.test.ts",+ "control-api/test/services.codexSubscriptionCatalog.realPostgres.integration.test.ts",+ "control-api/test/services.codexSubscriptionLifecycle.realPostgres.integration.test.ts",+ "control-api/test/services.codexSubscriptionOAuth.realPostgres.integration.test.ts",+ "control-api/test/services.codexSubscriptionRefreshRejected.realPostgres.integration.test.ts",+ "control-api/test/services.controlAdminReplaceInviter.realPostgres.integration.test.ts",+ "control-api/test/services.directory.userRetirement.realPostgres.integration.test.ts",+ "control-api/test/services.grokProviderAttemptRedemption.realPostgres.integration.test.ts",+ "control-api/test/services.grokProviderAttemptRedemption.refresh.realPostgres.integration.test.ts",+ "control-api/test/services.grokSubscriptionConnection.realPostgres.integration.test.ts",+ "control-api/test/services.llmCatalogSync.realPostgres.integration.test.ts",+ "control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts",+ "control-api/test/services.llmProviderAttemptFinalization.realPostgres.integration.test.ts",+ "control-api/test/services.llmProviderAttemptRedemption.realPostgres.integration.test.ts",+ "control-api/test/services.llmProviderAttemptStore.realPostgres.integration.test.ts",+ "control-api/test/services.mcpSecretRollbackPermit.realPostgres.integration.test.ts",+ "control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts",+ "control-api/test/services.pluginWorkloadSdkFinalization.realPostgres.integration.test.ts",+ "control-api/test/services.rateLimiter.realPostgres.integration.test.ts",+ "control-api/test/services.rateLimiterPoolSaturation.realPostgres.integration.test.ts",+ "control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts",+ "control-api/test/services.workflowScheduleForbid.realPostgres.integration.test.ts"+ ],+ "privatePostgres": {+ "local": "control-api/test/r4l1.resetPasswordPayload.externalRest.realPostgres.integration.test.ts",+ "configured": "control-api/test/bug192.passwordRecovery.memberRegistration.realPostgres.integration.test.ts"+ },+ "composedContract": ["control-api/test/passwordRecovery.http.contract.test.ts"],+ "consumer": ["external-rest-api/test/invitations.passwordRecovery.public.test.ts"]+}