Skip to content
Merged
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
104 changes: 104 additions & 0 deletions apps/integration-calendar-service/src/calendar-service-context.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { createHmac, randomBytes } from 'node:crypto';
import { describe, expect, it } from 'vitest';
import {
CalendarContextInvalidError,
CalendarContextUnavailableError,
} from './calendar-service-context';

const WORKSPACE_ID = '11111111-1111-4111-8111-111111111111';
const TEST_CONTEXT_KEY = randomBytes(32).toString('base64url');
const NOW_SECONDS = 1_786_291_200;

interface CalendarContextModule {
requireTrustedCalendarWorkspaceContext(
headers: Readonly<{
workspaceId: unknown;
issuedAt: unknown;
signature: unknown;
}>,
secret: unknown,
nowSeconds?: number,
): string;
}

async function contextModule(): Promise<CalendarContextModule> {
const modulePath = './calendar-service-context';
const module = (await import(modulePath).catch(() => ({}))) as Readonly<
Record<string, unknown>
>;
expect(typeof module.requireTrustedCalendarWorkspaceContext).toBe('function');
return module as unknown as CalendarContextModule;
}

function signature(workspaceId: string, issuedAt: string): string {
return createHmac('sha256', TEST_CONTEXT_KEY)
.update(`life-os.calendar-workspace.v1\n${workspaceId}\n${issuedAt}`, 'utf8')
.digest('base64url');
}

describe('trusted calendar workspace context', () => {
it('accepts one fresh signed UUIDv4 workspace context', async () => {
const { requireTrustedCalendarWorkspaceContext } = await contextModule();
const issuedAt = String(NOW_SECONDS);

expect(
requireTrustedCalendarWorkspaceContext(
{
workspaceId: WORKSPACE_ID,
issuedAt,
signature: signature(WORKSPACE_ID, issuedAt),
},
TEST_CONTEXT_KEY,
NOW_SECONDS,
),
).toBe(WORKSPACE_ID);
});

it('classifies untrusted contexts as invalid and unusable server configuration as unavailable', async () => {
const { requireTrustedCalendarWorkspaceContext } = await contextModule();
const issuedAt = String(NOW_SECONDS);
const valid = {
workspaceId: WORKSPACE_ID,
issuedAt,
signature: signature(WORKSPACE_ID, issuedAt),
};
const invalid = [
{ ...valid, signature: undefined },
{
...valid,
signature: signature(
'22222222-2222-4222-8222-222222222222',
issuedAt,
),
},
{
...valid,
issuedAt: String(NOW_SECONDS - 61),
signature: signature(WORKSPACE_ID, String(NOW_SECONDS - 61)),
},
{
...valid,
issuedAt: String(NOW_SECONDS + 6),
signature: signature(WORKSPACE_ID, String(NOW_SECONDS + 6)),
},
{ ...valid, workspaceId: 'attacker-selected-workspace' },
];

for (const candidate of invalid) {
expect(() =>
requireTrustedCalendarWorkspaceContext(
candidate,
TEST_CONTEXT_KEY,
NOW_SECONDS,
),
).toThrow(CalendarContextInvalidError);
}
expect(() =>
requireTrustedCalendarWorkspaceContext(
valid,
'short-secret',
NOW_SECONDS,
),
).toThrow(CalendarContextUnavailableError);
});
Comment thread
seonghobae marked this conversation as resolved.
});
103 changes: 103 additions & 0 deletions apps/integration-calendar-service/src/calendar-service-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { createHmac, timingSafeEqual } from 'node:crypto';

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 ISSUED_AT_PATTERN = /^\d{10}$/u;
const SIGNATURE_PATTERN = /^[A-Za-z0-9_-]{43}$/u;
const MINIMUM_SECRET_BYTES = 32;
const MAXIMUM_CONTEXT_AGE_SECONDS = 60;
const MAXIMUM_FUTURE_SKEW_SECONDS = 5;
const CONTEXT_VERSION = 'life-os.calendar-workspace.v1';

/** Headers accepted from the trusted LifeOS gateway boundary. */
export interface CalendarWorkspaceContextHeaders {
readonly workspaceId: unknown;
readonly issuedAt: unknown;
readonly signature: unknown;
}

/** Marks a missing or unusable server-side verification configuration. */
export class CalendarContextUnavailableError extends Error {
constructor() {
super('trusted calendar context is unavailable');
this.name = 'CalendarContextUnavailableError';
}
}

