merge dc/DC-153 into p7-wave1

This commit is contained in:
Hermes committed 2026-10-03 22:34:32 -07:00
commit a5ef5b345e
6 files changed
+820 -32

No files matched your search

@@ -285,14 +285,176 @@ describe('tailscale provider: revokeDevice()', () => {
});
});
describe('tailscale provider: syncAccess()', () => {
test('throws ProviderError code=not_implemented_in_provider (DC-148 lands later)', async () => {
const p = createTailscaleProvider({ coordClient: makeCoord() });
await expect(p.syncAccess({}, [])).rejects.toMatchObject({
describe('tailscale provider: syncAccess() (DC-153 contract tests)', () => {
const { LockoutError } = require('../src/network/acl-compiler');
const { AclPushError } = require('../src/network/acl-push');
/** aclSync engine mock factory (src/network/acl-sync.js surface). */
function makeAclSync(overrides = {}) {
return {
compile: jest.fn(async () => ({
policy: { acls: [] },
hash: 'sha256:abc',
usersAffected: 2,
})),
preview: jest.fn(async () => ({ feasible: true, errors: [] })),
push: jest.fn(async () => ({ pushed: true, hash: 'sha256:abc' })),
getState: jest.fn(() => null),
...overrides,
};
}
const input = () => ({
accessMap: { grants: [{ principal: { type: 'person', id: 'p1' }, resource: 'dashcaddy', allowed: true }] },
people: [
{ id: 'p1', providerUserId: '1001', groups: ['Admin'], status: 'active' },
{ id: 'p2', providerUserId: '2002', groups: [], status: 'active' },
],
resources: [{ name: 'dashcaddy', host: 'dns2.tail.ts.net', ports: ['*'] }],
hostDeviceId: 'dev-host',
});
test('happy path: compiles → previews → pushes, returns {pushed, hash, usersAffected}', async () => {
const aclSync = makeAclSync();
const p = createTailscaleProvider({ coordClient: makeCoord(), aclSync });
const res = await p.syncAccess(input());
expect(res).toEqual({ pushed: true, hash: 'sha256:abc', usersAffected: 2 });
// Compile receives the caller shapes + the derived guard inputs.
expect(aclSync.compile).toHaveBeenCalledWith(
expect.objectContaining({
accessMap: input().accessMap,
people: expect.any(Array),
resources: expect.any(Array),
hostDeviceId: 'dev-host',
adminUserIds: ['1001'], // derived from the active Admin-group person
hostResource: { host: 'dns2.tail.ts.net', ports: ['*'] },
})
);
// Preview runs on the compiled policy, BEFORE the push.
expect(aclSync.preview).toHaveBeenCalledTimes(1);
expect(aclSync.preview).toHaveBeenCalledWith({ acls: [] });
expect(aclSync.push).toHaveBeenCalledWith({ acls: [] });
});
test('LockoutError from compile → ProviderError lockout_guard, nothing previewed or pushed', async () => {
const aclSync = makeAclSync({
compile: jest.fn(() => {
throw new LockoutError('every active admin (1001) would be denied the host resource');
}),
});
const p = createTailscaleProvider({ coordClient: makeCoord(), aclSync });
await expect(p.syncAccess(input())).rejects.toMatchObject({
name: 'ProviderError',
code: 'not_implemented_in_provider',
code: 'lockout_guard',
retryable: false,
});
expect(aclSync.preview).not.toHaveBeenCalled();
expect(aclSync.push).not.toHaveBeenCalled();
});
test('preview errors[] → ProviderError acl_preview_failed, NOTHING pushed', async () => {
const aclSync = makeAclSync({
preview: jest.fn(() => Promise.reject(new AclPushError('ACL preview reported errors', {
code: 'acl_rejected',
cause: ['bad dst'],
}))),
});
const p = createTailscaleProvider({ coordClient: makeCoord(), aclSync });
await expect(p.syncAccess(input())).rejects.toMatchObject({
name: 'ProviderError',
code: 'acl_preview_failed',
retryable: false,
});
expect(aclSync.push).not.toHaveBeenCalled();
});
test('push API failure (acl_rejected) → ProviderError bad_input, mapped not leaked', async () => {
const aclSync = makeAclSync({
push: jest.fn(() => Promise.reject(new AclPushError('POST acl returned 400', {
code: 'acl_rejected',
}))),
});
const p = createTailscaleProvider({ coordClient: makeCoord(), aclSync });
await expect(p.syncAccess(input())).rejects.toMatchObject({
name: 'ProviderError',
code: 'bad_input',
});
});
test('explicit adminUserIds/hostResource pass through verbatim', async () => {
const aclSync = makeAclSync();
const p = createTailscaleProvider({ coordClient: makeCoord(), aclSync });
await p.syncAccess({
...input(),
adminUserIds: ['9999'],
hostResource: { host: 'other-host', ports: ['22'] },
});
expect(aclSync.compile).toHaveBeenCalledWith(
expect.objectContaining({ adminUserIds: ['9999'], hostResource: { host: 'other-host', ports: ['22'] } })
);
});
describe('default construction (dep OMITTED — real acl-compiler + acl-push wiring)', () => {
const fsReal = require('fs');
const os = require('os');
const pathMod = require('path');
let stateDir;
beforeAll(() => {
stateDir = fsReal.mkdtempSync(pathMod.join(os.tmpdir(), 'dc-ts-syncaccess-'));
global.__DC_ACL_STATE_DIR__ = stateDir; // acl-push state file location
});
afterAll(() => {
delete global.__DC_ACL_STATE_DIR__;
fsReal.rmSync(stateDir, { recursive: true, force: true });
});
test('coord mock: ACL preview + push POST bodies contain per-user srcs', async () => {
const request = jest.fn(async (method, apiPath) => {
if (apiPath === '/tailnet/-/acl/preview') return { feasible: true, errors: [] };
if (apiPath === '/tailnet/-/acl') return {};
throw new Error('unexpected ' + method + ' ' + apiPath);
});
const coord = makeCoord({ request });
const p = createTailscaleProvider({ coordClient: coord }); // aclSync OMITTED
const res = await p.syncAccess(input());
expect(res.pushed).toBe(true);
expect(res.hash).toMatch(/^sha256:[0-9a-f]{64}$/);
expect(res.usersAffected).toBe(1); // user 1001 only (host device excluded)
const previewCall = request.mock.calls.find((c) => c[1] === '/tailnet/-/acl/preview');
const pushCall = request.mock.calls.find((c) => c[1] === '/tailnet/-/acl');
expect(previewCall).toBeTruthy();
expect(pushCall).toBeTruthy();
// preview BEFORE push, both carrying the compiled policy
expect(request.mock.calls.indexOf(previewCall)).toBeLessThan(request.mock.calls.indexOf(pushCall));
for (const call of [previewCall, pushCall]) {
const acls = call[2].body.acls;
// per-user src (never a group), dst host:port per resource grant
expect(acls).toContainEqual({
action: 'accept',
src: ['1001'],
dst: ['dns2.tail.ts.net:*'],
proto: ['tcp', 'udp'],
});
// host device egress rule
expect(acls).toContainEqual({
action: 'accept',
src: ['dev-host'],
dst: ['*:*'],
proto: ['tcp', 'udp'],
});
}
});
test('no coord client attached → not_configured (never builds a dead engine)', async () => {
const p = createTailscaleProvider(); // no coordClient, no aclSync
await expect(p.syncAccess(input())).rejects.toMatchObject({
name: 'ProviderError',
code: 'not_configured',
});
});
});
});
@@ -531,16 +531,224 @@ describe('wireguard provider: invites (spec §8.5)', () => {
});
});
describe('wireguard provider: unsupported / not-implemented surface', () => {
test('syncAccess → not_implemented (DC-151 injects the firewall compiler)', async () => {
const { provider } = makeProvider();
await expect(provider.syncAccess()).rejects.toMatchObject({
name: 'ProviderError',
code: 'not_implemented',
retryable: false,
});
describe('wireguard provider: syncAccess() (DC-153 contract tests)', () => {
const {
FirewallCheckError,
FirewallApplyError,
FirewallVerifyError,
} = require('../src/network/wg-firewall');
/** firewall engine mock factory (applier surface). */
function makeFirewall(overrides = {}) {
return {
apply: jest.fn(async () => ({
applied: true,
verified: true,
tempPath: '/tmp/x.nft',
rollbackFile: '/tmp/rb.nft',
previousExisted: false,
})),
rollback: jest.fn(async () => ({ applied: true, rollbackFile: '/tmp/rb.nft' })),
...overrides,
};
}
const input = () => ({
accessMap: { grants: [{ principal: { type: 'person', id: 'p1' }, resource: 'plex', allowed: true }] },
people: [
{ id: 'p1', groups: ['Admin'], status: 'active' },
{ id: 'p2', groups: [], status: 'active' },
],
resources: { plex: { ip: '10.53.0.1', port: 32400 } },
peerAddresses: { 'p1/d1': '10.53.0.2', 'p2/d2': '10.53.0.3' },
adminPeers: ['p1'],
});
function makeProviderWithFirewall(firewall) {
const fs = makeFs();
const exec = makeExec();
const provider = createWireGuardProvider({
execFileImpl: exec,
fsImpl: fs,
dataDir: '/data',
confPath: '/wg/dcnet0.conf',
unitPath: '/sys/dcnet-hub.service',
getuid: () => 0,
now: () => 1700000000000,
firewall,
});
return { provider, fs, exec };
}
test('happy path: applies the compiled ruleset, returns {applied, resourcesAffected}', async () => {
const firewall = makeFirewall();
const { provider } = makeProviderWithFirewall(firewall);
const res = await provider.syncAccess(input());
expect(res).toEqual({ applied: true, resourcesAffected: 1 });
expect(firewall.apply).toHaveBeenCalledTimes(1);
const ruleset = firewall.apply.mock.calls[0][0];
// The ruleset is the REAL compiler output for these shapes: admin set
// scoped to p1's peer IP, plex resource set with p1 (allowed) but not p2.
expect(ruleset).toContain('set net_dc_admins');
expect(ruleset).toContain('elements = { 10.53.0.2 }');
expect(ruleset).toContain('set net_dc_res_plex');
expect(ruleset).toContain('10.53.0.2'); // p1 in the plex resource set
expect(ruleset).not.toContain('10.53.0.3'); // p2 (no grant) in NO set
});
test('adminPeers defaults to active Admin-group people when omitted', async () => {
const firewall = makeFirewall();
const { provider } = makeProviderWithFirewall(firewall);
const { adminPeers: _omit, ...withoutAdminPeers } = input();
await provider.syncAccess(withoutAdminPeers);
const ruleset = firewall.apply.mock.calls[0][0];
expect(ruleset).toContain('elements = { 10.53.0.2 }'); // p1 = Admin group
});
test('admin lockout at compile (no active admin peer IPs) → ProviderError lockout_guard, nothing applied', async () => {
const firewall = makeFirewall();
const { provider } = makeProviderWithFirewall(firewall);
await expect(
provider.syncAccess({ ...input(), peerAddresses: {} })
).rejects.toMatchObject({
name: 'ProviderError',
code: 'lockout_guard',
retryable: false,
});
expect(firewall.apply).not.toHaveBeenCalled();
});
test('FirewallCheckError → ProviderError firewall_check_failed, .detail carries stderr + applied:false', async () => {
const firewall = makeFirewall({
apply: jest.fn(() => Promise.reject(
new FirewallCheckError('nft -c rejected ruleset (syntax)', { stderr: 'syntax error' })
)),
});
const { provider } = makeProviderWithFirewall(firewall);
const err = await provider.syncAccess(input()).catch((e) => e);
expect(err).toMatchObject({
name: 'ProviderError',
code: 'firewall_check_failed',
retryable: false,
});
expect(err.detail).toEqual({ stderr: 'syntax error', applied: false });
});
test('FirewallApplyError → ProviderError firewall_apply_failed, .detail records NOT partially applied', async () => {
const firewall = makeFirewall({
apply: jest.fn(() => Promise.reject(
new FirewallApplyError('nft -f apply failed (op not permitted)', { stderr: 'op not permitted' })
)),
});
const { provider } = makeProviderWithFirewall(firewall);
const err = await provider.syncAccess(input()).catch((e) => e);
expect(err).toMatchObject({ name: 'ProviderError', code: 'firewall_apply_failed' });
expect(err.detail).toEqual({ stderr: 'op not permitted', applied: false, rolledBack: false });
});
test('FirewallVerifyError → ProviderError firewall_verify_failed, .detail preserves rolledBack info', async () => {
const firewall = makeFirewall({
apply: jest.fn(() => Promise.reject(
new FirewallVerifyError('post-apply verify failed (missing table); rollback succeeded', {
stderr: 'missing table',
rolledBack: true,
})
)),
});
const { provider } = makeProviderWithFirewall(firewall);
const err = await provider.syncAccess(input()).catch((e) => e);
expect(err).toMatchObject({ name: 'ProviderError', code: 'firewall_verify_failed' });
expect(err.detail).toEqual({ stderr: 'missing table', applied: true, rolledBack: true });
});
describe('default construction (dep OMITTED — real wg-firewall applier wiring)', () => {
/**
* exec stub: default WG behavior PLUS `nft` (check/apply ok, list table
* returns the dcnet table text so verify passes). Records every call.
*/
function makeExecWithNft() {
const base = makeExec();
const calls = [];
const fn = async (bin, args, opts = {}) => {
calls.push({ bin, args, opts });
if (bin === 'nft') {
if (args[0] === '-c') return { stdout: '', stderr: '' };
if (args[0] === '-f') return { stdout: '', stderr: '' };
if (args[0] === 'list') return { stdout: 'table inet dcnet {\n}\n', stderr: '' };
}
return base(bin, args, opts);
};
fn.calls = calls;
return fn;
}
test('execFile mock receives nft -c -f THEN nft -f (transactional order)', async () => {
const exec = makeExecWithNft();
const fs = makeFs();
const provider = createWireGuardProvider({
execFileImpl: exec,
fsImpl: fs,
dataDir: '/data',
confPath: '/wg/dcnet0.conf',
unitPath: '/sys/dcnet-hub.service',
getuid: () => 0,
now: () => 1700000000000,
// firewall dep OMITTED — default createWgFirewallApplier(execFileImpl)
});
const res = await provider.syncAccess(input());
expect(res).toEqual({ applied: true, resourcesAffected: 1 });
const nftCalls = exec.calls.filter((c) => c.bin === 'nft');
expect(nftCalls.length).toBeGreaterThanOrEqual(4);
// Sequence: `nft -c -f` (check) → `nft list table` (capture previous)
// → `nft -f` (apply) → `nft list table` (verify), strictly in order.
const checkCall = nftCalls.find((c) => c.args[0] === '-c');
const applyCall = nftCalls.find((c) => c.args[0] === '-f');
const listCalls = nftCalls.filter((c) => c.args[0] === 'list');
expect(checkCall).toBeTruthy();
expect(applyCall).toBeTruthy();
expect(listCalls.length).toBeGreaterThanOrEqual(2);
expect(nftCalls.indexOf(checkCall)).toBeLessThan(nftCalls.indexOf(applyCall));
expect(listCalls[0].args).toEqual(['list', 'table', 'inet', 'dcnet']);
// The checked file and the applied file are the same temp ruleset.
expect(applyCall.args[1]).toBe(checkCall.args[2]);
// The applied ruleset text is the REAL compiler output.
const appliedText = fs.readFileSync(applyCall.args[1], 'utf8');
expect(appliedText).toContain('set net_dc_admins');
expect(appliedText).toContain('elements = { 10.53.0.2 }');
});
test('default applier: nft -c failure → firewall_check_failed with stderr detail, no apply', async () => {
const base = makeExec();
const calls = [];
const exec = async (bin, args, opts = {}) => {
calls.push({ bin, args, opts });
if (bin === 'nft' && args[0] === '-c') {
const e = new Error('nft: syntax error');
e.stderr = 'nft: syntax error near line 4';
throw e;
}
return base(bin, args, opts);
};
const provider = createWireGuardProvider({
execFileImpl: exec,
fsImpl: makeFs(),
dataDir: '/data',
confPath: '/wg/dcnet0.conf',
unitPath: '/sys/dcnet-hub.service',
getuid: () => 0,
now: () => 1700000000000,
});
const err = await provider.syncAccess(input()).catch((e) => e);
expect(err).toMatchObject({ name: 'ProviderError', code: 'firewall_check_failed' });
expect(err.detail).toMatchObject({ stderr: 'nft: syntax error near line 4', applied: false });
// check failed ⇒ `nft -f` apply NEVER ran
expect(calls.filter((c) => c.bin === 'nft' && c.args[0] === '-f')).toHaveLength(0);
});
});
});
describe('wireguard provider: unsupported / not-implemented surface', () => {
test('configureDns → unsupported (splitDnsApi capability false)', async () => {
const { provider } = makeProvider();
await expect(provider.configureDns({ zone: 'z', server: 's' })).rejects.toMatchObject({
@@ -0,0 +1,80 @@
/**
* DC-153 syncAccess contract suite — exercises the src/network/acl-sync.js
* adapter (the injectable Tailscale enforcement engine) directly, plus the
* cross-provider guarantees the judge gate asked for: shapes pass through,
* error classes map to ProviderError codes, success shapes hold, and the
* DEFAULT construction paths run the real DC-148/DC-151 engines against
* injected coord/exec mocks.
*
* Provider-level behavior tests live in network-provider-{tailscale,wireguard}.test.js.
*/
'use strict';
const { createAclSync } = require('../src/network/acl-sync');
const { compileAndValidate, LockoutError } = require('../src/network/acl-compiler');
const { AclPushError } = require('../src/network/acl-push');
function tsInput() {
return {
accessMap: { grants: [{ principal: { type: 'person', id: 'p1' }, resource: 'app', allowed: true }] },
people: [{ id: 'p1', providerUserId: '1001', groups: ['Admin'], status: 'active' }],
resources: [{ name: 'app', host: 'host.ts.net', ports: ['*'] }],
hostDeviceId: 'dev-host',
adminUserIds: ['1001'],
hostResource: { host: 'host.ts.net', ports: ['*'] },
};
}
describe('acl-sync adapter (createAclSync)', () => {
test('compile: runs the real compileAndValidate, returns policy + hash + usersAffected', async () => {
const sync = createAclSync({ pusher: {} }); // compile path needs no pusher
const out = await sync.compile(tsInput());
expect(out.hash).toMatch(/^sha256:[0-9a-f]{64}$/);
expect(out.usersAffected).toBe(1); // 1001 only; host device excluded
// same policy the raw engine produces
expect(out.policy).toEqual(compileAndValidate(tsInput()).policy);
});
test('compile: LockoutError propagates untouched (no admin ids)', async () => {
const sync = createAclSync({ pusher: {} });
const bad = { ...tsInput(), adminUserIds: [] };
await expect(sync.compile(bad)).rejects.toBeInstanceOf(LockoutError);
});
test('preview/push delegate to the pusher; getState to getLastKnownGood', async () => {
const pusher = {
previewPolicy: jest.fn(async () => ({ feasible: true, errors: [] })),
pushPolicy: jest.fn(async () => ({ pushed: true, hash: 'sha256:x' })),
getLastKnownGood: jest.fn(() => ({ hash: 'sha256:x', policy: { acls: [] } })),
};
const sync = createAclSync({ pusher });
await expect(sync.preview({ acls: [] })).resolves.toEqual({ feasible: true, errors: [] });
await expect(sync.push({ acls: [] })).resolves.toEqual({ pushed: true, hash: 'sha256:x' });
expect(sync.getState()).toMatchObject({ hash: 'sha256:x' });
expect(pusher.previewPolicy).toHaveBeenCalledWith({ acls: [] });
expect(pusher.pushPolicy).toHaveBeenCalledWith({ acls: [] });
});
test('built from a coordClient: preview POSTs to /tailnet/{t}/acl/preview', async () => {
const coord = {
request: jest.fn(async (m, p) => {
if (p === '/tailnet/-/acl/preview') return { feasible: true, errors: [] };
return {};
}),
};
const sync = createAclSync({ coordClient: coord, tailnet: '-' });
await sync.preview({ acls: [] });
expect(coord.request).toHaveBeenCalledWith('POST', '/tailnet/-/acl/preview', {
body: { acls: [] },
});
});
test('pusher errors[] surface as AclPushError (caller must refuse to push)', async () => {
const coord = {
request: jest.fn(async () => ({ feasible: false, errors: ['dst unreachable'] })),
};
const sync = createAclSync({ coordClient: coord });
await expect(sync.preview({ acls: [] })).rejects.toBeInstanceOf(AclPushError);
});
});