diff --git a/crates/roads/tests/least_privilege.rs b/crates/roads/tests/least_privilege.rs index 5aa7114..b289c2d 100644 --- a/crates/roads/tests/least_privilege.rs +++ b/crates/roads/tests/least_privilege.rs @@ -15,6 +15,12 @@ //! sending side is exactly what a road names (no supernet, QA R-02); every firewall source sits on its own //! peer as a /32 (no spoofing, QA R-10); invalid and expired roads change no byte; removing a road or moving //! `now` forward never adds a rule (P-3, P-4); `explain` agrees with the firewall (P-7). +//! +//! IPv6 (QA F-10): the oracle works in `u32`, so IPv6 is checked by embedding instead. P-6v6 writes the same +//! world with every IPv4 address `a` replaced by `fd00::a` and every prefix `/L` by `/(L+96)` (the default +//! route by `::/0`), compiles both, maps the IPv4 plans through the same embedding and requires them to be +//! equal to the IPv6 plans: so every IPv6 path (`/128` hosts, nesting, overlap, `except`, exits, the kill +//! switch) behaves exactly like the IPv4 one that P-1 checks against the oracle, plus the same problems. use jiff::{SignedDuration, Timestamp as Instant}; use proptest::prelude::*; @@ -249,6 +255,13 @@ fn ports_text(p: &[(&str, u16, u16)]) -> String { /// The world as store bytes, written here without the library's writer. fn to_store(w: &World, roads: &[(usize, &R)], when: Instant) -> Store { + let (files, directory, devices) = store_parts(w, roads, when); + Store::from_parts(&files, Some(directory.as_bytes()), Some(devices.as_bytes())) +} + +type Parts = (Vec<(String, Vec)>, String, String); + +fn store_parts(w: &World, roads: &[(usize, &R)], when: Instant) -> Parts { let people: Vec = (0..w.people) .map(|p| format!(r#"{{"id":"p{p}","name":"P{p}"}}"#)) .collect(); @@ -342,7 +355,87 @@ fn to_store(w: &World, roads: &[(usize, &R)], when: Instant) -> Store { }) .collect(); let _ = when; - Store::from_parts(&files, Some(directory.as_bytes()), Some(devices.as_bytes())) + (files, directory, devices) +} + +// ------------------------------------------------------------------ IPv6 by embedding (QA F-10) + +fn v6_of(a: std::net::Ipv4Addr) -> std::net::Ipv6Addr { + std::net::Ipv6Addr::from(0xfd00_u128 << 112 | u32::from(a) as u128) +} + +/// One IPv4 address or network, embedded; anything else unchanged. +fn embed_token(t: &str) -> Option { + let (a, len) = match t.split_once('/') { + Some((a, l)) => (a, Some(l.parse::().ok().filter(|l| *l <= 32)?)), + None => (t, None), + }; + let a: std::net::Ipv4Addr = a.parse().ok()?; + if a.to_string() != t.split('/').next().unwrap() { + return None; + } + Some(match len { + None => v6_of(a).to_string(), + Some(0) if a.is_unspecified() => "::/0".to_string(), + Some(l) => format!("{}/{}", v6_of(a), l + 96), + }) +} + +/// Replaces every IPv4 address or network in `text` (a maximal run of digits, dots and one slash). +fn embed_text(text: &str) -> String { + let mut out = String::new(); + let mut run = String::new(); + let flush = |run: &mut String, out: &mut String| { + out.push_str(&embed_token(run).unwrap_or_else(|| run.clone())); + run.clear(); + }; + for c in text.chars() { + if c.is_ascii_digit() || c == '.' || (c == '/' && !run.is_empty() && !run.contains('/')) { + run.push(c); + } else { + flush(&mut run, &mut out); + out.push(c); + } + } + flush(&mut run, &mut out); + out +} + +fn embed_parts((files, dir, devs): Parts) -> Parts { + ( + files + .into_iter() + .map(|(n, b)| (n, embed_text(&String::from_utf8(b).unwrap()).into_bytes())) + .collect(), + dir, + embed_text(&devs), + ) +} + +/// A plan as JSON with IPv4 embedded (when `embed`), the two default routes made one spelling, and every +/// list sorted, so plans of the two families compare. +fn normal(plan: &roads::Plan, embed: bool) -> serde_json::Value { + fn walk(v: &mut serde_json::Value, embed: bool) { + match v { + serde_json::Value::String(s) => { + // Raw blocks are free text: embed inside them too, as the store's text was. + if embed { + *s = embed_text(s); + } else if s == "0.0.0.0/0" { + *s = "::/0".into(); + } + } + serde_json::Value::Array(a) => { + a.iter_mut().for_each(|x| walk(x, embed)); + a.sort_by_key(|x| x.to_string()); + } + serde_json::Value::Object(m) => m.values_mut().for_each(|x| walk(x, embed)), + _ => {} + } + } + let mut v = serde_json::to_value(plan).unwrap(); + walk(&mut v, embed); + v } // ------------------------------------------------------------------ the oracle (no roads code) @@ -654,6 +747,31 @@ proptest! { } } +proptest! { + #![proptest_config(ProptestConfig { cases: 1_000, failure_persistence: None, .. ProptestConfig::default() })] + + #[test] + fn p6v6_ipv6_compiles_like_ipv4(bytes in proptest::collection::vec(any::(), 64..400)) { + CASES.fetch_add(1, Ordering::Relaxed); + let w = world(&bytes); + let all: Vec<(usize, &R)> = w.roads.iter().enumerate().collect(); + let v4 = store_parts(&w, &all, now()); + let v6 = embed_parts(v4.clone()); + prop_assert!(!v6.2.contains("\"100.96."), "the device list was not embedded"); + let s4 = Store::from_parts(&v4.0, Some(v4.1.as_bytes()), Some(v4.2.as_bytes())); + let s6 = Store::from_parts(&v6.0, Some(v6.1.as_bytes()), Some(v6.2.as_bytes())); + let (c4, c6) = (compile(&s4, now()), compile(&s6, now())); + prop_assert!(c6.has_plans(), "the IPv6 snapshots are valid: {:?}", c6.problems.iter().filter(|p| !p.path.starts_with("roads/")).collect::>()); + let key = |p: &roads::Problem| (p.path.clone(), p.field.clone(), p.code, p.severity); + let k4: BTreeSet<_> = c4.problems.iter().map(key).collect(); + let k6: BTreeSet<_> = c6.problems.iter().map(key).collect(); + prop_assert_eq!(k4, k6, "IPv4 and IPv6 report different problems"); + for (k, p4) in &c4.plans { + prop_assert_eq!(normal(p4, true), normal(&c6.plans[k], false), "{} compiles differently in IPv6", p4.name); + } + } +} + proptest! { #![proptest_config(ProptestConfig { cases: 500, failure_persistence: None, .. ProptestConfig::default() })]