diff --git a/README.md b/README.md index 5d1deec..9d72140 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ npm run cleanroom -- validate examples/clean-room/calculator.spec.json # See docs/clean-room/README.md for the separate-room approval and scaffold commands. ``` -**Optional offline Room B execution:** `sandbox-test` revalidates a separately pinned reviewer, public key and immutable Docker image, stages only three allowlisted files, and runs independent compatibility tests in a constrained local Docker container. This constrains evaluation, not the authoring agent or upstream source access. See the [isolated runner guide](docs/clean-room/README.md#optional-room-b-isolated-evaluation). +**Optional offline Room B execution:** `sandbox-test` revalidates the signed contract and independently pinned policy, stages only three allowlisted files, and runs each approved vector in a separate subprocess inside a restricted local Docker container. It requires complete vector accounting, and can produce a separately signed worker evidence report. This constrains evaluation, not the authoring agent or upstream source access. See the [isolated runner guide](docs/clean-room/README.md#optional-room-b-isolated-evaluation) and [ADR 142](docs/adr/ADR-142-vector-evidence-attestation.md). **Important boundary:** The CLI does not provision independent OS identities, prevent covert data encoded inside permitted scalars, attest a human reviewer, establish a license exception, or prove functional equivalence. Independent source access isolation, human evidence review, and legal authorization are required before describing a deployment as clean room. diff --git a/docs/adr/ADR-141-room-b-isolated-evaluation.md b/docs/adr/ADR-141-room-b-isolated-evaluation.md index 2c61386..4fa6c35 100644 --- a/docs/adr/ADR-141-room-b-isolated-evaluation.md +++ b/docs/adr/ADR-141-room-b-isolated-evaluation.md @@ -16,8 +16,8 @@ Add an **optional Linux-only Room B evaluation command** which fails closed unle 1. A versioned Room B trust policy independently pins an Ed25519 SPKI fingerprint, signed reviewer, target, immutable container image digest, maximum approval age and expiry time. 2. The signed handoff is verified again against the trusted public key and matching policy before touching any implementation or creating any worker directory. -3. Room B's project contains **exactly four expected scaffold files**. The approved contract, compatibility runner and approval summary must match the verified scaffold byte for byte. Only \`implementation.mjs\` may change. Symlinks, hardlinks, extra files, changed tests, changed contracts and size violations fail. -4. A temporary staging directory contains exactly \`contract.json\`, \`compat.test.mjs\` and \`implementation.mjs\`. The original project directory, signed artifact, public key, reviewer receipt, Room A sources, logs and credentials are **not mounted** in the container. +3. Room B's project contains **exactly four expected scaffold files**. The approved contract, compatibility runner and approval summary must match the verified scaffold byte for byte. Only `implementation.mjs` may change. Symlinks, hardlinks, extra files, changed tests, changed contracts and size violations fail. +4. A temporary staging directory contains exactly `contract.json`, `compat.test.mjs` and `implementation.mjs`. The original project directory, signed artifact, public key, reviewer receipt, Room A sources, logs and credentials are **not mounted** in the container. 5. Docker runs on the **local Linux Unix socket** only, with no network, read-only root and input bind, all Linux capabilities dropped, no-new-privileges, UID 65534, 64 PID limit, 256 MiB memory limit, one CPU and a 60-second subprocess deadline. The chosen digest must be already installed. No automatic pull is permitted at evaluation time. 6. The test runner executes only the independent implementation against the signed, allowlisted compatibility vectors. CLI writes a small JSON report outside the implementation tree with approval/spec digests, public-key fingerprint, implementation hash, runtime digest, vector count, outcome and hashes of captured stdout/stderr, without exposing raw logs. 7. Timed-out runs trigger Docker container removal. Cleanup failure is an error, not a successful result. Temporary stage files are removed on completion. @@ -26,7 +26,7 @@ No Docker socket, agent credentials, Room A analysis output, entire repository, ## Data flow -\`\`\`text +```text Room A Room B (separate tenant / VM) original source trusted reviewer key and policy | | @@ -47,7 +47,7 @@ No Docker socket, agent credentials, Room A analysis output, entire repository, | v hashed evaluation report (Room B) -\`\`\` +``` ## Threats and residual risks @@ -57,9 +57,9 @@ No Docker socket, agent credentials, Room A analysis output, entire repository, | Mutated interface contract or test harness | Signature verification and byte-for-byte scaffold regeneration | Legitimate reviewer can approve undesirable data; covert encoding in permitted scalar vectors still possible | | Stolen reviewer key / forged claimed review | Out-of-band fingerprint, target/reviewer allowlist, expiry and age window | No online revocation, hardware-backed custody or proof a human reviewed | | Malicious model-generated code | Offline, read-only, unprivileged container and bounded resources | Docker daemon access is privileged; kernel/container escape, runtime supply-chain compromise and local host compromise remain | -| Docker image substitution | Room B trust policy fixes image by SHA256 digest; \`--pull=never\` | Trusted image acquisition/scan and digest policy governance are external | +| Docker image substitution | Room B trust policy fixes image by SHA256 digest; `--pull=never` | Trusted image acquisition/scan and digest policy governance are external | | Host secrets through mounts | Staged copy is the only bind mount | Full docker daemon control on a host containing Room A data would still be unsafe | -| Report manipulation | Exclusive output with digests and fixed fields | Unsigned local report can be edited later; remote attestation and signed ledger are separate future controls | +| Report manipulation | Exclusive v2 report with optional worker-key Ed25519 attestation (ADR 142) | Unsigned reports remain editable; signatures do not prove a trustworthy host or legal independence | | Unsafe inference that passed fixtures prove equivalence | Report records only vector count and pass/fail | Unseen inputs, stateful protocols, asynchronous behavior and performance are not covered | ## Safety invariants @@ -80,14 +80,18 @@ Unit tests inject a fake Docker client to inspect mount arguments and staged fil Run: -\`\`\`bash +```bash npm run test:cleanroom -\`\`\` +``` -The real Docker test is enabled when \`RUDEVOLUTION_TEST_IMAGE\` references a locally available, pinned image digest. It is intentionally skipped without that environment variable; the CI job supplies it. +The real Docker test is enabled when `RUDEVOLUTION_TEST_IMAGE` references a locally available, pinned image digest. It is intentionally skipped without that environment variable; the CI job supplies it. These checks establish a narrow, reproducible execution boundary **for the evaluation run**, not source independence of the implementer or formal noninterference. Production use still requires a separate Room B OS identity or VM, operator-reviewed legal permissions, image security patching, isolated model context, key lifecycle and an external evidence ledger. ## Rollback -Disable \`sandbox-test\` and revert this runner/CI suite; v1 \`validate\`, \`approve\`, \`verify\` and \`scaffold\` remain unaffected. Revoke any exposed reviewer keys through an external trust policy and prevent reuse of old worker images. +Disable `sandbox-test` and revert this runner/CI suite; v1 `validate`, `approve`, `verify` and `scaffold` remain unaffected. Revoke any exposed reviewer keys through an external trust policy and prevent reuse of old worker images. + +## Security follow-up: vector execution and evidence + +[ADR 142](ADR-142-vector-evidence-attestation.md) supersedes the original exit-code-only evaluation criterion. The hardened runner isolates every approved vector in its own subprocess, verifies the final TAP vector count, and supports optional independent Ed25519 signing of the v2 evaluation report. The implementation author still needs an actually separate Room B context and an independent review of test sufficiency. diff --git a/docs/adr/ADR-142-vector-evidence-attestation.md b/docs/adr/ADR-142-vector-evidence-attestation.md new file mode 100644 index 0000000..66fc4b1 --- /dev/null +++ b/docs/adr/ADR-142-vector-evidence-attestation.md @@ -0,0 +1,57 @@ +# ADR 142: Vector execution accounting and signed Room B evidence + +Status: Accepted for clean room developer preview +Date: 2026-10-08 +Dependencies: ADR 139, ADR 140, ADR 141 + +## Problem and observed failure + +The prior generated `compat.test.mjs` imported `implementation.mjs` before registering the `node:test` vectors. An implementation containing only `process.exit(0)` could cause `node --test` to exit successfully without executing any approved compatibility vector. The v1 Docker evaluator treated exit code zero as success, so a malformed or adversarial Room B implementation could receive a passing report with no test evidence. + +The signed specification handoff was not compromised; the failure was **untrusted implementer code controlling the test-harness lifecycle**. It also demonstrated why an exit code, successful harness startup, or self-reported result is not sufficient provenance. + +The evaluator report also consisted of unsigned JSON. An operator or downstream process could alter counts, implementation digest or outcome without cryptographic detection. + +## Decision + +1. **Isolated vector subprocesses.** The trusted test runner never directly imports independent code. It reads the approved contract, verifies the contract hash, registers one test for each approved vector, then launches an individual short-lived Node subprocess that imports and calls one implementation operation. The untrusted child has a bounded input payload, isolated environment, 2-second timeout and 4 KiB output limit. It must emit exactly one primitive JSON outcome. +2. **Fail closed on premature exit.** `process.exit(0)`, forged TAP output, missing exports, malformed JSON, unexpected output, signals and timeouts cannot short circuit the parent test runner. The parent fails the corresponding vector. +3. **Independent counter verification.** After Docker exits, the host requires a complete Node TAP footer with exact `tests == pass == approved-vector-count`, and `fail == cancelled == skipped == todo == 0`. A zero exit code with absent, duplicate or incomplete counters becomes a failed evaluation. +4. **Versioned report.** `rudevolution.cleanroom.sandbox-report/v2` includes `executedVectors`, `passedVectors`, `policySha256`, and `harnessSha256`. These complement the existing approval, specification, implementation, runtime image and output-log hashes. Old unverified v1 reports are not silently promoted to v2. +5. **Optional worker-signed attestation.** After verified isolated execution and Docker cleanup, a separate Room B private Ed25519 key signs a canonical, domain-separated report commitment. The associated `rudevolution.cleanroom.evaluation-attestation/v1` envelope binds worker ID, signing time, report digest and public-key fingerprint. Independent verification requires an out-of-band trusted worker public key and expected approval digest. +6. **No original-source transfer.** Neither original source, analyst receipts, signer keys nor Room A knowledge are mounted in the isolated test container. The additional signing key resides only on the operator-controlled Room B host. + +## Invariants + +* **CR-10:** Every passing evaluation must have a matching count of actually registered and successful approved vectors. +* **CR-11:** Untrusted implementation code cannot terminate the trusted test parent via `process.exit(0)` in its own evaluation subprocess. +* **CR-12:** Signed evidence rejects modification of measured outcome, vector counts, approved-spec identity, implementation hash, harness hash, policy hash, runtime image and signing metadata. +* **CR-13:** The Room B worker attestation key is distinct from the independent Room A reviewer key, and never crosses the Docker mount boundary. + +## Evidence limits + +* These tests cover declared primitive operations and approved vectors, **not** complete API compatibility. Implementations can hardcode public vectors and still pass. +* The child subprocess shares the container's PID/user isolation domain. A malicious implementation may send signals to sibling processes. The report requires a trusted vector footer to pass, but this is not equivalent to process isolation across users, virtual machines or TEE attestation. +* Every vector starts a fresh child process, so the harness does not model cross-call state, session semantics, persistent storage, concurrency or performance. +* An Ed25519 evidence signature authenticates the signing key and the stated report bytes, not the honesty or integrity of the host evaluator. Host compromise or misuse of the worker signing key can yield a signed false claim. +* The initial protocol accepts only small primitive vectors. The signed contract can still carry covertly encoded information, so human review, DLP and legal authorization remain mandatory. +* Existing Room B scaffold test runners must be regenerated from an already approved artifact before the v2 evaluator can accept them. Only independently authored implementation code should be retained. + +## Tests and promotion gate + +From a clean checkout: + +```bash +npm run test:cleanroom +npm test +``` + +The suite includes negative tests for premature exit, forged TAP, incomplete reports, modified signatures, forged worker identifiers, changed implementation hashes and wrong signing keys. The dedicated CI job runs an actual Docker implementation and checks the v2 counts and host signature. Local runs without a pinned Docker image intentionally skip the container smoke test. + +### Acceptance + +A synthetic `process.exit(0)` implementation must fail with zero verified vectors, while an independently supplied synthetic implementation passes all approved vectors. A modified signed outcome must fail independent worker-key verification. Node 22/24, Rust, dashboard and the Docker worker must pass CI before merge. + +### Rollback + +If optional evidence signing fails, disable only the signing mode while preserving the v2 subprocess harness and vector-accounting gate. **Do not revert to pre-v2 direct implementation import or exit-code-only pass criteria.** Revoke an exposed worker key through the organization's external trust system. diff --git a/docs/clean-room/README.md b/docs/clean-room/README.md index 0bf0e38..0aa5a6e 100644 --- a/docs/clean-room/README.md +++ b/docs/clean-room/README.md @@ -71,13 +71,13 @@ Do not enable LLM agent tools that can read Room A knowledge, a shared RuVector ## Optional Room B isolated evaluation -The new \`sandbox-test\` command enforces a narrow **evaluation-time** security boundary on Linux with a local Docker daemon. It does not run source from Room A, reconstruct third-party code, or create a clean room development machine. The independent implementation is still authored outside the test container and must come from a separately controlled Room B workspace. +The new `sandbox-test` command enforces a narrow **evaluation-time** security boundary on Linux with a local Docker daemon. It does not run source from Room A, reconstruct third-party code, or create a clean room development machine. The independent implementation is still authored outside the test container and must come from a separately controlled Room B workspace. -**Prerequisites:** Linux, Docker with local \`/var/run/docker.sock\`, Node.js 22+, a private Room B worker host with no Room A data or credentials, and an **independently trusted** signing key. Access to the Docker daemon is privileged: use an isolated, operator-managed worker, not a general-purpose desktop shared with source analysts. +**Prerequisites:** Linux, Docker with local `/var/run/docker.sock`, Node.js 22+, a private Room B worker host with no Room A data or credentials, and an **independently trusted** signing key. Access to the Docker daemon is privileged: use an isolated, operator-managed worker, not a general-purpose desktop shared with source analysts. A Room B policy stored **outside** the signed handoff must pin all of the following: -\`\`\`json +```json { "format": "rudevolution.cleanroom.policy/v1", "target": "calculator-compatibility", @@ -87,22 +87,22 @@ A Room B policy stored **outside** the signed handoff must pin all of the follow "expiresAt": "", "maxApprovalAgeHours": 168 } -\`\`\` +``` -The placeholders above are intentionally **not usable** until the Room B operator supplies a real trusted key fingerprint, runtime digest and expiration. Never discover your trust anchor by trusting an unverified \`approved.json\` bundle. Pin the reviewer and image digest through your organization's independent approval process. +The placeholders above are intentionally **not usable** until the Room B operator supplies a real trusted key fingerprint, runtime digest and expiration. Never discover your trust anchor by trusting an unverified `approved.json` bundle. Pin the reviewer and image digest through your organization's independent approval process. Retrieve the approved container image on the isolated worker **before** evaluation. A development smoke test can discover the digest of a fetched Node image: -\`\`\`bash +```bash docker pull node:22-alpine docker image inspect node:22-alpine --format '{{index .RepoDigests 0}}' -\`\`\` +``` -For production, use a separately reviewed, patched image and independently pin its immutable digest in the Room B policy. The runner **refuses mutable image tags** and uses \`--pull=never\` to avoid fetching images while evaluating. +For production, use a separately reviewed, patched image and independently pin its immutable digest in the Room B policy. The runner **refuses mutable image tags** and uses `--pull=never` to avoid fetching images while evaluating. -Run from the repository root, with the report destination **outside** the \`fresh-implementation\` scaffold: +Run from the repository root, with the report destination **outside** the `fresh-implementation` scaffold: -\`\`\`bash +```bash node npm/src/clean-room/cli.js sandbox-test \ approved.json \ room-b-trusted-public.pem \ @@ -110,25 +110,62 @@ node npm/src/clean-room/cli.js sandbox-test \ fresh-implementation \ node@sha256: \ independent-evaluation-report.json -\`\`\` +``` -The command rechecks the signature, reviewer, target, age, policy expiration, key fingerprint and image digest **before** loading an implementation. It then requires the scaffold to contain exactly \`APPROVAL.txt\`, \`contract.json\`, \`compat.test.mjs\` and \`implementation.mjs\`. Only the last file may be edited. Unknown files, source maps, changed tests, symlinks, hardlinks and modified contracts are rejected. +The command rechecks the signature, reviewer, target, age, policy expiration, key fingerprint and image digest **before** loading an implementation. It then requires the scaffold to contain exactly `APPROVAL.txt`, `contract.json`, `compat.test.mjs` and `implementation.mjs`. Only the last file may be edited. Unknown files, source maps, changed tests, symlinks, hardlinks and modified contracts are rejected. -The implementation runs in Docker with no container network, no elevated Linux capabilities, a read-only filesystem, an ephemeral \`/tmp\`, unprivileged UID 65534, CPU/memory/PID limits, and a single read-only mount containing **only three required files**. Neither Room A nor the original Room B project directory is mounted. The runner records a JSON report with review, specification, implementation and image hashes, test outcome, duration and hashed logs, without embedding raw execution logs. +The implementation runs in Docker with no container network, no elevated Linux capabilities, a read-only filesystem, an ephemeral `/tmp`, unprivileged UID 65534, CPU/memory/PID limits, and a single read-only mount containing **only three required files**. Neither Room A nor the original Room B project directory is mounted. The runner records a versioned JSON report with review, specification, policy, generated harness, implementation and image digests, verified vector counts, duration and hashed logs, without embedding raw execution logs. If Docker is unavailable or the image is not locally present, the command fails rather than executing the implementation on the host. This is a defense-in-depth sandbox, not a mathematical noninterference proof or a substitute for independent implementation workflows. For an end-to-end Linux smoke test using Docker, run: -\`\`\`bash +```bash RUDEVOLUTION_TEST_IMAGE='node@sha256:' \ node --test npm/test/clean-room-docker.test.js -\`\`\` +``` The CI workflow derives a real digest and runs this integration test. Without that environment variable, the Docker test is skipped; policy, staging, malicious-file and cleanup tests still run locally. See [ADR 141](../adr/ADR-141-room-b-isolated-evaluation.md) for the threat model and explicit runtime controls. The Docker flags correspond to documented options in [Docker run](https://docs.docker.com/reference/cli/docker/container/run), [bind mounts](https://docs.docker.com/engine/storage/bind-mounts/), and [tmpfs](https://docs.docker.com/engine/storage/tmpfs/). +## Verified-vector harness and signed Room B evidence + +**Security fix:** Earlier scaffolds imported independent implementation code directly into the Node test runner before tests registered. An implementation containing only `process.exit(0)` could therefore cause a successful process exit without running any approved vectors. The hardened scaffold launches **one short-lived subprocess per approved vector**. Each child receives a single primitive call and must return one well-formed JSON result; the trusted parent checks the result. The Docker evaluator separately requires a complete TAP summary matching every vector, with no skips, failures or cancellations. Its report uses `rudevolution.cleanroom.sandbox-report/v2` and records `executedVectors`, `passedVectors`, and digests of both the approved policy and generated harness. + +**Migration:** Existing Room B scaffolds do not have the hardened test runner and are intentionally rejected by the isolated evaluator. Create a fresh directory with `scaffold` using the same approved artifact and the independently pinned public key. Independently review and copy only your **Room B authored** implementation into the fresh scaffold. Do not copy old test scripts or third-party reference material. + +An evaluator report may optionally be **signed by a separate Room B worker key** on the host after container termination. The worker key must be provisioned and protected independently from the Room A review key and must never be mounted in the test container. Generate a dedicated key in the isolated Room B signing environment: + +```bash +umask 077 +openssl genpkey -algorithm Ed25519 -out room-b-worker-private.pem +openssl pkey -in room-b-worker-private.pem -pubout -out trusted-worker-public.pem +``` + +Add the attestation arguments after the usual six evaluation inputs: + +```bash +node npm/src/clean-room/cli.js sandbox-test \ + approved.json room-b-trusted-public.pem room-b-policy.json \ + fresh-implementation 'node@sha256:' \ + evaluation-report.json \ + --attest room-b-worker-private.pem worker-one signed-evaluation.json +``` + +This writes an ordinary v2 evaluation report and a separately signed `rudevolution.cleanroom.evaluation-attestation/v1` envelope. Verify it with a public key obtained **out of band**, the expected worker identifier and the SHA256 of the independently approved artifact: + +```bash +node npm/src/clean-room/cli.js verify-attestation \ + signed-evaluation.json trusted-worker-public.pem worker-one \ + +``` + +Signatures bind the report bytes, approved artifact digest, image digest, implementation hash, policy digest, harness digest and recorded vector counts. They **do not attest** that the host ran unmodified software, that the implementation was independently authored, or that the replacement is legally permissible. The current signer does not use a hardware-backed or remote attestation service. Use a separate trusted Room B signing host and an external key lifecycle/revocation policy for higher assurance. + +The v2 harness tests approved primitive call results independently. It cannot establish untested behavior, stateful equivalence, secret-independent development or immunity to malicious implementations that deliberately return memorized public test vectors. + + ## Reproducible smoke test ```bash diff --git a/npm/src/clean-room/attestation.js b/npm/src/clean-room/attestation.js new file mode 100644 index 0000000..383154d --- /dev/null +++ b/npm/src/clean-room/attestation.js @@ -0,0 +1,98 @@ +'use strict'; + +/** + * Optional Ed25519 integrity attestation for a Room B evaluation report. + * A signature identifies the signing key and binds report bytes. It does not + * attest host isolation, source independence or the legality of reimplementation. + */ +const { KeyObject, createPublicKey, createPrivateKey, sign, verify } = require('node:crypto'); +const { canonicalStringify, sha256 } = require('./index'); + +const FORMAT = 'rudevolution.cleanroom.evaluation-attestation/v1'; +const REPORT = 'rudevolution.cleanroom.sandbox-report/v2'; +const DOMAIN = FORMAT + '\n'; +const ID = /^[a-z][a-z0-9-]{0,47}$/; +const HEX = /^[a-f0-9]{64}$/; +const IMAGE = /^[a-z0-9][a-z0-9./_-]{0,127}@sha256:[a-f0-9]{64}$/; +const REPORT_KEYS = ['format','approvalSha256','specSha256','policySha256', + 'publicKeyFingerprint','implementationSha256','harnessSha256','image', + 'vectorCount','executedVectors','passedVectors','status','exitCode', + 'durationMs','stdoutSha256','stderrSha256']; + +function reject(text) { throw Error('Clean room attestation rejected: ' + text); } +function exact(obj, keys) { + if (!obj || Array.isArray(obj) || Object.getPrototypeOf(obj) !== Object.prototype || + Object.keys(obj).length !== keys.length || + Object.keys(obj).some(k => !keys.includes(k))) reject('unexpected/missing fields'); +} +function validDate(s) { + return typeof s === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(s) && + Number.isFinite(Date.parse(s)) && new Date(s).toISOString() === s; +} +function fp(key) { + const pub = key instanceof KeyObject && key.type === 'public' ? key : createPublicKey(key); + return sha256(pub.export({ format:'der', type:'spki' })); +} +function validateReport(r) { + exact(r, REPORT_KEYS); + if (r.format !== REPORT) reject('unsupported report version'); + for (const k of REPORT_KEYS.filter(k => k.endsWith('Sha256') || k === 'publicKeyFingerprint')) { + if (typeof r[k] !== 'string' || !HEX.test(r[k])) reject('invalid digest ' + k); + } + if (typeof r.image !== 'string' || !IMAGE.test(r.image)) reject('untrusted image'); + if (!Number.isInteger(r.vectorCount) || r.vectorCount < 1 || r.vectorCount > 24) reject('invalid vector count'); + for (const k of ['executedVectors','passedVectors']) { + if (!Number.isInteger(r[k]) || r[k] < 0 || r[k] > r.vectorCount) reject('invalid vector accounting'); + } + if (r.passedVectors > r.executedVectors) reject('passing vectors exceed executed'); + if (!['passed','failed','timeout','runner_error'].includes(r.status)) reject('invalid status'); + if (r.exitCode !== null && (!Number.isInteger(r.exitCode) || r.exitCode < 0 || r.exitCode > 255)) reject('invalid exit code'); + if (!Number.isInteger(r.durationMs) || r.durationMs < 0 || r.durationMs > 120000) reject('invalid duration'); + if (r.status === 'passed' && (r.exitCode !== 0 || r.executedVectors !== r.vectorCount || + r.passedVectors !== r.vectorCount)) reject('unexecuted vectors cannot pass'); + if (Buffer.byteLength(canonicalStringify(r)) > 8192) reject('report too large'); + return r; +} +function message(r, workerId, signedAt, digest) { + return DOMAIN + canonicalStringify({ report:r, workerId, signedAt, reportSha256:digest }); +} +function attestReport(report, {privateKey, workerId, now=new Date()}) { + validateReport(report); + if (typeof workerId !== 'string' || !ID.test(workerId)) reject('invalid worker ID'); + if (!(now instanceof Date) || !Number.isFinite(now.getTime())) reject('invalid clock'); + const key = privateKey instanceof KeyObject ? privateKey : createPrivateKey(privateKey); + if (key.type !== 'private' || key.asymmetricKeyType !== 'ed25519') reject('Ed25519 private key required'); + if (fp(key) === report.publicKeyFingerprint) reject('worker key must differ from Room A reviewer key'); + const signedAt = now.toISOString(), reportSha256 = sha256(canonicalStringify(report)); + const signature = sign(null, Buffer.from(message(report, workerId, signedAt, reportSha256)), key).toString('base64'); + return { format:FORMAT, report, attester:{ + workerId, signedAt, reportSha256, publicKeyFingerprint:fp(key), signature, + }}; +} +function verifyAttestation(envelope, trustedPublicKey, { + workerId, approvalSha256, maxAgeHours=168, now=new Date(), +}={}) { + exact(envelope, ['format','report','attester']); + if (envelope.format !== FORMAT) reject('unsupported attestation'); + const report = validateReport(envelope.report); + const a = envelope.attester; + exact(a, ['workerId','signedAt','reportSha256','publicKeyFingerprint','signature']); + if (typeof a.workerId !== 'string' || !ID.test(a.workerId) || !validDate(a.signedAt)) reject('invalid attester metadata'); + if (typeof a.reportSha256 !== 'string' || a.reportSha256 !== sha256(canonicalStringify(report))) reject('report digest mismatch'); + if (typeof a.publicKeyFingerprint !== 'string' || !HEX.test(a.publicKeyFingerprint)) reject('invalid signer fingerprint'); + if (typeof a.signature !== 'string' || !/^[A-Za-z0-9+/]{86}==$/.test(a.signature)) reject('invalid signature encoding'); + const sig=Buffer.from(a.signature, 'base64'); + if (sig.length !== 64 || sig.toString('base64') !== a.signature) reject('noncanonical signature'); + const key=trustedPublicKey instanceof KeyObject ? trustedPublicKey : createPublicKey(trustedPublicKey); + if (key.type !== 'public' || key.asymmetricKeyType !== 'ed25519') reject('Ed25519 public key required'); + if (fp(key) !== a.publicKeyFingerprint) reject('untrusted signing key'); + if (!verify(null, Buffer.from(message(report,a.workerId,a.signedAt,a.reportSha256)), key, sig)) reject('bad signature'); + if (workerId !== undefined && workerId !== a.workerId) reject('untrusted worker identity'); + if (approvalSha256 !== undefined && approvalSha256 !== report.approvalSha256) reject('unexpected approval'); + if (!Number.isInteger(maxAgeHours) || maxAgeHours < 1 || maxAgeHours > 720 || + !(now instanceof Date) || !Number.isFinite(now.getTime())) reject('invalid verification policy'); + const delta=now.getTime()-Date.parse(a.signedAt); + if (delta < -300000 || delta > maxAgeHours*3600000) reject('future/expired attestation'); + return {report,workerId:a.workerId,reportSha256:a.reportSha256,publicKeyFingerprint:a.publicKeyFingerprint}; +} +module.exports={FORMAT,REPORT,validateReport,attestReport,verifyAttestation}; diff --git a/npm/src/clean-room/cli.js b/npm/src/clean-room/cli.js index ee226f1..5078da3 100644 --- a/npm/src/clean-room/cli.js +++ b/npm/src/clean-room/cli.js @@ -6,6 +6,7 @@ const fs = require('node:fs'); const path = require('node:path'); const { validateSpec, approveSpec, verifyApproved, scaffoldFiles } = require('./index'); const { sandboxTest } = require('./isolated-runner'); +const { attestReport, verifyAttestation } = require('./attestation'); function assertNoSymlinkAncestors(filename) { let current = path.resolve(path.dirname(filename)); @@ -95,24 +96,59 @@ function main(argv) { return; } case 'sandbox-test': { - requireArgs(args, 6, 'node npm/src/clean-room/cli.js sandbox-test approved.json trusted-public.pem room-b-policy.json independent-project IMAGE@sha256:DIGEST report.json'); - const [approvedFile, publicKeyFile, policyFile, projectDir, image, reportFile] = args; - const project = path.resolve(projectDir); - const output = path.resolve(reportFile); - const relative = path.relative(project, output); - if (relative === '' || (relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative))) { - throw Error('Room B test report must be stored outside the implementation project'); + if (args.length !== 6 && args.length !== 10) { + throw Error('Usage: sandbox-test approved.json trusted-public.pem room-b-policy.json independent-project image@sha256:DIGEST report.json [--attest worker-private.pem worker-id attestation.json]'); } + const [approvedFile, publicKeyFile, policyFile, projectDir, image, reportFile, flag, workerKeyFile, workerId, attestationFile] = args; + const project = path.resolve(projectDir); + const outsideProject = filename => { + const output = path.resolve(filename); + const relative = path.relative(project, output); + if (relative === '' || (relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative))) { + throw Error('Evaluation outputs must be outside the implementation project'); + } + }; + outsideProject(reportFile); verifyOutputParent(reportFile); if (fs.existsSync(reportFile)) throw Error('Refusing to overwrite a previous evaluation report'); + if (args.length === 10) { + if (flag !== '--attest') throw Error('Explicit --attest flag required'); + outsideProject(attestationFile); + verifyOutputParent(attestationFile); + if (path.resolve(attestationFile) === path.resolve(reportFile) || fs.existsSync(attestationFile)) { + throw Error('Attestation must be a new, separate file'); + } + } const report = sandboxTest({ approvedFile, publicKeyFile, policyFile, projectDir, image }); - safeOutput(reportFile, JSON.stringify(report, null, 2) + '\n'); - process.stdout.write('Room B isolated test: ' + report.status + ', approved vectors=' + report.vectorCount + '\n'); + // Sign only results returned by this verified runner, not arbitrary user JSON. + // Private key is loaded on the Room B host after container termination. + const signed = args.length === 10 + ? attestReport(report, { privateKey: readPrivateKey(workerKeyFile), workerId }) + : null; + let createdReport = false; + try { + safeOutput(reportFile, JSON.stringify(report, null, 2) + '\n'); + createdReport = true; + if (signed) safeOutput(attestationFile, JSON.stringify(signed, null, 2) + '\n'); + } catch (error) { + if (signed && createdReport) fs.unlinkSync(reportFile); + throw error; + } + process.stdout.write('Room B isolated test: ' + report.status + ', executed=' + report.executedVectors + '/' + report.vectorCount + '\n'); if (report.status !== 'passed') process.exitCode = 1; return; } + case 'verify-attestation': { + requireArgs(args, 4, 'verify-attestation attestation.json trusted-worker-public.pem worker-id expected-approval-sha256'); + const [attestationFile, workerPublicKeyFile, workerId, approvalSha256] = args; + const envelope = readJson(attestationFile, 32 * 1024); + const key = readBounded(workerPublicKeyFile, 8192); + const verified = verifyAttestation(envelope, key, { workerId, approvalSha256 }); + process.stdout.write('Verified worker evidence: ' + verified.report.status + ', report=' + verified.reportSha256 + '\n'); + return; + } default: - throw Error('Usage: cli.js ...'); + throw Error('Usage: cli.js ...'); } } diff --git a/npm/src/clean-room/index.js b/npm/src/clean-room/index.js index b4ce231..191bf65 100644 --- a/npm/src/clean-room/index.js +++ b/npm/src/clean-room/index.js @@ -156,7 +156,49 @@ function scaffoldFiles(artifact, publicKey) { }).join('\n\n'); const contractText = `${canonicalStringify(spec)}\n`; const contractDigest = sha256(contractText); - const runner = `import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport { createHash } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\nconst contractBytes = readFileSync(new URL('./contract.json', import.meta.url));\nconst observedDigest = createHash('sha256').update(contractBytes).digest('hex');\nif (observedDigest !== '${contractDigest}') throw new Error('Approved contract integrity mismatch');\nconst spec = JSON.parse(contractBytes.toString('utf8'));\nconst implementation = await import('./implementation.mjs');\nfor (const [index, vector] of spec.vectors.entries()) {\n test(\`compatibility vector \${index}: \${vector.operation}\`, () => {\n const actual = implementation[vector.operation](...vector.arguments);\n assert.deepStrictEqual(actual, vector.expected === null && spec.operations.find(op => op.name === vector.operation).returns === 'void' ? undefined : vector.expected);\n });\n}\n`; + // Never import implementer-controlled code into the trusted test process. + // Node's test runner can misleadingly exit 0 if a module calls process.exit(0) + // during import. One disposable subprocess is used for every approved vector. + const worker = [ + "import { readFileSync } from 'node:fs';", + "const call = JSON.parse(readFileSync(0, 'utf8'));", + "const implementation = await import('./implementation.mjs');", + "const fn = implementation[call.operation];", + "if (typeof fn !== 'function') throw new Error('missing operation export');", + "const result = await fn(...call.arguments);", + "process.stdout.write(JSON.stringify(result === undefined ? { kind: 'void' } : { kind: 'value', value: result }));", + ].join('\n'); + const runner = [ + "import test from 'node:test';", + "import assert from 'node:assert/strict';", + "import { spawnSync } from 'node:child_process';", + "import { createHash } from 'node:crypto';", + "import { readFileSync } from 'node:fs';", + "const contractBytes = readFileSync(new URL('./contract.json', import.meta.url));", + "const observedDigest = createHash('sha256').update(contractBytes).digest('hex');", + "if (observedDigest !== " + JSON.stringify(contractDigest) + ") throw new Error('Approved contract integrity mismatch');", + "const spec = JSON.parse(contractBytes.toString('utf8'));", + "const WORKER = " + JSON.stringify(worker) + ";", + "for (const [index, vector] of spec.vectors.entries()) {", + " test('compatibility vector ' + index + ': ' + vector.operation, () => {", + " const child = spawnSync(process.execPath, ['--input-type=module', '--eval', WORKER], {", + " cwd: new URL('.', import.meta.url),", + " input: JSON.stringify({ operation: vector.operation, arguments: vector.arguments }),", + " encoding: 'utf8', timeout: 2000, maxBuffer: 4096,", + " env: { HOME: '/tmp', TMPDIR: '/tmp' },", + " });", + " assert.equal(child.error, undefined, child.error?.message);", + " assert.equal(child.signal, null, 'worker terminated by signal');", + " assert.equal(child.status, 0, 'worker exited without returning a result: ' + (child.stderr || ''));", + " const observed = JSON.parse(child.stdout);", + " const operation = spec.operations.find(op => op.name === vector.operation);", + " const expected = operation.returns === 'void'", + " ? { kind: 'void' } : { kind: 'value', value: vector.expected };", + " assert.deepStrictEqual(observed, expected);", + " });", + "}", + "", + ].join('\n'); return { 'contract.json': contractText, 'implementation.mjs': `${fnDocs}\n`, diff --git a/npm/src/clean-room/isolated-runner.js b/npm/src/clean-room/isolated-runner.js index 90f07fe..a6534d7 100644 --- a/npm/src/clean-room/isolated-runner.js +++ b/npm/src/clean-room/isolated-runner.js @@ -13,10 +13,10 @@ const os = require('node:os'); const path = require('node:path'); const { randomBytes } = require('node:crypto'); const { spawnSync } = require('node:child_process'); -const { verifyApproved, scaffoldFiles, sha256 } = require('./index'); +const { verifyApproved, scaffoldFiles, canonicalStringify, sha256 } = require('./index'); const POLICY_FORMAT = 'rudevolution.cleanroom.policy/v1'; -const REPORT_FORMAT = 'rudevolution.cleanroom.sandbox-report/v1'; +const REPORT_FORMAT = 'rudevolution.cleanroom.sandbox-report/v2'; const IMAGE = /^[a-z0-9][a-z0-9./_-]{0,127}@sha256:[a-f0-9]{64}$/; const HEX = /^[a-f0-9]{64}$/; const REVIEWER = /^[A-Za-z0-9][A-Za-z0-9_.@-]{1,79}$/; @@ -115,6 +115,8 @@ function prepareRoomB({ approvedFile, publicKeyFile, policyFile, projectDir, ima // or a project directory containing arbitrary files. return { verified, + policySha256: sha256(canonicalStringify(policy)), + harnessSha256: sha256(reference['compat.test.mjs']), vectorCount: verified.spec.vectors.length, files: { 'contract.json': reference['contract.json'], @@ -140,9 +142,34 @@ function dockerArgs(stageDir, image, containerName) { '--tmpfs=/tmp:rw,noexec,nosuid,nodev,size=16m,mode=1777', '--mount=type=bind,source=' + stageDir + ',target=/work,readonly', '--workdir=/work', '--env=HOME=/tmp', '--env=TMPDIR=/tmp', - '--entrypoint=node', image, '--test', 'compat.test.mjs', + '--entrypoint=node', image, '--test', '--test-reporter=tap', 'compat.test.mjs', ]; } +/** + * The Docker exit status alone is not sufficient to establish that approved + * vectors actually ran. Require an unambiguous Node TAP footer with exactly + * one passing result per approved vector, no skips or cancellations. + */ +function parseTapSummary(output, expectedVectors) { + if (typeof output !== 'string' || !Number.isInteger(expectedVectors) || expectedVectors < 1) return null; + if (!/^TAP version 13(?:\r?\n)/.test(output)) return null; + const counters = {}; + const matches = output.matchAll(/^# (tests|pass|fail|cancelled|skipped|todo) (\d+)\r?$/gm); + for (const match of matches) { + const field = match[1]; + if (Object.prototype.hasOwnProperty.call(counters, field)) return null; + counters[field] = Number(match[2]); + if (!Number.isSafeInteger(counters[field])) return null; + } + for (const name of ['tests', 'pass', 'fail', 'cancelled', 'skipped', 'todo']) { + if (!Object.prototype.hasOwnProperty.call(counters, name)) return null; + } + if (counters.tests !== expectedVectors || counters.pass !== expectedVectors || + counters.fail !== 0 || counters.cancelled !== 0 || + counters.skipped !== 0 || counters.todo !== 0) return null; + return { executedVectors: counters.tests, passedVectors: counters.pass }; +} + function sandboxTest(options, spawn = spawnSync) { if (process.platform !== 'linux') deny('isolated runner requires Linux'); const { approvedFile, publicKeyFile, policyFile, projectDir, image, now = new Date() } = options; @@ -165,14 +192,19 @@ function sandboxTest(options, spawn = spawnSync) { started = true; const timedOut = result.error && result.error.code === 'ETIMEDOUT'; const errored = result.error && !timedOut; - const passed = result.status === 0 && !result.signal && !result.error; + const summary = parseTapSummary(result.stdout, prepared.vectorCount); + const passed = result.status === 0 && !result.signal && !result.error && summary !== null; const report = { format: REPORT_FORMAT, approvalSha256: prepared.verified.approvalSha256, - specSha256: sha256(require('./index').canonicalStringify(prepared.verified.spec)), + specSha256: sha256(canonicalStringify(prepared.verified.spec)), + policySha256: prepared.policySha256, + harnessSha256: prepared.harnessSha256, publicKeyFingerprint: prepared.verified.publicKeyFingerprint, implementationSha256: sha256(prepared.files['implementation.mjs']), image, vectorCount: prepared.vectorCount, + executedVectors: summary?.executedVectors ?? 0, + passedVectors: summary?.passedVectors ?? 0, status: passed ? 'passed' : timedOut ? 'timeout' : errored ? 'runner_error' : 'failed', exitCode: Number.isInteger(result.status) ? result.status : null, durationMs: Math.max(0, Date.now() - start), @@ -198,5 +230,5 @@ function sandboxTest(options, spawn = spawnSync) { module.exports = { POLICY_FORMAT, REPORT_FORMAT, checkPolicy, readRegular, prepareRoomB, - dockerArgs, sandboxTest, + dockerArgs, parseTapSummary, sandboxTest, }; diff --git a/npm/test/clean-room-attestation.test.js b/npm/test/clean-room-attestation.test.js new file mode 100644 index 0000000..b0160ea --- /dev/null +++ b/npm/test/clean-room-attestation.test.js @@ -0,0 +1,107 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { generateKeyPairSync, createHash } = require('node:crypto'); +const { FORMAT, REPORT, validateReport, attestReport, verifyAttestation } = require('../src/clean-room/attestation'); + +const pair = () => generateKeyPairSync('ed25519'); +const NOW = new Date('2026-10-08T22:00:00.000Z'); +const digest = c => c.repeat(64); +const sample = () => ({ + format: REPORT, + approvalSha256: digest('a'), specSha256: digest('b'), policySha256: digest('c'), + publicKeyFingerprint: digest('d'), implementationSha256: digest('e'), + harnessSha256: digest('f'), image: 'node@sha256:' + digest('9'), + vectorCount: 3, executedVectors: 3, passedVectors: 3, + status: 'passed', exitCode: 0, durationMs: 812, + stdoutSha256: digest('1'), stderrSha256: digest('2'), +}); +const clone = o => JSON.parse(JSON.stringify(o)); + +test('independent worker key signs complete evaluation report and verifies offline', () => { + const { privateKey, publicKey } = pair(); + const report = sample(); + const signed = attestReport(report, { privateKey, workerId: 'worker-a', now: NOW }); + assert.equal(signed.format, FORMAT); + assert.equal(signed.report.status, 'passed'); + const checked = verifyAttestation(signed, publicKey, { + workerId: 'worker-a', approvalSha256: report.approvalSha256, + now: new Date('2026-10-08T22:01:00.000Z'), + }); + assert.equal(checked.reportSha256, signed.attester.reportSha256); + assert.equal(checked.report.approvalSha256, report.approvalSha256); +}); + +test('report signature rejects tampering and untrusted worker identity', () => { + const { privateKey, publicKey } = pair(); + const attested = attestReport(sample(), { privateKey, workerId: 'worker-a', now: NOW }); + const cases = [ + signed => { signed.report.status = 'failed'; }, + signed => { signed.report.passedVectors = 2; }, + signed => { signed.report.stdoutSha256 = digest('8'); }, + signed => { signed.report.harnessSha256 = digest('8'); }, + signed => { signed.attester.workerId = 'worker-b'; }, + signed => { signed.attester.signedAt = '2026-10-07T22:00:00.000Z'; }, + signed => { signed.attester.signature = 'A'.repeat(86) + '=='; }, + signed => { signed.debugSource = 'secret'; }, + signed => { signed.report.referenceSource = 'secret'; }, + ]; + for (const change of cases) { + const copy = clone(attested); + change(copy); + assert.throws(() => verifyAttestation(copy, publicKey, { now: NOW }), /rejected/); + } + assert.throws(() => verifyAttestation(attested, pair().publicKey, { now: NOW }), /untrusted/); + assert.throws(() => verifyAttestation(attested, publicKey, { workerId: 'wrong', now: NOW }), /untrusted/); + assert.throws(() => verifyAttestation(attested, publicKey, { approvalSha256: digest('9'), now: NOW }), /unexpected approval/); +}); + +test('reports cannot lie about executed vectors or use unsigned extra fields', () => { + const bad = [ + r => { r.status = 'passed'; r.executedVectors = 0; }, + r => { r.status = 'passed'; r.passedVectors = 2; }, + r => { r.vectorCount = 25; }, + r => { r.vectorCount = -1; }, + r => { r.passedVectors = 7; }, + r => { r.exitCode = 999; }, + r => { r.status = 'opaque'; }, + r => { r.image = 'node:latest'; }, + r => { r.harnessSha256 = 'wrong'; }, + r => { r.durationMs = -1; }, + r => { r.source = 'impl'; }, + ]; + for (const mutate of bad) { + const report = sample(); + mutate(report); + assert.throws(() => validateReport(report), /rejected/); + } +}); + +test('failed evaluations can be attested but cannot be misreported as passing', () => { + const pair0 = pair(); + const failed = { ...sample(), status: 'failed', exitCode: 1, executedVectors: 0, passedVectors: 0 }; + const signed = attestReport(failed, { privateKey: pair0.privateKey, workerId: 'worker-failure', now: NOW }); + const verified = verifyAttestation(signed, pair0.publicKey, { now: NOW }); + assert.equal(verified.report.status, 'failed'); + assert.equal(verified.report.passedVectors, 0); +}); + +test('attestation age, clocks and key types are validated', () => { + const { privateKey, publicKey } = pair(); + const signed = attestReport(sample(), { privateKey, workerId: 'worker-a', now: NOW }); + assert.throws(() => verifyAttestation(signed, publicKey, { now: new Date('2026-11-01T22:00:00.000Z') }), /expired/); + assert.throws(() => verifyAttestation(signed, publicKey, { now: new Date('2026-10-08T21:00:00.000Z') }), /future/); + assert.throws(() => attestReport(sample(), { privateKey: publicKey, workerId: 'worker-a', now: NOW }), /private key required/); + assert.throws(() => attestReport(sample(), { privateKey, workerId: 'INVALID!', now: NOW }), /worker ID/); + assert.throws(() => verifyAttestation(signed, privateKey, { now: NOW }), /public key required/); +}); + +test('the evaluator signing key cannot reuse the Room A review key', () => { + const { privateKey, publicKey } = pair(); + const report = sample(); + report.publicKeyFingerprint = createHash('sha256') + .update(publicKey.export({ type: 'spki', format: 'der' })).digest('hex'); + assert.throws(() => attestReport(report, { + privateKey, workerId: 'worker-a', now: NOW, + }), /worker key must differ/); +}); diff --git a/npm/test/clean-room-docker.test.js b/npm/test/clean-room-docker.test.js index 3ee1748..5212811 100644 --- a/npm/test/clean-room-docker.test.js +++ b/npm/test/clean-room-docker.test.js @@ -42,6 +42,12 @@ test('real Docker Room B denies Room A filesystem, network and writes while test const policyFile = path.join(b, 'room-b-policy.json'); const projectDir = path.join(b, 'implementation'); const reportFile = path.join(b, 'test-report.json'); + const signedFile = path.join(b, 'signed-evaluation.json'); + const workerKeys = generateKeyPairSync('ed25519'); + const workerPrivateFile = path.join(b, 'worker-signing-private.pem'); + const workerPublicFile = path.join(b, 'worker-trusted-public.pem'); + fs.writeFileSync(workerPrivateFile, workerKeys.privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 }); + fs.writeFileSync(workerPublicFile, workerKeys.publicKey.export({ format: 'pem', type: 'spki' })); fs.writeFileSync(approvedFile, JSON.stringify(artifact)); fs.writeFileSync(publicKeyFile, keys.publicKey.export({ format: 'pem', type: 'spki' })); const expiresAt = new Date(Date.now() + 4 * 3600000).toISOString(); @@ -79,16 +85,40 @@ test('real Docker Room B denies Room A filesystem, network and writes while test '', ].join('\n'); fs.writeFileSync(path.join(projectDir, 'implementation.mjs'), independent); - const result = cli(['sandbox-test', approvedFile, publicKeyFile, policyFile, projectDir, IMAGE, reportFile]); + const result = cli(['sandbox-test', approvedFile, publicKeyFile, policyFile, projectDir, IMAGE, + reportFile, '--attest', workerPrivateFile, 'worker-ci', signedFile]); assert.equal(result.status, 0, 'Docker smoke test failed: ' + result.stdout + result.stderr); const report = JSON.parse(fs.readFileSync(reportFile, 'utf8')); assert.equal(report.format, REPORT_FORMAT); assert.equal(report.status, 'passed'); assert.equal(report.vectorCount, 3); + assert.equal(report.executedVectors, 3); + assert.equal(report.passedVectors, 3); + assert.match(report.harnessSha256, /^[a-f0-9]{64}$/); + assert.match(report.policySha256, /^[a-f0-9]{64}$/); assert.equal(report.exitCode, 0); assert.equal(report.publicKeyFingerprint, receipt.publicKeyFingerprint); assert(!fs.readFileSync(reportFile, 'utf8').includes('NEVER_CROSS_ROOM_BOUNDARY_383')); assert(!fs.readdirSync(b).includes('secret-implementation.js')); + const checked = cli(['verify-attestation', signedFile, workerPublicFile, 'worker-ci', report.approvalSha256]); + assert.equal(checked.status, 0, checked.stdout + checked.stderr); + const altered = JSON.parse(fs.readFileSync(signedFile, 'utf8')); + altered.report.passedVectors = 0; + const forged = path.join(b, 'forged-evaluation.json'); + fs.writeFileSync(forged, JSON.stringify(altered)); + const rejected = cli(['verify-attestation', forged, workerPublicFile, 'worker-ci', report.approvalSha256]); + assert.notEqual(rejected.status, 0, 'edited evaluation must not verify'); + + // Adversarial implementation exits successfully without calling any public + // operation. The evaluator must not mistake its exit code for vector success. + fs.writeFileSync(path.join(projectDir, 'implementation.mjs'), 'process.exit(0);\n'); + const bypassFile = path.join(b, 'bypass-report.json'); + const bypass = cli(['sandbox-test', approvedFile, publicKeyFile, policyFile, projectDir, IMAGE, bypassFile]); + assert.notEqual(bypass.status, 0, 'exit(0) cannot bypass contract evaluation'); + const rejectedBypass = JSON.parse(fs.readFileSync(bypassFile, 'utf8')); + assert.equal(rejectedBypass.status, 'failed'); + assert.equal(rejectedBypass.passedVectors, 0); + fs.writeFileSync(path.join(projectDir, 'implementation.mjs'), independent); // Invalid/unsigned edits must be rejected before creating a report or // calling Docker. Each run uses a fresh report file. diff --git a/npm/test/clean-room-isolation.test.js b/npm/test/clean-room-isolation.test.js index 9210131..77078a9 100644 --- a/npm/test/clean-room-isolation.test.js +++ b/npm/test/clean-room-isolation.test.js @@ -7,7 +7,7 @@ const path = require('node:path'); const { generateKeyPairSync } = require('node:crypto'); const { approveSpec, scaffoldFiles } = require('../src/clean-room'); const { - POLICY_FORMAT, checkPolicy, readRegular, prepareRoomB, dockerArgs, sandboxTest, + POLICY_FORMAT, checkPolicy, readRegular, prepareRoomB, dockerArgs, parseTapSummary, sandboxTest, } = require('../src/clean-room/isolated-runner'); const fixture = require('../../examples/clean-room/calculator.spec.json'); @@ -127,7 +127,8 @@ test('Docker args allow only one read-only stage mount and deny network, privile const mounts = args.filter(item => item.startsWith('--mount=')); assert.equal(mounts.length, 1); assert.match(mounts[0], /^--mount=type=bind,source=\/tmp\/rudevolution-room-b-example,target=\/work,readonly$/); - assert.equal(args.at(-3), IMAGE); + assert.equal(args.at(-4), IMAGE); + assert(args.includes('--test-reporter=tap')); assert.throws(() => dockerArgs('/tmp/with,malicious', IMAGE, 'rudevolution-b-' + 'a'.repeat(24)), /rejected/); assert.throws(() => dockerArgs('/tmp/safe', 'node:22-alpine', 'rudevolution-b-' + 'a'.repeat(24)), /immutable sha256/); assert.throws(() => dockerArgs('/tmp/safe', IMAGE, 'contaminated'), /rejected/); @@ -149,7 +150,7 @@ test('isolated runner mounts only a verified minimal staging copy and produces h const text = fs.readFileSync(path.join(tempDir, name), 'utf8'); assert.doesNotMatch(text, new RegExp(env.marker)); } - return { status: 0, stdout: '# pass 3\n', stderr: '', signal: null }; + return { status: 0, stdout: 'TAP version 13\n1..3\n# tests 3\n# suites 0\n# pass 3\n# fail 0\n# cancelled 0\n# skipped 0\n# todo 0\n', stderr: '', signal: null }; } return { status: 1, stderr: 'No such container', stdout: '' }; }; @@ -204,3 +205,31 @@ test('no symlinked policy and no hardlinked implementation', () => scoped(env => fs.linkSync(file, sibling); assert.throws(() => readRegular(file, 1024 * 1024), /uniquely linked/); })); + +test('TAP parser refuses zero tests, incomplete counters, skipped tests and forged counts', () => { + const valid = 'TAP version 13\n# tests 3\n# pass 3\n# fail 0\n# cancelled 0\n# skipped 0\n# todo 0\n'; + assert.deepEqual(parseTapSummary(valid, 3), { executedVectors: 3, passedVectors: 3 }); + const invalid = [ + '', + '# tests 3\n# pass 3\n', + 'TAP version 13\n# tests 0\n# pass 0\n# fail 0\n# cancelled 0\n# skipped 0\n# todo 0\n', + valid.replace('# pass 3', '# pass 2'), + valid.replace('# skipped 0', '# skipped 1'), + valid.replace('# fail 0', '# fail 1'), + valid.replace('# todo 0', '# todo 1'), + valid.replace('# cancelled 0', '# cancelled 1'), + valid + '# tests 3\n', + ]; + for (const str of invalid) assert.equal(parseTapSummary(str, 3), null); +}); + +test('even Docker exit 0 is not sufficient without verified vector accounting', () => scoped(env => { + const fake = (program, args) => args.includes('run') + ? { status: 0, signal: null, stderr: '', stdout: 'TAP version 13\n# tests 0\n# pass 0\n# fail 0\n# cancelled 0\n# skipped 0\n# todo 0\n' } + : { status: 1, stderr: 'No such container', stdout: '' }; + const report = sandboxTest(env.options, fake); + assert.equal(report.status, 'failed'); + assert.equal(report.vectorCount, 3); + assert.equal(report.executedVectors, 0); + assert.equal(report.passedVectors, 0); +})); diff --git a/npm/test/clean-room.test.js b/npm/test/clean-room.test.js index 822d429..72dce20 100644 --- a/npm/test/clean-room.test.js +++ b/npm/test/clean-room.test.js @@ -180,3 +180,52 @@ test('CLI rejects symlinked inputs and symlinked output parent', () => { assert.equal(cli(['scaffold', p, pub, path.join(fake, 'out')]).status, 1); } finally { fs.rmSync(root, {recursive:true, force:true}); } }); + +test('a Room B implementation cannot hide skipped vectors by exiting the test process', () => { + const root = temporary(); + try { + const { artifact, pair } = signSpec(); + const files = scaffoldFiles(artifact, pair.publicKey); + for (const [name, content] of Object.entries(files)) fs.writeFileSync(path.join(root, name), content); + + fs.writeFileSync(path.join(root, 'implementation.mjs'), 'process.exit(0);\n'); + const earlyExit = spawnSync(process.execPath, ['--test', '--test-reporter=tap', 'compat.test.mjs'], { + cwd: root, encoding: 'utf8', timeout: 15000, env: { PATH: process.env.PATH, HOME: process.env.HOME }, + }); + assert.notEqual(earlyExit.status, 0, 'exit(0) must not cause a false passing test suite'); + assert.match(earlyExit.stdout, /# fail 3/); + + fs.writeFileSync(path.join(root, 'implementation.mjs'), + "process.stdout.write('TAP version 13\\n# tests 3\\n# pass 3\\n# fail 0\\n# cancelled 0\\n# skipped 0\\n# todo 0\\n'); process.exit(0);"); + const fakeTAP = spawnSync(process.execPath, ['--test', '--test-reporter=tap', 'compat.test.mjs'], { + cwd: root, encoding: 'utf8', timeout: 15000, env: { PATH: process.env.PATH, HOME: process.env.HOME }, + }); + assert.notEqual(fakeTAP.status, 0, 'forged TAP from untrusted child must not pass'); + assert.match(fakeTAP.stdout, /# fail 3/); + } finally { fs.rmSync(root, { recursive: true, force: true }); } +}); + +test('void return uses an explicit undefined outcome, not null', () => { + const root = temporary(); + try { + const one = { + format: 'rudevolution.cleanroom.spec/v1', + target: 'void-contract', + operations: [{ name: 'ping', inputs: [], returns: 'void', errors: [] }], + vectors: [{ operation: 'ping', arguments: [], expected: null }], + }; + const { artifact, pair } = signSpec(one); + const files = scaffoldFiles(artifact, pair.publicKey); + for (const [name, content] of Object.entries(files)) fs.writeFileSync(path.join(root, name), content); + const run = () => spawnSync(process.execPath, ['--test', '--test-reporter=tap', 'compat.test.mjs'], { + cwd: root, encoding: 'utf8', timeout: 15000, env: { PATH: process.env.PATH, HOME: process.env.HOME }, + }); + fs.writeFileSync(path.join(root, 'implementation.mjs'), 'export function ping() { return null; }\n'); + assert.notEqual(run().status, 0, 'null is not an approved void return'); + fs.writeFileSync(path.join(root, 'implementation.mjs'), 'export function ping() { return undefined; }\n'); + const pass = run(); + assert.equal(pass.status, 0, pass.stdout + pass.stderr); + assert.match(pass.stdout, /# tests 1/); + assert.match(pass.stdout, /# pass 1/); + } finally { fs.rmSync(root, { recursive: true, force: true }); } +}); diff --git a/package.json b/package.json index 5a8fca9..6a64912 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "scripts": { "test": "node npm/test/decompiler-reconstruction.js && node --test npm/test/security.test.js && npm run test:cleanroom", "bench": "node npm/bench/rename.js", - "test:cleanroom": "node --test npm/test/clean-room.test.js npm/test/clean-room-isolation.test.js npm/test/clean-room-docker.test.js", + "test:cleanroom": "node --test npm/test/clean-room.test.js npm/test/clean-room-isolation.test.js npm/test/clean-room-attestation.test.js npm/test/clean-room-docker.test.js", "cleanroom": "node npm/src/clean-room/cli.js" } }