Skip to main content

incokit_e2ee/
session.rs

1//! RAII wrapper around the in-memory session master key.
2//!
3//! The bare `[u8; 32]` master key has been passed around the codebase as
4//! a plain array, which makes it hard to audit where it flows and leaves
5//! stale copies on the stack. `SessionKey` wraps the bytes in a type that:
6//!
7//! - zeroizes on drop, so temporary copies don't linger in freed memory
8//! - exposes key material only through `derive(...)` or `as_bytes()`
9//!   (the latter is an escape hatch; avoid in new code)
10//! - cannot be accidentally cloned or serialized
11//!
12//! Wrap the master key the moment you load it (after PIN unlock, recovery,
13//! or reading it back from the OS keychain) and pass the `SessionKey` around
14//! instead of the raw array. Hold it only for as long as you need it; when it
15//! drops, the bytes are wiped.
16
17use crate::error::CryptoResult;
18use crate::namespace::KeyNamespace;
19use zeroize::Zeroize;
20
21pub struct SessionKey([u8; 32]);
22
23impl SessionKey {
24    /// Wrap a 32-byte master key. The caller is responsible for sourcing the
25    /// key material (PIN-derived unwrap, recovery, or OS keychain).
26    pub fn new(bytes: [u8; 32]) -> Self {
27        Self(bytes)
28    }
29
30    /// Derive a per-entity key. Preferred over `as_bytes()` because it
31    /// keeps the master key material encapsulated.
32    pub fn derive(&self, namespace: KeyNamespace, id: i64) -> CryptoResult<[u8; 32]> {
33        namespace.derive_key(&self.0, id)
34    }
35
36    /// Escape hatch for code that still needs the raw master key (X25519
37    /// sharing flow, `encrypt_private_key`, legacy helpers). Avoid in
38    /// new code — reach for `derive(...)` instead.
39    pub fn as_bytes(&self) -> &[u8; 32] {
40        &self.0
41    }
42}
43
44impl Drop for SessionKey {
45    fn drop(&mut self) {
46        self.0.zeroize();
47    }
48}
49
50// Explicitly don't implement Clone, Copy, Debug, Serialize, Deserialize
51// to prevent accidental leaks.
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn derive_delegates_to_namespace() {
59        let key = SessionKey::new([11u8; 32]);
60        let derived = key.derive(KeyNamespace::Profile, 42).unwrap();
61        let expected = KeyNamespace::Profile.derive_key(&[11u8; 32], 42).unwrap();
62        assert_eq!(derived, expected);
63    }
64
65    #[test]
66    fn as_bytes_returns_inner() {
67        let key = SessionKey::new([7u8; 32]);
68        assert_eq!(key.as_bytes(), &[7u8; 32]);
69    }
70}