File size: 11,901 Bytes
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122b842
 
bdd8da5
 
 
 
122b842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdd8da5
 
 
 
 
 
 
 
 
 
122b842
 
bdd8da5
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env node

/**
 * Destructive mutation tests isolated in the operating-system temp directory.
 * The checked-out repository is never modified.
 */

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}`);

  // 1. A forged Parquet manifest must not be accepted.
  {
    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" });
  }

  // 2. Two byte-identical but stale audit files must still fail.
  {
    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"] });
  }

  // 3. Invalid boolean input must block the builder without touching Parquet.
  {
    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 });
  }

  // 4. Invalid numeric input is rejected rather than parsed or omitted.
  {
    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 });
  }

  // 5. Release artifacts are accepted only with a matching manifest/SHA file.
  {
    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 });
}