Manage shared ARNavi VPS contours and application keys from infrastructure

This commit is contained in:
DCCONSTRUCTIONS
2026-09-30 15:34:39 +03:00
parent 6ca6738bab
commit 1828a05332
22 changed files with 1099 additions and 2 deletions
@@ -8,6 +8,7 @@
"test": "node --test test/*.test.mjs"
},
"dependencies": {
"oauth4webapi": "3.8.8",
"pg": "8.22.0"
},
"engines": {
+12
View File
@@ -81,6 +81,7 @@ export function createControlCoreApp({
gatewayIngest = null,
edgeChannelStatusProvider = null,
typedCommandRuntime = null,
b2Infrastructure = null,
} = {}) {
if (!repository || typeof repository.health !== "function") {
throw new TypeError("device_repository_required");
@@ -204,6 +205,17 @@ export function createControlCoreApp({
});
}
if (request.method === "POST" && requestUrl.pathname === "/internal/v1/b2/infrastructure") {
if (!managementApiEnabled || !b2Infrastructure) return writeJson(response, 503, { ok: false, error: "b2_infrastructure_unavailable" });
if (!matchesBearer(request.headers.authorization, managementToken)) return writeJson(response, 401, { ok: false, error: "device_management_auth_required" });
const requestId = String(request.headers["idempotency-key"] || "");
if (!/^[a-f0-9]{32}$/.test(requestId)) throw new TypeError("b2_request_id_invalid");
const actor = managementActorFromHeaders(request.headers);
const input = await readJsonBody(request, 64 * 1024);
const result = await b2Infrastructure.execute(actor, input, requestId);
return writeJson(response, 200, { ok: true, result });
}
const managementCommandKind = managementRoutes.get(requestUrl.pathname);
if (request.method === "POST" && managementCommandKind) {
if (!managementApiEnabled) {
@@ -0,0 +1,159 @@
import { createHash, timingSafeEqual } from 'node:crypto';
import { lookup } from 'node:dns/promises';
import { request, Agent } from 'node:https';
import { connect } from 'node:tls';
import { isIP } from 'node:net';
import * as oauth from 'oauth4webapi';
export function b2Error(code, statusCode = 400) {
return Object.assign(new Error(code), { statusCode });
}
export function connectionPackage(value) {
if (!value || value.schema !== 'nodedc.b2-connection/v2') throw b2Error('b2_connection_invalid');
const url = new URL(value.endpoint);
if (url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
throw b2Error('b2_endpoint_invalid');
}
if (!/^[a-f0-9]{64}$/.test(value.fingerprint) || !/^[A-Za-z0-9_-]{1,128}$/.test(value.client_id)
|| typeof value.client_secret !== 'string' || value.client_secret.length < 16 || value.client_secret.length > 1024
|| !/^[a-f0-9]{32}$/.test(value.integration_id) || typeof value.host_id !== 'string'
|| value.host_id.length > 160 || !['host', 'contours'].includes(value.authority)
|| value.issuer !== url.origin + '/' || value.audience !== url.origin + '/v2' || value.scope !== 'b2') {
throw b2Error('b2_connection_invalid');
}
return Object.freeze({ schema: value.schema, endpoint: url.origin, fingerprint: value.fingerprint,
issuer: value.issuer, audience: value.audience, scope: 'b2', host_id: value.host_id,
integration_id: value.integration_id, client_id: value.client_id, client_secret: value.client_secret,
authority: value.authority });
}
export function isPublicIPv4(value) {
if (isIP(value) !== 4) return false;
const [a, b, c] = value.split('.').map(Number);
return !(a === 0 || a === 10 || a === 127 || a >= 224
|| (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254)
|| (a === 172 && b >= 16 && b <= 31) || (a === 192 && (b === 168 || b === 0 || b === 2))
|| (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100)))
|| (a === 203 && b === 0 && c === 113));
}
export function pinnedFetch(pkg, { lookupImpl = lookup, connectImpl = connect, requestImpl = request, timeoutMs = 8000 } = {}) {
return async (input, init = {}) => {
const url = new URL(input instanceof Request ? input.url : input);
if (url.origin !== pkg.endpoint || !(/^\/v2(?:\/|$)/.test(url.pathname) || url.pathname === '/oauth2/token')) {
throw b2Error('b2_endpoint_invalid');
}
const started = Date.now();
let dnsTimer;
let cancelDNS;
let addresses;
try {
addresses = await Promise.race([
lookupImpl(url.hostname, { all: true, family: 4 }),
new Promise((_, reject) => {
cancelDNS = () => reject(b2Error('b2_request_timeout', 504));
dnsTimer = setTimeout(cancelDNS, timeoutMs);
init.signal?.addEventListener('abort', cancelDNS, { once: true });
if (init.signal?.aborted) cancelDNS();
}),
]);
} catch (error) {
if (error?.message?.startsWith('b2_')) throw error;
throw b2Error('b2_host_unavailable', 502);
} finally {
clearTimeout(dnsTimer); init.signal?.removeEventListener('abort', cancelDNS);
}
if (!addresses.length || addresses.some(({ address }) => !isPublicIPv4(address))) throw b2Error('b2_public_endpoint_required');
// Complete and verify TLS before handing the socket to HTTP. No credentials
// are written to a peer whose certificate does not match the imported pin.
const socket = connectImpl({ host: addresses[0].address, port: Number(url.port || 443),
servername: isIP(url.hostname) ? undefined : url.hostname, rejectUnauthorized: false });
const abort = () => socket.destroy(b2Error('b2_request_timeout', 504));
const timer = setTimeout(abort, Math.max(1, timeoutMs - (Date.now() - started)));
init.signal?.addEventListener('abort', abort, { once: true });
try {
if (init.signal?.aborted) throw b2Error('b2_request_timeout', 504);
await new Promise((resolve, reject) => {
socket.once('error', reject);
socket.once('secureConnect', () => {
try {
const cert = socket.getPeerCertificate();
if (!cert.raw || !timingSafeEqual(createHash('sha256').update(cert.raw).digest(), Buffer.from(pkg.fingerprint, 'hex'))) {
throw b2Error('b2_certificate_mismatch', 502);
}
resolve();
} catch (error) { reject(error); }
});
});
return await new Promise((resolve, reject) => {
const headers = Object.fromEntries(new Headers(init.headers));
const body = init.body == null ? null : String(init.body);
if (body) headers['content-length'] = String(Buffer.byteLength(body));
const agent = new Agent({ keepAlive: false, maxSockets: 1 });
agent.createConnection = () => socket;
const req = requestImpl(url, { method: init.method || 'GET', headers, agent }, (res) => {
const chunks = []; let length = 0;
res.on('data', (chunk) => {
length += chunk.length;
if (length > 1024 * 1024) { req.destroy(b2Error('b2_response_too_large', 502)); return; }
chunks.push(chunk);
});
res.on('error', reject);
res.on('end', () => resolve(new Response(Buffer.concat(chunks), {
status: res.statusCode, headers: res.headers,
})));
});
req.on('error', reject);
req.end(body);
});
} catch (error) {
if (error?.message?.startsWith('b2_')) throw error;
throw b2Error('b2_host_unavailable', 502);
} finally {
clearTimeout(timer); init.signal?.removeEventListener('abort', abort); socket.destroy();
}
};
}
export function createB2Client(input, { fetchImpl } = {}) {
const pkg = connectionPackage(input);
const transport = fetchImpl || pinnedFetch(pkg);
const server = { issuer: pkg.issuer, token_endpoint: pkg.endpoint + '/oauth2/token' };
const client = { client_id: pkg.client_id };
let token = null; let expires = 0; let pending = null;
async function accessToken() {
if (token && Date.now() < expires) return token;
if (!pending) pending = (async () => {
const response = await oauth.clientCredentialsGrantRequest(server, client,
oauth.ClientSecretBasic(pkg.client_secret), { scope: 'b2', audience: pkg.audience },
{ [oauth.customFetch]: transport });
const value = await oauth.processClientCredentialsResponse(server, client, response);
token = value.access_token;
expires = Date.now() + Math.max(0, Math.min(value.expires_in || 0, 300) - 15) * 1000;
return token;
})().finally(() => { pending = null; });
return pending;
}
return {
package: pkg,
async call(path, body) {
if (!/^\/v2\//.test(path)) throw b2Error('b2_resource_invalid');
let bearer;
try { bearer = await accessToken(); } catch { throw b2Error('b2_key_rejected', 502); }
const res = await transport(pkg.endpoint + path, {
method: body === undefined ? 'GET' : 'POST',
headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
const value = await res.json().catch(() => null);
if (!res.ok) {
if (res.status === 401 || res.status === 403) { token = null; throw b2Error('b2_access_denied', 403); }
if (res.status === 409) throw b2Error('b2_conflict', 409);
throw b2Error('b2_host_request_failed', 502);
}
if (!value || typeof value !== 'object') throw b2Error('b2_response_invalid', 502);
return value;
},
};
}
@@ -0,0 +1,162 @@
import { randomUUID } from 'node:crypto';
import { applyOntologyManagementCommand } from '../ontology-repository.mjs';
import { normalizeOntologyManagementCommand } from '../ontology-management.mjs';
import { findProjectWithCapability } from '../lifecycle-repository.mjs';
import { assertActorCanManageOwnerScope } from '../project-management.mjs';
import { b2Error, connectionPackage, createB2Client } from './connection.mjs';
function ref(value, prefix) {
if (typeof value !== 'string' || !new RegExp(`^${prefix}:[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`).test(value)) throw b2Error('b2_reference_invalid');
return value.slice(prefix.length + 1);
}
function opaque(value) {
if (typeof value !== 'string' || !/^[a-f0-9]{32}$/.test(value)) throw b2Error('b2_identifier_invalid');
return value;
}
function fields(input, names) {
if (Object.keys(input).some((key) => !['projectRef', 'hostRef', 'action', ...names].includes(key))) throw b2Error('b2_unexpected_field');
}
export class B2Infrastructure {
constructor({ pool, secrets, clientFactory = createB2Client }) {
this.pool = pool; this.secrets = secrets; this.clientFactory = clientFactory;
this.clients = new Map();
}
async clientFor(source) {
// Private file refs are immutable. Re-importing/replacing a key creates a
// new ref and therefore cannot reuse the previous OAuth token cache.
const cached = this.clients.get(source.secret_ref);
if (cached) return cached;
const client = this.clientFactory(await this.secrets.read(source.secret_ref));
if (this.clients.size >= 64) this.clients.delete(this.clients.keys().next().value);
this.clients.set(source.secret_ref, client);
return client;
}
async execute(actor, input, requestId) {
const projectId = ref(input.projectRef, 'project');
const hostId = ref(input.hostRef, 'host');
const action = input.action;
const readOnly = ['status', 'devices'].includes(action);
const db = await this.pool.connect();
try {
await db.query('begin');
const project = await findProjectWithCapability(db, actor, projectId, readOnly ? 'infrastructure.read' : 'infrastructure.manage');
// Host management can affect all projects of the company. A project-only
// grant must not turn into company-wide administration.
if (action !== 'devices') assertActorCanManageOwnerScope(actor, { scopeKind: project.scope_kind, ownerRef: project.owner_ref });
if (['connect', 'key-issue', 'key-revoke'].includes(action)) {
await findProjectWithCapability(db, actor, projectId, 'credential.manage');
}
const host = (await db.query('select id,host_key,display_name,provider_ref from device_infrastructure_hosts where id=$1 and project_id=$2 and lifecycle_state <> $3 for share',
[hostId, projectId, 'retired'])).rows[0];
if (!host) throw b2Error('b2_project_host_not_found', 404);
const source = (await db.query(`select s.* from device_b2_hosts s join device_b2_host_views v on v.source_id=s.id
where v.host_id=$1 and v.project_id=$2 ${readOnly ? '' : 'for update of s'}`, [hostId, projectId])).rows[0];
let result;
if (action === 'connect') {
fields(input, ['connection']);
const pkg = connectionPackage(typeof input.connection === 'string' ? JSON.parse(input.connection) : input.connection);
if (source && (source.remote_host_id !== pkg.host_id || source.integration_id !== pkg.integration_id)) {
throw b2Error('b2_connection_identity_conflict', 409);
}
const remote = this.clientFactory(pkg);
const identity = await remote.call('/v2/identity');
if (identity.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
const status = pkg.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours');
if (pkg.authority === 'host' && status.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
const secret = await this.secrets.save(pkg);
const saved = (await db.query(`insert into device_b2_hosts
(id,owner_scope_id,remote_host_id,endpoint,fingerprint,integration_id,authority,secret_ref)
values($1,$2,$3,$4,$5,$6,$7,$8)
on conflict(owner_scope_id,remote_host_id) do update set
secret_ref=excluded.secret_ref,revision=device_b2_hosts.revision+1,updated_at=now()
where device_b2_hosts.integration_id=excluded.integration_id
and device_b2_hosts.endpoint=excluded.endpoint and device_b2_hosts.fingerprint=excluded.fingerprint
and device_b2_hosts.authority=excluded.authority returning id`,
[randomUUID(), project.owner_scope_id, pkg.host_id, pkg.endpoint, pkg.fingerprint, pkg.integration_id, pkg.authority, secret])).rows[0];
if (!saved) throw b2Error('b2_connection_identity_conflict', 409);
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4) on conflict(host_id) do nothing`, [hostId, projectId, project.owner_scope_id, saved.id]);
result = { connected: true, endpoint: pkg.endpoint, authority: pkg.authority };
} else if (!source) {
if (action !== 'status') throw b2Error('b2_host_not_connected', 409);
result = { connected: false };
} else {
const remote = await this.clientFor(source);
const links = (await db.query('select contour_id,project_id from device_b2_contour_links where source_id=$1 order by contour_id', [source.id])).rows;
if (action === 'status') {
fields(input, []);
const value = source.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours');
result = { connected: true, endpoint: source.endpoint, authority: source.authority,
contours: value.contours || value.items, applications: value.applications || [],
links: links.map((link) => ({ contourId: link.contour_id, projectRef: `project:${link.project_id}` })) };
} else if (action === 'link') {
fields(input, ['contourId', 'targetProjectRef']);
const targetId = ref(input.targetProjectRef || input.projectRef, 'project');
const target = await findProjectWithCapability(db, actor, targetId, 'infrastructure.manage');
if (target.owner_scope_id !== project.owner_scope_id) throw b2Error('b2_company_mismatch', 403);
const contour = opaque(input.contourId);
const permitted = await remote.call('/v2/contours');
if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403);
const current = links.find((link) => link.contour_id === contour);
if (current && current.project_id !== targetId) throw b2Error('b2_contour_already_linked', 409);
await db.query(`insert into device_b2_contour_links(source_id,contour_id,project_id,owner_scope_id,created_by_ref)
values($1,$2,$3,$4,$5) on conflict(source_id,contour_id) do nothing`,
[source.id, contour, targetId, project.owner_scope_id, actor.userRef]);
if (targetId !== projectId) {
const related = (await db.query('select host_id from device_b2_host_views where source_id=$1 and project_id=$2', [source.id, targetId])).rows[0];
if (!related) {
const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure',
command: normalizeOntologyManagementCommand('infrastructure_host.ensure', {
projectRef: `project:${targetId}`, hostKey: `b2-${source.id}`, displayName: host.display_name,
providerRef: host.provider_ref, externalRef: source.remote_host_id,
managementCredentialRef: null, lifecycleState: 'active',
}) });
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4)`, [ref(registered.host.hostRef, 'host'), targetId, project.owner_scope_id, source.id]);
}
}
result = { linked: true, contourId: contour, projectRef: `project:${targetId}` };
} else if (action === 'devices') {
fields(input, []);
const contours = links.filter((link) => link.project_id === projectId);
const items = [];
for (const link of contours) {
const snapshot = await remote.call(`/v2/contours/${link.contour_id}/devices`);
items.push(...snapshot.items.map((device) => ({ id: device.id, name: device.name, number: device.number, active: device.active,
identifier: { masked: '…' + String(device.imei).slice(-5) }, contourId: link.contour_id })));
}
result = { items };
} else {
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
if (action === 'contour-create') {
fields(input, ['key', 'name']);
result = await remote.call('/v2/management/contours', { key: input.key, name: input.name });
} else if (action === 'application-create') {
fields(input, ['key', 'name', 'contourId']);
result = await remote.call('/v2/management/applications', {
key: input.key, name: input.name, grants: { [opaque(input.contourId)]: 'manage' },
});
} else if (action === 'key-issue') {
fields(input, ['integrationId', 'replace']);
if (typeof input.replace !== 'boolean') throw b2Error('b2_replace_invalid');
// Server reserves this request before generation. No automatic replay.
const packageValue = await remote.call('/v2/management/credentials', {
integration_id: opaque(input.integrationId), replace: input.replace, request_id: requestId,
});
result = { connection: packageValue };
} else if (action === 'key-revoke') {
fields(input, ['clientId']);
if (!/^[A-Za-z0-9_-]{1,128}$/.test(input.clientId)) throw b2Error('b2_client_invalid');
result = await remote.call('/v2/management/credentials/revoke', { client_id: input.clientId });
} else throw b2Error('b2_action_invalid');
}
}
if (!readOnly) await db.query(`insert into device_audit_events(id,event_type,actor_ref,payload,project_id)
values($1,$2,$3,$4::jsonb,$5)`, [randomUUID(), 'b2.' + action, actor.userRef,
JSON.stringify({ projectRef: input.projectRef, hostRef: input.hostRef, requestId }), projectId]);
await db.query('commit');
return result;
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
}
}
@@ -0,0 +1,43 @@
import { constants } from 'node:fs';
import { open, lstat } from 'node:fs/promises';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { b2Error, connectionPackage } from './connection.mjs';
// Dedicated persistent private mount provisioned by the canonical installer.
// It is not served, included in images, stored in audit payloads or returned by reads.
export class B2Secrets {
constructor(root) { this.root = root; }
async directory() {
if (!this.root) throw b2Error('b2_private_storage_unavailable', 503);
const info = await lstat(this.root);
if (!info.isDirectory() || info.isSymbolicLink() || (info.mode & 0o077) || info.uid !== process.getuid()) {
throw b2Error('b2_private_storage_invalid', 503);
}
}
path(ref) {
if (!/^b2-secret:[a-f0-9-]{36}$/.test(ref)) throw b2Error('b2_secret_reference_invalid');
return join(this.root, ref.slice(10) + '.json');
}
async save(input) {
const value = connectionPackage(input);
await this.directory();
const ref = 'b2-secret:' + randomUUID();
const file = await open(this.path(ref), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
try { await file.writeFile(JSON.stringify(value)); await file.sync(); } finally { await file.close(); }
const directory = await open(this.root, 'r');
try { await directory.sync(); } finally { await directory.close(); }
return ref;
}
async read(ref) {
await this.directory();
const file = await open(this.path(ref), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
try {
const info = await file.stat();
if (!info.isFile() || info.nlink !== 1 || info.uid !== process.getuid() || (info.mode & 0o077) || info.size > 16384) {
throw b2Error('b2_private_storage_invalid', 503);
}
return connectionPackage(JSON.parse(await file.readFile('utf8')));
} finally { await file.close(); }
}
}
@@ -15,6 +15,9 @@ import { createDeviceGatewayIngest } from "./gateway-ingest.mjs";
import { PostgresDeviceRepository } from "./postgres-repository.mjs";
import { createTypedCommandRuntime } from "./typed-command-runtime.mjs";
import { B2Infrastructure } from "./b2/infrastructure.mjs";
import { B2Secrets } from "./b2/secrets.mjs";
const config = await readConfig();
const repository = new PostgresDeviceRepository({
databaseUrl: config.databaseUrl,
@@ -57,6 +60,9 @@ const server = createControlCoreApp({
? () => edgeChannelSupervisor.status()
: null,
typedCommandRuntime,
b2Infrastructure: process.env.DEVICE_B2_SECRET_ROOT ? new B2Infrastructure({
pool: repository.pool, secrets: new B2Secrets(process.env.DEVICE_B2_SECRET_ROOT),
}) : null,
});
server.listen(config.port, config.host, () => {
@@ -0,0 +1,158 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { mkdtemp, chmod, rm, readFile, symlink } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { connectionPackage, createB2Client, isPublicIPv4, pinnedFetch } from '../src/b2/connection.mjs';
import { B2Secrets } from '../src/b2/secrets.mjs';
import { B2Infrastructure } from '../src/b2/infrastructure.mjs';
const pkg = { schema: 'nodedc.b2-connection/v2', endpoint: 'https://vps.example.invalid:19443',
fingerprint: 'a'.repeat(64), issuer: 'https://vps.example.invalid:19443/',
audience: 'https://vps.example.invalid:19443/v2', scope: 'b2', host_id: 'synthetic-host',
integration_id: 'b'.repeat(32), client_id: 'b2_test', client_secret: 'synthetic-test-secret-not-production', authority: 'host' };
const projectId = '11111111-1111-4111-8111-111111111111';
const otherProject = '22222222-2222-4222-8222-222222222222';
const hostId = '33333333-3333-4333-8333-333333333333';
const ownerId = '44444444-4444-4444-8444-444444444444';
const actor = { userRef: 'user:operator', hubRole: 'owner', groupRefs: [], ownerScopes: [{ scopeKind: 'company', ownerRef: 'company:example' }] };
const source = { id: '55555555-5555-4555-8555-555555555555', owner_scope_id: ownerId,
remote_host_id: pkg.host_id, endpoint: pkg.endpoint, fingerprint: pkg.fingerprint,
integration_id: pkg.integration_id, authority: pkg.authority, secret_ref: 'private-ref' };
function repository({ role = 'owner', links = [], otherOwner = ownerId } = {}) {
const writes = [];
const db = { release() {}, async query(sql, values) {
if (['begin', 'commit', 'rollback'].includes(sql)) return { rows: [] };
if (sql.includes('from device_projects')) return { rows: [{ id: values[0], owner_scope_id: values[0] === projectId ? ownerId : otherOwner,
lifecycle_state: 'active', owner_lifecycle_state: 'active', scope_kind: 'company', owner_ref: 'company:example' }] };
if (sql.includes('from device_project_grants')) return { rows: [{ id: 'grant', principal_kind: 'user', principal_ref: actor.userRef,
project_role: role, capability_allow: [], capability_deny: [], lifecycle_state: 'active' }] };
if (sql.includes('from device_infrastructure_hosts')) return { rows: [{ id: hostId }] };
if (sql.includes('from device_b2_hosts')) return { rows: [source] };
if (sql.includes('from device_b2_contour_links')) return { rows: links };
if (sql.startsWith('insert')) { writes.push({ sql, values }); return { rows: [] }; }
throw new Error('unexpected test query: ' + sql);
} };
return { pool: { connect: async () => db }, writes };
}
test('connection import fixes issuer, audience and authority to the supplied host', () => {
assert.equal(connectionPackage(pkg).endpoint, pkg.endpoint);
for (const change of [{ endpoint: 'http://vps.example.invalid' }, { issuer: 'https://other.invalid/' },
{ audience: 'https://other.invalid/v2' }, { fingerprint: 'x' }, { authority: 'owner' }]) {
assert.throws(() => connectionPackage({ ...pkg, ...change }));
}
});
test('standard OAuth client caches access token and does not log or return credentials', async () => {
let tokens = 0; let calls = 0;
const client = createB2Client(pkg, { fetchImpl: async (url, init) => {
if (String(url).endsWith('/oauth2/token')) {
tokens += 1;
const headers = new Headers(init.headers);
assert.match(headers.get('authorization'), /^Basic /);
const body = new URLSearchParams(init.body);
assert.equal(body.get('grant_type'), 'client_credentials');
assert.equal(body.get('audience'), pkg.audience);
return new Response(JSON.stringify({ access_token: 'opaque-test-token', token_type: 'Bearer', expires_in: 300 }), { headers: { 'content-type': 'application/json' } });
}
calls += 1;
assert.equal(new Headers(init.headers).get('authorization'), 'Bearer opaque-test-token');
return new Response('{"items":[]}');
} });
await Promise.all([client.call('/v2/contours'), client.call('/v2/contours')]);
assert.equal(tokens, 1); assert.equal(calls, 2);
await assert.rejects(client.call('/admin/clients'));
});
test('outbound adapter rejects private networks, redirects and foreign origins before TLS', async () => {
for (const address of ['127.0.0.1', '10.1.2.3', '172.16.1.1', '192.168.1.3', '169.254.169.254', '::1', '100.64.1.1']) assert.equal(isPublicIPv4(address), false);
const fetcher = pinnedFetch(pkg, { lookupImpl: async () => [{ address: '127.0.0.1' }], connectImpl: () => assert.fail('must not connect') });
await assert.rejects(fetcher(pkg.endpoint + '/v2/contours'), /b2_public_endpoint_required/);
await assert.rejects(fetcher('https://other.invalid/v2/contours'), /b2_endpoint_invalid/);
await assert.rejects(fetcher(pkg.endpoint + '/admin/clients'), /b2_endpoint_invalid/);
});
test('private file store uses unique 0600 files and rejects permissive roots and symlinks', async () => {
const root = await mkdtemp(join(tmpdir(), 'ndc-b2-secrets-'));
try {
await chmod(root, 0o700);
const store = new B2Secrets(root);
const ref = await store.save(pkg);
assert.equal((await store.read(ref)).client_secret, pkg.client_secret);
assert.equal(JSON.parse(await readFile(store.path(ref), 'utf8')).client_id, pkg.client_id);
const bad = 'b2-secret:66666666-6666-4666-8666-666666666666';
await symlink(store.path(ref), store.path(bad));
await assert.rejects(store.read(bad));
await chmod(root, 0o755);
await assert.rejects(store.read(ref), /b2_private_storage_invalid/);
await assert.rejects(store.save(pkg), /b2_private_storage_invalid/);
} finally { await rm(root, { recursive: true, force: true }); }
});
test('DNS resolution consumes the same bounded request deadline and respects cancellation', async () => {
const stalled = pinnedFetch(pkg, { timeoutMs: 20, lookupImpl: () => new Promise(() => {}),
connectImpl: () => assert.fail('no connection after DNS timeout') });
await assert.rejects(stalled(pkg.endpoint + '/v2/identity'), /b2_request_timeout/);
const controller = new AbortController(); controller.abort();
await assert.rejects(stalled(pkg.endpoint + '/v2/identity', { signal: controller.signal }), /b2_request_timeout/);
});
test('service reuses tokens only for the same immutable secret reference', async () => {
let reads = 0; let created = 0;
const service = new B2Infrastructure({ pool: {}, secrets: { read: async () => { reads += 1; return pkg; } },
clientFactory: () => ({ generation: ++created }) });
assert.equal((await service.clientFor(source)).generation, 1);
assert.equal((await service.clientFor(source)).generation, 1);
assert.equal((await service.clientFor({ ...source, secret_ref: 'new-private-ref' })).generation, 2);
assert.equal(reads, 2);
});
test('project reader sees only explicitly linked fleet, even with a host-management connection', async () => {
const own = 'a'.repeat(32); const other = 'b'.repeat(32);
const repo = repository({ role: 'viewer', links: [{ contour_id: own, project_id: projectId }, { contour_id: other, project_id: otherProject }] });
const calls = [];
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) { calls.push(path); return { items: [] }; } }) });
assert.deepEqual(await service.execute({ ...actor, hubRole: 'member' }, { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'devices' }, '1'.repeat(32)), { items: [] });
assert.deepEqual(calls, [`/v2/contours/${own}/devices`]);
await assert.rejects(service.execute({ ...actor, hubRole: 'member' }, { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'contour-create', key: 'foreign', name: 'Foreign' }, '2'.repeat(32)));
});
test('company management refuses linking to another company before any remote request', async () => {
const repo = repository({ otherOwner: '77777777-7777-4777-8777-777777777777' });
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: () => assert.fail('no remote mutation') }) });
await assert.rejects(service.execute(actor, { action: 'link', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`,
targetProjectRef: `project:${otherProject}`, contourId: 'c'.repeat(32) }, '3'.repeat(32)), /b2_company_mismatch/);
assert.deepEqual(repo.writes, []);
});
test('TLS pin is verified before any HTTP credential reaches the peer', async () => {
const { execFileSync } = await import('node:child_process');
const { createServer } = await import('node:https');
const tls = await import('node:tls');
const { X509Certificate, createHash } = await import('node:crypto');
const root = await mkdtemp(join(tmpdir(), 'ndc-b2-tls-'));
let server;
try {
execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1', '-subj', '/CN=unit.invalid',
'-keyout', join(root, 'key.pem'), '-out', join(root, 'cert.pem')], { stdio: 'ignore' });
const key = await readFile(join(root, 'key.pem')); const cert = await readFile(join(root, 'cert.pem'));
let received = 0;
server = createServer({ key, cert }, (req, res) => {
received += 1;
assert.equal(req.headers.authorization, 'Bearer synthetic-token');
res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('{"ok":true}');
});
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
const deps = { lookupImpl: async () => [{ address: '8.8.8.8' }],
connectImpl: (options) => tls.connect({ ...options, host: '127.0.0.1', port: server.address().port }) };
const good = { ...pkg, fingerprint: createHash('sha256').update(new X509Certificate(cert).raw).digest('hex') };
const response = await pinnedFetch(good, deps)(pkg.endpoint + '/v2/contours', { headers: { Authorization: 'Bearer synthetic-token' } });
assert.equal(response.status, 200); assert.equal(received, 1);
await assert.rejects(pinnedFetch(pkg, deps)(pkg.endpoint + '/v2/contours', { headers: { Authorization: 'Bearer must-never-arrive' } }), /b2_certificate_mismatch/);
assert.equal(received, 1);
} finally {
if (server?.listening) await new Promise((resolve) => server.close(resolve));
await rm(root, { recursive: true, force: true });
}
});