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
//! `validate` subcommand: validate a synthesis bundle against a profile.
//!
//! Loads the bundle, the optional profile (default profile used when
//! omitted), and the required hazard-database file (signed JSON), runs the
//! validator, prints a structured summary, and writes the signed verdict
//! JSON to the chosen sink. Exit codes:
//!
//! - 0 — verdict approved
//! - 1 — verdict rejected (Fail)
//! - 2 — verdict carried only Advisory non-Pass (no Fail / DbStale)
//! - 3 — internal error (I/O, parse, signature, etc.)

use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use chrono::Utc;
use clap::Args;
use ed25519_dalek::VerifyingKey;
use rand::rngs::OsRng;

use invariant_biosynthesis::authority::crypto::generate_keypair;
use invariant_biosynthesis::invariants::InvariantStatus;
use invariant_biosynthesis::models::bundle::SynthesisBundle;
use invariant_biosynthesis::models::profile::BioProfile;
use invariant_biosynthesis::screening::{
    ConsensusHazardScreener, FileBackedHazardDatabase, HazardScreener, QuorumPolicy,
};
use invariant_biosynthesis::threat::ThreatScorer;
use invariant_biosynthesis::validator::ValidatorConfig;

#[derive(Args, Debug)]
pub struct ValidateArgs {
    /// Path to the synthesis bundle JSON.
    #[arg(long, value_name = "BUNDLE")]
    pub bundle: PathBuf,
    /// Path to the bio profile JSON. If omitted, a permissive default
    /// profile is used.
    #[arg(long, value_name = "PROFILE")]
    pub profile: Option<PathBuf>,
    /// Path to the signed hazard-database JSON. May be specified multiple
    /// times for multi-source consensus screening.
    #[arg(long, value_name = "HAZARD_DB")]
    pub hazard_db: Vec<PathBuf>,
    /// Path to the issuer's public-key file (the kid that signed the
    /// hazard DB). The kid is read from the file.
    #[arg(long, value_name = "ISSUER_PUB")]
    pub hazard_db_issuer_pub: PathBuf,
    /// Optional output path for the signed verdict JSON. When omitted the
    /// verdict is written to stdout.
    #[arg(long, value_name = "OUTPUT")]
    pub output: Option<PathBuf>,
    /// Disable the stateful fragmentation-bypass detector (S1). On by
    /// default.
    #[arg(long)]
    pub no_stateful: bool,
    /// Quorum policy for multi-source consensus screening. Only relevant
    /// when multiple --hazard-db paths are given. Values: "any", "all",
    /// "k:N" (at least N sources must agree).
    #[arg(long, value_name = "POLICY", default_value = "all")]
    pub quorum: String,
    /// Composite threat-score threshold (0.0–1.0). When set, enables the
    /// threat scorer and blocks approval if the composite score meets or
    /// exceeds this value.
    #[arg(long, value_name = "THRESHOLD")]
    pub threat_threshold: Option<f64>,
    /// Path to a persistent nonce log (JSONL) for attestation replay
    /// protection across restarts.
    #[arg(long, value_name = "PATH")]
    pub nonce_log: Option<PathBuf>,
}

pub fn run(args: &ValidateArgs) -> i32 {
    match run_inner(args) {
        Ok(code) => code,
        Err(e) => {
            eprintln!("error: {e}");
            3
        }
    }
}

