invariant-firewall 0.0.3

Invariant — a cryptographic command-validation firewall for AI-controlled physical systems (robotics, biosynthesis). Installs the `invariant` binary. Part of the unified workspace at https://github.com/clay-good/invariant.
Documentation
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! `invariant verify-package` — deep proof package verification (Section 20.2).
//!
//! Verifies the integrity of a proof package by:
//! 1. Parsing the manifest and validating its schema
//! 2. Verifying SHA-256 hashes of every file listed in the manifest
//! 3. Checking directory structure completeness
//! 4. Validating summary statistics consistency
//! 5. Computing Merkle root from audit log if present

use clap::Args;
use std::path::PathBuf;

use invariant_robotics::proof_package::{verify_format_version, ProofPackageManifest};
use invariant_robotics::util::sha256_hex;

#[derive(Args)]
pub struct VerifyPackageArgs {
    /// Path to the proof package directory.
    #[arg(long, value_name = "PACKAGE_DIR")]
    pub path: PathBuf,
}

/// Result of a single verification check.
struct Check {
    name: String,
    passed: bool,
    detail: String,
}

impl Check {
    fn pass(name: &str, detail: impl std::fmt::Display) -> Self {
        Self {
            name: name.to_string(),
            passed: true,
            detail: detail.to_string(),
        }
    }
    fn fail(name: &str, detail: impl std::fmt::Display) -> Self {
        Self {
            name: name.to_string(),
            passed: false,
            detail: detail.to_string(),
        }
    }
}

