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

369 lines
18 KiB
TypeScript

import type {Api} from '../src/api/api';
import type {Capabilities, DnsLogRecord, FlowDetail, RuleList, RuntimeOutbounds, RuntimeSettings} from '../src/api/model';
import {ApiError} from '../src/api/error';
import {ipLiteral, sourceIp} from '../src/api/selectors';
import * as fixtures from './fixtures/network';
import {instanceId, now, observedAt} from './fixtures/clock';
import {found, createPager, pageLimit} from './common';
import {routingTrace} from './routing';
import type {MockRecording} from './recording';
// Healthy demo logs contain successful lookups; refused ad lookups, upstream timeouts and server failures are seeded
// only in the faults scenario. These samples do not evaluate the DNS rules. NXDOMAIN is an answer.
function buildDnsLog(flows: FlowDetail[], faults: boolean): DnsLogRecord[] {
let seed = 941;
const next = () => (seed = (seed * 48271) % 2147483647) / 2147483647;
const domains = [...new Set(flows.map(flow => flow.input.domain).filter((name): name is string => !!name))];
const sources = [...new Set([...fixtures.connections.tcp, ...fixtures.connections.udp].map(row => sourceIp(row.src)))];
const blocked = ['ad.doubleclick.net', 'pagead2.googlesyndication.com', 'ads.tracker.example'];
let age = 0;
return Array.from({length: 480}, (_, i) => {
age += 12 + Math.floor(next() * 24) + (i % 96 < 28 ? 4 : 32);
const denied = faults && i % 73 === 0;
const domain = denied ? blocked[i % blocked.length] : domains[Math.floor(next() * (next() < 0.72 ? Math.min(domains.length, 16) : domains.length))];
const name = domain.replace(/\.$/, '') + '.';
const type = i % 4 === 0 ? 'AAAA' : 'A';
const entry = fixtures.dnsCache.entries.find(row => row.domain === name && row.type === type);
const cached = !denied && !!entry && i % 3 === 0;
const failed = faults && !cached && !denied && i % 23 === 7;
const missing = !cached && !failed && !denied && i % 11 === 5;
const status = denied ? 'REFUSED' : cached ? entry!.status : failed ? (i % 2 ? 'TIMEOUT' : 'SERVFAIL') : missing ? 'NXDOMAIN' : 'NOERROR';
const upstream = cached || denied ? null : i % 7 === 0 ? 'udp://223.5.5.5' : i % 4 === 0 ? 'https://dns.google/dns-query' : 'tls://1.1.1.1';
return {
id: 'dl-' + String(i + 1).padStart(6, '0'),
observed_at: new Date(Date.parse(observedAt) - age * 1000).toISOString(),
src: `${sources[Math.floor(next() * sources.length)]}:${40000 + (i % 20000)}`,
question: {name, type},
status,
cached,
upstream,
route: {source: 'default', rule: null},
elapsed_ms: cached ? 0 : denied ? 2 : failed ? 3000 + (i % 3) * 400 : i % 9 === 2 ? 150 + (i % 7) * 32 : 8 + (i % 31),
// In the faults ring one upstream answer (record 242, a fresh NOERROR) outgrows a page's response budget and ends that page early.
answers:
faults && i === 241
? Array.from({length: 3000}, (_, n) => ({
name,
type,
class: 'IN',
ttl: 300,
data: type === 'AAAA' ? `2001:db8::${n.toString(16)}` : `198.18.${n >> 8}.${n & 255}`
}))
: cached
? (entry?.answers ?? [])
: status === 'NOERROR'
? [{name, type, class: 'IN', ttl: 300, data: type === 'AAAA' ? '2001:db8::20' : '192.0.2.20'}]
: []
};
});
}
type NetworkApi = Pick<
Api,
| 'connections'
| 'flows'
| 'flow'
| 'routingTrace'
| 'dnsCache'
| 'dnsLog'
| 'dnsQuery'
| 'closeConnection'
| 'closeConnections'
| 'deleteDnsEntry'
| 'deleteDnsCacheByName'
| 'flushDnsCache'
>;
export function createNetwork(
capabilities: Capabilities,
big: boolean,
profile: string | null,
outbounds: RuntimeOutbounds,
revision: () => string,
ruleSnapshot: () => Promise<RuleList>,
dnsUpstreams: () => Promise<string[]>,
recording: MockRecording,
settings: () => Pick<RuntimeSettings, 'dns_log' | 'flows'>,
busy = false,
faults = false
) {
const flowPage = createPager('flows');
const cachePage = createPager('dnsCache');
// 256 KiB, which a full page of the demo's ordinary records stays under.
const logPage = createPager('dnsLog', 262144);
const large = big ? fixtures.connectionFixtures() : undefined;
const flows = large?.flows ?? structuredClone(fixtures.flows);
const connections = large?.connections ?? structuredClone(fixtures.connections);
if (faults && !large) connections.tcp.push(structuredClone(fixtures.failedConnection));
// honk's first release observes userspace only; the mock says so the same way.
if (profile === 'm1') connections.visibility = 'partial';
const dnsCache = structuredClone(fixtures.dnsCache);
const dnsLog = buildDnsLog(flows, faults);
function trimRecords() {
const limits = settings();
const expired = new Set(
flows
.filter(flow => flow.ended_at !== null && Date.now() - Date.parse(flow.ended_at) >= (limits.flows?.retention_seconds ?? Infinity) * 1000)
.map(flow => flow.id)
);
const remaining = flows.filter(flow => !expired.has(flow.id));
const excess = remaining.length - (limits.flows?.max_flows ?? Infinity);
if (excess > 0) {
remaining.sort(
(a, b) =>
Number(a.ended_at === null) - Number(b.ended_at === null) ||
Date.parse(a.ended_at ?? a.started_at ?? observedAt) - Date.parse(b.ended_at ?? b.started_at ?? observedAt)
);
remaining.slice(0, excess).forEach(flow => expired.add(flow.id));
}
for (let i = flows.length - 1; i >= 0; i--) if (expired.has(flows[i].id)) flows.splice(i, 1);
flowPage.invalidate(expired);
const evicted = dnsLog.splice(limits.dns_log?.max_records ?? dnsLog.length);
logPage.invalidate(new Set(evicted.map(record => record.id)));
}
trimRecords();
// Ends a live connection the userspace datapath owns: the row, its outbound counter and its recorded flow.
function closeLive(connection: (typeof connections.tcp)[number], reason: string) {
if (connection.state === 'active') {
const counter = outbounds.outbounds.find(row => row.name === connection.outbound);
if (counter) counter.active_connections--;
}
connection.state = 'closed';
connection.upload_bytes_per_second = connection.download_bytes_per_second = '0';
const flow = flows.find(f => f.connection_id === connection.id);
if (!flow) return;
const observed_at = new Date().toISOString();
const last = flow.trace.steps[flow.trace.steps.length - 1];
flow.state = 'closed';
flow.ended_at = observed_at;
flow.revision++;
flow.trace.steps.push({
seq: (last?.seq ?? 0) + 1,
observed_at,
elapsed_us: Math.max(last?.elapsed_us ?? 0, (Date.now() - Date.parse(flow.started_at!)) * 1000),
generation_id: revision(),
evidence: 'observed',
stage: 'connection',
data: {state: 'closed', milestone: 'terminal', reason, attempt_id: null, reply_received: null, error: null}
});
}
const api: NetworkApi = {
connections: async (query, signal) => {
signal?.throwIfAborted();
if (!capabilities.resources.connections.available) throw new ApiError(404, 'capability_not_supported', 'Connections are unavailable');
if (busy)
for (const c of [...connections.tcp, ...connections.udp]) if (c.state === 'active') c.download_bytes = String(BigInt(c.download_bytes ?? '0') + 1460n);
const src = query?.src === undefined ? undefined : ipLiteral(query.src);
if (query?.src !== undefined && !src) throw new ApiError(400, 'invalid_request', 'Expected a source IP literal');
const tcp = query?.type === 'udp' ? [] : connections.tcp.filter(c => !src || sourceIp(c.src) === src);
const udp = query?.type === 'tcp' ? [] : connections.udp.filter(c => !src || sourceIp(c.src) === src);
const limit = pageLimit(query?.limit);
// A summary leaves out the endpoints and the domain, which only the full detail carries.
const shown = <T extends object>(rows: T[]) =>
query?.detail === 'full'
? structuredClone(rows)
: rows.map(({src, dst, domain, ...row}: T & {src?: unknown; dst?: unknown; domain?: unknown}) => structuredClone(row));
return {
...connections,
total_tcp: tcp.length,
total_udp: udp.length,
tcp: shown(tcp.slice(0, limit)),
udp: shown(udp.slice(0, Math.max(0, limit - tcp.length))),
truncated: tcp.length + udp.length > limit
};
},
flows: async (query, signal) => {
signal?.throwIfAborted();
if (!capabilities.resources.flows.available) throw new ApiError(404, 'capability_not_supported', 'Flows are unavailable');
trimRecords();
const result = flowPage(
flows.filter(
f =>
(!query?.network || query.network === 'all' || f.network === query.network) &&
(!query?.state || query.state === 'all' || f.state === query.state) &&
(query?.connection_id === undefined || f.connection_id === query.connection_id)
),
query
);
recording.renew('flows');
return {
instance_id: instanceId,
observed_at: observedAt,
coverage: {
userspace_tcp: 'full',
userspace_udp: 'full',
kernel_direct: 'partial',
kernel_block: 'partial',
dns_intercept: 'partial',
kernel_bypass: 'none'
},
dropped_records: big || !faults ? '0' : fixtures.flowDroppedRecords,
flows: result.items.map(({trace, input, ...summary}) => (fixtures.flowSummaryOmitsInput[summary.id] ? summary : {...summary, input})),
next_cursor: result.next_cursor
};
},
flow: async (id, signal) => {
signal?.throwIfAborted();
if (!capabilities.resources.flows.available) throw new ApiError(404, 'capability_not_supported', 'Flows are unavailable');
trimRecords();
const result = structuredClone(
found(
flows.find(f => f.id === id),
'Flow'
)
);
recording.renew('flows');
return result;
},
routingTrace: async (request, signal) => {
signal?.throwIfAborted();
if (!capabilities.resources.routing_trace.available) throw new ApiError(404, 'capability_not_supported', 'Routing trace is unavailable');
return routingTrace(request, await ruleSnapshot(), dnsCache);
},
dnsCache: async (query, signal) => {
signal?.throwIfAborted();
if (!capabilities.resources.dns_cache.available || !capabilities.resources.dns_cache.read)
throw new ApiError(404, 'capability_not_supported', 'DNS cache unavailable');
const name = query?.name ?? query?.domain;
// Expired against the fixture clock, so the demo's entries do not lapse while the page stays open.
const entries = dnsCache.entries.filter(
e =>
(!name || e.domain === name || e.domain === name + '.') &&
(!query?.type || query.type.includes(e.type)) &&
(query?.include_expired || Date.parse(e.expires_at) > now)
);
const result = cachePage(entries, query);
// Usage covers the whole cache, whatever the listing's filters.
const usage = {entries: String(dnsCache.entries.length), entry_capacity: '256'};
// A summary leaves out the answers, which only the full detail carries.
const shown = query?.detail === 'full' ? result.items : result.items.map(({answers, ...entry}) => entry);
return {...dnsCache, coverage: {...dnsCache.coverage}, entries: shown, total: result.total, next_cursor: result.next_cursor, usage};
},
dnsLog: async (query, signal) => {
signal?.throwIfAborted();
const limits = capabilities.resources.dns_log;
if (!limits.available) throw new ApiError(404, 'capability_not_supported', 'DNS log unavailable');
if (query?.limit !== undefined && query.limit > limits.max_page_size!)
throw new ApiError(400, 'invalid_request', 'limit exceeds the advertised page size');
const needle = query?.name?.toLowerCase();
const src = query?.src === undefined ? undefined : ipLiteral(query.src);
if (query?.src !== undefined && !src) throw new ApiError(400, 'invalid_request', 'Expected a source IP literal');
trimRecords();
const ring = dnsLog;
const records = ring.filter(
r =>
(!needle || r.question.name.toLowerCase().includes(needle)) &&
(!query?.type || r.question.type === query.type) &&
(!src || (r.src !== null && sourceIp(r.src) === src))
);
const result = logPage(records, {...query, limit: query?.limit ?? 200});
recording.renew('dns_log');
// total counts the ring before filters, as the contract defines it.
return {observed_at: new Date().toISOString(), total: ring.length, next_cursor: result.next_cursor, records: result.items};
},
dnsQuery: async (domain, types, signal, cacheMode = 'normal', upstream) => {
signal?.throwIfAborted();
if (!capabilities.resources.dns_query.available) throw new ApiError(404, 'capability_not_supported', 'DNS query unavailable');
const forced = upstream === undefined ? null : (await dnsUpstreams()).find(name => name === upstream);
if (forced === undefined) throw new ApiError(422, 'unsupported_value', 'Unknown configured DNS upstream');
const name = domain.trim().toLowerCase().replace(/\.$/, '') + '.';
return {
domain: name,
cache_mode: cacheMode,
query_time: new Date().toISOString(),
results: types.map(type => {
const entry =
cacheMode === 'normal' && forced === null
? dnsCache.entries.find(e => e.domain === name && e.type === type && Date.parse(e.expires_at) > Date.now())
: undefined;
const data = type === 'AAAA' ? '2001:db8::14' : type === 'HTTPS' ? '1 . alpn="h2"' : '192.0.2.14';
return {
type,
cached: !!entry,
cache_entry_id: entry?.entry_id ?? null,
upstream: entry ? null : (forced ?? 'udp://192.0.2.53'),
route: {source: forced ? ('forced' as const) : ('default' as const), rule: null},
status: entry?.status ?? 'NOERROR',
elapsed_ms: entry ? 0 : 8,
question: {name, type},
answers: entry ? structuredClone(entry.answers ?? []) : [{name, type, class: 'IN', ttl: 60, data}]
};
})
};
},
closeConnection: async (connectionId, signal) => {
signal?.throwIfAborted();
if (!capabilities.resources.connections.can_close) throw new ApiError(404, 'capability_not_supported', 'Closing connections is unavailable');
for (const list of [connections.tcp, connections.udp]) {
const index = list.findIndex(c => c.id === connectionId);
if (index < 0) continue;
// Only the userspace datapath can cancel what it owns; kernel-observed entries stay.
if (list[index].observed_by === 'ebpf') throw new ApiError(409, 'state_conflict', 'Connection is not owned by the userspace datapath');
closeLive(list[index], 'closed_by_request');
list.splice(index, 1);
return;
}
throw new ApiError(404, 'resource_not_found', 'Connection not found');
},
closeConnections: async (query, signal) => {
signal?.throwIfAborted();
if (!capabilities.resources.connections.can_close) throw new ApiError(404, 'capability_not_supported', 'Closing connections is unavailable');
const src = query?.src === undefined ? undefined : ipLiteral(query.src);
if (query?.src !== undefined && !src) throw new ApiError(400, 'invalid_request', 'Expected a source IP literal');
const type = query?.type ?? 'all';
if (type === 'all' && !src && !query?.all) throw new ApiError(400, 'invalid_request', 'An unfiltered close needs all=true');
const lists: Array<'tcp' | 'udp'> = type === 'tcp' ? ['tcp'] : type === 'udp' ? ['udp'] : ['tcp', 'udp'];
const selected = lists.flatMap(network => connections[network].filter(c => !src || sourceIp(c.src) === src).map(c => ({network, c})));
const max = capabilities.resources.connections.max_bulk_close ?? 1000;
if (selected.length > max) throw new ApiError(413, 'request_too_large', `More than ${max} connections match`);
let closed = 0;
let skipped = 0;
for (const {network, c} of selected) {
if (c.observed_by === 'ebpf') {
skipped += 1;
continue;
}
closeLive(c, 'closed_by_request');
connections[network].splice(connections[network].indexOf(c), 1);
closed += 1;
}
return {closed, skipped};
},
deleteDnsEntry: async (entryId, signal) => {
signal?.throwIfAborted();
if (!capabilities.resources.dns_cache.available || !capabilities.resources.dns_cache.delete_entry)
throw new ApiError(404, 'capability_not_supported', 'Deleting DNS entries is unavailable');
const index = dnsCache.entries.findIndex(entry => entry.entry_id === entryId);
if (index < 0) return {deleted: 0};
dnsCache.entries.splice(index, 1);
return {deleted: 1};
},
deleteDnsCacheByName: async (query, signal) => {
signal?.throwIfAborted();
if (!capabilities.resources.dns_cache.available || !capabilities.resources.dns_cache.delete_name)
throw new ApiError(404, 'capability_not_supported', 'Deleting DNS names is unavailable');
if (!query.name.trim()) throw new ApiError(400, 'invalid_request', 'A DNS name is required');
const name = query.name.trim().toLowerCase().replace(/\.$/, '') + '.';
const matches = dnsCache.entries.filter(entry => entry.domain.toLowerCase() === name && (!query.type || query.type.includes(entry.type)));
for (const entry of matches) dnsCache.entries.splice(dnsCache.entries.indexOf(entry), 1);
return {matched: matches.length, deleted: matches.length};
},
flushDnsCache: async signal => {
signal?.throwIfAborted();
if (!capabilities.resources.dns_cache.available || !capabilities.resources.dns_cache.flush)
throw new ApiError(404, 'capability_not_supported', 'Flushing DNS cache is unavailable');
const matched = dnsCache.entries.length;
dnsCache.entries.length = 0;
return {matched, deleted: matched};
}
};
function interrupt(groupId: string, network: 'tcp' | 'udp') {
let interrupted = false;
for (const connection of connections[network]) {
if (connection.outbound !== groupId || !['active', 'dialing', 'routing'].includes(connection.state)) continue;
interrupted = true;
closeLive(connection, 'group_selection_changed');
}
return interrupted;
}
return {api, interrupt, trimRecords};
}