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, 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 }); } });