pub fn run(args: &VerifyPackageArgs) -> i32 {
    if !args.path.is_dir() {
        eprintln!("error: package directory {:?} does not exist", args.path);
        return 2;
    }

    let mut checks: Vec<Check> = Vec::new();

    // 1. Parse manifest.
    let manifest_path = args.path.join("manifest.json");
    let manifest = match std::fs::read_to_string(&manifest_path) {
        Ok(data) => match serde_json::from_str::<ProofPackageManifest>(&data) {
            Ok(m) => {
                // v12 N-5: reject manifests whose format_version is outside the
                // supported range before any later check inspects the body.
                match verify_format_version(m.format_version) {
                    Ok(()) => {
                        checks.push(Check::pass(
                            "Manifest",
                            format!(
                                "valid (campaign: {}, profile: {}, format_version: {})",
                                m.campaign_name, m.profile_name, m.format_version
                            ),
                        ));
                        Some(m)
                    }
                    Err(e) => {
                        checks.push(Check::fail("Manifest", format!("{e}")));
                        None
                    }
                }
            }
            Err(e) => {
                checks.push(Check::fail("Manifest", format!("parse error: {e}")));
                None
            }
        },
        Err(_) => {
            checks.push(Check::fail("Manifest", "manifest.json missing"));
            None
        }
    };

    // 2. Verify file hashes from manifest.
    if let Some(ref m) = manifest {
        let (hash_ok, hash_fail) = verify_file_hashes(&args.path, m);
        if hash_fail == 0 {
            checks.push(Check::pass(
                "File integrity",
                format!("{hash_ok} files verified, 0 mismatches"),
            ));
        } else {
            checks.push(Check::fail(
                "File integrity",
                format!(
                    "{hash_fail} of {} files have hash mismatches",
                    hash_ok + hash_fail
                ),
            ));
        }
    } else {
        checks.push(Check::fail("File integrity", "skipped (no manifest)"));
    }

    // 3. Directory structure completeness.
    let required_dirs = ["campaign", "results", "adversarial", "integrity"];
    let mut dirs_present = 0;
    for dir_name in &required_dirs {
        if args.path.join(dir_name).is_dir() {
            dirs_present += 1;
        }
    }
    if dirs_present == required_dirs.len() {
        checks.push(Check::pass(
            "Directory structure",
            format!(
                "{dirs_present}/{} required directories present",
                required_dirs.len()
            ),
        ));
    } else {
        checks.push(Check::fail(
            "Directory structure",
            format!(
                "{dirs_present}/{} required directories present",
                required_dirs.len()
            ),
        ));
    }

    // 4. Audit log presence.
    let audit_path = args.path.join("results").join("audit.jsonl");
    if audit_path.exists() {
        let size = std::fs::metadata(&audit_path).map(|m| m.len()).unwrap_or(0);
        let lines = std::fs::read_to_string(&audit_path)
            .map(|s| s.lines().filter(|l| !l.trim().is_empty()).count())
            .unwrap_or(0);
        checks.push(Check::pass(
            "Audit log",
            format!("{lines} entries, {size} bytes"),
        ));
    } else {
        checks.push(Check::fail("Audit log", "results/audit.jsonl missing"));
    }

    // 5. Summary statistics consistency.
    let summary_path = args.path.join("results").join("summary.json");
    if let Some(ref m) = manifest {
        let s = &m.summary;
        let total_ok = s.total_commands == s.commands_approved + s.commands_rejected;
        let escape_ok = s.violation_escapes == 0;
        if total_ok && escape_ok {
            checks.push(Check::pass(
                "Summary statistics",
                format!(
                    "{} commands ({} approved, {} rejected), 0 escapes",
                    s.total_commands, s.commands_approved, s.commands_rejected,
                ),
            ));
        } else if !total_ok {
            checks.push(Check::fail(
                "Summary statistics",
                format!(
                    "total {} != approved {} + rejected {}",
                    s.total_commands, s.commands_approved, s.commands_rejected,
                ),
            ));
        } else {
            checks.push(Check::fail(
                "Summary statistics",
                format!("{} violation escapes detected", s.violation_escapes),
            ));
        }
    } else if summary_path.exists() {
        checks.push(Check::pass(
            "Summary statistics",
            "present (no manifest to cross-check)",
        ));
    } else {
        checks.push(Check::fail(
            "Summary statistics",
            "results/summary.json missing",
        ));
    }

    // 6. Adversarial reports.
    let adversarial_dir = args.path.join("adversarial");
    if adversarial_dir.is_dir() {
        let count = std::fs::read_dir(&adversarial_dir)
            .map(|d| d.filter(|e| e.is_ok()).count())
            .unwrap_or(0);
        if count > 0 {
            checks.push(Check::pass(
                "Adversarial reports",
                format!("{count} report files"),
            ));
        } else {
            checks.push(Check::fail("Adversarial reports", "directory empty"));
        }
    } else {
        checks.push(Check::fail("Adversarial reports", "directory missing"));
    }

    // 7. Public keys.
    let keys_path = args.path.join("integrity").join("public_keys.json");
    if keys_path.exists() {
        checks.push(Check::pass("Public keys", "present"));
    } else {
        checks.push(Check::fail(
            "Public keys",
            "integrity/public_keys.json missing",
        ));
    }

    // 8. Binary hash.
    let binary_hash_path = args.path.join("integrity").join("binary_hash.txt");
    if let Some(ref m) = manifest {
        if binary_hash_path.exists() {
            let on_disk = std::fs::read_to_string(&binary_hash_path).unwrap_or_default();
            if on_disk.trim() == m.binary_hash {
                checks.push(Check::pass(
                    "Binary hash",
                    format!(
                        "matches manifest ({})",
                        &m.binary_hash[..20.min(m.binary_hash.len())]
                    ),
                ));
            } else {
                checks.push(Check::fail(
                    "Binary hash",
                    "integrity/binary_hash.txt does not match manifest",
                ));
            }
        } else {
            checks.push(Check::fail(
                "Binary hash",
                "integrity/binary_hash.txt missing",
            ));
        }
    } else if binary_hash_path.exists() {
        checks.push(Check::pass(
            "Binary hash",
            "present (no manifest to cross-check)",
        ));
    } else {
        checks.push(Check::fail(
            "Binary hash",
            "integrity/binary_hash.txt missing",
        ));
    }

    // 9. Merkle root from audit log (RFC 6962 — v11 1.3). The legacy
    //    `replication::merkle_root_from_log` helper computes a different,
    //    non-domain-separated root and is kept around only for v0 witness
    //    compatibility; the proof-package writer (v11 1.4 / 1.5) uses the
    //    RFC 6962 implementation in `invariant_core::merkle`, so the
    //    verifier must mirror it.
    if audit_path.exists() {
        match std::fs::read_to_string(&audit_path) {
            Ok(content) if !content.trim().is_empty() => {
                if let Some(root) = rfc6962_root_from_log(&content) {
                    let merkle_path = args.path.join("integrity").join("merkle_root.txt");
                    if merkle_path.exists() {
                        let on_disk = std::fs::read_to_string(&merkle_path).unwrap_or_default();
                        if on_disk.trim() == root {
                            checks.push(Check::pass(
                                "Merkle root",
                                "computed root matches integrity/merkle_root.txt",
                            ));
                        } else {
                            checks.push(Check::fail(
                                "Merkle root",
                                "computed root does NOT match integrity/merkle_root.txt",
                            ));
                        }
                    } else {
                        checks.push(Check::pass(
                            "Merkle root",
                            format!("computed: {}...", &root[..20.min(root.len())]),
                        ));
                    }
                } else {
                    checks.push(Check::pass("Merkle root", "no entries to hash"));
                }
            }
            _ => {
                checks.push(Check::pass("Merkle root", "audit log empty, skipped"));
            }
        }
    }

    // Print results.
    println!();
    let passed = checks.iter().filter(|c| c.passed).count();
    let total = checks.len();

    for check in &checks {
        let symbol = if check.passed { "\u{2713}" } else { "\u{2717}" };
        println!("  {symbol} {}: {}", check.name, check.detail);
    }

    println!();
    if passed == total {
        println!("PACKAGE VERIFIED. {passed}/{total} checks passed.");
        0
    } else {
        let failed = total - passed;
        println!("PACKAGE VERIFICATION FAILED. {passed}/{total} checks passed, {failed} failed.");
        1
    }
}

