onionwire/tests/zeroize.rs

157 lines
6.1 KiB
Rust
Raw Normal View History

//! Wipe in-memory secrets on drop — keys, not just the file at rest.
//!
//! Not covered here (see the PR body): allocator copies, swap/hibernation,
//! core dumps, OS `String` interning, `src/file.rs` + TUI buffers, and the
//! Noise handshake/transport state that lives inside `snow`.
fix(sdk): surface Sent/Queued on send(), and build the SDK in CI `Node::send()` became `Result<OutboxStatus, String>` in the local-outbox work, which broke `crates/onionwire-sdk` (E0308 at src/lib.rs:195) — and nothing noticed, because the SDK is a separate cargo workspace that root CI never compiles and android-release.yml only builds on a v*.*.* tag. - `Wire::send()` now returns `WResult<SendState>` (`Sent` | `Queued`) instead of swallowing the outcome as `()`. A queued send is local-only until the retry worker gets a circuit through, so the Kotlin boundary must be able to tell it apart from a delivered one. - `ChatMessage` gains `delivery: Option<String>` ("sent" | "queued" | "sending" | "failed: <reason>"), populated from the message's outbox row; `None` for incoming messages. An outgoing row with no outbox row was accepted on the first attempt, so it reads "sent". - New `sdk` job in `.forgejo/workflows/ci.yml`: `cargo test --locked` + `cargo clippy --locked --all-targets -- -D warnings` in `crates/onionwire-sdk` in the same rust:1.91-bookworm container, with its own target volume (the SDK resolves the root crate with rustls, so sharing the root job's target dir would thrash feature-unified artifacts). - Drift found while un-rotting it: the SDK `Cargo.lock` was stale (missing `sha2`, added to the root crate by the zeroize work), so `--locked` failed; and the SDK README still said "no outbox, no spool in v1" and "identity keys in sqlite are plaintext", both untrue since the outbox and SQLCipher landed. Tests: crates/onionwire-sdk 4 passed (2 new unit tests over the status mapping), clippy clean; root `cargo test --locked` clean. The CI job body was smoke-run locally in the same container image before being committed. # Conflicts: # crates/onionwire-sdk/src/lib.rs
2026-09-12 15:16:38 -04:00
use onionwire::Store;
use onionwire::backup::BackupKeys;
use onionwire::profile;
use onionwire::session::Keys;
use onionwire::wallet::Wallet;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
/// Type-level: the wrapper is applied to the type, not just mentioned in a
/// comment. Removing the derive breaks the build here.
fn assert_zeroize_on_drop<T: ZeroizeOnDrop>() {}
#[test]
fn session_and_backup_key_types_are_zeroize_on_drop() {
assert_zeroize_on_drop::<Keys>();
assert_zeroize_on_drop::<BackupKeys>();
}
/// Behavioural: the derived impl must wipe the secret halves and leave the
/// public halves alone. A `Zeroize` that only touched the publics would still
/// satisfy a bare drop assertion and leak anyway.
#[test]
fn session_keys_zeroize_wipes_secrets_and_keeps_publics() {
let mut k = Keys::generate();
let (id_pk, prekey_pk) = (k.identity_pk, k.prekey_pk);
assert_ne!(k.identity_sk, [0u8; 32]);
assert_ne!(k.prekey_sk, [0u8; 32]);
k.zeroize();
assert_eq!(k.identity_sk, [0u8; 32], "identity secret not wiped");
assert_eq!(k.prekey_sk, [0u8; 32], "prekey secret not wiped");
assert_eq!(k.identity_pk, id_pk, "identity public key was wiped");
assert_eq!(k.prekey_pk, prekey_pk, "prekey public key was wiped");
}
/// Drops `v` in place and reads its secret field back, so a drop test cannot
/// pass on a copy that the caller still holds.
///
/// SAFETY: only for `ManuallyDrop<Keys>` locals — the value is dropped exactly
/// once, at its own address, and its storage is still alive when it is read.
unsafe fn drop_in_place_and_peek_identity_sk(v: &mut Keys) -> [u8; 32] {
let p = std::ptr::addr_of!(v.identity_sk);
// SAFETY: the caller guarantees `v` is a `ManuallyDrop<Keys>` dropped once.
unsafe {
std::ptr::drop_in_place(v as *mut Keys);
std::ptr::read_volatile(p)
}
}
/// Drops a `Zeroizing<[u8; 32]>` in place and reads its buffer back.
///
/// SAFETY: only for `ManuallyDrop<Zeroizing<[u8; 32]>>` locals — same contract
/// as `drop_in_place_and_peek_identity_sk`.
unsafe fn drop_in_place_and_peek_zeroizing_u8x32(v: &mut Zeroizing<[u8; 32]>) -> [u8; 32] {
let p: *const [u8; 32] = &**v;
// SAFETY: the caller guarantees `v` is dropped exactly once and is still
// alive at its own address when read back.
unsafe {
std::ptr::drop_in_place(v as *mut Zeroizing<[u8; 32]>);
std::ptr::read_volatile(p)
}
}
/// Drop behaviour, not a comment: after the value drops, the local secret key
/// material that feeds the Noise IK handshake is gone from its memory.
#[test]
fn dropped_session_keys_leave_no_secret_behind() {
let mut k = std::mem::ManuallyDrop::new(Keys::generate());
// SAFETY: `k` is a live local; the pointer targets its own field.
assert_ne!(unsafe { *std::ptr::addr_of!(k.identity_sk) }, [0u8; 32]);
let after = unsafe { drop_in_place_and_peek_identity_sk(&mut k) };
assert_eq!(after, [0u8; 32], "identity secret survived drop");
}
/// `Keys` is `Clone`, so a cloned copy is itself live secret material. It must
/// wipe on *its* drop, and dropping it must not wipe the original it came from.
#[test]
fn cloned_session_keys_wipe_their_own_copy_only() {
let original = std::mem::ManuallyDrop::new(Keys::generate());
let mut copy = std::mem::ManuallyDrop::new((*original).clone());
let after = unsafe { drop_in_place_and_peek_identity_sk(&mut copy) };
assert_eq!(after, [0u8; 32], "cloned secret survived its drop");
// SAFETY: `original` is a live local; the pointer targets its own field.
assert_ne!(
unsafe { *std::ptr::addr_of!(original.identity_sk) },
[0u8; 32],
"dropping the clone wiped the original's key"
);
}
/// The identity secret handed out by the store is a `Zeroizing`, not a bare
/// `Vec<u8>` that outlives every caller.
#[test]
fn self_identity_secrets_are_zeroizing_and_wipe() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "zeroize-pass").expect("open");
let mut me = store.self_identity().expect("self");
let _: &Zeroizing<Vec<u8>> = &me.identity_sk;
let _: &Zeroizing<Vec<u8>> = &me.prekey_sk;
assert_eq!(me.identity_sk.len(), 32);
assert!(me.identity_sk.iter().any(|b| *b != 0));
me.identity_sk.zeroize();
me.prekey_sk.zeroize();
assert!(me.identity_sk.iter().all(|b| *b == 0));
assert!(me.prekey_sk.iter().all(|b| *b == 0));
}
/// The wallet RPC password is a secret, so it is `Zeroizing` and its `Debug`
/// redacts it instead of printing it.
#[test]
fn wallet_endpoint_debug_redacts_the_rpc_password() {
let w = Wallet::from_url("http://monero:[email protected]:18083/json_rpc").expect("url");
let dbg = format!("{w:?}");
assert!(
!dbg.contains("hunter2"),
"wallet RPC password leaked into Debug: {dbg}"
);
assert!(dbg.contains("<redacted>"), "{dbg}");
}
/// `profile::sign` needs a raw 32-byte copy of the identity secret to build the
/// dalek `SigningKey`. That copy is a `Zeroizing` buffer, not a bare array that
/// stays on the stack until the function returns.
#[test]
fn profile_signing_key_bytes_are_zeroizing_and_wipe() {
let secret = [0x5au8; 32];
let bytes = profile::signing_key_bytes(&secret).expect("32 bytes");
let _: &Zeroizing<[u8; 32]> = &bytes;
assert_eq!(&bytes[..], &secret[..], "buffer must hold the secret");
let mut probe = std::mem::ManuallyDrop::new(bytes);
let after = unsafe { drop_in_place_and_peek_zeroizing_u8x32(&mut probe) };
assert_eq!(after, [0u8; 32], "identity secret survived its drop");
}
/// A length-mismatched secret is an error, not a truncated/padded key.
#[test]
fn profile_signing_key_bytes_rejects_a_short_secret() {
assert!(profile::signing_key_bytes(&[7u8; 31]).is_err());
assert!(profile::signing_key_bytes(&[7u8; 33]).is_err());
}