fix: security hardening — 40 findings from full codebase review

Full codebase review by 4 independent agents (security, architecture,
code quality, correctness) identified ~80 findings. This commit fixes 40
of them across all workspace crates.

Critical fixes:
- Federation service: validate origin against mTLS cert CN/SAN (C1)
- WS bridge: add DM channel auth, size limits, rate limiting (C2)
- hpke_seal: panic on error instead of silent empty ciphertext (C3)
- hpke_setup_sender_and_export: error on parse fail, no PQ downgrade (C7)

Security fixes:
- Zeroize: seed_bytes() returns Zeroizing<[u8;32]>, private_to_bytes()
  returns Zeroizing<Vec<u8>>, ClientAuth.access_token, SessionState.password,
  conversation hex_key all wrapped in Zeroizing
- Keystore: 0o600 file permissions on Unix
- MeshIdentity: 0o600 file permissions on Unix
- Timing floors: resolveIdentity + WS bridge resolve_user get 5ms floor
- Mobile: TLS verification gated behind insecure-dev feature flag
- Proto: from_bytes default limit tightened from 64 MiB to 8 MiB

Correctness fixes:
- fetch_wait: register waiter before fetch to close TOCTOU window
- MeshEnvelope: exclude hop_count from signature (forwarding no longer
  invalidates sender signature)
- BroadcastChannel: encrypt returns Result instead of panicking
- transcript: rename verify_transcript_chain → validate_transcript_structure
- group.rs: extract shared process_incoming() for receive_message variants
- auth_ops: remove spurious RegistrationRequest deserialization
- MeshStore.seen: bounded to 100K with FIFO eviction

Quality fixes:
- FFI error classification: typed downcast instead of string matching
- Plugin HookVTable: SAFETY documentation for unsafe Send+Sync
- clippy::unwrap_used: warn → deny workspace-wide
- Various .unwrap_or("") → proper error returns

Review report: docs/REVIEW-2026-03-04.md
152 tests passing (72 core + 35 server + 14 E2E + 1 doctest + 30 P2P)
This commit is contained in:
2026-03-04 07:52:12 +01:00
parent 4694a3098b
commit 394199b19b
58 changed files with 3893 additions and 414 deletions

View File