/// Recompute the RFC 6962 Merkle root over a newline-framed audit log by
/// streaming each entry's `entry_hash` through [`MerkleAccumulator`]
/// exactly as `assemble` / `audit verify --merkle-root` do. Returns
/// `None` only when the log contains no parseable entries.
fn rfc6962_root_from_log(jsonl: &str) -> Option<String> {
    use invariant_core::merkle::{leaf_hash, MerkleAccumulator};
    let mut acc = MerkleAccumulator::new();
    let mut any = false;
    for line in jsonl.lines() {
        if line.trim().is_empty() {
            continue;
        }
        let value: serde_json::Value = serde_json::from_str(line).ok()?;
        let entry_hash = value.get("entry_hash").and_then(|v| v.as_str())?;
        acc.push_leaf_hash(leaf_hash(entry_hash.as_bytes()));
        any = true;
    }
    if !any {
        return None;
    }
    let root = acc.root();
    let mut hex = String::with_capacity(64);
    for b in root {
        hex.push_str(&format!("{b:02x}"));
    }
    Some(hex)
}

/// Verify SHA-256 hashes of all files listed in the manifest.
/// Returns (files_ok, files_failed).
fn verify_file_hashes(base: &std::path::Path, manifest: &ProofPackageManifest) -> (usize, usize) {
    let mut ok = 0usize;
    let mut failed = 0usize;

    for (rel_path, expected_hash) in &manifest.file_hashes {
        let full_path = base.join(rel_path);
        match std::fs::read(&full_path) {
            Ok(bytes) => {
                let actual = sha256_hex(&bytes);
                if actual == *expected_hash {
                    ok += 1;
                } else {
                    eprintln!(
                        "  hash mismatch: {rel_path} (expected {}, got {})",
                        &expected_hash[..20.min(expected_hash.len())],
                        &actual[..20.min(actual.len())]
                    );
                    failed += 1;
                }
            }
            Err(_) => {
                eprintln!("  missing file: {rel_path}");
                failed += 1;
            }
        }
    }

    (ok, failed)
}

#[cfg(test)]
mod tests {
    use super::*;
    use invariant_robotics::proof_package::{assemble, CampaignSummary, PackageInputs};
    use std::collections::HashMap;

    #[test]
    fn nonexistent_dir_returns_2() {
        let args = VerifyPackageArgs {
            path: PathBuf::from("/nonexistent/package"),
        };
        assert_eq!(run(&args), 2);
    }

    #[test]
    fn empty_dir_returns_1() {
        let dir = tempfile::tempdir().unwrap();
        let args = VerifyPackageArgs {
            path: dir.path().to_path_buf(),
        };
        assert_eq!(run(&args), 1);
    }

