Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.
2 changes: 1 addition & 1 deletion apps/ai-service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
174 changes: 174 additions & 0 deletions apps/ai-service/src/gateway-context-http.integration.test.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, string>> {
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<Record<string, string>>,
): 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;
}
});
});
158 changes: 158 additions & 0 deletions apps/ai-service/src/gateway-context.test.ts
Original file line number Diff line number Diff line change
@@ -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',
);
});
});
Loading
Loading