| #!/usr/bin/env node |
|
|
| |
| |
| |
| |
|
|
| import fs from "node:fs/promises"; |
| import os from "node:os"; |
| import path from "node:path"; |
| import { createHash } from "node:crypto"; |
| import { spawnSync } from "node:child_process"; |
| import { fileURLToPath } from "node:url"; |
|
|
| const here = path.dirname(fileURLToPath(import.meta.url)); |
| const root = path.resolve(here, ".."); |
| const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "agency-transfer-hardening-")); |
| const results = []; |
|
|
| function sha256(value) { |
| return createHash("sha256").update(value).digest("hex"); |
| } |
|
|
| async function fixture(name) { |
| const target = path.join(tempRoot, name); |
| await fs.cp(root, target, { |
| recursive: true, |
| filter: (source) => { |
| const relative = path.relative(root, source); |
| if (!relative) return true; |
| const first = relative.split(path.sep)[0]; |
| return ![".git", "release"].includes(first) && !first.startsWith(".parquet-build-") && !first.startsWith(".parquet-backup-"); |
| } |
| }); |
| return target; |
| } |
|
|
| function run(repo, script, args = []) { |
| return spawnSync(process.execPath, [path.join(repo, "scripts", script), ...args], { |
| cwd: repo, |
| encoding: "utf8", |
| maxBuffer: 32 * 1024 * 1024 |
| }); |
| } |
|
|
| function errorCodes(result) { |
| try { |
| return JSON.parse(result.stdout).integrity.errors.map((item) => item.code); |
| } catch { |
| return []; |
| } |
| } |
|
|
| function assert(condition, message) { |
| if (!condition) throw new Error(message); |
| } |
|
|
| try { |
| if (!(await fs.stat(path.join(root, "node_modules", "parquetjs-lite")).catch(() => null))) { |
| throw new Error("node_modules/parquetjs-lite is required. Run npm ci before npm run test:hardening."); |
| } |
| const baseline = run(root, "validate-data.mjs"); |
| assert(baseline.status === 0, `Baseline validation must pass before mutation tests.\n${baseline.stdout || baseline.stderr}`); |
|
|
| |
| { |
| const repo = await fixture("parquet-manifest"); |
| const manifestPath = path.join(repo, "parquet", "manifest.json"); |
| const manifest = JSON.parse(await fs.readFile(manifestPath, "utf8")); |
| manifest.tables[0].sha256 = "0".repeat(64); |
| await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); |
| const validation = run(repo, "validate-data.mjs"); |
| const codes = errorCodes(validation); |
| assert(validation.status !== 0 && codes.includes("PARQUET_FILE_HASH_MISMATCH"), "Mutated Parquet manifest was not rejected by file hash"); |
| results.push({ mutation: "parquet_manifest_hash", status: "rejected", code: "PARQUET_FILE_HASH_MISMATCH" }); |
| } |
|
|
| |
| { |
| const repo = await fixture("stale-audit"); |
| const auditPath = path.join(repo, "data", "audit.json"); |
| const audit = JSON.parse(await fs.readFile(auditPath, "utf8")); |
| audit.summary.table_row_counts.cases += 1; |
| const stale = `${JSON.stringify(audit, null, 2)}\n`; |
| await fs.writeFile(auditPath, stale); |
| await fs.writeFile(path.join(repo, "data", "audit-v03.json"), stale); |
| const validation = run(repo, "validate-data.mjs"); |
| const codes = errorCodes(validation); |
| assert( |
| validation.status !== 0 && codes.includes("STORED_AUDIT_ROW_COUNT_MISMATCH") && codes.includes("STORED_AUDIT_STALE"), |
| "Byte-identical stale audits were not rejected" |
| ); |
| results.push({ mutation: "stored_audit_count", status: "rejected", codes: ["STORED_AUDIT_ROW_COUNT_MISMATCH", "STORED_AUDIT_STALE"] }); |
| } |
|
|
| |
| { |
| const repo = await fixture("invalid-coercion"); |
| const casesPath = path.join(repo, "data", "cases.csv"); |
| const original = await fs.readFile(casesPath, "utf8"); |
| const lines = original.split("\n"); |
| const headers = lines[0].split(","); |
| const anchorIndex = headers.indexOf("anchor_case"); |
| assert(anchorIndex >= 0, "cases.csv lacks anchor_case fixture column"); |
| const cells = lines[1].split(","); |
| assert(cells[anchorIndex] === "true" || cells[anchorIndex] === "false", "Unexpected quoted/complex anchor_case fixture value"); |
| cells[anchorIndex] = "truthy"; |
| lines[1] = cells.join(","); |
| await fs.writeFile(casesPath, lines.join("\n")); |
| const statsPath = path.join(repo, "data", "stats.json"); |
| const stats = JSON.parse(await fs.readFile(statsPath, "utf8")); |
| stats._integrity.file_sha256["cases.csv"] = sha256(await fs.readFile(casesPath)); |
| await fs.writeFile(statsPath, `${JSON.stringify(stats, null, 2)}\n`); |
| const parquetPath = path.join(repo, "parquet", "cases.parquet"); |
| const before = sha256(await fs.readFile(parquetPath)); |
| const build = run(repo, "build-parquet.mjs"); |
| const after = sha256(await fs.readFile(parquetPath)); |
| assert( |
| build.status !== 0 && /FIELD_TYPE_INVALID|invalid boolean/i.test(`${build.stdout}\n${build.stderr}`), |
| `Invalid boolean coercion did not block the build as expected.\n${build.stdout}\n${build.stderr}` |
| ); |
| assert(before === after, "Failed Parquet build modified the existing output"); |
| results.push({ mutation: "invalid_boolean_coercion", status: "rejected", existing_parquet_preserved: true }); |
| } |
|
|
| |
| { |
| const repo = await fixture("invalid-numeric-coercion"); |
| const csvPath = path.join(repo, "data", "coverage_summary.csv"); |
| const lines = (await fs.readFile(csvPath, "utf8")).split("\n"); |
| const headers = lines[0].split(","); |
| const countIndex = headers.indexOf("included_case_count"); |
| assert(countIndex >= 0, "coverage_summary.csv lacks included_case_count fixture column"); |
| const cells = lines[1].split(","); |
| cells[countIndex] = "12records"; |
| lines[1] = cells.join(","); |
| await fs.writeFile(csvPath, lines.join("\n")); |
| const statsPath = path.join(repo, "data", "stats.json"); |
| const stats = JSON.parse(await fs.readFile(statsPath, "utf8")); |
| stats._integrity.file_sha256["coverage_summary.csv"] = sha256(await fs.readFile(csvPath)); |
| await fs.writeFile(statsPath, `${JSON.stringify(stats, null, 2)}\n`); |
| const parquetPath = path.join(repo, "parquet", "coverage_summary.parquet"); |
| const before = sha256(await fs.readFile(parquetPath)); |
| const build = run(repo, "build-parquet.mjs"); |
| const after = sha256(await fs.readFile(parquetPath)); |
| assert( |
| build.status !== 0 && /FIELD_TYPE_INVALID|invalid integer/i.test(`${build.stdout}\n${build.stderr}`), |
| `Invalid numeric coercion did not block the build as expected.\n${build.stdout}\n${build.stderr}` |
| ); |
| assert(before === after, "Failed numeric Parquet build modified the existing output"); |
| results.push({ mutation: "invalid_numeric_coercion", status: "rejected", existing_parquet_preserved: true }); |
| } |
|
|
| |
| { |
| const repo = await fixture("release-artifact"); |
| const releaseDir = path.join(repo, "release"); |
| await fs.mkdir(releaseDir, { recursive: true }); |
| const zipName = "agency-transfer-election-cases-v0.4.0.zip"; |
| const workbookName = "agency-transfer-election-evidence-index-v0.4.0.xlsx"; |
| await fs.writeFile(path.join(releaseDir, workbookName), "external-runtime workbook fixture\n"); |
| const packageBuild = run(repo, "build-package.mjs"); |
| assert(packageBuild.status === 0, `Deterministic package fixture build failed.\n${packageBuild.stdout}\n${packageBuild.stderr}`); |
| const firstZipHash = sha256(await fs.readFile(path.join(releaseDir, zipName))); |
| const packageRebuild = run(repo, "build-package.mjs"); |
| const secondZipHash = sha256(await fs.readFile(path.join(releaseDir, zipName))); |
| assert(packageRebuild.status === 0 && firstZipHash === secondZipHash, "Repeated package build was not byte-deterministic"); |
| const packageVerification = run(repo, "verify-package.mjs"); |
| assert(packageVerification.status === 0, `Package member verification failed.\n${packageVerification.stdout}\n${packageVerification.stderr}`); |
| const initialCheckoutParity = run(repo, "verify-package.mjs", ["--checkout-parity"]); |
| assert(initialCheckoutParity.status === 0, `Fresh package must match its checkout.\n${initialCheckoutParity.stdout}\n${initialCheckoutParity.stderr}`); |
| const manifestBuild = run(repo, "build-release-manifest.mjs"); |
| assert(manifestBuild.status === 0, `Release manifest fixture build failed.\n${manifestBuild.stdout}\n${manifestBuild.stderr}`); |
| const cleanValidation = run(repo, "validate-data.mjs"); |
| assert(cleanValidation.status === 0, `Matching release manifest fixture did not validate.\n${cleanValidation.stdout}\n${cleanValidation.stderr}`); |
| const releaseManifestPath = path.join(releaseDir, "release-manifest.json"); |
| const cleanReleaseManifest = await fs.readFile(releaseManifestPath, "utf8"); |
| const duplicateManifest = JSON.parse(cleanReleaseManifest); |
| duplicateManifest.package_files[1] = { ...duplicateManifest.package_files[0] }; |
| await fs.writeFile(releaseManifestPath, `${JSON.stringify(duplicateManifest, null, 2)}\n`); |
| const duplicateValidation = run(repo, "validate-data.mjs"); |
| assert( |
| duplicateValidation.status !== 0 && errorCodes(duplicateValidation).includes("RELEASE_PACKAGE_FILE_DUPLICATE"), |
| "Duplicate release package-file entries were not rejected" |
| ); |
| await fs.writeFile(releaseManifestPath, cleanReleaseManifest); |
| const manifestBeforeCheckoutChange = sha256(await fs.readFile(releaseManifestPath)); |
| await fs.appendFile(path.join(repo, "README.md"), "\nPost-release mutable-main documentation fixture.\n"); |
| const frozenVerification = run(repo, "verify-package.mjs"); |
| assert(frozenVerification.status === 0, `Mutable checkout incorrectly invalidated the frozen package.\n${frozenVerification.stdout}\n${frozenVerification.stderr}`); |
| const changedCheckoutParity = run(repo, "verify-package.mjs", ["--checkout-parity"]); |
| assert( |
| changedCheckoutParity.status !== 0 && /differs from current checkout/i.test(`${changedCheckoutParity.stdout}\n${changedCheckoutParity.stderr}`), |
| "Explicit checkout-parity verification did not reject mutable-main drift" |
| ); |
| const manifestRebuild = run(repo, "build-release-manifest.mjs"); |
| const manifestAfterCheckoutChange = sha256(await fs.readFile(releaseManifestPath)); |
| assert( |
| manifestRebuild.status === 0 && manifestBeforeCheckoutChange === manifestAfterCheckoutChange, |
| "Release manifest changed when only the mutable checkout diverged from the frozen ZIP" |
| ); |
| const mutableMainValidation = run(repo, "validate-data.mjs"); |
| assert( |
| mutableMainValidation.status === 0, |
| `Mutable-main documentation incorrectly invalidated the frozen release.\n${mutableMainValidation.stdout}\n${mutableMainValidation.stderr}` |
| ); |
| await fs.appendFile(path.join(releaseDir, zipName), "tampered\n"); |
| const tamperedValidation = run(repo, "validate-data.mjs"); |
| const codes = errorCodes(tamperedValidation); |
| assert( |
| tamperedValidation.status !== 0 && codes.includes("RELEASE_ARTIFACT_HASH_MISMATCH"), |
| "Tampered release artifact was not rejected" |
| ); |
| results.push({ |
| mutation: "release_artifact_after_manifest", status: "rejected", |
| code: "RELEASE_ARTIFACT_HASH_MISMATCH", deterministic_package_rebuild: true, |
| package_member_verification: "pass", mutable_main_release_verification: "pass", |
| explicit_checkout_parity_after_drift: "rejected", duplicate_package_file_entry: "rejected" |
| }); |
| } |
|
|
| process.stdout.write(`${JSON.stringify({ status: "pass", isolated_temp_root: tempRoot, tests: results }, null, 2)}\n`); |
| } finally { |
| await fs.rm(tempRoot, { recursive: true, force: true }); |
| } |
|
|