    #[test]
    fn assembled_package_verifies_successfully() {
        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("proof-package");

        // Create a fake audit log.
        let audit_path = dir.path().join("audit.jsonl");
        std::fs::write(&audit_path, "{\"entry\":1}\n{\"entry\":2}\n").unwrap();

        // Create a fake adversarial report.
        let adv_path = dir.path().join("protocol_report.json");
        std::fs::write(&adv_path, r#"{"attacks":100,"escapes":0}"#).unwrap();

        // Create fake public keys.
        let keys_path = dir.path().join("public_keys.json");
        std::fs::write(&keys_path, r#"{"keys":[]}"#).unwrap();

        let summary = CampaignSummary::compute(1000, 950, 50, 0, 100, 0, 100.0);

        let mut adversarial = HashMap::new();
        adversarial.insert("protocol_report.json".into(), adv_path);

        let inputs = PackageInputs {
            campaign_config: None,
            profile: None,
            audit_log: Some(audit_path),
            adversarial_reports: adversarial,
            compliance_mappings: HashMap::new(),
            public_keys: Some(keys_path),
            campaign_name: "verify_test".into(),
            profile_name: "test_robot".into(),
            binary_hash: "sha256:abc123".into(),
            summary,
            merkle_root_hex: None,
            signing_key: None,
        };

        assemble(&inputs, &output).unwrap();

        let args = VerifyPackageArgs {
            path: output.clone(),
        };
        assert_eq!(
            run(&args),
            0,
            "assembled package should verify successfully"
        );
    }

    #[test]
    fn tampered_file_fails_hash_check() {
        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("proof-package");

        let summary = CampaignSummary::compute(100, 90, 10, 0, 0, 0, 100.0);

        let inputs = PackageInputs {
            campaign_config: None,
            profile: None,
            audit_log: None,
            adversarial_reports: HashMap::new(),
            compliance_mappings: HashMap::new(),
            public_keys: None,
            campaign_name: "tamper_test".into(),
            profile_name: "test".into(),
            binary_hash: "sha256:original".into(),
            summary,
            merkle_root_hex: None,
            signing_key: None,
        };

        assemble(&inputs, &output).unwrap();

        // Tamper with the summary file.
        let summary_path = output.join("results/summary.json");
        std::fs::write(&summary_path, r#"{"tampered": true}"#).unwrap();

        let args = VerifyPackageArgs {
            path: output.clone(),
        };
        // Should fail because summary.json hash no longer matches manifest.
        assert_eq!(run(&args), 1);
    }

    #[test]
    fn package_with_escapes_fails_summary_check() {
        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("proof-package");

        // Summary with escapes.
        let summary = CampaignSummary::compute(1000, 950, 50, 3, 100, 2, 100.0);

        let inputs = PackageInputs {
            campaign_config: None,
            profile: None,
            audit_log: None,
            adversarial_reports: HashMap::new(),
            compliance_mappings: HashMap::new(),
            public_keys: None,
            campaign_name: "escape_test".into(),
            profile_name: "test".into(),
            binary_hash: "sha256:abc".into(),
            summary,
            merkle_root_hex: None,
            signing_key: None,
        };

        assemble(&inputs, &output).unwrap();

        let args = VerifyPackageArgs {
            path: output.clone(),
        };
        // Should fail because violation_escapes > 0.
        assert_eq!(run(&args), 1);
    }

    #[test]
    fn verify_file_hashes_detects_mismatch() {
        let dir = tempfile::tempdir().unwrap();
        let base = dir.path();

        std::fs::create_dir_all(base.join("results")).unwrap();
        std::fs::write(base.join("results/test.txt"), "original").unwrap();

        let correct_hash = sha256_hex(b"original");
        let mut file_hashes = HashMap::new();
        file_hashes.insert("results/test.txt".into(), correct_hash);

        let manifest = ProofPackageManifest {
            format_version: invariant_robotics::proof_package::CURRENT_FORMAT_VERSION,
            version: "1.0.0".into(),
            generated_at: chrono::Utc::now(),
            campaign_name: "test".into(),
            profile_name: "test".into(),
            profile_hash: String::new(),
            binary_hash: String::new(),
            invariant_version: "0.1.0".into(),
            summary: CampaignSummary::compute(0, 0, 0, 0, 0, 0, 100.0),
            file_hashes,
            merkle_root: None,
            manifest_signature: None,
            manifest_signer_kid: None,
        };

        // Before tampering: should pass.
        let (ok, fail) = verify_file_hashes(base, &manifest);
        assert_eq!(ok, 1);
        assert_eq!(fail, 0);

        // After tampering: should fail.
        std::fs::write(base.join("results/test.txt"), "tampered").unwrap();
        let (ok, fail) = verify_file_hashes(base, &manifest);
        assert_eq!(ok, 0);
        assert_eq!(fail, 1);
    }
}