/** Marks an untrusted, malformed, stale, or forged calendar context. */
export class CalendarContextInvalidError extends Error {
constructor() {
super('trusted calendar context is invalid');
this.name = 'CalendarContextInvalidError';
}
}

function requireSecret(secret: unknown): string {
if (
typeof secret !== 'string' ||
Buffer.byteLength(secret, 'utf8') < MINIMUM_SECRET_BYTES
) {
throw new CalendarContextUnavailableError();
}
return secret;
}

function requireIssuedAt(value: unknown, nowSeconds: number): string {
if (typeof value !== 'string' || !ISSUED_AT_PATTERN.test(value)) {
throw new CalendarContextInvalidError();
}
const issuedAt = Number(value);
if (
!Number.isSafeInteger(nowSeconds) ||
!Number.isSafeInteger(issuedAt) ||
issuedAt < nowSeconds - MAXIMUM_CONTEXT_AGE_SECONDS ||
issuedAt > nowSeconds + MAXIMUM_FUTURE_SKEW_SECONDS
) {
throw new CalendarContextInvalidError();
}
return value;
}

function expectedSignature(
workspaceId: string,
issuedAt: string,
secret: string,
): Buffer {
return Buffer.from(
createHmac('sha256', secret)
.update(`${CONTEXT_VERSION}\n${workspaceId}\n${issuedAt}`, 'utf8')
.digest('base64url'),
'ascii',
);
}

/**
* Verifies one short-lived server-derived workspace context and returns only
* the authenticated UUIDv4 workspace identifier.
*/
export function requireTrustedCalendarWorkspaceContext(
headers: CalendarWorkspaceContextHeaders,
secret: unknown,
nowSeconds = Math.floor(Date.now() / 1000),
): string {
const safeSecret = requireSecret(secret);
if (
typeof headers.workspaceId !== 'string' ||
!UUID_V4_PATTERN.test(headers.workspaceId) ||
typeof headers.signature !== 'string' ||
!SIGNATURE_PATTERN.test(headers.signature)
) {
throw new CalendarContextInvalidError();
}
const workspaceId = headers.workspaceId.toLowerCase();
const issuedAt = requireIssuedAt(headers.issuedAt, nowSeconds);
const providedSignature = Buffer.from(headers.signature, 'ascii');
const canonicalSignature = expectedSignature(workspaceId, issuedAt, safeSecret);
if (
providedSignature.length !== canonicalSignature.length ||
!timingSafeEqual(providedSignature, canonicalSignature)
) {
throw new CalendarContextInvalidError();
}
return workspaceId;
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createHmac, randomBytes } from 'node:crypto';
import type { AddressInfo } from 'node:net';
import { NestFactory } from '@nestjs/core';
import { describe, expect, it } from 'vitest';
Expand All @@ -13,6 +14,7 @@ const WORKSPACE_ID = 'e021b411-f75e-4490-97a4-f1f6ee811849';
const OTHER_WORKSPACE_ID = '474c83ae-08af-4a63-957b-49eb2093a61d';
const BLOCK_ID = '1f06da41-cf62-4387-adad-6f53dd8ee66c';
const SYNTHETIC_CSRF_TOKEN = 'synthetic-test-csrf-token';
const CALENDAR_CONTEXT_KEY = randomBytes(32).toString('base64url');

interface StoredCalendarResource {
readonly calendarData: string;
Expand Down Expand Up @@ -65,6 +67,21 @@ function unfoldIcalendar(value: string): string {
return value.replace(/\r\n[ \t]/g, '');
}

function trustedWorkspaceHeaders(workspaceId: string): Record<string, string> {
const issuedAt = String(Math.floor(Date.now() / 1000));
const signature = createHmac('sha256', CALENDAR_CONTEXT_KEY)
.update(
`life-os.calendar-workspace.v1\n${workspaceId}\n${issuedAt}`,
'utf8',
)
.digest('base64url');
return {
'x-life-os-workspace-id': workspaceId,
'x-life-os-context-issued-at': issuedAt,
'x-life-os-context-signature': signature,
};
}

async function postSync(
port: number,
workspaceId: string,
Expand All @@ -75,14 +92,107 @@ async function postSync(
headers: {
'content-type': 'application/json',
'x-csrf-token': SYNTHETIC_CSRF_TOKEN,
'x-workspace-id': workspaceId,
'x-workspace-id': 'attacker-selected-workspace',
...trustedWorkspaceHeaders(workspaceId),
},
body: JSON.stringify(body),
});
}

