Files
arcanum/tests/qa_consumer_api.rs
mnovak 6780abc0c2 fix: QA second review R2-01 to R2-05
R2-01: PublicKey::encapsulate, SecretKey::decapsulate and SharedSecret::as_bytes
are hazmat-only; release consumers reach keys only through exchange and seal.
R2-02: PublicKey::from_bytes refuses a non-canonical X25519 half (bit 255 set,
or a value of at least 2^255 - 19). Honest keys and the draft vectors pass.
R2-03: schedule::expand takes one static label and one fixed-width field, so
its info is injective by signature. v1 bytes unchanged (golden vectors pass).
R2-04: generate, initiate, respond and seal say the RNG must be the OS RNG.
R2-05: Initiation is ZeroizeOnDrop; seal's buffer stays Zeroizing until the
plaintext in it is encrypted, so the MessageTooLong path wipes it.
QA's A-33 case for PublicKey::encapsulate moves to exchange::respond, and its
A-08 test pins the new expand signature to the v1 encoding.
2026-11-25 08:37:11 +01:00

197 lines
8.7 KiB
Rust

//! QA second review (PR #1): what a **consumer** of Arcanum can and cannot write, checked by
//! compiling small programs against the crate with **default features**, as via-core and via will.
//!
//! The test suite itself always builds Arcanum with `hazmat` (the self-dev-dependency), so no
//! in-process test can see the release API. This one writes a throwaway crate under
//! `CARGO_TARGET_TMPDIR` that depends on Arcanum by path without features, and runs
//! `cargo check --offline` on it. A program that must not compile is a compile-fail test (QA A-33,
//! A-34); a control program proves the harness is not blind.
//!
//! Cases:
//! - control: the safe API (generate, mutual exchange, seal/open) compiles;
//! - A-33: an RNG that is `Rng` but not `CryptoRng` is refused by the type system;
//! - A-34: none of the deterministic `_derand` / `from_seed` entry points is reachable;
//! - QA-R2-01: the raw X-Wing shared secret must not be reachable without the key schedule.
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;
/// All cases share one crate (so the dependencies are checked once); they must not run at once.
static LOCK: Mutex<()> = Mutex::new(());
const PRELUDE: &str = r#"
#![allow(unused)]
use core::convert::Infallible;
use rand_core::{TryCryptoRng, TryRng};
/// A counter: deterministic, and therefore NOT a cryptographic RNG.
pub struct Counter(pub u64);
impl TryRng for Counter {
type Error = Infallible;
fn try_next_u32(&mut self) -> Result<u32, Infallible> { self.0 += 1; Ok(self.0 as u32) }
fn try_next_u64(&mut self) -> Result<u64, Infallible> { self.0 += 1; Ok(self.0) }
fn try_fill_bytes(&mut self, d: &mut [u8]) -> Result<(), Infallible> {
for b in d { self.0 += 1; *b = self.0 as u8; }
Ok(())
}
}
/// The same counter, *claiming* to be cryptographic (a stand-in for a real CSPRNG in the control).
pub struct Claimed(pub Counter);
impl TryRng for Claimed {
type Error = Infallible;
fn try_next_u32(&mut self) -> Result<u32, Infallible> { self.0.try_next_u32() }
fn try_next_u64(&mut self) -> Result<u64, Infallible> { self.0.try_next_u64() }
fn try_fill_bytes(&mut self, d: &mut [u8]) -> Result<(), Infallible> { self.0.try_fill_bytes(d) }
}
impl TryCryptoRng for Claimed {}
"#;
fn consumer_dir() -> PathBuf {
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("qa-consumer-api");
std::fs::create_dir_all(dir.join("src")).unwrap();
let arcanum = env!("CARGO_MANIFEST_DIR").replace('\\', "/");
let manifest = format!(
"[package]\nname = \"qa-consumer-api\"\nversion = \"0.0.0\"\nedition = \"2024\"\npublish = false\n\n\
[dependencies]\narcanum = {{ path = \"{arcanum}\" }}\n\
rand_core = {{ version = \"0.10\", default-features = false }}\n\n[workspace]\n"
);
std::fs::write(dir.join("Cargo.toml"), manifest).unwrap();
// Same dependency versions as Arcanum itself; cargo prunes what the consumer does not use.
if !dir.join("Cargo.lock").exists() {
std::fs::copy(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.lock"), dir.join("Cargo.lock")).unwrap();
}
dir
}
/// `cargo check` a consumer whose `main` body is `body`. Returns (compiled, compiler output).
fn check(body: &str) -> (bool, String) {
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = consumer_dir();
std::fs::write(dir.join("src/main.rs"), format!("{PRELUDE}\nfn main() {{\n{body}\n}}\n")).unwrap();
let out = Command::new(env!("CARGO"))
.current_dir(&dir)
.args(["check", "--offline", "--quiet", "--message-format", "short"])
.env_remove("CARGO_TARGET_DIR")
.output()
.expect("run cargo check");
(out.status.success(), String::from_utf8_lossy(&out.stderr).into_owned())
}
fn assert_compiles(what: &str, body: &str) {
let (ok, err) = check(body);
assert!(ok, "{what}: the control program must compile, or the harness is blind:\n{err}");
}
fn assert_refused(what: &str, body: &str, needles: &[&str]) {
let (ok, err) = check(body);
assert!(!ok, "{what}: compiled against Arcanum with default features, and must not");
assert!(
needles.iter().any(|n| err.contains(n)),
"{what}: refused, but not for the expected reason ({needles:?}):\n{err}"
);
}
#[test]
fn control_the_safe_api_compiles_without_hazmat() {
assert_compiles(
"control",
r#"
let mut rng = Claimed(Counter(0));
let a = arcanum::xwing::SecretKey::generate(&mut rng);
let b = arcanum::xwing::SecretKey::generate(&mut rng);
let init = arcanum::exchange::initiate(&a, b.public_key(), b"ctx", &mut rng).unwrap();
let (ct, rs) = arcanum::exchange::respond(&b, a.public_key(), init.ciphertext(), b"ctx", &mut rng).unwrap();
let is = init.finish(&ct).unwrap();
let _ = (is.wireguard_psk(1), rs.wireguard_psk(1));
let sealed = arcanum::seal::seal(b.public_key(), b"m", b"", &mut rng).unwrap();
let _ = arcanum::seal::open(&b, &sealed, b"").unwrap();
"#,
);
}
/// QA A-33: `R: CryptoRng`, not `R: Rng`. A counter is refused everywhere randomness enters.
#[test]
fn a33_a_non_crypto_rng_does_not_compile() {
let calls = [
("SecretKey::generate", "let _ = arcanum::xwing::SecretKey::generate(&mut Counter(0));"),
// Builder, with the R2-01 fix: `PublicKey::encapsulate` is hazmat-only now, so it no longer
// exists for a consumer (qa_r2_01 checks that). Its place is taken by the other release
// function that takes an RNG, `exchange::respond`.
(
"exchange::respond",
"let k = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
let ct = arcanum::xwing::Ciphertext::from_bytes(&[0; 1120]).unwrap(); \
let _ = arcanum::exchange::respond(&k, k.public_key(), &ct, b\"\", &mut Counter(0));",
),
(
"exchange::initiate",
"let k = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
let _ = arcanum::exchange::initiate(&k, k.public_key(), b\"\", &mut Counter(0));",
),
(
"seal::seal",
"let k = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
let _ = arcanum::seal::seal(k.public_key(), b\"\", b\"\", &mut Counter(0));",
),
];
for (what, body) in calls {
assert_refused(what, body, &["CryptoRng"]);
}
}
/// QA A-34: with default features, no deterministic entry point exists in the public API.
#[test]
fn a34_deterministic_entry_points_are_not_reachable_without_hazmat() {
let k = "let k = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap();";
let calls = [
("SecretKey::from_seed", "let _ = arcanum::xwing::SecretKey::from_seed([1; 32]);".to_string()),
("PublicKey::encapsulate_derand", format!("{k} let _ = k.public_key().encapsulate_derand(&[0; 64]);")),
(
"exchange::initiate_derand",
format!("{k} let _ = arcanum::exchange::initiate_derand(&k, k.public_key(), b\"\", &[0; 64]);"),
),
(
"exchange::respond_derand",
format!(
"{k} let ct = arcanum::xwing::Ciphertext::from_bytes(&[0; 1120]).unwrap(); \
let _ = arcanum::exchange::respond_derand(&k, k.public_key(), &ct, b\"\", &[0; 64]);"
),
),
(
"seal::seal_derand",
format!("{k} let _ = arcanum::seal::seal_derand(k.public_key(), b\"\", b\"\", &[0; 64]);"),
),
];
for (what, body) in calls {
// E0425: no such function; E0599: no such method or associated function.
assert_refused(what, &body, &["E0425", "E0599"]);
}
}
/// QA-R2-01 (major): a release consumer can take the raw X-Wing shared secret of a **one-way**
/// encapsulation and use it as a key, skipping the mutual exchange, the transcript, the context
/// and the `domi/arcanum/v1` labels. That is exactly the single-direction PSK that QA A-15 (and the
/// crate's own `exchange` docs) say lets a quantum attacker who impersonates the initiator choose
/// the responder's PSK. Fails while `PublicKey::encapsulate` / `SecretKey::decapsulate` hand out a
/// `SharedSecret` whose bytes are public without `hazmat`.
#[test]
fn qa_r2_01_raw_shared_secret_is_not_reachable_without_hazmat() {
let (ok, err) = check(
r#"
let mut rng = Claimed(Counter(0));
let peer = arcanum::xwing::SecretKey::generate(&mut rng);
let (_ct, ss) = peer.public_key().encapsulate(&mut rng).unwrap();
let one_way_psk: [u8; 32] = *ss.as_bytes();
let _ = one_way_psk;
"#,
);
assert!(
!ok,
"the raw one-way X-Wing secret is reachable in a release build: \
`PublicKey::encapsulate(..).1.as_bytes()` compiles without `hazmat`"
);
let _ = err;
}