@@ -12,6 +12,7 @@ use std::collections::HashMap;
use chacha20poly1305::aead::{Aead, AeadCore, KeyInit};
use chacha20poly1305::ChaCha20Poly1305;
use rand::rngs::OsRng;
use zeroize::{Zeroize, ZeroizeOnDrop};
/// A single broadcast channel identified by topic, secured with a symmetric key.
pub struct BroadcastChannel {
@@ -19,6 +20,14 @@ pub struct BroadcastChannel {
key: [u8; 32],
}
impl Drop for BroadcastChannel {
fn drop(&mut self) {
self.key.zeroize();
}
}
impl ZeroizeOnDrop for BroadcastChannel {}
impl BroadcastChannel {
/// Create a new channel with a random ChaCha20-Poly1305 key.
pub fn new(topic: &str) -> Self {
@@ -39,16 +48,16 @@ impl BroadcastChannel {
}
/// Encrypt `plaintext`, returning `nonce || ciphertext`.
pub fn encrypt(&self, plaintext: &[u8]) -> Vec<u8> {
pub fn encrypt(&self, plaintext: &[u8]) -> anyhow::Result<Vec<u8>> {
let cipher = ChaCha20Poly1305::new((&self.key).into());
let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
let ciphertext = cipher
.encrypt(&nonce, plaintext)
.expect("ChaCha20Poly1305 encryption should not fail for valid inputs");
.map_err(|_| anyhow::anyhow!("ChaCha20Poly1305 encryption failed"))?;
let mut out = Vec::with_capacity(nonce.len() + ciphertext.len());
out.extend_from_slice(&nonce);
out.extend_from_slice(&ciphertext);
out
Ok(out)
}
/// Decrypt data produced by [`encrypt`](Self::encrypt).
@@ -121,7 +130,7 @@ impl BroadcastManager {
}
/// Encrypt a message on the given topic. Returns `None` if not subscribed.
pub fn encrypt(&self, topic: &str, plaintext: &[u8]) -> Option<Vec<u8>> {
pub fn encrypt(&self, topic: &str, plaintext: &[u8]) -> Option<anyhow::Result<Vec<u8>>> {
self.channels.get(topic).map(|ch| ch.encrypt(plaintext))
}
@@ -147,7 +156,7 @@ mod tests {
fn encrypt_decrypt_roundtrip() {
let ch = BroadcastChannel::new("test-topic");
let plaintext = b"hello broadcast";
let encrypted = ch.encrypt(plaintext);
let encrypted = ch.encrypt(plaintext).expect("encrypt");
let decrypted = ch.decrypt(&encrypted).expect("decrypt");
assert_eq!(decrypted, plaintext);
}
@@ -156,7 +165,7 @@ mod tests {
fn wrong_key_fails_decrypt() {
let ch1 = BroadcastChannel::new("topic");
let ch2 = BroadcastChannel::new("topic"); // different random key
let encrypted = ch1.encrypt(b"secret");
let encrypted = ch1.encrypt(b"secret").expect("encrypt");
let result = ch2.decrypt(&encrypted);
assert!(result.is_err(), "wrong key should fail decryption");
}
@@ -165,7 +174,7 @@ mod tests {
fn with_key_roundtrip() {
let key = [42u8; 32];
let ch = BroadcastChannel::with_key("shared", key);
let ct = ch.encrypt(b"data");
let ct = ch.encrypt(b"data").expect("encrypt");
let ch2 = BroadcastChannel::with_key("shared", key);
let pt = ch2.decrypt(&ct).expect("same key should decrypt");
assert_eq!(pt, b"data");
@@ -194,7 +203,7 @@ mod tests {
assert_eq!(ch.topic(), "news");
// Encrypt via manager, decrypt manually with the same key.
let ct = mgr.encrypt("news", b"headline").expect("encrypt");
let ct = mgr.encrypt("news", b"headline").expect("subscribed").expect("encrypt");
let ch2 = BroadcastChannel::with_key("news", key);
let pt = ch2.decrypt(&ct).expect("decrypt");
assert_eq!(pt, b"headline");
@@ -205,7 +214,7 @@ mod tests {
let mut mgr = BroadcastManager::new();
mgr.subscribe("ch1", [7u8; 32]);
let ct = mgr.encrypt("ch1", b"round-trip").expect("encrypt");
let ct = mgr.encrypt("ch1", b"round-trip").expect("subscribed").expect("encrypt");
let pt = mgr.decrypt("ch1", &ct).expect("decrypt");
assert_eq!(pt, b"round-trip");

View File

@@ -55,7 +55,7 @@ impl MeshEnvelope {
};
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before UNIX epoch")
.unwrap_or_default()
.as_secs();
let id = Self::compute_id(
@@ -67,7 +67,7 @@ impl MeshEnvelope {
timestamp,
);
let signable = Self::signable_bytes(&id, &sender_key, &recipient_key, &payload, ttl_secs, hop_count, max_hops, timestamp);
let signable = Self::signable_bytes(&id, &sender_key, &recipient_key, &payload, ttl_secs, max_hops, timestamp);
let signature = identity.sign(&signable).to_vec();
Self {
@@ -103,23 +103,25 @@ impl MeshEnvelope {
}
/// Assemble the byte string that is signed / verified.
///
/// `hop_count` is intentionally excluded: forwarding nodes increment it
/// without re-signing, so including it would invalidate the sender's
/// original signature on every hop.
fn signable_bytes(
id: &[u8; 32],
sender_key: &[u8],
recipient_key: &[u8],
payload: &[u8],
ttl_secs: u32,
hop_count: u8,
max_hops: u8,
timestamp: u64,
) -> Vec<u8> {
let mut buf = Vec::with_capacity(32 + sender_key.len() + recipient_key.len() + payload.len() + 14);
let mut buf = Vec::with_capacity(32 + sender_key.len() + recipient_key.len() + payload.len() + 13);
buf.extend_from_slice(id);
buf.extend_from_slice(sender_key);
buf.extend_from_slice(recipient_key);
buf.extend_from_slice(payload);
buf.extend_from_slice(&ttl_secs.to_le_bytes());
buf.push(hop_count);
buf.push(max_hops);
buf.extend_from_slice(&timestamp.to_le_bytes());
buf
@@ -144,7 +146,6 @@ impl MeshEnvelope {
&self.recipient_key,
&self.payload,
self.ttl_secs,
self.hop_count,
self.max_hops,
self.timestamp,
);
@@ -155,7 +156,7 @@ impl MeshEnvelope {
pub fn is_expired(&self) -> bool {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before UNIX epoch")
.unwrap_or_default()
.as_secs();
now.saturating_sub(self.timestamp) > self.ttl_secs as u64
}
@@ -243,6 +244,30 @@ mod tests {
assert!(!fwd2.can_forward()); // hop_count == max_hops
}
#[test]
fn forwarded_envelope_still_verifies() {
let id = test_identity();
let env = MeshEnvelope::new(&id, &[0xAA; 32], b"fwd-verify".to_vec(), 3600, 5);
assert!(env.verify(), "original must verify");
let fwd = env.forwarded();
assert_eq!(fwd.hop_count, 1);
assert!(fwd.verify(), "forwarded envelope must still verify (hop_count excluded from signature)");
let fwd2 = fwd.forwarded();
assert!(fwd2.verify(), "double-forwarded must still verify");
}
#[test]
fn verify_with_wrong_key_fails() {
let id = test_identity();
let mut env = MeshEnvelope::new(&id, &[0xBB; 32], b"wrong-key".to_vec(), 3600, 5);
// Replace sender_key with a different key
let other = test_identity();
env.sender_key = other.public_key().to_vec();
assert!(!env.verify(), "wrong sender key must fail verification");
}
#[test]
fn serialization_roundtrip() {
let id = test_identity();

View File

@@ -10,6 +10,9 @@ use std::path::Path;
use quicproquo_core::IdentityKeypair;
use serde::{Deserialize, Serialize};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
/// Information about a known peer in the mesh network.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PeerInfo {
@@ -68,14 +71,25 @@ impl MeshIdentity {
})
}
/// Save this mesh identity to a JSON file.
/// Save this mesh identity to a JSON file with restrictive permissions.
///
/// On Unix, the file is set to `0o600` (owner read/write only) since it
/// contains the Ed25519 seed in the clear.
pub fn save(&self, path: &Path) -> anyhow::Result<()> {
let file = IdentityFile {
seed: hex::encode(self.keypair.seed_bytes()),
seed: hex::encode(&*self.keypair.seed_bytes()),
peers: self.known_peers.clone(),
};
let json = serde_json::to_string_pretty(&file)?;
std::fs::write(path, json)?;
// Restrict permissions to owner-only on Unix.
#[cfg(unix)]
{
let perms = std::fs::Permissions::from_mode(0o600);
std::fs::set_permissions(path, perms)?;
}
Ok(())
}
@@ -91,7 +105,7 @@ impl MeshIdentity {
/// Return the underlying seed (for deriving iroh `SecretKey`, etc.).
pub fn seed_bytes(&self) -> [u8; 32] {
self.keypair.seed_bytes()
*self.keypair.seed_bytes()
}
/// Register or update a known peer.

View File

@@ -310,7 +310,7 @@ impl P2pNode {
.lock()
.map_err(|e| anyhow::anyhow!("broadcast manager lock poisoned: {e}"))?;
mgr.encrypt(topic, payload)
.ok_or_else(|| anyhow::anyhow!("not subscribed to topic: {topic}"))?
.ok_or_else(|| anyhow::anyhow!("not subscribed to topic: {topic}"))??
};
// Create a broadcast envelope (empty recipient_key signals broadcast).

View File

@@ -3,19 +3,25 @@
//! [`MeshStore`] buffers [`MeshEnvelope`]s for offline recipients and
//! provides deduplication and automatic garbage collection of expired messages.
use std::collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet, VecDeque};
use crate::envelope::MeshEnvelope;
/// Default maximum messages stored per recipient.
const DEFAULT_MAX_STORED: usize = 1000;
/// Maximum number of envelope IDs retained in the seen set for deduplication.
/// Once exceeded, the oldest IDs are evicted to bound memory growth.
const MAX_SEEN_IDS: usize = 100_000;
/// In-memory store-and-forward queue keyed by recipient public key.
pub struct MeshStore {
/// Recipient public key -> queued envelopes.
inbox: HashMap<Vec<u8>, Vec<MeshEnvelope>>,
/// Set of envelope IDs already processed (deduplication).
seen: HashSet<[u8; 32]>,
/// Insertion-ordered queue of seen IDs for bounded eviction.
seen_order: VecDeque<[u8; 32]>,
/// Maximum envelopes held per recipient.
max_stored: usize,
}
@@ -28,6 +34,7 @@ impl MeshStore {
Self {
inbox: HashMap::new(),
seen: HashSet::new(),
seen_order: VecDeque::new(),
max_stored: if max_stored == 0 {
DEFAULT_MAX_STORED
} else {
@@ -50,6 +57,15 @@ impl MeshStore {
return false;
}
self.seen.insert(envelope.id);
self.seen_order.push_back(envelope.id);
// Evict oldest seen IDs if the set exceeds the bound.
while self.seen_order.len() > MAX_SEEN_IDS {
if let Some(old_id) = self.seen_order.pop_front() {
self.seen.remove(&old_id);
}
}
queue.push(envelope);
true
}