describe('calendar synchronization HTTP boundary', () => {
it('rejects legacy client-selected workspace authority and accepts the signed workspace context', async () => {
const previousSecret = process.env.CALENDAR_GATEWAY_CONTEXT_SECRET;
process.env.CALENDAR_GATEWAY_CONTEXT_SECRET = CALENDAR_CONTEXT_KEY;
const provider = new ConflictSafeRecordingProvider();
const app = await NestFactory.create(CalendarAppModule.register(provider), {
logger: false,
});
await app.listen(0, '127.0.0.1');

try {
const address = app.getHttpServer().address() as AddressInfo;
const legacyResponse = await fetch(
`http://127.0.0.1:${address.port}/v1/calendar/sync`,
{
method: 'POST',
headers: {
'content-type': 'application/json',
'x-csrf-token': SYNTHETIC_CSRF_TOKEN,
'x-workspace-id': WORKSPACE_ID,
},
body: JSON.stringify(timeBlock()),
},
);
expect(legacyResponse.status).toBe(401);
expect(provider.resources.size).toBe(0);

const trustedResponse = await fetch(
`http://127.0.0.1:${address.port}/v1/calendar/sync`,
{
method: 'POST',
headers: {
'content-type': 'application/json',
'x-csrf-token': SYNTHETIC_CSRF_TOKEN,
...trustedWorkspaceHeaders(WORKSPACE_ID),
},
body: JSON.stringify(timeBlock()),
},
);
expect(trustedResponse.status).toBe(200);
expect(provider.resources.size).toBe(1);
} finally {
await app.close();
if (previousSecret === undefined) {
delete process.env.CALENDAR_GATEWAY_CONTEXT_SECRET;
} else {
process.env.CALENDAR_GATEWAY_CONTEXT_SECRET = previousSecret;
}
}
});

it('returns calendar_context_unavailable without creating provider state when the verifier secret is missing', async () => {
const previousSecret = process.env.CALENDAR_GATEWAY_CONTEXT_SECRET;
delete process.env.CALENDAR_GATEWAY_CONTEXT_SECRET;
const provider = new ConflictSafeRecordingProvider();
const app = await NestFactory.create(CalendarAppModule.register(provider), {
logger: false,
});
await app.listen(0, '127.0.0.1');

try {
const address = app.getHttpServer().address() as AddressInfo;
const response = await fetch(
`http://127.0.0.1:${address.port}/v1/calendar/sync`,
{
method: 'POST',
headers: {
'content-type': 'application/json',
'x-csrf-token': SYNTHETIC_CSRF_TOKEN,
...trustedWorkspaceHeaders(WORKSPACE_ID),
},
body: JSON.stringify(timeBlock()),
},
);

expect(response.status).toBe(503);
expect(await response.json()).toMatchObject({
status: 503,
code: 'calendar_context_unavailable',
});
expect(provider.resources.size).toBe(0);
} finally {
await app.close();
if (previousSecret === undefined) {
delete process.env.CALENDAR_GATEWAY_CONTEXT_SECRET;
} else {
process.env.CALENDAR_GATEWAY_CONTEXT_SECRET = previousSecret;
}
}
});

it('prevents duplicates and silent overwrites while retaining tenant isolation', async () => {
const previousSecret = process.env.CALENDAR_GATEWAY_CONTEXT_SECRET;
process.env.CALENDAR_GATEWAY_CONTEXT_SECRET = CALENDAR_CONTEXT_KEY;
const provider = new ConflictSafeRecordingProvider();
const app = await NestFactory.create(CalendarAppModule.register(provider), {
logger: false,
Expand Down Expand Up @@ -164,6 +274,7 @@ describe('calendar synchronization HTTP boundary', () => {
headers: {
'x-csrf-token': SYNTHETIC_CSRF_TOKEN,
'x-workspace-id': WORKSPACE_ID,
...trustedWorkspaceHeaders(WORKSPACE_ID),
},
},
);
Expand All @@ -176,6 +287,11 @@ describe('calendar synchronization HTTP boundary', () => {
expect(ownershipInjection.status).toBe(400);
} finally {
await app.close();
if (previousSecret === undefined) {
delete process.env.CALENDAR_GATEWAY_CONTEXT_SECRET;
} else {
process.env.CALENDAR_GATEWAY_CONTEXT_SECRET = previousSecret;
}
}
});
});
Loading
Loading