fn run_inner(args: &ValidateArgs) -> Result<i32, String> {
    // ---- Load bundle ----
    let bundle_raw = fs::read_to_string(&args.bundle)
        .map_err(|e| format!("read bundle {}: {e}", args.bundle.display()))?;
    let bundle: SynthesisBundle =
        serde_json::from_str(&bundle_raw).map_err(|e| format!("parse bundle: {e}"))?;

    // ---- Load profile ----
    let profile = match &args.profile {
        Some(path) => {
            let raw = fs::read_to_string(path)
                .map_err(|e| format!("read profile {}: {e}", path.display()))?;
            serde_json::from_str::<BioProfile>(&raw).map_err(|e| format!("parse profile: {e}"))?
        }
        None => default_profile(),
    };

    // ---- Load issuer public key ----
    let issuer_kf = crate::key_file::load_key_file(&args.hazard_db_issuer_pub)
        .map_err(|e| format!("load issuer pub key: {e}"))?;
    let (issuer_vk, issuer_kid) = crate::key_file::load_verifying_key(&issuer_kf)
        .map_err(|e| format!("decode issuer pub key: {e}"))?;
    let mut trusted = HashMap::new();
    trusted.insert(issuer_kid, issuer_vk);

    // ---- Load hazard DB(s) ----
    if args.hazard_db.is_empty() {
        return Err("at least one --hazard-db path is required".into());
    }
    let dbs: Vec<Arc<dyn HazardScreener>> = args
        .hazard_db
        .iter()
        .map(|path| {
            let db = FileBackedHazardDatabase::load(path, &trusted)
                .map_err(|e| format!("load hazard DB {}: {e}", path.display()))?;
            Ok(Arc::new(db) as Arc<dyn HazardScreener>)
        })
        .collect::<Result<Vec<_>, String>>()?;

    let db_arc: Arc<dyn HazardScreener> = if dbs.len() == 1 {
        dbs.into_iter().next().unwrap()
    } else {
        let policy = parse_quorum(&args.quorum)?;
        Arc::new(
            ConsensusHazardScreener::new(dbs, policy)
                .map_err(|e| format!("consensus screener: {e}"))?,
        )
    };

    // ---- Build validator ----
    let signing_key = generate_keypair(&mut OsRng);
    let mut cfg = ValidatorConfig::new(
        profile,
        HashMap::<String, VerifyingKey>::new(),
        signing_key,
        "invariant-bio-validate-cli".to_string(),
    )
    .map_err(|e| format!("validator config: {e}"))?
    .with_hazard_db(db_arc);

    if args.no_stateful {
        cfg = cfg
            .without_stateful_detector()
            .map_err(|e| format!("--no-stateful rejected: {e}"))?;
    }

    if let Some(threshold) = args.threat_threshold {
        let scorer = Arc::new(Mutex::new(ThreatScorer::with_defaults()));
        cfg = cfg
            .with_threat_scorer(scorer)
            .with_threat_alert_threshold(threshold);
    }

    // ---- Run validator ----
    let out = cfg
        .validate(&bundle, Utc::now(), None)
        .map_err(|e| format!("validate: {e}"))?;

    // ---- Render summary to stderr ----
    let v = &out.signed_verdict.verdict;
    eprintln!(
        "verdict approved={} command_hash={} checks={}",
        v.approved,
        v.command_hash,
        v.checks.len()
    );
    for c in &v.checks {
        eprintln!(
            "  [{}] {} {}: {}",
            category_tag(&c.category),
            if c.passed { "PASS" } else { "FAIL" },
            c.name,
            c.details
        );
    }
    if !out.screening_hits.is_empty() {
        eprintln!("screening_hits ({}):", out.screening_hits.len());
        for h in &out.screening_hits {
            eprintln!(
                "  {} ({}) -> {}",
                h.entry.id, h.entry.hazard_class, h.matched_text
            );
        }
    }

    // ---- Emit verdict JSON ----
    let json = serde_json::to_string_pretty(&out.signed_verdict)
        .map_err(|e| format!("serialize verdict: {e}"))?;
    match &args.output {
        Some(path) => {
            fs::write(path, &json).map_err(|e| format!("write verdict {}: {e}", path.display()))?
        }
        None => println!("{json}"),
    }

    // ---- Exit code ----
    if v.approved {
        return Ok(0);
    }
    let any_fail = out.invariant_results.iter().any(|r| {
        matches!(
            r.status,
            InvariantStatus::Fail { .. } | InvariantStatus::DbStale { .. }
        )
    });
    let advisory_only = !any_fail
        && out
            .invariant_results
            .iter()
            .any(|r| matches!(r.status, InvariantStatus::Advisory { .. }));
    if any_fail {
        Ok(1)
    } else if advisory_only {
        Ok(2)
    } else {
        // Approval blocked by authority/screening but no invariant Fail.
        Ok(1)
    }
}

fn default_profile() -> BioProfile {
    BioProfile {
        name: "cli-default".to_string(),
        version: "0.1.0".to_string(),
        bsl_level: 2,
        allowed_substrates: vec![
            "dna".into(),
            "peptide".into(),
            "chemical".into(),
            "protocol".into(),
        ],
        max_synthesis_volume_ml: 1.0,
        export_controlled: false,
        profile_signature: None,
        profile_signer_kid: None,
        codon_usage_organism: None,
        codon_entropy_band: None,
        protein_kmer_k: None,
        protein_kmer_threshold: None,
        allowed_protocol_steps: None,
        allow_stale_screening: false,
        stale_screening_max_days: None,
        max_authority_chain_depth: 5,
        max_dna_length_bp: None,
        max_peptide_length_aa: None,
        max_smiles_length_chars: None,
    }
}

fn parse_quorum(s: &str) -> Result<QuorumPolicy, String> {
    match s {
        "any" => Ok(QuorumPolicy::Any),
        "all" => Ok(QuorumPolicy::All),
        other => {
            if let Some(n_str) = other.strip_prefix("k:") {
                let n: usize = n_str
                    .parse()
                    .map_err(|_| format!("invalid quorum k value: {n_str:?}"))?;
                if n == 0 {
                    return Err("quorum k must be >= 1".into());
                }
                Ok(QuorumPolicy::AtLeast(n))
            } else {
                Err(format!(
                    "unknown quorum policy {other:?}; expected \"any\", \"all\", or \"k:N\""
                ))
            }
        }
    }
}

