23f7624596
ADR-166 MCP Bridge Security Lock / Static-source security lock (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / Compose default binds loopback + Mongo has auth (push) Failing after 2s
CodeQL Advanced / Analyze (rust) (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / plugin-agent-federation bindHost default (push) Failing after 1s
ADR-166 MCP Bridge Security Lock / Runtime behavior — 401 + terminal gate + fail-closed (push) Failing after 4s
business-pods-smoke / smoke (push) Failing after 1s
all-plugins-smoke / smoke-all (push) Failing after 2s
CI/CD Pipeline / Security & Code Quality (push) Failing after 1s
CI/CD Pipeline / Test Suite (ubuntu-latest) (push) Failing after 1s
CI/CD Pipeline / Build & Package (macos-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (ubuntu-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (windows-latest) (push) Has been skipped
CI/CD Pipeline / Documentation & Examples (push) Failing after 1s
Clone Tracker (14-day rolling) / Snapshot clones for ruflo ecosystem (push) Failing after 1s
CodeQL Advanced / Analyze (actions) (push) Failing after 1s
CodeQL Advanced / Analyze (javascript-typescript) (push) Failing after 1s
federation-peer-rust / stable-noop (push) Failing after 1s
metaharness-ci / score (push) Failing after 1s
metaharness-ci / router-compat (push) Failing after 0s
metaharness-ci / similarity-tests (push) Failing after 0s
no-agentbbs-smoke / smoke-without-agentbbs (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (windows-latest) (push) Has been skipped
codex-integration-audit / Codex integration audit (push) Failing after 1s
helpers-manifest-guard / guard (push) Failing after 1s
🔗 Cross-Agent Integration Tests / 🤝 Agent Coordination Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🧠 Memory Sharing Integration (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🛡️ Fault Tolerance Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / ⚡ Performance Integration Tests (push) Has been skipped
metaharness-ci / mcp-scan (push) Failing after 1s
metaharness-ci / eject-dryrun (push) Failing after 1s
metaharness-ci / metaharness-real-data (push) Failing after 0s
no-cli-optdep-bloat-2561 / guard (push) Failing after 1s
no-metaharness-smoke / smoke-without-metaharness (push) Failing after 1s
no-phantom-agentic-flow-subpath / guard (push) Failing after 1s
🔄 Automated Rollback Manager / 🚨 Failure Detection (push) Failing after 1s
V3 CI/CD Pipeline / Plugin hooks smoke / ubuntu-latest / Node 22 (push) Failing after 1s
V3 CI/CD Pipeline / ruflo-graph-intelligence build + test smoke (#2044, ADR-123) (push) Failing after 1s
CVE Audit Gate / Audit root (critical-blocking) (push) Failing after 2s
cost-tracker-smoke / smoke (push) Failing after 3s
oia-audit-weekly / audit (push) Failing after 2s
ruflo-agent-smoke / ruflo-agent structural smoke (push) Failing after 1s
📊 Status Badges Update / 📊 Update Status Badges (push) Failing after 1s
V3 CI/CD Pipeline / Static regression guards (#2267 YAML + (push) Failing after 1s
V3 CI/CD Pipeline / Test V3 Packages (push) Failing after 0s
V3 CI/CD Pipeline / agent_execute provider routing smoke (#2042) (push) Failing after 0s
CVE Audit Gate / Audit v3 (critical-blocking) (push) Failing after 1s
federation-peer-rust / stable-native (push) Failing after 2s
🔗 Cross-Agent Integration Tests / 🚀 Integration Test Setup (push) Failing after 2s
neural-trader-smoke / runtime-smoke (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (macos-latest) (push) Has been skipped
V3 CI/CD Pipeline / Build V3 (ubuntu-latest) (push) Has been skipped
V3 CI/CD Pipeline / Type Check V3 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 24 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 22 (push) Failing after 2s
V3 CI/CD Pipeline / browser rvf create flag smoke (#2015) (push) Failing after 0s
V3 CI/CD Pipeline / Dependency review (#2046) (push) Has been skipped
V3 CI/CD Pipeline / Supply-chain audit (#2046) (push) Failing after 0s
V3 CI/CD Pipeline / witness marker drift smoke (#2021) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader portfolio CG smoke (#2068, ADR-126 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader backtest signing smoke (#2068, ADR-126 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / kg-extract type-import classification smoke (#2049) (push) Failing after 0s
V3 CI/CD Pipeline / witness verify precondition smoke (#1880) (push) Failing after 2s
V3 CI/CD Pipeline / neural-trader pipeline risk-gate smoke (#2068, ADR-126 Phase 5) (push) Failing after 0s
V3 CI/CD Pipeline / neural-trader feature attribution smoke (#2068, ADR-126 Phase 6) (push) Failing after 0s
V3 CI/CD Pipeline / plugin-registry signature verification smoke (#1922, CWE-347) (push) Failing after 4s
V3 CI/CD Pipeline / memory stats legacy-DB smoke (#2120) (push) Failing after 4s
V3 CI/CD Pipeline / github deprecated actions smoke (#2089, ADR-127 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / graph query + pathfinder smoke (ADR-130 P2+P5) (push) Has been skipped
V3 CI/CD Pipeline / graph trajectory hooks smoke (ADR-130 P3) (push) Has been skipped
V3 CI/CD Pipeline / graph plugin adapter smoke (ADR-130 P4) (push) Has been skipped
V3 CI/CD Pipeline / graph benchmark (ADR-130 P6) (push) Has been skipped
V3 CI/CD Pipeline / statusline generator delegation smoke (#2195) (push) Failing after 1s
V3 CI/CD Pipeline / wizard init regression guard (#2206 (push) Failing after 1s
V3 CI/CD Pipeline / memory no-stray-db smoke (ADR-125 P7) (push) Failing after 1s
V3 CI/CD Pipeline / github-safe injection smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github actions pin smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github attribution opt-in smoke (#2089, ADR-127 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / pre-bash hook safety smoke (#2017) (push) Failing after 1s
V3 CI/CD Pipeline / Memory import smoke / ubuntu-latest (push) Failing after 0s
V3 CI/CD Pipeline / MCP protocol smoke / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / ruvllm WASM auto-init smoke (#2086) (push) Failing after 4s
V3 CI/CD Pipeline / MCP paired-tool round-trip smoke (#1889) (push) Failing after 1s
V3 CI/CD Pipeline / Plugin package install-safety (#1902/#1903/#1904) (push) Failing after 1s
V3 CI/CD Pipeline / Tool description discoverability (ADR-112) (push) Failing after 3s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (22) (push) Failing after 1s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (24) (push) Failing after 1s
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Vector-index dimension audit (#1947) (push) Failing after 0s
V3 CI/CD Pipeline / Hook-command install safety (#1921) (push) Failing after 1s
V3 CI/CD Pipeline / ToolOutputGuardrail smoke (ADR-131, (push) Failing after 1s
V3 CI/CD Pipeline / init-bundle invariants smoke (#2095, ADR-128 Phase 5) (push) Failing after 1s
V3 CI/CD Pipeline / wasm provider bridge smoke (ADR-129 P1) (push) Failing after 2s
V3 CI/CD Pipeline / wasm gallery CRUD smoke (ADR-129 P3) (push) Failing after 1s
V3 CI/CD Pipeline / wasm plugin bridge smoke (ADR-129 P4) (push) Failing after 0s
V3 CI/CD Pipeline / wasm compose smoke (ADR-129 P2) (push) Failing after 4s
V3 CI/CD Pipeline / graph schema smoke (ADR-130 P1) (push) Failing after 0s
Validate Marketplace / validate (push) Failing after 1s
🔍 Verification Pipeline / 🚀 Setup Verification (push) Failing after 1s
🔍 Verification Pipeline / 🛡️ Security Verification (push) Has been skipped
🔍 Verification Pipeline / 📝 Code Quality (push) Has been skipped
🔍 Verification Pipeline / 🧪 Test Verification (${{ matrix.os }}, Node ${{ matrix.node }}) (push) Has been skipped
🔍 Verification Pipeline / 🏗️ Build Verification (push) Has been skipped
🔍 Verification Pipeline / 📚 Documentation Verification (push) Has been skipped
CVE Audit Gate / High-severity report (warn only) (push) Has been cancelled
🔄 Automated Rollback Manager / 🔄 Execute Rollback (push) Has been cancelled
🔄 Automated Rollback Manager / ✅ Post-Rollback Verification (push) Has been cancelled
🔄 Automated Rollback Manager / 📊 Rollback Monitoring (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / windows-latest (push) Has been cancelled
🔄 Automated Rollback Manager / ⏳ Manual Rollback Approval (push) Has been cancelled
V3 CI/CD Pipeline / MCP protocol smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Memory import smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / ubuntu-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Publish to npm (alpha) (push) Has been cancelled
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / macos-latest / Node 22 (push) Has been cancelled
V3 CI/CD Pipeline / Plugin hooks smoke / macos-latest / Node 22 (push) Has been cancelled
CI/CD Pipeline / Deploy & Release (push) Has been cancelled
CI/CD Pipeline / CI Status (push) Has been cancelled
🔗 Cross-Agent Integration Tests / 📊 Integration Test Report (push) Has been cancelled
🔄 Automated Rollback Manager / 🔍 Pre-Rollback Validation (push) Has been cancelled
🔍 Verification Pipeline / ⚡ Performance Verification (push) Has been cancelled
🔍 Verification Pipeline / 📊 Verification Report (push) Has been cancelled
434 lines
16 KiB
TypeScript
434 lines
16 KiB
TypeScript
/**
|
|
* RoutingService Tests
|
|
*
|
|
* Tests the real RoutingService from source with real domain entities.
|
|
* Dependencies (generateEnvelopeId, signEnvelope, etc.) are provided as
|
|
* simple inline implementations — no mocks of the class under test.
|
|
*/
|
|
|
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|
import {
|
|
RoutingService,
|
|
type RoutingServiceDeps,
|
|
} from '../../src/domain/services/routing-service.js';
|
|
import {
|
|
FederationEnvelope,
|
|
CONSENSUS_REQUIRED_TYPES,
|
|
type FederationMessageType,
|
|
} from '../../src/domain/entities/federation-envelope.js';
|
|
import { FederationSession } from '../../src/domain/entities/federation-session.js';
|
|
import { TrustLevel } from '../../src/domain/entities/trust-level.js';
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function makeSession(overrides: Partial<{
|
|
sessionId: string;
|
|
localNodeId: string;
|
|
remoteNodeId: string;
|
|
trustLevel: TrustLevel;
|
|
active: boolean;
|
|
expired: boolean;
|
|
sessionToken: string;
|
|
}> = {}): FederationSession {
|
|
const expiresAt = overrides.expired
|
|
? new Date(Date.now() - 1000) // already expired
|
|
: new Date(Date.now() + 3_600_000); // +1 h
|
|
|
|
const session = new FederationSession({
|
|
sessionId: overrides.sessionId ?? 'sess-1',
|
|
localNodeId: overrides.localNodeId ?? 'local',
|
|
remoteNodeId: overrides.remoteNodeId ?? 'remote-1',
|
|
trustLevel: overrides.trustLevel ?? TrustLevel.ATTESTED,
|
|
negotiatedCapabilities: ['send'],
|
|
createdAt: new Date(),
|
|
expiresAt,
|
|
heartbeatInterval: 30_000,
|
|
sessionToken: overrides.sessionToken ?? 'token-1',
|
|
metrics: FederationSession.createMetrics(),
|
|
});
|
|
|
|
if (overrides.active === false) {
|
|
session.terminate();
|
|
}
|
|
|
|
return session;
|
|
}
|
|
|
|
function makeDeps(overrides: Partial<RoutingServiceDeps> = {}): RoutingServiceDeps {
|
|
let counter = 0;
|
|
return {
|
|
generateEnvelopeId: overrides.generateEnvelopeId ?? (() => `env-${counter++}`),
|
|
generateNonce: overrides.generateNonce ?? (() => `nonce-${counter++}`),
|
|
signEnvelope: overrides.signEnvelope ?? ((payload, token) => `hmac-${token}-${payload.length}`),
|
|
verifyEnvelope: overrides.verifyEnvelope ?? ((payload, sig, token) => sig === `hmac-${token}-${payload.length}`),
|
|
scanPii: overrides.scanPii ?? ((text, _trustLevel) => ({
|
|
transformedText: text,
|
|
scanResult: {
|
|
scanned: true,
|
|
piiFound: false,
|
|
detections: [],
|
|
actionsApplied: [],
|
|
scanDurationMs: 0,
|
|
},
|
|
})),
|
|
sendToNode: overrides.sendToNode ?? vi.fn(async () => {}),
|
|
getActiveSessions: overrides.getActiveSessions ?? (() => []),
|
|
getLocalNodeId: overrides.getLocalNodeId ?? (() => 'local'),
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Tests
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('RoutingService', () => {
|
|
let service: RoutingService;
|
|
let deps: RoutingServiceDeps;
|
|
let sessions: FederationSession[];
|
|
|
|
beforeEach(() => {
|
|
sessions = [
|
|
makeSession({ sessionId: 'sess-1', remoteNodeId: 'remote-1', sessionToken: 'token-1' }),
|
|
makeSession({ sessionId: 'sess-2', remoteNodeId: 'remote-2', sessionToken: 'token-2' }),
|
|
makeSession({ sessionId: 'sess-3', remoteNodeId: 'remote-3', sessionToken: 'token-3' }),
|
|
];
|
|
|
|
deps = makeDeps({
|
|
getActiveSessions: () => sessions,
|
|
sendToNode: vi.fn(async () => {}),
|
|
});
|
|
|
|
service = new RoutingService(deps);
|
|
});
|
|
|
|
// -----------------------------------------------------------------------
|
|
// selectMode
|
|
// -----------------------------------------------------------------------
|
|
|
|
describe('selectMode', () => {
|
|
it('should return consensus for trust-change', () => {
|
|
expect(service.selectMode('trust-change')).toBe('consensus');
|
|
});
|
|
|
|
it('should return consensus for topology-change', () => {
|
|
expect(service.selectMode('topology-change')).toBe('consensus');
|
|
});
|
|
|
|
it('should return consensus for agent-spawn', () => {
|
|
expect(service.selectMode('agent-spawn')).toBe('consensus');
|
|
});
|
|
|
|
it('should return broadcast for status-broadcast', () => {
|
|
expect(service.selectMode('status-broadcast')).toBe('broadcast');
|
|
});
|
|
|
|
it('should return direct for other message types', () => {
|
|
const directTypes: FederationMessageType[] = [
|
|
'task-assignment', 'memory-query', 'memory-response',
|
|
'context-share', 'heartbeat',
|
|
];
|
|
for (const t of directTypes) {
|
|
expect(service.selectMode(t)).toBe('direct');
|
|
}
|
|
});
|
|
});
|
|
|
|
// -----------------------------------------------------------------------
|
|
// send
|
|
// -----------------------------------------------------------------------
|
|
|
|
describe('send', () => {
|
|
it('should send successfully for an active, non-expired session', async () => {
|
|
const session = sessions[0];
|
|
const result = await service.send(session, 'task-assignment', { task: 'do-work' });
|
|
|
|
expect(result.success).toBe(true);
|
|
expect(result.mode).toBe('direct');
|
|
expect(result.envelopeId).toBeTruthy();
|
|
expect(result.targetNodeIds).toContain('remote-1');
|
|
expect(deps.sendToNode).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it('should fail when session is inactive', async () => {
|
|
const session = makeSession({ active: false });
|
|
const result = await service.send(session, 'task-assignment', { data: 1 });
|
|
|
|
expect(result.success).toBe(false);
|
|
expect(result.error).toMatch(/not active/i);
|
|
});
|
|
|
|
it('should fail when session is expired', async () => {
|
|
const session = makeSession({ expired: true });
|
|
const result = await service.send(session, 'task-assignment', { data: 1 });
|
|
|
|
expect(result.success).toBe(false);
|
|
expect(result.error).toMatch(/expired/i);
|
|
});
|
|
|
|
it('should block the message when PII scan returns block action', async () => {
|
|
deps = makeDeps({
|
|
getActiveSessions: () => sessions,
|
|
sendToNode: vi.fn(async () => {}),
|
|
scanPii: (_text, _trust) => ({
|
|
transformedText: '',
|
|
scanResult: {
|
|
scanned: true,
|
|
piiFound: true,
|
|
detections: [{ type: 'ssn', action: 'block', confidence: 0.99 }],
|
|
actionsApplied: ['block'],
|
|
scanDurationMs: 1,
|
|
},
|
|
}),
|
|
});
|
|
service = new RoutingService(deps);
|
|
|
|
const session = sessions[0];
|
|
const result = await service.send(session, 'context-share', { ssn: '123-45-6789' });
|
|
|
|
expect(result.success).toBe(false);
|
|
expect(result.error).toMatch(/blocked.*pii/i);
|
|
expect(deps.sendToNode).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('should record messagesSent and piiRedactions on the session metrics', async () => {
|
|
// Use a scanPii that flags PII as found but only redacts (not blocks)
|
|
deps = makeDeps({
|
|
getActiveSessions: () => sessions,
|
|
sendToNode: vi.fn(async () => {}),
|
|
scanPii: (text, _trust) => ({
|
|
transformedText: text.replace(/alice@example\.com/, '[REDACTED]'),
|
|
scanResult: {
|
|
scanned: true,
|
|
piiFound: true,
|
|
detections: [{ type: 'email', action: 'redact', confidence: 0.95 }],
|
|
actionsApplied: ['redact'],
|
|
scanDurationMs: 1,
|
|
},
|
|
}),
|
|
});
|
|
service = new RoutingService(deps);
|
|
|
|
const session = sessions[0];
|
|
expect(session.metrics.messagesSent).toBe(0);
|
|
expect(session.metrics.piiRedactions).toBe(0);
|
|
|
|
await service.send(session, 'context-share', { email: 'alice@example.com' });
|
|
|
|
expect(session.metrics.messagesSent).toBe(1);
|
|
expect(session.metrics.piiRedactions).toBe(1);
|
|
});
|
|
});
|
|
|
|
// -----------------------------------------------------------------------
|
|
// broadcast
|
|
// -----------------------------------------------------------------------
|
|
|
|
describe('broadcast', () => {
|
|
it('should send to all active, non-expired sessions', async () => {
|
|
const results = await service.broadcast('status-broadcast', { status: 'ok' });
|
|
|
|
expect(results).toHaveLength(3);
|
|
expect(results.every(r => r.success)).toBe(true);
|
|
expect(deps.sendToNode).toHaveBeenCalledTimes(3);
|
|
});
|
|
|
|
it('should skip expired sessions', async () => {
|
|
// Replace one session with an expired one
|
|
sessions[2] = makeSession({ sessionId: 'sess-3', remoteNodeId: 'remote-3', expired: true });
|
|
|
|
const results = await service.broadcast('status-broadcast', { status: 'ok' });
|
|
|
|
// Only 2 should succeed; the expired one is filtered out by broadcast
|
|
expect(results).toHaveLength(2);
|
|
expect(results.every(r => r.success)).toBe(true);
|
|
});
|
|
});
|
|
|
|
// -----------------------------------------------------------------------
|
|
// propose
|
|
// -----------------------------------------------------------------------
|
|
|
|
describe('propose', () => {
|
|
it('should create a proposal with correct quorum (default 2/3)', async () => {
|
|
const proposal = await service.propose('trust-change', { newLevel: 3 });
|
|
|
|
expect(proposal.proposalId).toBeTruthy();
|
|
expect(proposal.proposerNodeId).toBe('local');
|
|
expect(proposal.messageType).toBe('trust-change');
|
|
// ceil(3 * 2/3) = 2
|
|
expect(proposal.quorumRequired).toBe(2);
|
|
expect(proposal.votes.size).toBe(0);
|
|
});
|
|
|
|
it('should broadcast the proposal to all active sessions', async () => {
|
|
await service.propose('topology-change', { nodes: ['a'] });
|
|
|
|
// broadcast sends to 3 sessions
|
|
expect(deps.sendToNode).toHaveBeenCalledTimes(3);
|
|
});
|
|
|
|
it('should respect custom quorumFraction', async () => {
|
|
const proposal = await service.propose('agent-spawn', { agent: 'x' }, 0.5);
|
|
|
|
// ceil(3 * 0.5) = 2
|
|
expect(proposal.quorumRequired).toBe(2);
|
|
});
|
|
});
|
|
|
|
// -----------------------------------------------------------------------
|
|
// recordVote
|
|
// -----------------------------------------------------------------------
|
|
|
|
describe('recordVote', () => {
|
|
it('should record a valid vote and return true', async () => {
|
|
const proposal = await service.propose('trust-change', { level: 3 });
|
|
const ok = service.recordVote(proposal.proposalId, 'remote-1', true);
|
|
expect(ok).toBe(true);
|
|
expect(proposal.votes.get('remote-1')).toBe(true);
|
|
});
|
|
|
|
it('should return false for an unknown proposal', () => {
|
|
const ok = service.recordVote('nonexistent', 'node-1', true);
|
|
expect(ok).toBe(false);
|
|
});
|
|
|
|
it('should return false for an expired proposal', async () => {
|
|
const proposal = await service.propose('trust-change', { level: 3 });
|
|
|
|
// Force the proposal to be expired by mutating expiresAt
|
|
// ConsensusProposal uses readonly but the Map holds the reference
|
|
(proposal as { expiresAt: Date }).expiresAt = new Date(Date.now() - 1000);
|
|
|
|
const ok = service.recordVote(proposal.proposalId, 'remote-1', true);
|
|
expect(ok).toBe(false);
|
|
});
|
|
});
|
|
|
|
// -----------------------------------------------------------------------
|
|
// isConsensusReached
|
|
// -----------------------------------------------------------------------
|
|
|
|
describe('isConsensusReached', () => {
|
|
it('should report reached + approved when quorum met', async () => {
|
|
const proposal = await service.propose('trust-change', { level: 3 });
|
|
// quorumRequired = 2 (ceil(3 * 2/3))
|
|
service.recordVote(proposal.proposalId, 'remote-1', true);
|
|
service.recordVote(proposal.proposalId, 'remote-2', true);
|
|
|
|
const status = service.isConsensusReached(proposal.proposalId);
|
|
expect(status.reached).toBe(true);
|
|
expect(status.approved).toBe(true);
|
|
});
|
|
|
|
it('should report early rejection when too many votes against', async () => {
|
|
const proposal = await service.propose('trust-change', { level: 3 });
|
|
// quorumRequired = 2, totalVoters = 3
|
|
// rejections > totalVoters - quorumRequired => rejections > 1 => need 2 rejections
|
|
service.recordVote(proposal.proposalId, 'remote-1', false);
|
|
service.recordVote(proposal.proposalId, 'remote-2', false);
|
|
|
|
const status = service.isConsensusReached(proposal.proposalId);
|
|
expect(status.reached).toBe(true);
|
|
expect(status.approved).toBe(false);
|
|
});
|
|
|
|
it('should report not yet reached when votes are insufficient', async () => {
|
|
const proposal = await service.propose('trust-change', { level: 3 });
|
|
service.recordVote(proposal.proposalId, 'remote-1', true);
|
|
|
|
const status = service.isConsensusReached(proposal.proposalId);
|
|
expect(status.reached).toBe(false);
|
|
expect(status.approved).toBe(false);
|
|
});
|
|
|
|
it('should return reached=false for unknown proposal', () => {
|
|
const status = service.isConsensusReached('nonexistent');
|
|
expect(status.reached).toBe(false);
|
|
expect(status.approved).toBe(false);
|
|
});
|
|
});
|
|
|
|
// -----------------------------------------------------------------------
|
|
// verifyInboundEnvelope
|
|
// -----------------------------------------------------------------------
|
|
|
|
describe('verifyInboundEnvelope', () => {
|
|
it('should return true for a correctly signed envelope', () => {
|
|
const envelope = new FederationEnvelope({
|
|
envelopeId: 'env-100',
|
|
sourceNodeId: 'remote-1',
|
|
targetNodeId: 'local',
|
|
sessionId: 'sess-1',
|
|
messageType: 'task-assignment',
|
|
payload: { task: 'test' },
|
|
timestamp: new Date(),
|
|
nonce: 'nonce-100',
|
|
hmacSignature: '', // will be computed below
|
|
piiScanResult: FederationEnvelope.emptyScanResult(),
|
|
});
|
|
|
|
// The deps.signEnvelope produces `hmac-<token>-<payload.length>`
|
|
const signablePayload = envelope.toSignablePayload();
|
|
const validSig = `hmac-token-1-${signablePayload.length}`;
|
|
|
|
// Re-create envelope with correct signature
|
|
const signed = new FederationEnvelope({
|
|
...envelope,
|
|
hmacSignature: validSig,
|
|
piiScanResult: FederationEnvelope.emptyScanResult(),
|
|
});
|
|
|
|
expect(service.verifyInboundEnvelope(signed, 'token-1')).toBe(true);
|
|
});
|
|
|
|
it('should return false for a tampered envelope', () => {
|
|
const envelope = new FederationEnvelope({
|
|
envelopeId: 'env-200',
|
|
sourceNodeId: 'remote-1',
|
|
targetNodeId: 'local',
|
|
sessionId: 'sess-1',
|
|
messageType: 'task-assignment',
|
|
payload: { task: 'test' },
|
|
timestamp: new Date(),
|
|
nonce: 'nonce-200',
|
|
hmacSignature: 'bad-signature',
|
|
piiScanResult: FederationEnvelope.emptyScanResult(),
|
|
});
|
|
|
|
expect(service.verifyInboundEnvelope(envelope, 'token-1')).toBe(false);
|
|
});
|
|
});
|
|
|
|
// -----------------------------------------------------------------------
|
|
// cleanExpiredProposals
|
|
// -----------------------------------------------------------------------
|
|
|
|
describe('cleanExpiredProposals', () => {
|
|
it('should remove proposals that have expired', async () => {
|
|
const proposal = await service.propose('trust-change', { level: 3 });
|
|
|
|
// Force expiry
|
|
(proposal as { expiresAt: Date }).expiresAt = new Date(Date.now() - 1000);
|
|
|
|
service.cleanExpiredProposals();
|
|
|
|
// After cleanup, the proposal should be gone
|
|
const status = service.isConsensusReached(proposal.proposalId);
|
|
expect(status.reached).toBe(false);
|
|
expect(status.approved).toBe(false);
|
|
});
|
|
|
|
it('should keep proposals that have not expired', async () => {
|
|
const proposal = await service.propose('trust-change', { level: 3 });
|
|
|
|
service.cleanExpiredProposals();
|
|
|
|
// Still accessible
|
|
const ok = service.recordVote(proposal.proposalId, 'remote-1', true);
|
|
expect(ok).toBe(true);
|
|
});
|
|
});
|
|
});
|