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/vault.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, name: 'Test project', 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 }); } }); test('project inventory releases DB before networking and never exposes other projects or credentials', async () => { const contour = 'c'.repeat(32); let released = false; const calls = []; const repo = repository({ role: 'viewer' }); const db = await repo.pool.connect(); const original = db.query; db.release = () => { released = true; }; db.query = async (sql, values) => { if (sql.includes('from device_b2_hosts')) { assert.match(sql, /v.project_id=\$1 and h.lifecycle_state='active'/); assert.match(sql, /l.project_id=v.project_id/); assert.deepEqual(values, [projectId]); return { rows: [{ ...source, host_id: hostId, display_name: 'VPS', contour_ids: [contour] }] }; } return original(sql, values); }; const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) { assert.equal(released, true); calls.push(path); return path === '/v2/identity' ? { host_id: pkg.host_id } : { items: [{ id: 'device', imei: '123456789012345', number: 1, name: 'B2', active: true }] }; } }) }); const result = await service.execute({ ...actor, hubRole: 'member' }, { projectRef: `project:${projectId}`, action: 'inventory' }); assert.deepEqual(calls, ['/v2/identity', `/v2/contours/${contour}/devices`]); assert.equal(result.items[0].identifier.masked, '…12345'); assert.equal(result.hosts[0].reachable, true); assert.equal(result.hosts[0].devices, 1); const json = JSON.stringify(result); for (const secret of [pkg.client_secret, source.secret_ref, '123456789012345', otherProject]) assert.equal(json.includes(secret), false); assert.equal('online' in result.items[0], false); }); test('unreachable or mismatched host is reported as unavailable, not an empty healthy fleet', async () => { for (const fail of [false, true]) { const repo = repository(); const db = await repo.pool.connect(); const original = db.query; db.query = (sql, values) => sql.includes('from device_b2_hosts') ? { rows: [{ ...source, host_id: hostId, display_name: 'VPS', contour_ids: [] }] } : original(sql, values); const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call() { if (fail) throw Error('contains-private-details'); return { host_id: 'wrong-host' }; } }) }); const result = await service.execute(actor, { projectRef: `project:${projectId}`, action: 'inventory' }); assert.equal(result.hosts[0].reachable, false); assert.equal(result.hosts[0].devices, null); assert.deepEqual(result.items, []); assert.equal(JSON.stringify(result).includes('private-details'), false); } }); test('project connection generates stable contour identity and links it without user codes', async () => { const repo = repository(); const calls = []; const contour = 'c'.repeat(32); const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) { calls.push({ path, body }); return path === '/v2/management/contours' ? { id: contour } : { items: [{ id: contour }] }; } }) }); const result = await service.execute(actor, { action: 'project-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, targetProjectRef: `project:${projectId}` }, 'a'.repeat(32)); assert.equal(result.linked, true); assert.equal(calls[0].body.key, 'dc-' + projectId); assert.equal(calls[0].body.name, 'Test project'); assert.equal(repo.writes.filter((x) => x.sql.includes('device_b2_contour_links')).length, 1); }); test('connecting an already linked project does not create another contour', async () => { const contour = 'c'.repeat(32); const repo = repository({ links: [{ contour_id: contour, project_id: projectId }] }); const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) { assert.equal(path, '/v2/contours'); return { items: [{ id: contour }] }; } }) }); const result = await service.execute(actor, { action: 'project-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}` }, 'a'.repeat(32)); assert.equal(result.contourId, contour); }); test('application creation and issuance use one server-generated request identity', async () => { const contour = 'c'.repeat(32); const repo = repository({ links: [{ contour_id: contour, project_id: projectId }] }); const calls = []; const requestId = 'd'.repeat(32); const app = 'e'.repeat(32); const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) { calls.push({ path, body }); return path.endsWith('applications') ? { id: app } : { synthetic: true }; } }) }); const result = await service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Partner', contourId: contour }, requestId); assert.equal(calls[0].body.key, 'app-' + requestId); assert.equal(calls[1].body.request_id, requestId); assert.equal(result.id, app); assert.ok(result.connection); assert.equal(JSON.stringify(repo.writes).includes('synthetic'), false); await assert.rejects(service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Other', contourId: 'f'.repeat(32) }, requestId), /b2_access_denied/); assert.equal(calls.length, 2); }); test('tracker settings keep project and contour authority across remote calls', async () => { const contour = 'c'.repeat(32), device = 'd'.repeat(32), calls = []; const repo = repository({ role: 'viewer' }); const db = await repo.pool.connect(); let released = false; const original = db.query; db.release = () => { released = true; }; db.query = async (sql, values) => { if (sql.includes('from device_b2_hosts')) { assert.match(sql, /l.project_id=v.project_id/); assert.match(sql, /h.lifecycle_state='active'/); assert.deepEqual(values, [hostId, projectId, contour]); return { rows: [source] }; } return original(sql, values); }; const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) { assert.equal(released, true); calls.push({path,body}); return path === '/v2/identity' ? {host_id:pkg.host_id} : {revision:1}; } }) }); const input = {action:'tracker',projectRef:`project:${projectId}`,hostRef:`host:${hostId}`,contourId:contour,deviceId:device,request:{action:'state'}}; assert.deepEqual(await service.execute({...actor,hubRole:'member'},input), {revision:1}); assert.equal(calls[1].path, `/v2/contours/${contour}/devices/${device}/settings`); for (const action of ['save','apply','read','command','cancel','firmware-upload','profile-save']) { await assert.rejects(service.execute({...actor,hubRole:'member'},{...input,request:{action}})); } assert.equal(calls.length,2); db.query = async (sql,values) => sql.includes('from device_b2_hosts') ? {rows:[]} : original(sql,values); await assert.rejects(service.execute(actor,input), /b2_access_denied/); assert.equal(calls.length,2); }); test('VPS onboarding rejects invalid or application-only credentials without creating a host', async () => { for (const input of ['bad-json', JSON.stringify({ ...pkg, authority: 'contours' }), JSON.stringify(pkg)]) { const repo = repository(); let secrets = 0; const service = new B2Infrastructure({ pool: repo.pool, secrets: { save: async () => { secrets += 1; return 'private-ref'; } }, clientFactory: () => ({ call: async (path) => path === '/v2/identity' ? { host_id: input === JSON.stringify(pkg) ? 'foreign-host' : pkg.host_id } : { items: [] } }) }); await assert.rejects(service.execute(actor, { action: 'register-host', projectRef: `project:${projectId}`, name: 'VPS', connection: input }, 'a'.repeat(32))); assert.equal(secrets, 0); assert.deepEqual(repo.writes, []); } }); test('VPS onboarding reuses the project host and audits no credential material', async () => { const queries = []; let existing = false; const base = repository(); const db = await base.pool.connect(); const original = db.query.bind(db); db.query = async (sql, values) => { queries.push({ sql, values }); if (sql.includes('pg_advisory_xact_lock')) return { rows: [] }; if (sql.startsWith('insert into device_b2_hosts')) return { rows: [{ id: source.id }] }; if (sql.startsWith('select h.host_key')) return { rows: existing ? [{ host_key: 'b2-existing-project-view' }] : [] }; if (sql.startsWith('insert into device_infrastructure_hosts')) return { rows: [{ id: hostId, host_key: values[3], display_name: values[4], project_id: projectId, owner_scope_id: ownerId, lifecycle_state: 'active', created: !existing }] }; if (sql.startsWith('insert into device_b2_host_views')) { existing = true; return { rows: [] }; } return original(sql, values); }; const service = new B2Infrastructure({ pool: base.pool, secrets: { save: async () => 'private-ref' }, clientFactory: () => ({ call: async () => ({ host_id: pkg.host_id }) }) }); const input = { action: 'register-host', projectRef: `project:${projectId}`, name: 'VPS', connection: JSON.stringify(pkg) }; const first = await service.execute(actor, input, 'a'.repeat(32)); const second = await service.execute(actor, input, 'b'.repeat(32)); assert.equal(first.hostRef, second.hostRef); assert.equal(queries.filter((q) => q.sql === 'commit').length, 2); const hosts = queries.filter((q) => q.sql.startsWith('insert into device_infrastructure_hosts')); assert.equal(hosts[0].values[3], `b2-${source.id}`); assert.equal(hosts[1].values[3], 'b2-existing-project-view'); const audit = queries.filter((q) => q.sql.includes('insert into device_audit_events')); assert.ok(audit.length > 0); assert.ok(!JSON.stringify(audit).includes(pkg.client_secret)); }); test('application deletion requires company and credential authority and forwards only the application ID', async () => { const repo = repository(); const calls = []; const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) { calls.push({ path, body }); return { deleted: true, id: body.integration_id }; } }) }); const input = { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'application-delete', integrationId: 'c'.repeat(32) }; await assert.rejects(service.execute({ ...actor, hubRole: 'member', ownerScopes: [] }, input, '1'.repeat(32)), /device_owner_scope_access_denied/); await assert.rejects(service.execute(actor, { ...input, integrationId: '../foreign' }, '1'.repeat(32)), /b2_identifier_invalid/); await assert.rejects(service.execute(actor, { ...input, force: true }, '1'.repeat(32)), /b2_unexpected_field/); assert.equal(calls.length, 0); assert.deepEqual(await service.execute(actor, input, '1'.repeat(32)), { deleted: true, id: input.integrationId }); assert.deepEqual(calls, [{ path: '/v2/management/applications/delete', body: { integration_id: input.integrationId } }]); assert.equal(repo.writes.at(-1).values[1], 'b2.application-delete'); });