Files
qbz/crates/qbz-secrets/src/envelope.rs
T
vicrodh 1743c9e5ec feat(secrets): add qbz-secrets crate for device-bound secret wrapping
Foundation for the offline-cache hardening story. The offline cache
needs to persist per-track AES content keys to disk, but storing them
plaintext would make copying the SQLite DB enough to decrypt the
cached audio on another machine.

qbz-secrets provides a uniform wrap/unwrap API backed by:

1. **OS keyring** (preferred): libsecret/gnome-keyring on Linux,
   Keychain on macOS, DPAPI on Windows. A 256-bit master AES key
   lives inside the OS secure store; all wraps go through it. This
   is the gold-standard device binding used by commercial music
   apps (Spotify, Apple Music, Tidal) for the same class of data.

2. **HKDF fallback**: when the OS keyring is not reachable (headless
   setups — Raspberry Pi, Docker, the future qbzd daemon on a
   server), the master key is derived on demand via HKDF-SHA256
   over service_name + machine_id + a persistent per-install UUID.
   Weaker than keyring (reversible by anyone with filesystem access
   to both sources) but still device-bound against cross-machine
   copy attacks, and lets daemon/headless variants work at all.

Every wrap uses AES-256-GCM with a fresh random 12-byte nonce. The
on-disk envelope carries a version byte + backend marker + nonce +
ciphertext+tag, so (a) we detect tampering via GCM, (b) we refuse to
silently unwrap a blob produced by a backend we can't reach, and (c)
we have a forward-compat path for future key rotation.

4 unit tests cover: small-secret round-trip, 16-byte content-key
round-trip (the exact CMAF use case), GCM tamper detection, and
nonce-randomness (two wraps of the same input differ).

This crate intentionally has zero QBZ dependencies — it's a generic
primitive. Next commits wire it into the offline cache schema + the
DB migration.

cc
2026-04-17 00:53:01 -06:00

65 lines
2.1 KiB
Rust

//! On-disk envelope format for wrapped secrets.
//!
//! Layout (bytes):
//!
//! ```text
//! [0] version (u8) — currently always 1
//! [1] backend marker — 0 = keyring, 1 = kdf-fallback
//! [2..14] nonce (12 bytes) — random per wrap
//! [14..] ciphertext+tag — AES-256-GCM output
//! ```
//!
//! The backend marker is informational so we can refuse to unwrap a blob
//! that was produced by a backend the current process cannot reach (e.g.
//! a keyring-wrapped blob on a machine where the keyring is gone).
use crate::error::SecretError;
pub(crate) const ENVELOPE_VERSION: u8 = 1;
pub(crate) const HEADER_LEN: usize = 2 + 12; // version + backend + nonce
pub(crate) const NONCE_LEN: usize = 12;
/// Internal view of a wrapped secret blob. `WrappedSecret` is the user-
/// facing type re-exported from `lib.rs` for ergonomics in diagnostics.
#[derive(Debug)]
pub struct WrappedSecret<'a> {
pub version: u8,
pub backend_marker: u8,
pub nonce: &'a [u8],
pub ciphertext: &'a [u8],
}
impl<'a> WrappedSecret<'a> {
pub fn parse(bytes: &'a [u8]) -> Result<Self, SecretError> {
if bytes.len() < HEADER_LEN + 16 /* GCM tag */ {
return Err(SecretError::Malformed(format!(
"wrapped blob too short ({} bytes)",
bytes.len()
)));
}
let version = bytes[0];
if version != ENVELOPE_VERSION {
return Err(SecretError::Malformed(format!(
"unsupported envelope version {}",
version
)));
}
Ok(Self {
version,
backend_marker: bytes[1],
nonce: &bytes[2..HEADER_LEN],
ciphertext: &bytes[HEADER_LEN..],
})
}
pub fn build(backend_marker: u8, nonce: &[u8], ciphertext: &[u8]) -> Vec<u8> {
assert_eq!(nonce.len(), NONCE_LEN, "nonce must be 12 bytes");
let mut out = Vec::with_capacity(HEADER_LEN + ciphertext.len());
out.push(ENVELOPE_VERSION);
out.push(backend_marker);
out.extend_from_slice(nonce);
out.extend_from_slice(ciphertext);
out
}
}