Files
ruflo/v3/@claude-flow/cli/__tests__/policy-runtime.test.ts
T
rUvandClaude 1bd734e272 dream(security): #3102 bind ADR-377 caller-identity verification into live authorizeMcpTool chokepoint (evaluated, ACCEPT-with-caveats) (#3103)
* dream(security): #TBD bind ADR-377 caller-identity verification into live authorizeMcpTool chokepoint (evaluated, ACCEPT-with-caveats)

authorizeMcpTool() trusted the plain, unsigned CLAUDE_FLOW_PRINCIPAL_ID env
var as caller identity with zero verification (OWASP ASI07-class gap).
ADR-377 Phase 3 already implemented Ed25519 issueInvocationToken/
verifyInvocationToken but never wired it into a live dispatch path.

Binds the two: DualModeOrchestrator mints a per-worker signed
InvocationToken at spawn (worker-lifetime TTL, wildcard tool scope --
disclosed reduction from the primitive's original per-call design);
authorizeMcpTool verifies it before trusting identity, failing closed on
missing/forged/expired tokens. Off by default (CLAUDE_FLOW_MCP_CALLER_AUTH).

6 new deterministic Vitest scenarios plus an independent adversarial
critique (fresh session, verdict CONFIRMED-SAFE-WITH-CAVEATS) are recorded
in docs/dream-cycle/dream-gist-2026-08-26.md. Darwin skipped (scope
mismatch -- binary crypto gate, no tunable parameter space).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_015bfVASxkNXKpZbMSLhVU1L

* fix(ci): register ADR-377 Phase 3 caller-identity env vars as known escape hatches

CLAUDE_FLOW_MCP_CALLER_PUBKEY and CLAUDE_FLOW_MCP_INVOCATION_TOKEN
(DualModeOrchestrator's per-worker Ed25519 credential pair, read by
resolveMcpCallerIdentity()) weren't registered in
audit-env-var-precedence.mjs's KNOWN_ESCAPE_HATCHES, so the audit flagged
CLAUDE_FLOW_MCP_CALLER_PUBKEY as a real violation (exit 1). Same no-CLI-flag
reasoning as the existing CLAUDE_FLOW_PRINCIPAL_ID entry: these are
credentials minted into a spawned worker's own environment, not a value
any caller should be able to select via a flag.

Verified: audit-env-var-precedence.mjs now exits 0. policy-runtime.test.ts
still 18/18.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01RYP825phHMjPRmmjkcAWpq

* fix(ci): regenerate root package-lock.json for codex's new @claude-flow/security dep

The CI Test Suite job runs plain `npm ci` at repo root (no v3 pnpm
install step), so it resolves workspace deps strictly from
package-lock.json — not from v3/pnpm-lock.yaml, which this PR had
already updated. codex/package.json's new @claude-flow/security
dependency was missing from package-lock.json's codex entry, so CI's
npm ci never linked it and every dual-mode test importing
orchestrator.ts failed with "Cannot find package '@claude-flow/security'".

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01RYP825phHMjPRmmjkcAWpq

* fix(ci): build @claude-flow/security before Test Suite runs it

Complements d492ea835 (codex's package-lock.json entry) rather than
duplicating it: that commit fixed `npm ci` not *linking*
@claude-flow/security for codex at all ("Cannot find package"); this
fixes the fact that even where it IS linked (codex now, @claude-flow/cli
already), nothing builds its dist/ before tests run, so importers hit
ERR_MODULE_NOT_FOUND on dist/index.js instead.

This was already a known, pre-existing gap for @claude-flow/cli:
v3/@claude-flow/cli/__tests__/policy-runtime.test.ts has carried a
scripts/ci-test-baseline.txt entry for exactly this reason since before
this PR existed. dual-mode.test.ts and dual-mode-stdin-2947.test.ts
(added by the caller-identity candidate on this branch) newly trip the
same gap in @claude-flow/codex, confirmed by diffing main's own Test
Suite ratchet failures (3, pre-existing, unrelated oauth/publisher
plugin tests) against this branch's (5: the same 3 plus these 2). Adding
new files to ci-test-baseline.txt to paper over this is explicitly
forbidden by that file's own header ("Never add entries to make a
regression green"), and gutting the tests to avoid the import would
remove real coverage of the orchestrator/security integration point.

Real fix: build @claude-flow/security before "Run all tests", using its
own existing `npm run build` (tsc && verify-oauth-exports.mjs). Verified
locally end-to-end by removing both dist/ and the stale
tsconfig.tsbuildinfo (simulating a fresh CI checkout, since both are
gitignored) -- the build step produces a full dist/, both new codex test
files pass, and (bonus, explicitly allowed by the baseline file's own
"remove entries when fixed" rule) the pre-existing policy-runtime.test.ts
baseline entry is now consistently green too, so it's removed here.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_015bfVASxkNXKpZbMSLhVU1L

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-14 21:05:45 +00:00

381 lines
16 KiB
TypeScript

import { afterEach, describe, expect, it } from 'vitest';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync, realpathSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir, userInfo } from 'node:os';
import { createHash, createHmac } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import {
authorizeMcpTool,
autoMigratePolicyStateIfNeeded,
classifyMcpTool,
evaluatePolicyRequest,
issuePolicyApproval,
loadPolicyState,
setPolicyBudget,
setPolicyMode,
upsertPolicyRule,
verifyPolicyLedger,
} from '../src/services/policy-runtime.js';
import { callMCPTool } from '../src/mcp-client.js';
import {
encodeTokenEnvelope,
generateCallerIdentityKey,
issueInvocationToken,
} from '@claude-flow/security';
const roots: Array<{ root: string; trust: string }> = [];
function project(): string {
const root = mkdtempSync(join(tmpdir(), 'ruflo-policy-runtime-'));
mkdirSync(join(root, '.claude-flow'), { recursive: true });
// policy-runtime derives the trust-anchor id from the CANONICAL root
// (realpathSync), so hash the same thing here — on macOS tmpdir() sits
// behind a symlink, so hashing the raw path pointed this test (and its
// cleanup) at a directory that is never created, leaking real anchors.
const projectId = createHash('sha256').update(realpathSync(root)).digest('hex');
roots.push({
root,
trust: join(userInfo().homedir, '.config', 'ruflo', 'policy-trust', projectId),
});
return root;
}
afterEach(() => {
for (const item of roots.splice(0)) {
rmSync(item.trust, { recursive: true, force: true });
rmSync(item.root, { recursive: true, force: true });
}
delete process.env.CLAUDE_FLOW_POLICY_APPROVERS;
delete process.env.CLAUDE_FLOW_CAPABILITY_ENVELOPE;
delete process.env.CLAUDE_FLOW_MCP_CALLER_AUTH;
delete process.env.CLAUDE_FLOW_PRINCIPAL_ID;
delete process.env.CLAUDE_FLOW_MCP_INVOCATION_TOKEN;
delete process.env.CLAUDE_FLOW_MCP_CALLER_PUBKEY;
});
describe('policy runtime compatibility and transactions', () => {
it('derives security attributes from trusted tool identity', () => {
expect(classifyMcpTool('memory_search')).toMatchObject({
actionType: 'memory.read',
namespaceAccess: 'read',
destructive: false,
});
expect(classifyMcpTool('memory_delete')).toMatchObject({
actionType: 'memory.write',
namespaceAccess: 'write',
destructive: true,
});
expect(classifyMcpTool('policy_rule_upsert')).toMatchObject({
actionType: 'policy.admin.rule_upsert',
destructive: true,
});
});
it('does not exempt policy administration from the MCP chokepoint', async () => {
const root = project();
await autoMigratePolicyStateIfNeeded(root);
await setPolicyMode('enforce', root);
await expect(callMCPTool('policy_rule_upsert', {
rule: { id: 'self-allow', effect: 'allow', actions: ['*'] },
projectRoot: root,
}, {
projectRoot: root,
principalId: 'agent:untrusted',
principalType: 'agent',
})).rejects.toThrow('MCP tool not found');
expect(loadPolicyState(root).rules).toHaveLength(0);
});
it('enforces a spawned worker capability envelope at MCP dispatch', async () => {
const root = project();
await autoMigratePolicyStateIfNeeded(root);
await upsertPolicyRule({ id: 'allow-tools', effect: 'allow', actions: ['mcp.tool.call'] }, root);
await setPolicyMode('enforce', root);
process.env.CLAUDE_FLOW_CAPABILITY_ENVELOPE = JSON.stringify({
actions: ['*'],
resources: ['*'],
tools: ['*'],
network: false,
destructive: false,
maxConcurrency: 1,
});
await expect(callMCPTool('terminal_execute', {
command: 'echo should-not-run',
}, { projectRoot: root })).rejects.toThrow('network-outside-envelope');
});
it('uses parent policy from an isolated git worktree', async () => {
const root = project();
execFileSync('git', ['init', '-q', root]);
writeFileSync(join(root, 'README.md'), 'policy worktree test\n');
execFileSync('git', ['-C', root, 'add', 'README.md']);
execFileSync('git', [
'-C', root, '-c', 'user.name=Ruflo Test', '-c', 'user.email=test@invalid',
'commit', '-qm', 'initial',
]);
await autoMigratePolicyStateIfNeeded(root);
await upsertPolicyRule({ id: 'allow-tools', effect: 'allow', actions: ['mcp.tool.call'] }, root);
await setPolicyMode('enforce', root);
const worktree = `${root}-worker`;
execFileSync('git', ['-C', root, 'worktree', 'add', '--detach', worktree, 'HEAD']);
const previousCwd = process.cwd();
process.env.CLAUDE_FLOW_CAPABILITY_ENVELOPE = JSON.stringify({
actions: ['*'],
resources: ['*'],
tools: ['*'],
network: false,
destructive: false,
});
try {
process.chdir(worktree);
await expect(callMCPTool('terminal_execute', {
command: 'echo should-not-run',
})).rejects.toThrow('network-outside-envelope');
expect(loadPolicyState(root).receipts).toHaveLength(1);
} finally {
process.chdir(previousCwd);
execFileSync('git', ['-C', root, 'worktree', 'remove', '--force', worktree]);
}
});
it('auto-migrates an existing installation once in legacy mode', async () => {
const root = project();
expect(await autoMigratePolicyStateIfNeeded(root)).toMatchObject({ migrated: true, mode: 'legacy' });
expect(await autoMigratePolicyStateIfNeeded(root)).toMatchObject({ migrated: false, mode: 'legacy' });
expect(loadPolicyState(root).migratedFrom).toContain('pre-ADR-324');
});
it('applies Codex policy mode changes without overwriting later CLI transitions', async () => {
const root = project();
mkdirSync(join(root, '.agents'), { recursive: true });
const config = join(root, '.agents', 'config.toml');
writeFileSync(config, '[policy]\nmode = "observe"\n');
expect(await autoMigratePolicyStateIfNeeded(root)).toMatchObject({ mode: 'observe' });
await setPolicyMode('enforce', root);
expect(await autoMigratePolicyStateIfNeeded(root)).toMatchObject({ mode: 'enforce' });
writeFileSync(config, '[policy]\nmode = "legacy"\n');
expect(await autoMigratePolicyStateIfNeeded(root)).toMatchObject({ mode: 'enforce' });
});
it('fails closed when enforced policy state is modified or removed', async () => {
const root = project();
await autoMigratePolicyStateIfNeeded(root);
await setPolicyMode('enforce', root);
const statePath = join(root, '.claude-flow', 'policy', 'state.json');
expect(existsSync(roots.at(-1)!.trust)).toBe(true);
const original = readFileSync(statePath, 'utf8');
const changed = JSON.parse(original) as { mode: string };
changed.mode = 'legacy';
writeFileSync(statePath, JSON.stringify(changed));
expect(() => loadPolicyState(root)).toThrow('policy-state-authentication-failed');
writeFileSync(statePath, original);
expect(loadPolicyState(root).mode).toBe('enforce');
unlinkSync(statePath);
expect(() => loadPolicyState(root)).toThrow('policy-state-missing-for-anchored-project');
});
it('binds the trust anchor to the canonical project path', async () => {
const root = project();
await autoMigratePolicyStateIfNeeded(root);
await setPolicyMode('enforce', root);
const alias = `${root}-alias`;
symlinkSync(root, alias);
try {
expect(loadPolicyState(alias).mode).toBe('enforce');
} finally {
unlinkSync(alias);
}
});
it('does not treat a local issuer string as authenticated human authority', async () => {
const root = project();
await autoMigratePolicyStateIfNeeded(root);
await expect(issuePolicyApproval({
id: 'forged-local-approval',
principal: 'agent:release',
actions: ['deployment.promote'],
issuedBy: 'user:claimed-admin',
expiresAt: Date.now() + 60_000,
maxUses: 1,
}, root)).rejects.toThrow('untrusted-approval-issuer');
});
it('moves from observation to enforcement without changing rule semantics', async () => {
const root = project();
await autoMigratePolicyStateIfNeeded(root);
await upsertPolicyRule({ id: 'allow-read', effect: 'allow', actions: ['code.read'] }, root);
await setPolicyMode('observe', root);
const writeObserved = await evaluatePolicyRequest({
identity: { id: 'agent-1', type: 'agent' },
action: { type: 'code.write', resource: 'src/a.ts' },
}, root);
expect(writeObserved.outcome).toBe('denied');
expect(writeObserved.enforcedOutcome).toBe('allowed');
await setPolicyMode('enforce', root);
const read = await evaluatePolicyRequest({
identity: { id: 'agent-1', type: 'agent' },
action: { type: 'code.read', resource: 'src/a.ts' },
}, root);
expect(read.enforcedOutcome).toBe('allowed');
const write = await evaluatePolicyRequest({
identity: { id: 'agent-1', type: 'agent' },
action: { type: 'code.write', resource: 'src/a.ts' },
}, root);
expect(write.enforcedOutcome).toBe('denied');
expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 3 });
});
it('cryptographically binds signed evidence provenance claims', async () => {
const root = project();
await autoMigratePolicyStateIfNeeded(root);
await upsertPolicyRule({
id: 'verified-release',
effect: 'allow',
actions: ['deployment.promote'],
constraints: { requireSignedEvidence: true, requiredProvenance: ['tool_result'] },
}, root);
await setPolicyMode('enforce', root);
const key = 'test-evidence-key-material';
process.env.CLAUDE_FLOW_POLICY_EVIDENCE_KEYS = JSON.stringify({ ci: key });
const evidence = {
id: 'evidence-1',
provenance: 'tool_result' as const,
attestor: 'ci',
observedAt: 100,
contentHash: `sha256:${'a'.repeat(64)}`,
keyId: 'ci',
};
const claims = JSON.stringify(evidence);
const signature = `hmac-sha256:${createHmac('sha256', key).update(claims).digest('hex')}`;
try {
expect((await evaluatePolicyRequest({
identity: { id: 'agent:release', type: 'agent' },
action: { type: 'deployment.promote' },
context: { evidence: [{ ...evidence, signature }] },
}, root)).enforcedOutcome).toBe('allowed');
expect((await evaluatePolicyRequest({
identity: { id: 'agent:release', type: 'agent' },
action: { type: 'deployment.promote' },
context: {
evidence: [{ ...evidence, provenance: 'user_claim', signature }],
},
}, root)).enforcedOutcome).toBe('denied');
} finally {
delete process.env.CLAUDE_FLOW_POLICY_EVIDENCE_KEYS;
}
});
it('serializes concurrent decisions into one valid receipt chain', async () => {
const root = project();
await autoMigratePolicyStateIfNeeded(root);
await Promise.all(Array.from({ length: 20 }, (_, index) => evaluatePolicyRequest({
identity: { id: `agent:${index}`, type: 'agent' },
action: { type: 'code.read', resource: `file-${index}` },
}, root)));
expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 20 });
});
it('cannot overspend a budget under concurrent decisions', async () => {
const root = project();
await autoMigratePolicyStateIfNeeded(root);
await upsertPolicyRule({ id: 'allow-model', effect: 'allow', actions: ['model.call'] }, root);
await setPolicyBudget({
id: 'model-window',
principal: 'agent:*',
action: 'model.call',
maxCostUsd: 1,
periodMs: 60_000,
}, root);
await setPolicyMode('enforce', root);
const decisions = await Promise.all(Array.from({ length: 10 }, (_, index) => evaluatePolicyRequest({
identity: { id: `agent:${index}`, type: 'agent' },
action: { type: 'model.call', resource: 'openrouter', costUsd: 0.2 },
}, root)));
expect(decisions.filter((decision) => decision.enforcedOutcome === 'allowed')).toHaveLength(5);
expect(decisions.filter((decision) => decision.enforcedOutcome === 'denied')).toHaveLength(5);
expect(loadPolicyState(root).usage[0]?.costUsd).toBeCloseTo(1);
expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 10 });
});
});
// ADR-377 Phase 3 (dream-cycle candidate, 2026-08-26) — MCP caller-identity
// binding for `authorizeMcpTool`. `CLAUDE_FLOW_MCP_CALLER_AUTH` is off by
// default; scenario 1 below is the "attack succeeds" baseline that exists
// today (and continues to exist when the flag stays off, by design — see
// resolveMcpCallerIdentity's docstring in policy-runtime.ts). Scenarios 2-5
// are the candidate behavior once the flag is enabled.
describe('authorizeMcpTool: caller identity spoofing (ADR-377 Phase 3)', () => {
it('[baseline] caller-auth disabled: an unverified CLAUDE_FLOW_PRINCIPAL_ID is trusted outright', async () => {
const root = project();
process.env.CLAUDE_FLOW_PRINCIPAL_ID = 'agent:victim-worker';
// CLAUDE_FLOW_MCP_CALLER_AUTH intentionally left unset.
await expect(authorizeMcpTool('memory_search', {}, { projectRoot: root })).resolves.toBeDefined();
const receipts = loadPolicyState(root).receipts;
expect(receipts.at(-1)?.payload.request.identity).toEqual({ id: 'agent:victim-worker', type: 'agent' });
});
it('[candidate] caller-auth enabled, no token presented: fails closed', async () => {
const root = project();
process.env.CLAUDE_FLOW_MCP_CALLER_AUTH = 'true';
process.env.CLAUDE_FLOW_PRINCIPAL_ID = 'agent:victim-worker';
// No CLAUDE_FLOW_MCP_INVOCATION_TOKEN / CLAUDE_FLOW_MCP_CALLER_PUBKEY set.
await expect(authorizeMcpTool('memory_search', {}, { projectRoot: root }))
.rejects.toThrow('mcp-caller-auth-enabled-but-no-token');
});
it('[candidate] caller-auth enabled, forged token (wrong signing key): rejected as bad-signature', async () => {
const root = project();
process.env.CLAUDE_FLOW_MCP_CALLER_AUTH = 'true';
process.env.CLAUDE_FLOW_PRINCIPAL_ID = 'agent:victim-worker';
const realKey = generateCallerIdentityKey();
const attackerKey = generateCallerIdentityKey();
// Token signed by attackerKey, but presented alongside realKey's public key
// — the signature will not verify against the presented key.
const token = issueInvocationToken('agent:worker-7', '*', attackerKey);
process.env.CLAUDE_FLOW_MCP_INVOCATION_TOKEN = encodeTokenEnvelope(token);
process.env.CLAUDE_FLOW_MCP_CALLER_PUBKEY = realKey.publicKeyHex;
await expect(authorizeMcpTool('memory_search', {}, { projectRoot: root }))
.rejects.toThrow('mcp-caller-auth-verification-failed:bad-signature');
});
it('[candidate] caller-auth enabled, expired token: rejected as expired', async () => {
const root = project();
process.env.CLAUDE_FLOW_MCP_CALLER_AUTH = 'true';
process.env.CLAUDE_FLOW_PRINCIPAL_ID = 'agent:victim-worker';
const key = generateCallerIdentityKey();
const token = issueInvocationToken('agent:worker-7', '*', key, { ttlMs: -1 });
process.env.CLAUDE_FLOW_MCP_INVOCATION_TOKEN = encodeTokenEnvelope(token);
process.env.CLAUDE_FLOW_MCP_CALLER_PUBKEY = key.publicKeyHex;
await expect(authorizeMcpTool('memory_search', {}, { projectRoot: root }))
.rejects.toThrow('mcp-caller-auth-verification-failed:expired');
});
it('[candidate] caller-auth enabled, legitimate token: succeeds and the verified token wins over a disagreeing env var', async () => {
const root = project();
process.env.CLAUDE_FLOW_MCP_CALLER_AUTH = 'true';
// Deliberately disagrees with the token's callerId, to prove the token
// — not the env var — decides the identity that reaches the policy engine.
process.env.CLAUDE_FLOW_PRINCIPAL_ID = 'agent:victim-worker';
const key = generateCallerIdentityKey();
const token = issueInvocationToken('agent:worker-7', '*', key, { ttlMs: 300_000 });
process.env.CLAUDE_FLOW_MCP_INVOCATION_TOKEN = encodeTokenEnvelope(token);
process.env.CLAUDE_FLOW_MCP_CALLER_PUBKEY = key.publicKeyHex;
await expect(authorizeMcpTool('memory_search', {}, { projectRoot: root })).resolves.toBeDefined();
const receipts = loadPolicyState(root).receipts;
expect(receipts.at(-1)?.payload.request.identity).toEqual({ id: 'agent:worker-7', type: 'agent' });
});
});