Files
Zakk 7d9a875779 fix(mock): enforce capabilities and preserve network evidence
Reject unavailable operations and invalid DNS-log source filters before state changes. Reuse endpoint parsing for bare and IPv6 addresses, and enforce DNS-log response budgets in UTF-8 bytes without serializing unlimited pages.

Cover capability refusals, address evidence and multibyte pagination. Keep contract traversal valid when a profile cannot start an operation, and clarify that generated DNS logs are samples rather than rule evaluations.
2026-10-28 06:58:10 +00:00

342 lines
17 KiB
TypeScript

import {uuid} from '../src/api/hash';
import type {Api} from '../src/api/api';
import type {
ApiEvent,
Capabilities,
EventOptions,
LogOptions,
LogRecord,
Operation,
OperationAccepted,
OperationState,
Runtime,
RuntimeSettings
} from '../src/api/model';
import {ApiError} from '../src/api/error';
import {wait} from '../src/api/wait';
import {found} from './common';
import {eventKinds, logLevels} from '../src/api/selectors';
import {instanceId} from './fixtures/clock';
import {logSeed} from './fixtures/lifecycle';
import {flows} from './fixtures/network';
import type {MockRecording} from './recording';
const MAX_FINISHED_OPERATIONS = 128;
// `operation` answers GET /operations/{id} for the e2e backend and the tests; doona itself only polls.
export type OperationReader = {operation(id: string, signal?: AbortSignal): Promise<OperationState>};
type LifecycleApi = Pick<Api, 'pollOperation' | 'subscribeEvents' | 'subscribeLogs'> & OperationReader;
export interface MockLifecycle {
api: LifecycleApi;
enqueue<K extends OperationAccepted['kind']>(kind: K, finish: () => Extract<Operation, {kind: K; status: 'succeeded'}>['result']): OperationAccepted;
log(level: LogRecord['level'], target: string | null, message: string, fields?: LogRecord['fields']): void;
publish(event: ApiEvent): void;
eventData(): {instance_id: string; observed_at: string};
trimLogs(): void;
pending(kind: OperationAccepted['kind']): boolean;
}
export function createLifecycle(
logsCapability: Capabilities['resources']['logs'],
eventsCapability: Capabilities['resources']['events'],
operationsCapability: Capabilities['resources']['operations'],
runtime: Pick<Runtime, 'observed_at' | 'last_reload'>,
logSettings: () => RuntimeSettings['log'],
revision: () => string,
recording: MockRecording,
trickleEvery = 2500,
faults = false
): MockLifecycle {
const operations = new Map<string, OperationState>();
let operationSequence = 0;
const pruneOperations = () => {
const finished = [...operations].filter(([, operation]) => operation.finished_at !== null);
for (const [index, [id, operation]] of finished.entries())
if (
index < finished.length - MAX_FINISHED_OPERATIONS ||
Date.now() - Date.parse(operation.finished_at!) >= (operationsCapability.retention_seconds ?? 300) * 1000
)
operations.delete(id);
};
let sequence = 0;
const listeners = new Set<(event: ApiEvent) => void>();
const history: ApiEvent[] = [];
const cursors = new Map<string, {stream: 'events' | 'logs'; filter: string; position: number; issued: number}>();
const cursorIds = new Map<string, string>();
const pruneCursors = () => {
while (history.length && Date.now() - Date.parse(history[0].data.observed_at) > eventsCapability.retention_seconds! * 1000) history.shift();
const eventFloor = history.length ? Number(history[0].id.split(':')[1]) - 1 : sequence;
const logFloor = logRing.length ? Number(logRing[0].id.split(':')[2]) - 1 : logSequence;
for (const [id, cursor] of cursors) {
if (
cursor.position < (cursor.stream === 'events' ? eventFloor : logFloor) ||
(cursor.stream === 'events' && Date.now() - cursor.issued > eventsCapability.retention_seconds! * 1000)
) {
cursors.delete(id);
cursorIds.delete(JSON.stringify([cursor.stream, cursor.filter, cursor.position]));
}
}
};
const issueCursor = (stream: 'events' | 'logs', filter: string, position: number) => {
const key = JSON.stringify([stream, filter, position]);
const previous = cursorIds.get(key);
if (previous) return previous;
const id = uuid();
cursors.set(id, {stream, filter, position, issued: Date.now()});
cursorIds.set(key, id);
return id;
};
const resume = (id: string | undefined, stream: 'events' | 'logs', filter: string, baseline: number) => {
if (id === undefined) return baseline;
pruneCursors();
const cursor = cursors.get(id);
if (!cursor || cursor.stream !== stream || cursor.filter !== filter)
throw new ApiError(409, 'event_cursor_expired', 'The stream cursor cannot be replayed');
return cursor.position;
};
let timer: ReturnType<typeof setInterval> | undefined;
// A first visit has no chart history yet. The first stream repeats its opening ready a second later, as a resume from
// the same cursor would, so the client reads everything again and the CPU and latency lines get their second sample
// without waiting out the five-second runtime poll and the event gap. The repeat keeps the opening id, so the notices
// and the Events page replace that row rather than list a second one.
let warmed = false;
const eventData = () => ({instance_id: instanceId, observed_at: new Date().toISOString()});
function publish(event: ApiEvent) {
event.id = `${instanceId}:${++sequence}`;
history.push(event);
if (history.length > eventsCapability.max_buffered_events!) history.shift();
pruneCursors();
listeners.forEach(listener => listener(event));
}
function runtimeUpdated() {
runtime.observed_at = new Date().toISOString();
publish({id: '', event: 'runtime.updated', data: {...eventData(), href: '/api/v1/runtime'}});
}
const enqueue: MockLifecycle['enqueue'] = (kind, finish) => {
pruneOperations();
const operation_id = 'op-' + ++operationSequence;
const created_at = new Date().toISOString();
const common = {operation_id, kind, created_at, started_at: created_at};
operations.set(operation_id, {...common, finished_at: null, status: 'running', result: null, error: null, retryAfter: 1});
publish({
id: '',
event: 'operation.updated',
data: {...eventData(), resource_id: operation_id, status: 'running', href: '/api/v1/operations/' + operation_id}
});
setTimeout(() => {
try {
operations.set(operation_id, {...common, status: 'succeeded', result: finish(), error: null, finished_at: new Date().toISOString()} as OperationState);
} catch (error) {
operations.set(operation_id, {
...common,
status: 'failed',
finished_at: new Date().toISOString(),
result: null,
// An ApiError carries the operation error honk would set; anything else is a generic failure.
error:
error instanceof ApiError
? {code: error.code, message: error.message, details: error.details}
: {code: 'operation_failed', message: error instanceof Error ? error.message : String(error)}
} as OperationState);
}
const terminal = operations.get(operation_id)!;
if (kind === 'reload' && (terminal.status === 'succeeded' || terminal.status === 'failed'))
runtime.last_reload = {operation_id, status: terminal.status, finished_at: terminal.finished_at, error: terminal.error};
publish({
id: '',
event: 'operation.updated',
data: {...eventData(), resource_id: operation_id, status: terminal.status, href: '/api/v1/operations/' + operation_id}
});
runtimeUpdated();
pruneOperations();
}, 1000);
const href = '/api/v1/operations/' + operation_id;
return {operation_id, kind, status: 'queued', href, retryAfter: 1};
};
const operation = async (id: string, signal?: AbortSignal): Promise<OperationState> => {
signal?.throwIfAborted();
if (!operationsCapability.available) throw new ApiError(404, 'capability_not_supported', 'Operations are unavailable');
pruneOperations();
return structuredClone(found(operations.get(id), 'Operation'));
};
// Keep a bounded replay ring fed by mock activity and quiet background records.
const logRing: Array<LogRecord & {id: string}> = [];
const logListeners = new Set<(record: LogRecord & {id: string}) => void>();
let logSequence = 0;
function trimLogs() {
// An engine that reports no capacity keeps every record.
const limit = logSettings()?.buffered_records ?? Infinity;
if (logRing.length > limit) logRing.splice(0, logRing.length - limit);
pruneCursors();
}
const log = (level: LogRecord['level'], target: string | null, message: string, fields: LogRecord['fields'] = null, at = Date.now()) => {
const record = {id: `${instanceId}:logs:${++logSequence}`, ts: new Date(at).toISOString(), level, target, message, fields};
logRing.push(record);
trimLogs();
logListeners.forEach(listener => listener(record));
};
const trickle = [
() => log('info', 'honk::routing', 'Routing generation published.', {generation_id: revision()}),
() => log('debug', 'honk::dns', 'Upstream answered.', {upstream: 'tls://1.1.1.1:853', elapsed_ms: 12}),
() => log('info', 'honk::group', 'Health check finished.', {group: 'auto', healthy: 3, unavailable: 0}),
...(faults ? [() => log('warn', 'honk::subscription', 'Subscription served from cache.', {provider: 'harbor', age_seconds: 1800})] : []),
() => log('trace', 'honk::datapath', 'Kernel map synced.', {entries: 4096})
];
// A four-hour ring has routine traffic and busy periods; the faults scenario adds a stale subscription and a short
// health-check incident.
const started = Date.now();
for (let minute = faults ? 240 : 0; minute > 0; minute -= 2) {
const at = started - minute * 60000;
const trouble = faults && minute >= 34 && minute <= 48;
const busy = (minute >= 72 && minute <= 116) || (minute >= 164 && minute <= 188);
log('info', 'honk::group', 'Health check finished.', {group: 'auto', healthy: trouble ? 2 : 3, unavailable: trouble ? 1 : 0}, at);
log('debug', 'honk::dns', 'Upstream answered.', {upstream: 'tls://1.1.1.1:853', elapsed_ms: 12 + (minute % 9)}, at + 20000);
if (minute % 6 === 0) log('trace', 'honk::datapath', 'Kernel map synced.', {entries: 4096 + minute}, at + 10000);
if (faults && minute % 14 === 0) log('warn', 'honk::subscription', 'Subscription served from cache.', {provider: 'harbor', age_seconds: 1800}, at + 40000);
if (busy) log('info', 'honk::dns', 'Query answered.', {queries: 12 + (minute % 15)}, at + 30000);
if (trouble) {
log('warn', 'honk::group', 'Health check slow.', {node: 'us-01', elapsed_ms: 2400}, at + 30000);
log('error', 'honk::group', 'Health check failed.', {node: 'us-01', error: 'connect timeout'}, at + 50000);
}
}
const examples = logSeed.filter(record => faults || (record.level !== 'warn' && record.level !== 'error'));
// The healthy ring is 200 info records, the default Logs level, so the page opens full at either filter.
const routine = faults ? 0 : 200 - examples.length;
for (let n = routine; n > 0; n--) {
const at = started - Math.round((n * 4 * 3600000) / routine);
if (n % 2) log('info', 'honk::group', 'Health check finished.', {group: 'auto', healthy: 3, unavailable: 0}, at);
else log('info', 'honk::dns', 'Query answered.', {queries: 12 + (n % 15)}, at);
}
for (const record of examples) log(record.level, record.target, record.message, record.fields ?? null);
// Healthy history fills the default Events view; faults retain gaps and a failed operation.
for (let i = faults ? 28 : 200; i > 0; i--) {
const data = {instance_id: instanceId, observed_at: new Date(started - i * (faults ? 10000 : 1000)).toISOString()};
const flowId = faults ? `flow-r${String(i).padStart(2, '0')}` : flows[i % flows.length].id;
const flowUpdated: ApiEvent = {id: '', event: 'flow.updated', data: {...data, resource_id: flowId, revision: 1, href: `/api/v1/flows/${flowId}`}};
if (!faults && i >= 4 && i <= 7) {
publish(flowUpdated);
continue;
}
if (i === 21) publish({id: '', event: 'generation.changed', data: {...data, previous_generation_id: '39', generation_id: '40'}});
else if (i === 17)
publish({id: '', event: 'operation.updated', data: {...data, resource_id: 'op-1182', status: 'succeeded', href: '/api/v1/operations/op-1182'}});
else if (i === 7) publish({id: '', event: 'flow.gap', data: {...data, resource_id: null, reason: 'sampled', dropped_records: '3'}});
else if (i === 6) publish({id: '', event: 'flow.gap', data: {...data, resource_id: null, reason: 'buffer_overflow', dropped_records: '12'}});
else if (i === 5)
publish({id: '', event: 'operation.updated', data: {...data, resource_id: 'op-1183', status: 'failed', href: '/api/v1/operations/op-1183'}});
else if (i === 4) publish({id: '', event: 'flow.gap', data: {...data, resource_id: null, reason: 'recording_changed', dropped_records: '0'}});
else if (!faults || i % 3 === 0) publish(flowUpdated);
else publish({id: '', event: 'runtime.updated', data: {...data, href: '/api/v1/runtime'}});
}
let logTimer: ReturnType<typeof setInterval> | undefined;
async function logs({level, target, lastEventId, signal, onRecord, onConnectionChange}: LogOptions): Promise<void> {
if (signal?.aborted) return;
if (!logsCapability.available) throw new ApiError(404, 'capability_not_supported', 'Logs are unavailable');
if (level && !logsCapability.levels?.includes(level)) throw new ApiError(400, 'invalid_request', `Level ${level} is not advertised`);
const floor = level ? logLevels.indexOf(level) : 0;
const filter = JSON.stringify([level ?? null, target ?? null]);
const emit = (record: LogRecord & {id: string}) => {
if (logLevels.indexOf(record.level) >= floor && (!target || record.target?.startsWith(target)))
onRecord({...structuredClone(record), id: issueCursor('logs', filter, Number(record.id.split(':')[2]))});
};
const cursor = resume(lastEventId, 'logs', filter, 0);
const release = recording.attach('logs');
try {
onConnectionChange?.(true);
for (const record of logRing) if (Number(record.id.split(':')[2]) > cursor) emit(record);
if (signal?.aborted) {
onConnectionChange?.(false);
return;
}
logListeners.add(emit);
if (!logTimer) logTimer = setInterval(() => trickle[Math.floor(Math.random() * trickle.length)](), trickleEvery);
await new Promise<void>(resolve => {
signal?.addEventListener(
'abort',
() => {
logListeners.delete(emit);
if (!logListeners.size) {
clearInterval(logTimer);
logTimer = undefined;
}
onConnectionChange?.(false);
resolve();
},
{once: true}
);
});
} finally {
release();
}
}
async function events({kinds, lastEventId, signal, onEvent, onConnectionChange}: EventOptions): Promise<void> {
if (signal?.aborted) return;
if (!eventsCapability.available) throw new ApiError(404, 'capability_not_supported', 'Events are unavailable');
// No `kinds` means every kind, so naming them all keeps the cursor.
const filter = JSON.stringify([...new Set(kinds?.length ? kinds : eventKinds)].sort());
const emit = (event: ApiEvent) => {
if (event.event === 'stream.ready' || !kinds?.length || kinds.includes(event.event))
onEvent({...structuredClone(event), id: issueCursor('events', filter, Number(event.id.split(':')[1]))});
};
const cursor = resume(lastEventId, 'events', filter, 0);
const release = recording.attach(kinds?.some(kind => kind === 'flow.updated' || kind === 'flow.gap') ? 'flows' : undefined);
try {
onConnectionChange?.(true);
const opening: ApiEvent = {id: `${instanceId}:${Number.isFinite(cursor) ? cursor : sequence}`, event: 'stream.ready', data: eventData()};
emit(opening);
for (const event of history) if (Number(event.id.split(':')[1]) > cursor) emit(event);
if (signal?.aborted) {
onConnectionChange?.(false);
return;
}
listeners.add(emit);
if (!timer) timer = setInterval(runtimeUpdated, 5000);
let warmup: ReturnType<typeof setTimeout> | undefined;
if (!warmed) {
warmed = true;
warmup = setTimeout(() => emit({...opening, data: eventData()}), 1000);
}
await new Promise<void>(resolve => {
signal?.addEventListener(
'abort',
() => {
listeners.delete(emit);
clearTimeout(warmup);
if (!listeners.size) {
clearInterval(timer);
timer = undefined;
}
onConnectionChange?.(false);
resolve();
},
{once: true}
);
});
} finally {
release();
}
}
const api: LifecycleApi = {
operation,
pollOperation: async (accepted: OperationAccepted, signal?: AbortSignal) => {
let delay = accepted.retryAfter;
while (true) {
await wait(delay, signal);
const current = await operation(accepted.href.split('/').pop()!, signal);
if (current.status === 'succeeded' || current.status === 'failed') return current;
delay = current.retryAfter ?? 1;
}
},
subscribeEvents: events,
subscribeLogs: logs
};
return {
api,
enqueue,
log,
publish,
eventData,
trimLogs,
pending: (kind: OperationAccepted['kind']) => [...operations.values()].some(op => op.kind === kind && (op.status === 'queued' || op.status === 'running'))
};
}