diff --git a/.env.example b/.env.example index 749f1e170..7cdeef771 100644 --- a/.env.example +++ b/.env.example @@ -14,6 +14,7 @@ AI_TEST_DATABASE_URL=postgresql://lifeos:lifeos@postgres:5432/lifeos_test AI_DATABASE_POOL_MAX=10 AI_DATABASE_CONNECT_TIMEOUT_MS=5000 AI_DATABASE_IDLE_TIMEOUT_MS=30000 +AI_GATEWAY_CONTEXT_SECRET=replace-with-at-least-32-random-bytes NOTIFICATION_DATABASE_URL=postgresql://lifeos:lifeos@postgres:5432/lifeos NOTIFICATION_DATABASE_POOL_MAX=10 NOTIFICATION_DATABASE_CONNECT_TIMEOUT_MS=5000 diff --git a/CHANGELOG.md b/CHANGELOG.md index db2bd63df..3d89f5149 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ All notable changes to LifeOS are documented in this file. - A bounded notification runtime that composes one PostgreSQL pool, the reminder repository, the in-app gateway, and the scheduler with exactly-once pool shutdown. - A production AI runtime that persists every inert proposal before returning it and exposes tenant-scoped proposal evidence and append-only accept/reject decision history. - Replay-safe AI proposal decisions bound to the exact workspace, actor, proposal revision digest, UUIDv4 idempotency key, and decision timestamp. +- A short-lived HMAC-SHA256 AI gateway context that authenticates both workspace and actor scope before proposal generation, audit retrieval, or decision recording. ### Fixed @@ -27,4 +28,4 @@ All notable changes to LifeOS are documented in this file. - Planning-search upstream responses are stopped at a fixed byte limit before they can be fully buffered by the web boundary. - Notification persistence stores SHA-256 idempotency digests instead of raw delivery keys, validates every untrusted row, and keeps all SQL tenant-scoped and parameterized. -- The AI production boundary accepts workspace and actor scope only through trusted headers, rejects ownership injection in decision bodies, returns credential-free problem details, and exposes no proposal apply or execution route. +- The AI production boundary rejects legacy client-selected ownership headers, verifies a versioned short-lived private-gateway signature in constant time, returns credential-free problem details, and exposes no proposal apply or execution route. diff --git a/apps/ai-service/package.json b/apps/ai-service/package.json index ec0470dc2..2f7148468 100644 --- a/apps/ai-service/package.json +++ b/apps/ai-service/package.json @@ -5,7 +5,7 @@ "scripts": { "build": "nest build", "dev": "nest start --watch", - "lint": "tsc --noEmit", + "lint": "prettier --single-quote --check \"src/**/*.ts\" ../../docs/superpowers/plans/2026-08-04-ai-signed-gateway-context-slice.md && tsc --noEmit", "test": "vitest run --passWithNoTests --no-file-parallelism", "typecheck": "tsc --noEmit" }, diff --git a/apps/ai-service/src/gateway-context-http.integration.test.ts b/apps/ai-service/src/gateway-context-http.integration.test.ts new file mode 100644 index 000000000..ee7393fa0 --- /dev/null +++ b/apps/ai-service/src/gateway-context-http.integration.test.ts @@ -0,0 +1,174 @@ +import { createHmac, randomUUID } from 'node:crypto'; +import { request as httpRequest } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { INestApplication } from '@nestjs/common'; +import { NestFactory } from '@nestjs/core'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { AiAppModule } from './main'; + +const GATEWAY_SECRET = '0123456789abcdef0123456789abcdef'; +const ORIGINAL_GATEWAY_SECRET = process.env.AI_GATEWAY_CONTEXT_SECRET; +let app: INestApplication; +let address: AddressInfo; + +/** Creates the exact signature contract accepted by the AI service. */ +function signedHeaders( + workspaceId: string, + actorId: string, + issuedAt = String(Math.floor(Date.now() / 1000)), +): Readonly> { + const signature = createHmac('sha256', GATEWAY_SECRET) + .update( + `life-os.ai-context.v1\n${workspaceId}\n${actorId}\n${issuedAt}`, + 'utf8', + ) + .digest('base64url'); + return { + 'x-life-os-workspace-id': workspaceId, + 'x-life-os-actor-id': actorId, + 'x-life-os-context-issued-at': issuedAt, + 'x-life-os-context-signature': signature, + }; +} + +/** Changes a significant base64url character so the decoded digest must differ. */ +function forgeSignature(signature: string): string { + const replacement = signature.startsWith('A') ? 'B' : 'A'; + return `${replacement}${signature.slice(1)}`; +} + +/** Sends one bounded proposal request with an explicitly selected header set. */ +function postProposal( + headers: Readonly>, +): Promise<{ statusCode: number; body: unknown }> { + const payload = JSON.stringify({ + objective: 'Review signed AI gateway enforcement', + context: [ + { + id: randomUUID(), + kind: 'task', + title: 'Verify authenticated proposal generation', + status: 'active', + }, + ], + }); + return new Promise((resolve, reject) => { + const request = httpRequest( + { + hostname: '127.0.0.1', + port: address.port, + path: '/v1/proposals', + method: 'POST', + headers: { + accept: 'application/json', + 'content-type': 'application/json', + 'content-length': Buffer.byteLength(payload), + ...headers, + }, + }, + (response) => { + const chunks: Buffer[] = []; + response.on('data', (chunk: Buffer | string) => { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + }); + response.on('end', () => { + const text = Buffer.concat(chunks).toString('utf8'); + try { + resolve({ + statusCode: response.statusCode ?? 0, + body: text ? JSON.parse(text) : null, + }); + } catch { + reject(new Error('HTTP response was not valid JSON')); + } + }); + }, + ); + request.on('error', reject); + request.end(payload); + }); +} + +describe('AI signed gateway HTTP boundary', () => { + beforeAll(async () => { + process.env.AI_GATEWAY_CONTEXT_SECRET = GATEWAY_SECRET; + app = await NestFactory.create(AiAppModule, { logger: false }); + await app.listen(0, '127.0.0.1'); + address = app.getHttpServer().address() as AddressInfo; + }); + + afterAll(async () => { + await app.close(); + if (ORIGINAL_GATEWAY_SECRET === undefined) { + delete process.env.AI_GATEWAY_CONTEXT_SECRET; + } else { + process.env.AI_GATEWAY_CONTEXT_SECRET = ORIGINAL_GATEWAY_SECRET; + } + }); + + it('accepts the authenticated signed actor and workspace context', async () => { + const workspaceId = randomUUID(); + const actorId = randomUUID(); + const response = await postProposal(signedHeaders(workspaceId, actorId)); + + expect(response.statusCode).toBe(201); + expect(response.body).toMatchObject({ + workspaceId, + requiresConfirmation: true, + }); + }); + + it('does not authorize legacy client-selected ownership headers', async () => { + const response = await postProposal({ + 'x-workspace-id': randomUUID(), + 'x-actor-id': randomUUID(), + }); + + expect(response).toMatchObject({ + statusCode: 401, + body: { code: 'invalid_gateway_context' }, + }); + }); + + it('maps stale and forged contexts to the same credential-free refusal', async () => { + const workspaceId = randomUUID(); + const actorId = randomUUID(); + const stale = await postProposal( + signedHeaders( + workspaceId, + actorId, + String(Math.floor(Date.now() / 1000) - 61), + ), + ); + const authentic = signedHeaders(workspaceId, actorId); + const signature = authentic['x-life-os-context-signature']; + const forged = await postProposal({ + ...authentic, + 'x-life-os-context-signature': forgeSignature(signature), + }); + + expect(stale).toMatchObject({ + statusCode: 401, + body: { code: 'invalid_gateway_context' }, + }); + expect(forged).toMatchObject({ + statusCode: 401, + body: { code: 'invalid_gateway_context' }, + }); + }); + + it('fails closed when the verifier secret is unavailable', async () => { + delete process.env.AI_GATEWAY_CONTEXT_SECRET; + try { + const response = await postProposal( + signedHeaders(randomUUID(), randomUUID()), + ); + expect(response).toMatchObject({ + statusCode: 503, + body: { code: 'gateway_context_unavailable' }, + }); + } finally { + process.env.AI_GATEWAY_CONTEXT_SECRET = GATEWAY_SECRET; + } + }); +}); diff --git a/apps/ai-service/src/gateway-context.test.ts b/apps/ai-service/src/gateway-context.test.ts new file mode 100644 index 000000000..471553f09 --- /dev/null +++ b/apps/ai-service/src/gateway-context.test.ts @@ -0,0 +1,158 @@ +import { createHmac, randomUUID } from 'node:crypto'; +import { describe, expect, it } from 'vitest'; +import { + AiGatewayContextError, + requireTrustedAiContext, + type TrustedAiContextHeaders, +} from './gateway-context'; + +const SECRET = '0123456789abcdef0123456789abcdef'; +const NOW_SECONDS = 1_786_000_000; + +/** Creates the exact versioned signature expected from the authenticated gateway. */ +function signContext( + workspaceId: string, + actorId: string, + issuedAt: string, + secret = SECRET, +): string { + return createHmac('sha256', secret) + .update( + `life-os.ai-context.v1\n${workspaceId.toLowerCase()}\n${actorId.toLowerCase()}\n${issuedAt}`, + 'utf8', + ) + .digest('base64url'); +} + +/** Changes a significant base64url character so the decoded digest must differ. */ +function forgeSignature(signature: string): string { + const replacement = signature.startsWith('A') ? 'B' : 'A'; + return `${replacement}${signature.slice(1)}`; +} + +/** Builds one complete signed header set for focused mutation by each test. */ +function validHeaders( + issuedAt = String(NOW_SECONDS), +): TrustedAiContextHeaders { + const workspaceId = randomUUID(); + const actorId = randomUUID(); + return { + workspaceId, + actorId, + issuedAt, + signature: signContext(workspaceId, actorId, issuedAt), + }; +} + +/** Requires one stable credential-free verifier failure. */ +function expectFailure( + headers: TrustedAiContextHeaders, + failure: AiGatewayContextError['failure'], + secret: unknown = SECRET, + nowSeconds = NOW_SECONDS, +): void { + try { + requireTrustedAiContext(headers, secret, nowSeconds); + throw new Error('Expected trusted AI context verification to fail'); + } catch (error) { + expect(error).toBeInstanceOf(AiGatewayContextError); + expect(error).toMatchObject({ + name: 'AiGatewayContextError', + failure, + message: failure, + }); + } +} + +describe('trusted AI gateway context', () => { + it('accepts an authentic context, canonicalizes identifiers, and freezes the result', () => { + const issuedAt = String(Math.floor(Date.now() / 1000)); + const workspaceId = randomUUID().toUpperCase(); + const actorId = randomUUID().toUpperCase(); + const context = requireTrustedAiContext( + { + workspaceId, + actorId, + issuedAt, + signature: signContext(workspaceId, actorId, issuedAt), + }, + SECRET, + ); + + expect(context).toEqual({ + workspaceId: workspaceId.toLowerCase(), + actorId: actorId.toLowerCase(), + }); + expect(Object.isFrozen(context)).toBe(true); + }); + + it('accepts the exact age and future-skew boundaries', () => { + for (const issuedAt of [NOW_SECONDS - 60, NOW_SECONDS + 5]) { + const headers = validHeaders(String(issuedAt)); + expect(requireTrustedAiContext(headers, SECRET, NOW_SECONDS)).toEqual({ + workspaceId: String(headers.workspaceId), + actorId: String(headers.actorId), + }); + } + }); + + it('fails closed when verifier secret material is absent or too short', () => { + const headers = validHeaders(); + expectFailure(headers, 'gateway_context_unavailable', undefined); + expectFailure(headers, 'gateway_context_unavailable', 'short'); + }); + + it('rejects every malformed header field and invalid verifier clock', () => { + const base = validHeaders(); + const malformed: TrustedAiContextHeaders[] = [ + { ...base, workspaceId: undefined }, + { ...base, actorId: undefined }, + { ...base, issuedAt: undefined }, + { ...base, signature: undefined }, + { ...base, workspaceId: 'not-a-workspace' }, + { ...base, actorId: 'not-an-actor' }, + { ...base, issuedAt: '01' }, + { ...base, signature: 'not-a-signature' }, + ]; + for (const headers of malformed) { + expectFailure(headers, 'invalid_gateway_context'); + } + expectFailure(base, 'invalid_gateway_context', SECRET, -1); + expectFailure(base, 'invalid_gateway_context', SECRET, NOW_SECONDS + 0.5); + }); + + it('rejects stale and excessively future-dated authentic contexts', () => { + expectFailure( + validHeaders(String(NOW_SECONDS - 61)), + 'invalid_gateway_context', + ); + expectFailure( + validHeaders(String(NOW_SECONDS + 6)), + 'invalid_gateway_context', + ); + }); + + it('binds the signature to workspace, actor, and issuance time', () => { + const base = validHeaders(); + const otherWorkspaceId = randomUUID(); + const otherActorId = randomUUID(); + const otherIssuedAt = String(NOW_SECONDS - 1); + + expectFailure( + { ...base, workspaceId: otherWorkspaceId }, + 'invalid_gateway_context', + ); + expectFailure( + { ...base, actorId: otherActorId }, + 'invalid_gateway_context', + ); + expectFailure( + { ...base, issuedAt: otherIssuedAt }, + 'invalid_gateway_context', + ); + expectFailure( + { ...base, signature: forgeSignature(String(base.signature)) }, + 'invalid_gateway_context', + ); + }); +}); diff --git a/apps/ai-service/src/gateway-context.ts b/apps/ai-service/src/gateway-context.ts new file mode 100644 index 000000000..f794541f6 --- /dev/null +++ b/apps/ai-service/src/gateway-context.ts @@ -0,0 +1,115 @@ +import { createHmac, timingSafeEqual } from 'node:crypto'; + +/** Headers emitted by the private gateway after authenticating one actor and workspace. */ +export interface TrustedAiContextHeaders { + workspaceId: unknown; + actorId: unknown; + issuedAt: unknown; + signature: unknown; +} + +/** Authenticated tenant and actor scope accepted by the AI proposal boundary. */ +export interface TrustedAiContext { + readonly workspaceId: string; + readonly actorId: string; +} + +/** Stable verifier failure classifications mapped by the HTTP boundary. */ +export type AiGatewayContextFailure = + | 'invalid_gateway_context' + | 'gateway_context_unavailable'; + +/** Credential-free error raised when trusted gateway context cannot be accepted. */ +export class AiGatewayContextError extends Error { + constructor(readonly failure: AiGatewayContextFailure) { + super(failure); + this.name = 'AiGatewayContextError'; + } +} + +const UUID_V4_PATTERN = + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu; +const UNIX_SECONDS_PATTERN = /^(?:0|[1-9]\d{0,12})$/u; +const BASE64URL_SHA256_PATTERN = /^[A-Za-z0-9_-]{43}$/u; +const MINIMUM_GATEWAY_SECRET_BYTES = 32; +const MAXIMUM_CONTEXT_AGE_SECONDS = 60; +const MAXIMUM_FUTURE_SKEW_SECONDS = 5; + +/** Raises one stable invalid-context failure without retaining untrusted input. */ +function invalidGatewayContext(): never { + throw new AiGatewayContextError('invalid_gateway_context'); +} + +/** Raises one stable configuration failure without exposing secret material. */ +function unavailableGatewayContext(): never { + throw new AiGatewayContextError('gateway_context_unavailable'); +} + +/** Computes the versioned HMAC digest shared by the private gateway and AI service. */ +function aiContextDigest( + workspaceId: string, + actorId: string, + issuedAt: string, + secret: string, +): Buffer { + return createHmac('sha256', secret) + .update( + `life-os.ai-context.v1\n${workspaceId}\n${actorId}\n${issuedAt}`, + 'utf8', + ) + .digest(); +} + +/** + * Verifies a short-lived context created only after gateway authentication. + * Legacy client-selected ownership headers are deliberately outside this contract. + */ +export function requireTrustedAiContext( + headers: TrustedAiContextHeaders, + secret: unknown, + nowSeconds = Math.floor(Date.now() / 1000), +): TrustedAiContext { + if ( + typeof secret !== 'string' || + Buffer.byteLength(secret, 'utf8') < MINIMUM_GATEWAY_SECRET_BYTES + ) { + return unavailableGatewayContext(); + } + if ( + typeof headers.workspaceId !== 'string' || + typeof headers.actorId !== 'string' || + typeof headers.issuedAt !== 'string' || + typeof headers.signature !== 'string' || + !UUID_V4_PATTERN.test(headers.workspaceId) || + !UUID_V4_PATTERN.test(headers.actorId) || + !UNIX_SECONDS_PATTERN.test(headers.issuedAt) || + !BASE64URL_SHA256_PATTERN.test(headers.signature) || + !Number.isSafeInteger(nowSeconds) || + nowSeconds < 0 + ) { + return invalidGatewayContext(); + } + + const workspaceId = headers.workspaceId.toLowerCase(); + const actorId = headers.actorId.toLowerCase(); + const issuedAtSeconds = Number(headers.issuedAt); + if ( + issuedAtSeconds > nowSeconds + MAXIMUM_FUTURE_SKEW_SECONDS || + issuedAtSeconds < nowSeconds - MAXIMUM_CONTEXT_AGE_SECONDS + ) { + return invalidGatewayContext(); + } + + const expected = aiContextDigest( + workspaceId, + actorId, + headers.issuedAt, + secret, + ); + const actual = Buffer.from(headers.signature, 'base64url'); + if (!timingSafeEqual(actual, expected)) { + return invalidGatewayContext(); + } + + return Object.freeze({ workspaceId, actorId }); +} diff --git a/apps/ai-service/src/main.ts b/apps/ai-service/src/main.ts index 942d4fb60..9f60ce81b 100644 --- a/apps/ai-service/src/main.ts +++ b/apps/ai-service/src/main.ts @@ -13,6 +13,11 @@ import { } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { AiRuntime, createAiRuntime } from './ai-runtime'; +import { + AiGatewayContextError, + requireTrustedAiContext, + type TrustedAiContext, +} from './gateway-context'; import { ProposalAuditApplication, ProposalAuditNotFoundError, @@ -74,8 +79,37 @@ function problem(status: number, title: string, code: string): HttpException { return new HttpException(details, status); } -/** Maps proposal-audit failures to stable credential-free HTTP problems. */ +/** Derives actor and workspace scope only from the signed private-gateway context. */ +function trustedAiContext( + headers: Readonly>, +): TrustedAiContext { + return requireTrustedAiContext( + { + workspaceId: headers['x-life-os-workspace-id'], + actorId: headers['x-life-os-actor-id'], + issuedAt: headers['x-life-os-context-issued-at'], + signature: headers['x-life-os-context-signature'], + }, + process.env.AI_GATEWAY_CONTEXT_SECRET, + ); +} + +/** Maps proposal-audit and gateway failures to stable credential-free HTTP problems. */ function mapAuditError(error: unknown): never { + if (error instanceof AiGatewayContextError) { + if (error.failure === 'invalid_gateway_context') { + throw problem( + 401, + 'Trusted gateway context is invalid', + 'invalid_gateway_context', + ); + } + throw problem( + 503, + 'Trusted gateway context is unavailable', + 'gateway_context_unavailable', + ); + } if ( error instanceof ProposalValidationError || error instanceof ProposalAuditValidationError @@ -118,18 +152,16 @@ export class AiProposalController { return { status: 'ok', service: 'ai-service' }; } - /** Generates and persists one inert proposal for the trusted workspace scope. */ + /** Generates and persists one inert proposal for the authenticated workspace. */ @Post('v1/proposals') async createProposal( - @Headers('x-workspace-id') workspaceId: string | undefined, + @Headers() headers: Readonly>, @Body() body: unknown, ): Promise { try { - if (!workspaceId) { - throw new ProposalValidationError(); - } + const context = trustedAiContext(headers); return await this.proposalService.generateProposal( - workspaceId, + context.workspaceId, validateProposalRequest(body), ); } catch (error) { @@ -137,6 +169,7 @@ export class AiProposalController { throw problem(400, 'Proposal request is invalid', 'invalid_request'); } if ( + error instanceof AiGatewayContextError || error instanceof ProposalAuditValidationError || error instanceof ProposalAuditPersistenceError ) { @@ -164,69 +197,65 @@ export class AiProposalAuditController { private readonly application: ProposalAuditApplication, ) {} - /** Lists deterministic proposal evidence for the trusted workspace. */ + /** Lists deterministic proposal evidence for the authenticated workspace. */ @Get('v1/proposals') async listProposals( - @Headers('x-workspace-id') workspaceId: string | undefined, + @Headers() headers: Readonly>, ): Promise { try { - if (!workspaceId) { - throw new ProposalAuditValidationError(); - } - return await this.application.listProposals(workspaceId); + return await this.application.listProposals( + trustedAiContext(headers).workspaceId, + ); } catch (error) { return mapAuditError(error); } } - /** Returns one immutable proposal revision within the trusted workspace. */ + /** Returns one immutable proposal revision within the authenticated workspace. */ @Get('v1/proposals/:proposalId') async findProposal( - @Headers('x-workspace-id') workspaceId: string | undefined, + @Headers() headers: Readonly>, @Param('proposalId') proposalId: string, ): Promise { try { - if (!workspaceId) { - throw new ProposalAuditValidationError(); - } - return await this.application.findProposal(workspaceId, proposalId); + return await this.application.findProposal( + trustedAiContext(headers).workspaceId, + proposalId, + ); } catch (error) { return mapAuditError(error); } } - /** Lists append-only decisions for one workspace-owned proposal revision. */ + /** Lists append-only decisions for one authenticated workspace proposal. */ @Get('v1/proposals/:proposalId/decisions') async listDecisions( - @Headers('x-workspace-id') workspaceId: string | undefined, + @Headers() headers: Readonly>, @Param('proposalId') proposalId: string, ): Promise { try { - if (!workspaceId) { - throw new ProposalAuditValidationError(); - } - return await this.application.listDecisions(workspaceId, proposalId); + return await this.application.listDecisions( + trustedAiContext(headers).workspaceId, + proposalId, + ); } catch (error) { return mapAuditError(error); } } - /** Appends an explicit accept or reject event without executing operations. */ + /** Appends an explicit signed-actor decision without executing operations. */ @Post('v1/proposals/:proposalId/decisions') async appendDecision( - @Headers('x-workspace-id') workspaceId: string | undefined, - @Headers('x-actor-id') actorId: string | undefined, + @Headers() headers: Readonly>, @Param('proposalId') proposalId: string, @Body() body: unknown, ): Promise { try { - if (!workspaceId || !actorId) { - throw new ProposalAuditValidationError(); - } + const context = trustedAiContext(headers); return await this.application.appendDecision( - workspaceId, + context.workspaceId, proposalId, - actorId, + context.actorId, validateProposalDecisionRequest(body), ); } catch (error) { diff --git a/apps/ai-service/src/no-silent-mutation.integration.test.ts b/apps/ai-service/src/no-silent-mutation.integration.test.ts index 34543cadf..a9416daca 100644 --- a/apps/ai-service/src/no-silent-mutation.integration.test.ts +++ b/apps/ai-service/src/no-silent-mutation.integration.test.ts @@ -1,3 +1,4 @@ +import { createHmac } from 'node:crypto'; import { request as httpRequest } from 'node:http'; import type { AddressInfo } from 'node:net'; import { NestFactory } from '@nestjs/core'; @@ -10,8 +11,10 @@ import { } from './proposal-service'; const WORKSPACE_ID = '43eab0ee-0f7b-4c7f-9331-b133f2647675'; +const ACTOR_ID = 'd19b6077-2baa-4f84-97f6-c138b1d6ba34'; const TASK_ID = 'e29c36af-999a-407f-9ca9-cfe194ab51f4'; const PROPOSAL_ID = 'aedcb1d1-cc60-42c6-9357-ec90821fce1b'; +const GATEWAY_SECRET = '0123456789abcdef0123456789abcdef'; interface JsonHttpResponse { statusCode: number; @@ -40,10 +43,26 @@ function userOwnedState(): { }; } +/** Signs the authenticated actor and workspace context used by the AI boundary. */ +function signedContextHeaders(): Readonly> { + const issuedAt = String(Math.floor(Date.now() / 1000)); + const signature = createHmac('sha256', GATEWAY_SECRET) + .update( + `life-os.ai-context.v1\n${WORKSPACE_ID}\n${ACTOR_ID}\n${issuedAt}`, + 'utf8', + ) + .digest('base64url'); + return { + 'x-life-os-workspace-id': WORKSPACE_ID, + 'x-life-os-actor-id': ACTOR_ID, + 'x-life-os-context-issued-at': issuedAt, + 'x-life-os-context-signature': signature, + }; +} + function postJson( address: AddressInfo, path: string, - workspaceId: string, body: unknown, ): Promise { const payload = JSON.stringify(body); @@ -57,7 +76,7 @@ function postJson( headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload), - 'x-workspace-id': workspaceId, + ...signedContextHeaders(), }, }, (response) => { @@ -141,19 +160,16 @@ describe('AI proposal no-silent-mutation contract', () => { expect(JSON.stringify(state)).toBe(before); }); - it('exercises the production HTTP module without exposing a mutation route', async () => { + it('exercises the authenticated HTTP module without exposing a mutation route', async () => { const state = userOwnedState(); const before = JSON.stringify(state); + const originalSecret = process.env.AI_GATEWAY_CONTEXT_SECRET; + process.env.AI_GATEWAY_CONTEXT_SECRET = GATEWAY_SECRET; const app = await NestFactory.create(AiAppModule, { logger: false }); await app.listen(0, '127.0.0.1'); try { const address = app.getHttpServer().address() as AddressInfo; - const response = await postJson( - address, - '/v1/proposals', - WORKSPACE_ID, - state, - ); + const response = await postJson(address, '/v1/proposals', state); expect(response.statusCode).toBe(201); expect(response.body).toMatchObject({ @@ -171,12 +187,16 @@ describe('AI proposal no-silent-mutation contract', () => { const unsupportedMutation = await postJson( address, '/v1/proposals/apply', - WORKSPACE_ID, { proposalId: PROPOSAL_ID }, ); expect(unsupportedMutation.statusCode).toBe(404); } finally { await app.close(); + if (originalSecret === undefined) { + delete process.env.AI_GATEWAY_CONTEXT_SECRET; + } else { + process.env.AI_GATEWAY_CONTEXT_SECRET = originalSecret; + } } }); }); diff --git a/apps/ai-service/src/proposal-audit-http.integration.test.ts b/apps/ai-service/src/proposal-audit-http.integration.test.ts index 5b213cdbb..5d0417634 100644 --- a/apps/ai-service/src/proposal-audit-http.integration.test.ts +++ b/apps/ai-service/src/proposal-audit-http.integration.test.ts @@ -1,4 +1,4 @@ -import { randomUUID } from 'node:crypto'; +import { createHmac, randomUUID } from 'node:crypto'; import { readFile } from 'node:fs/promises'; import { request as httpRequest } from 'node:http'; import type { AddressInfo } from 'node:net'; @@ -10,6 +10,11 @@ import { AiProductionModule } from './main'; const TEST_DATABASE_URL = process.env.AI_TEST_DATABASE_URL; const ORIGINAL_APPLICATION_DATABASE_URL = process.env.AI_DATABASE_URL; +const ORIGINAL_GATEWAY_CONTEXT_SECRET = + process.env.AI_GATEWAY_CONTEXT_SECRET; +const TEST_GATEWAY_CONTEXT_SECRET = + '0123456789abcdef0123456789abcdef'; +const DEFAULT_ACTOR_ID = '20a6d1a2-8de8-47c1-aeba-84b10de74809'; const describeWithPostgres = TEST_DATABASE_URL ? describe : describe.skip; let administrativePool: Pool; @@ -51,6 +56,26 @@ async function applyMigration(pool: Pool): Promise { await pool.query(sql); } +/** Creates the exact short-lived signature expected from the authenticated gateway. */ +function signedContextHeaders( + workspaceId: string, + actorId: string, +): Readonly> { + const issuedAt = String(Math.floor(Date.now() / 1000)); + const signature = createHmac('sha256', TEST_GATEWAY_CONTEXT_SECRET) + .update( + `life-os.ai-context.v1\n${workspaceId}\n${actorId}\n${issuedAt}`, + 'utf8', + ) + .digest('base64url'); + return { + 'x-life-os-workspace-id': workspaceId, + 'x-life-os-actor-id': actorId, + 'x-life-os-context-issued-at': issuedAt, + 'x-life-os-context-signature': signature, + }; +} + /** Sends one bounded JSON request to the local production module. */ function requestJson( address: AddressInfo, @@ -58,7 +83,7 @@ function requestJson( path: string, workspaceId: string, body?: unknown, - actorId?: string, + actorId = DEFAULT_ACTOR_ID, ): Promise { const payload = body === undefined ? undefined : JSON.stringify(body); return new Promise((resolveResponse, reject) => { @@ -70,8 +95,7 @@ function requestJson( method, headers: { accept: 'application/json', - 'x-workspace-id': workspaceId, - ...(actorId === undefined ? {} : { 'x-actor-id': actorId }), + ...signedContextHeaders(workspaceId, actorId), ...(payload === undefined ? {} : { @@ -130,6 +154,7 @@ describeWithPostgres('AI production proposal audit HTTP API', () => { beforeAll(async () => { const testDatabaseUrl = requireTestDatabaseUrl(); process.env.AI_DATABASE_URL = testDatabaseUrl; + process.env.AI_GATEWAY_CONTEXT_SECRET = TEST_GATEWAY_CONTEXT_SECRET; administrativePool = new Pool({ connectionString: testDatabaseUrl, application_name: 'life-os-ai-http-integration-admin', @@ -149,10 +174,16 @@ describeWithPostgres('AI production proposal audit HTTP API', () => { } else { process.env.AI_DATABASE_URL = ORIGINAL_APPLICATION_DATABASE_URL; } + if (ORIGINAL_GATEWAY_CONTEXT_SECRET === undefined) { + delete process.env.AI_GATEWAY_CONTEXT_SECRET; + } else { + process.env.AI_GATEWAY_CONTEXT_SECRET = + ORIGINAL_GATEWAY_CONTEXT_SECRET; + } } }); - it('persists proposals across restarts and appends replay-safe decisions', async () => { + it('persists proposals across restarts and appends replay-safe signed-actor decisions', async () => { const workspaceId = randomUUID(); const otherWorkspaceId = randomUUID(); const actorId = randomUUID(); @@ -254,6 +285,7 @@ describeWithPostgres('AI production proposal audit HTTP API', () => { actorId, ); expect(accepted.statusCode).toBe(201); + expect(accepted.body).toMatchObject({ actorId }); expect(replayed).toEqual(accepted); const history = await requestJson( diff --git a/docs/superpowers/plans/2026-08-04-ai-signed-gateway-context-slice.md b/docs/superpowers/plans/2026-08-04-ai-signed-gateway-context-slice.md new file mode 100644 index 000000000..3ec38f059 --- /dev/null +++ b/docs/superpowers/plans/2026-08-04-ai-signed-gateway-context-slice.md @@ -0,0 +1,89 @@ +# AI signed gateway context slice + +## Objective + +Remove client-selectable tenant and actor authority from every AI proposal route while preserving the independently deployable AI service and its no-silent-mutation boundary. + +## Decision + +The private authenticated gateway signs a versioned context containing the canonical UUIDv4 workspace identifier, canonical UUIDv4 actor identifier, and Unix issuance time. The AI service accepts that context only when an HMAC-SHA256 tag verifies with the configured shared secret and the issuance time is within a bounded replay window. + +The canonical message is: + +```text +life-os.ai-context.v1\n\n\n +``` + +The signature is the untruncated 32-byte HMAC-SHA256 output encoded as unpadded RFC 4648 base64url. Verification uses a constant-time comparison after strict fixed-shape validation. The configured secret must contain at least 32 UTF-8 bytes and must be generated and stored as secret material rather than copied from the documented placeholder. + +## Standards basis + +- RFC 2104 defines HMAC as keyed-hash message authentication and requires strong secret-key generation, protection, and refresh practices. +- FIPS 198-1 remains NIST's published final HMAC standard as of August 4, 2026. NIST proposed withdrawing it in 2025 and moving the maintained specification to SP 800-224; SP 800-224 remains an Initial Public Draft, so this slice records the transition rather than misrepresenting the draft as final. +- NIST's hash-function policy encourages SHA-256 at minimum for interoperable hash applications and permits SHA-2 for secure-hash applications. +- RFC 4648 defines the URL- and filename-safe base64 alphabet and canonical encoding behavior used for the tag header. +- RFC 9457 defines the machine-readable problem-detail response shape used for authentication and configuration failures. + +## Trust boundary + +- The browser, model provider, and independent client cannot select `workspace_id` or `actor_id` through JSON, query parameters, `x-workspace-id`, or `x-actor-id`. +- Only a private gateway that has already authenticated the session and authorized workspace membership may create the signed headers. +- The AI service authenticates the context tag and freshness; it does not independently prove that the gateway performed correct membership authorization. +- Proposal generation and audit operations remain inert. Accepting a proposal decision records append-only evidence and does not execute a planning, habit, calendar, notification, or other user-data command. +- The shared HMAC secret authenticates the calling gateway, not an end user. Compromise of that secret permits context forgery and therefore requires immediate coordinated rotation and incident review. + +## Delivered boundary + +- `apps/ai-service/src/gateway-context.ts` validates configuration, identifiers, timestamps, canonical tag shape, freshness, and HMAC authenticity. +- Every proposal create, list, get, decision-history, and append-decision route derives workspace and actor scope from the verified context. +- Health remains credential-free and does not consume tenant context. +- Legacy ownership headers are ignored as authorization input. +- Invalid, malformed, stale, future-dated, or forged contexts return a stable `401 invalid_gateway_context` problem. +- Missing or insufficient verifier configuration returns a stable `503 gateway_context_unavailable` problem. +- Unit and HTTP tests cover exact freshness boundaries, signature binding, legacy-header refusal, configuration failure, tenant isolation, signed actor attribution, and the continued absence of an apply route. + +## Deployment and rotation + +1. Generate at least 32 bytes of cryptographically random secret material in the deployment secret manager. +2. Configure the same value as `AI_GATEWAY_CONTEXT_SECRET` in the private signer and AI-service verifier without exposing it to browsers, logs, metrics, build artifacts, or repository variables available to untrusted pull requests. +3. Deploy the verifier before routing signed production requests to the AI service. +4. Deploy the signer and verify successful authenticated proposal traffic within the 60-second maximum context age and five-second future-clock tolerance. +5. Remove any edge route that forwards legacy ownership headers as authority. + +This slice supports one active secret. A rotation therefore requires a coordinated signer/verifier deployment or a temporary maintenance boundary; it does not claim zero-downtime key rotation. A later slice may add explicit key identifiers and a bounded overlapping verification window after separate review. + +## Failure and rollback + +- Authentication failures fail closed and never fall back to legacy headers. +- Clock drift beyond the bounded tolerance fails closed; operators must correct time synchronization rather than widen the replay window informally. +- Rolling back only the signer would make requests fail authentication. Rolling back both signer and verifier to raw ownership headers would reopen the vulnerability and is not an acceptable production rollback. +- A safe rollback disables external AI proposal traffic while restoring a mutually compatible signed-context version. +- Secret compromise requires replacing the secret in both components, invalidating prior context tags by waiting at least the maximum context age, reviewing audit evidence for forged activity, and documenting the incident. + +## Deferred work + +- Gateway or same-origin BFF session introspection and production context signing. +- Multiple active verification keys and zero-downtime rotation. +- Asymmetric workload identity or service-mesh authentication. +- Fine-grained action authorization beyond authenticated workspace membership. +- Durable replay identifiers if the context contract later authorizes non-idempotent execution. + +## Verification gate + +The exact pull-request head must pass formatting, lint, type checking, all unit and PostgreSQL integration tests, build, Compose validation, AppGuardrail, SAST Semgrep, Security Scan, Commercial Readiness, CodeRabbit, and every actionable human or security review finding. No review thread may remain unresolved at merge. + +## References + +Josefsson, S. (2006). *The Base16, Base32, and Base64 data encodings* (RFC 4648). RFC Editor. https://doi.org/10.17487/RFC4648 + +Krawczyk, H., Bellare, M., & Canetti, R. (1997). *HMAC: Keyed-hashing for message authentication* (RFC 2104). RFC Editor. https://doi.org/10.17487/RFC2104 + +National Institute of Standards and Technology. (2008). *The keyed-hash message authentication code (HMAC)* (FIPS PUB 198-1). U.S. Department of Commerce. https://doi.org/10.6028/NIST.FIPS.198-1 + +National Institute of Standards and Technology. (2022, December 15). *NIST's policy on hash functions*. https://csrc.nist.gov/Projects/Hash-Functions/NIST-Policy-on-Hash-Functions + +National Institute of Standards and Technology. (2025, June 23). *Proposed withdrawal of FIPS 198-1, keyed-hash message authentication code (HMAC)*. https://csrc.nist.gov/news/2025/proposed-withdrawal-of-fips-198-1-hmac + +Nottingham, M., Wilde, E., & Dalal, S. (2023). *Problem details for HTTP APIs* (RFC 9457). RFC Editor. https://doi.org/10.17487/RFC9457 + +Turan, M. S., & Brandão, L. T. A. N. (2024). *Keyed-hash message authentication code (HMAC): Specification of HMAC and recommendations for message authentication* (NIST SP 800-224 Initial Public Draft). National Institute of Standards and Technology. https://doi.org/10.6028/NIST.SP.800-224.ipd