[domistream] Tests: sans-I/O guard and secret hygiene
Fails if src/ uses std::net, Instant::now, SystemTime::now, std::thread, std::fs, processes, env reads or OS randomness (comments stripped, grouped std imports caught). Checks forbid(unsafe_code) and that Debug never prints rikey, the PIN or the private key.
This commit is contained in:
@@ -0,0 +1,258 @@
|
||||
//! Repository rules that are checked by reading the crate itself: the sans-I/O guard (no sockets, clocks,
|
||||
//! threads, files or OS randomness in `src/`), `forbid(unsafe_code)`, and that `Debug` never prints a secret.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||
|
||||
mod common;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Things `src/` must never contain outside comments (CLAUDE.md "Sans-I/O"). The left side is matched with all
|
||||
/// whitespace removed, so `std :: net` and `use std::{fs, net}` are caught too.
|
||||
const FORBIDDEN: &[(&str, &str)] = &[
|
||||
("std::net", "sockets"),
|
||||
("Instant::now", "clock reads"),
|
||||
("SystemTime::now", "clock reads"),
|
||||
("std::time::Instant", "the std clock type (use crate::Instant)"),
|
||||
("std::time::SystemTime", "the std clock type"),
|
||||
("UNIX_EPOCH", "clock reads"),
|
||||
("std::thread", "threads"),
|
||||
("thread::spawn", "threads"),
|
||||
("std::fs", "files"),
|
||||
("File::open", "files"),
|
||||
("File::create", "files"),
|
||||
("std::process", "processes"),
|
||||
("std::env::var", "environment reads"),
|
||||
("OsRng", "OS randomness (randomness comes in through RandomSource)"),
|
||||
("thread_rng", "OS randomness"),
|
||||
("getrandom", "OS randomness"),
|
||||
("rand::random", "OS randomness"),
|
||||
("tokio", "async runtimes"),
|
||||
("mio::", "async runtimes"),
|
||||
];
|
||||
|
||||
/// Grouped imports `use std::{…}` naming a forbidden module.
|
||||
const FORBIDDEN_IN_STD_GROUP: &[&str] = &["net", "fs", "thread", "process"];
|
||||
|
||||
fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
for entry in std::fs::read_dir(dir).expect("read src dir") {
|
||||
let path = entry.expect("dir entry").path();
|
||||
if path.is_dir() {
|
||||
rust_files(&path, out);
|
||||
} else if path.extension().is_some_and(|e| e == "rs") {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The code of a file with `//` comments (line and doc comments) and `/* */` comments removed. String literals are
|
||||
/// kept: a forbidden name inside a string still fails, on purpose.
|
||||
fn strip_comments(src: &str) -> String {
|
||||
let mut out = String::with_capacity(src.len());
|
||||
let mut chars = src.chars().peekable();
|
||||
let mut in_str = false;
|
||||
while let Some(c) = chars.next() {
|
||||
if in_str {
|
||||
out.push(c);
|
||||
if c == '\\' {
|
||||
if let Some(n) = chars.next() {
|
||||
out.push(n);
|
||||
}
|
||||
} else if c == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match (c, chars.peek()) {
|
||||
('"', _) => {
|
||||
in_str = true;
|
||||
out.push(c);
|
||||
}
|
||||
('/', Some('/')) => {
|
||||
for n in chars.by_ref() {
|
||||
if n == '\n' {
|
||||
out.push('\n');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
('/', Some('*')) => {
|
||||
chars.next();
|
||||
let mut prev = ' ';
|
||||
for n in chars.by_ref() {
|
||||
if prev == '*' && n == '/' {
|
||||
break;
|
||||
}
|
||||
prev = n;
|
||||
}
|
||||
}
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn violations_in(code: &str) -> Vec<String> {
|
||||
let squashed: String = code.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
let mut found = Vec::new();
|
||||
for (needle, why) in FORBIDDEN {
|
||||
if squashed.contains(needle) {
|
||||
found.push(format!("`{needle}` ({why})"));
|
||||
}
|
||||
}
|
||||
let mut rest = squashed.as_str();
|
||||
while let Some(i) = rest.find("std::{") {
|
||||
let group = &rest[i + 6..];
|
||||
let end = group.find('}').unwrap_or(group.len());
|
||||
for item in group[..end].split(',') {
|
||||
let head = item.split("::").next().unwrap_or("");
|
||||
if FORBIDDEN_IN_STD_GROUP.contains(&head) {
|
||||
found.push(format!("`std::{{{head}}}` (grouped import)"));
|
||||
}
|
||||
}
|
||||
rest = &group[end.min(group.len())..];
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn src_is_sans_io() {
|
||||
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||
let mut files = Vec::new();
|
||||
rust_files(&src, &mut files);
|
||||
assert!(files.len() >= 20, "expected the whole crate under {}", src.display());
|
||||
let mut report = Vec::new();
|
||||
for file in &files {
|
||||
let code = strip_comments(&std::fs::read_to_string(file).expect("read source"));
|
||||
for v in violations_in(&code) {
|
||||
report.push(format!("{}: {v}", file.strip_prefix(&src).unwrap_or(file).display()));
|
||||
}
|
||||
}
|
||||
assert!(report.is_empty(), "sans-I/O rule broken:\n{}", report.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guard_catches_what_it_should() {
|
||||
// The guard itself must work, or `src_is_sans_io` proves nothing.
|
||||
for bad in [
|
||||
"use std::net::UdpSocket;",
|
||||
"let t = std::time::Instant::now();",
|
||||
"let t = Instant :: now();",
|
||||
"let t = SystemTime::now();",
|
||||
"std::thread::spawn(|| {});",
|
||||
"let f = std::fs::read(\"x\");",
|
||||
"use std::{fs, io};",
|
||||
"use std::{io, net::TcpStream};",
|
||||
"let mut r = rand::rngs::OsRng;",
|
||||
"getrandom::fill(&mut b);",
|
||||
] {
|
||||
assert!(!violations_in(&strip_comments(bad)).is_empty(), "guard missed: {bad}");
|
||||
}
|
||||
for fine in [
|
||||
"// no std::net here, only a comment",
|
||||
"/// Docs may say Instant::now is forbidden.",
|
||||
"/* std::fs in a block comment */ let x = 1;",
|
||||
"use crate::Instant; let t = Instant::from_micros(5);",
|
||||
"use std::{fmt, error};",
|
||||
"use core::time::Duration;",
|
||||
] {
|
||||
assert!(violations_in(&strip_comments(fine)).is_empty(), "guard flagged: {fine}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_module_forbids_unsafe() {
|
||||
let lib = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/lib.rs")).expect("lib.rs");
|
||||
assert!(lib.contains("#![forbid(unsafe_code)]"), "lib.rs must carry #![forbid(unsafe_code)]");
|
||||
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||
let mut files = Vec::new();
|
||||
rust_files(&src, &mut files);
|
||||
for file in files {
|
||||
let code = strip_comments(&std::fs::read_to_string(&file).expect("read"));
|
||||
assert_eq!(
|
||||
code.matches("unsafe").count(),
|
||||
code.matches("unsafe_code").count(),
|
||||
"{}: `unsafe` in src",
|
||||
file.display()
|
||||
);
|
||||
assert!(!code.contains("allow(unsafe_code)"), "{}: unsafe allowed", file.display());
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ secrets
|
||||
|
||||
const KEY: [u8; 16] = [0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6, 0x17, 0x28, 0x39, 0x4A, 0x5B, 0x6C, 0x7D, 0x8E, 0x9F, 0x10];
|
||||
|
||||
/// Every way the key could show up in a `Debug` string.
|
||||
fn leaks_key(s: &str) -> bool {
|
||||
let lower = s.to_lowercase();
|
||||
lower.contains(&common::to_hex(&KEY))
|
||||
|| lower.contains("161, 178")
|
||||
|| lower.contains("0xa1, 0xb2")
|
||||
|| lower.contains("a1b2c3")
|
||||
|| s.contains("[161")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_never_prints_keys() {
|
||||
let keys = domistream::SessionKeys { rikey: KEY, rikeyid: 7 };
|
||||
let control = domistream::control::ControlCipher::new(KEY);
|
||||
let video = domistream::video::VideoCipher::new(KEY);
|
||||
let audio = domistream::audio::AudioCipher::new(&keys);
|
||||
let config = domistream::control::ControlConfig {
|
||||
enet: domistream::enet::EnetConfig {
|
||||
channel_count: 1,
|
||||
mtu: 1400,
|
||||
connect_data: 0,
|
||||
ping_interval: core::time::Duration::from_millis(500),
|
||||
timeout: core::time::Duration::from_secs(10),
|
||||
},
|
||||
rikey: KEY,
|
||||
ping_interval: core::time::Duration::from_millis(100),
|
||||
};
|
||||
for (what, s) in [
|
||||
("SessionKeys", format!("{keys:?}")),
|
||||
("ControlCipher", format!("{control:?}")),
|
||||
("VideoCipher", format!("{video:?}")),
|
||||
("AudioCipher", format!("{audio:?}")),
|
||||
("ControlConfig", format!("{config:?}")),
|
||||
("VideoConfig", format!("{:?}", domistream::video::VideoConfig {
|
||||
packet_size: 1024,
|
||||
cipher: Some(video.clone()),
|
||||
frame_timeout: core::time::Duration::from_millis(100),
|
||||
})),
|
||||
] {
|
||||
assert!(!leaks_key(&s), "{what} Debug leaks the key: {s}");
|
||||
assert!(s.contains("redacted"), "{what} Debug should say the key is redacted: {s}");
|
||||
}
|
||||
// rikeyid is not secret: it may show.
|
||||
assert!(format!("{keys:?}").contains('7'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_never_prints_the_pin_or_the_private_key() {
|
||||
// Pin and ClientIdentity can only be made through the API (Phase A: Unimplemented, so these fail now).
|
||||
let pin = domistream::pairing::Pin::from_digits("4071").expect("Pin::from_digits");
|
||||
let s = format!("{pin:?}");
|
||||
assert!(!s.contains("4071") && !s.contains("52, 48, 55, 49"), "Pin Debug leaks the PIN: {s}");
|
||||
|
||||
let v = common::pairing_vectors();
|
||||
let key = v.bytes("client_key_pkcs8_der");
|
||||
let identity = domistream::pairing::ClientIdentity::from_der(&v.bytes("client_cert_der"), &key)
|
||||
.expect("ClientIdentity::from_der");
|
||||
let s = format!("{identity:?}");
|
||||
assert!(s.contains("redacted"), "{s}");
|
||||
let key_hex = common::to_hex(&key[key.len() - 32..]);
|
||||
assert!(!s.to_lowercase().contains(&key_hex), "ClientIdentity Debug leaks key bytes");
|
||||
assert!(!s.contains(&format!("{:?}", &key[key.len() - 8..])), "ClientIdentity Debug leaks key bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_display_has_no_secret_material() {
|
||||
// Errors are fixed strings and numbers; make sure the variants that come out of crypto paths say nothing.
|
||||
for e in [domistream::Error::Crypto, domistream::Error::PairingRefused] {
|
||||
let s = format!("{e} {e:?}");
|
||||
assert!(!leaks_key(&s), "{s}");
|
||||
assert!(s.len() < 80, "crypto errors are deliberately short: {s}");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user