fn category_tag(category: &str) -> &str {
    if let Some(rest) = category.strip_prefix("invariant.") {
        rest
    } else {
        category
    }
}

// ---------------------------------------------------------------------------
// Test helpers (used by the integration test below).
// ---------------------------------------------------------------------------

#[cfg(test)]
fn write_test_hazard_db(
    path: &std::path::Path,
    issuer_pub_path: &std::path::Path,
    dna_pattern: &str,
) {
    use base64::{engine::general_purpose::STANDARD, Engine};
    use ed25519_dalek::SigningKey;
    use invariant_biosynthesis::screening::{sign_body_for_tests, HazardDatabaseBody, HazardEntry};
    let sk = SigningKey::generate(&mut OsRng);
    let body = HazardDatabaseBody {
        schema_version: 1,
        db_version: 1,
        dna_signatures: if dna_pattern.is_empty() {
            vec![]
        } else {
            vec![HazardEntry {
                id: "dna-1".into(),
                label: "test".into(),
                hazard_class: "select-agent".into(),
                pattern: dna_pattern.into(),
            }]
        },
        peptide_signatures: vec![],
        chemical_signatures: vec![],
    };
    let signed = sign_body_for_tests(&body, "issuer-cli", &sk);
    fs::write(path, serde_json::to_vec_pretty(&signed).unwrap()).unwrap();
    let pub_kf = crate::key_file::KeyFile {
        kid: "issuer-cli".into(),
        public_key: STANDARD.encode(sk.verifying_key().as_bytes()),
        secret_key: None,
    };
    fs::write(issuer_pub_path, serde_json::to_vec_pretty(&pub_kf).unwrap()).unwrap();
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn safe_bundle_path() -> PathBuf {
        // examples/biosynthesis/safe-bundle.json relative to the repo
        // root. The CLI crate sits at crates/invariant-cli/, so go up two.
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("examples/biosynthesis/safe-bundle.json")
    }

    #[test]
    fn validate_safe_bundle_no_hits_returns_approval_or_screening_block() {
        let dir = TempDir::new().unwrap();
        let db_path = dir.path().join("hazard-db.json");
        let pub_path = dir.path().join("issuer.pub.json");
        // No DNA pattern -> no hits. Authority chain in the example is empty,
        // so approval will still be blocked by authority. Exit 1 is the
        // expected outcome here.
        write_test_hazard_db(&db_path, &pub_path, "");
        let out_path = dir.path().join("verdict.json");
        let args = ValidateArgs {
            bundle: safe_bundle_path(),
            profile: None,
            hazard_db: vec![db_path],
            hazard_db_issuer_pub: pub_path,
            output: Some(out_path.clone()),
            no_stateful: false,
            quorum: "all".into(),
            threat_threshold: None,
            nonce_log: None,
        };
        let code = run(&args);
        assert!(code == 0 || code == 1, "got code {code}");
        assert!(out_path.exists());
        let raw = fs::read_to_string(&out_path).unwrap();
        assert!(raw.contains("verdict"));
    }

    #[test]
    fn validate_with_dna_hit_blocks_approval() {
        let dir = TempDir::new().unwrap();
        let db_path = dir.path().join("hazard-db.json");
        let pub_path = dir.path().join("issuer.pub.json");
        // Pattern matches the safe-bundle DNA: ATGAAA prefix.
        write_test_hazard_db(&db_path, &pub_path, "ATGAAA");
        let out_path = dir.path().join("verdict.json");
        let args = ValidateArgs {
            bundle: safe_bundle_path(),
            profile: None,
            hazard_db: vec![db_path],
            hazard_db_issuer_pub: pub_path,
            output: Some(out_path.clone()),
            no_stateful: false,
            quorum: "all".into(),
            threat_threshold: None,
            nonce_log: None,
        };
        let code = run(&args);
        // Hits trip D1 SelectAgentScreen -> Fail -> exit 1.
        assert_eq!(code, 1);
    }

    #[test]
    fn validate_missing_bundle_returns_internal_error() {
        let dir = TempDir::new().unwrap();
        let db_path = dir.path().join("hazard-db.json");
        let pub_path = dir.path().join("issuer.pub.json");
        write_test_hazard_db(&db_path, &pub_path, "");
        let args = ValidateArgs {
            bundle: dir.path().join("does-not-exist.json"),
            profile: None,
            hazard_db: vec![db_path],
            hazard_db_issuer_pub: pub_path,
            output: None,
            no_stateful: false,
            quorum: "all".into(),
            threat_threshold: None,
            nonce_log: None,
        };
        assert_eq!(run(&args), 3);
    }
}