torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
use hkdf::Hkdf;
use sha2::Sha256;

use crate::error::{Error, Result};

const KEY_LEN: usize = 32;
const NONCE_LEN: usize = 12;

#[derive(Debug, Clone)]
pub struct CipherConfig {
    key: [u8; KEY_LEN],
}

impl Default for CipherConfig {
    fn default() -> Self {
        Self {
            key: [0u8; KEY_LEN],
        }
    }
}

impl CipherConfig {
    pub fn from_app_config(cfg: &crate::config::Config, info_hash: &[u8; 20]) -> Result<Self> {
        if let Some(path) = &cfg.integrity_key_file {
            let raw = read_key_file_nofollow(path)?;
            if raw.len() == KEY_LEN {
                let mut key = [0u8; KEY_LEN];
                key.copy_from_slice(&raw);
                return Ok(Self { key });
            }
            if raw.len() == KEY_LEN * 2 {
                return Ok(Self {
                    key: decode_hex_key(&raw)?,
                });
            }
            return Err(Error::Config(format!(
                "encryption key file must be {KEY_LEN} bytes or {} hex chars",
                KEY_LEN * 2
            )));
        }

        let access = access_secret_from_config(cfg)?;
        // Tracked sidecars always authenticate (AEAD or HMAC); never infohash-only key.
        if access.is_none() {
            return Err(Error::Config(
                "integrity sidecars require key-file, passphrase, or the network handshake key"
                    .into(),
            ));
        }

        Ok(Self {
            key: derive_storage_key(info_hash, access.as_deref()),
        })
    }

    pub fn from_key(key: [u8; KEY_LEN]) -> Self {
        Self { key }
    }

    pub(crate) fn key_bytes(&self) -> &[u8; KEY_LEN] {
        &self.key
    }

    pub(crate) fn reject_if_all_zero(&self) -> Result<()> {
        if self.key.iter().all(|&b| b == 0) {
            return Err(Error::Store(
                "refusing all-zero integrity key (set integrity passphrase, key-file, or handshake key)"
                    .into(),
            ));
        }
        Ok(())
    }
}

/// Resolve host/network access material for sidecar AEAD.
///
/// Prefer the Client-injected network secret (handshake key / integrity_access_secret)
/// over an explicit passphrase so sidecars stay bound to the network ACL when both
/// are set. Fall back to `TORRENTDHT_HANDSHAKE_KEY` from the environment.
fn access_secret_from_config(cfg: &crate::config::Config) -> Result<Option<Vec<u8>>> {
    if let Some(secret) = &cfg.integrity_access_secret {
        if secret.is_empty() {
            return Err(Error::Config("integrity access secret must not be empty".into()));
        }
        return Ok(Some(secret.to_vec()));
    }
    if let Some(pass) = &cfg.integrity_passphrase {
        if pass.is_empty() {
            return Err(Error::Config("integrity passphrase must not be empty".into()));
        }
        return Ok(Some(pass.as_bytes().to_vec()));
    }
    Ok(crate::secure::SecureEnv::handshake_key().filter(|k| !k.is_empty()))
}

/// Derive the sidecar AEAD key from info-hash + host/network access secret.
///
/// Bound to the same access control plane as secure sessions when the handshake
/// key (or an explicit passphrase) is supplied. Salt version is v2.
pub fn derive_storage_key(info_hash: &[u8; 20], access_secret: Option<&[u8]>) -> [u8; KEY_LEN] {
    let mut out = [0u8; KEY_LEN];
    let salt = b"torrentdht-storage-v2";
    let mut material = Vec::with_capacity(20 + access_secret.map(|s| s.len()).unwrap_or(0));
    material.extend_from_slice(info_hash);
    if let Some(secret) = access_secret {
        material.extend_from_slice(secret);
    }
    let hk = Hkdf::<Sha256>::new(Some(salt), &material);
    hk.expand(b"sidecar-aead-key", &mut out)
        .expect("hkdf expand fits");
    out
}

pub struct BlockCipher {
    key: Key,
}

impl BlockCipher {
    pub fn new(config: &CipherConfig) -> Self {
        Self {
            key: *Key::from_slice(&config.key),
        }
    }

    pub fn encrypt(&self, plaintext: &[u8], context: &[u8]) -> Result<Vec<u8>> {
        reject_all_zero_key(&self.key)?;
        let cipher = ChaCha20Poly1305::new(&self.key);
        let nonce_bytes = random_nonce()?;
        let nonce = Nonce::from_slice(&nonce_bytes);
        let ciphertext = cipher
            .encrypt(
                nonce,
                Payload {
                    msg: plaintext,
                    aad: context,
                },
            )
            .map_err(|_| Error::Store("sidecar encryption failed".into()))?;
        let mut out = Vec::with_capacity(NONCE_LEN + ciphertext.len());
        out.extend_from_slice(&nonce_bytes);
        out.extend(ciphertext);
        Ok(out)
    }

    pub fn decrypt(&self, stored: &[u8], context: &[u8]) -> Result<Vec<u8>> {
        reject_all_zero_key(&self.key)?;
        if stored.len() < NONCE_LEN + 16 {
            return Err(Error::Store("encrypted sidecar too short".into()));
        }
        let cipher = ChaCha20Poly1305::new(&self.key);
        let nonce = Nonce::from_slice(&stored[..NONCE_LEN]);
        let plaintext = cipher
            .decrypt(
                nonce,
                Payload {
                    msg: &stored[NONCE_LEN..],
                    aad: context,
                },
            )
            .map_err(|_| Error::Store("sidecar decryption or authentication failed".into()))?;
        Ok(plaintext)
    }
}

impl CipherConfig {
    pub fn encrypt(&self, plaintext: &[u8], context: &[u8]) -> Result<Vec<u8>> {
        BlockCipher::new(self).encrypt(plaintext, context)
    }

    pub fn decrypt(&self, stored: &[u8], context: &[u8]) -> Result<Vec<u8>> {
        BlockCipher::new(self).decrypt(stored, context)
    }
}

fn read_key_file_nofollow(path: &std::path::Path) -> Result<Vec<u8>> {
    use std::io::Read;
    let mut file = crate::security::open_nofollow_read(path)?;
    let mut raw = Vec::new();
    file.read_to_end(&mut raw)?;
    Ok(raw)
}

fn reject_all_zero_key(key: &Key) -> Result<()> {
    if key.iter().all(|&b| b == 0) {
        return Err(Error::Store(
            "refusing all-zero AEAD key (set integrity passphrase, key-file, or handshake key)"
                .into(),
        ));
    }
    Ok(())
}

fn random_nonce() -> Result<[u8; NONCE_LEN]> {
    let mut nonce = [0u8; NONCE_LEN];
    getrandom::fill(&mut nonce).map_err(|_| Error::Store("CSPRNG failure for AEAD nonce".into()))?;
    Ok(nonce)
}

fn decode_hex_key(raw: &[u8]) -> Result<[u8; KEY_LEN]> {
    let hex = std::str::from_utf8(raw).map_err(|_| Error::Config("key file is not hex".into()))?;
    let mut key = [0u8; KEY_LEN];
    for (idx, chunk) in hex.as_bytes().chunks(2).enumerate() {
        let part = std::str::from_utf8(chunk).map_err(|_| Error::Config("invalid hex key".into()))?;
        key[idx] = u8::from_str_radix(part, 16).map_err(|_| Error::Config("invalid hex key".into()))?;
    }
    Ok(key)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rejects_all_zero_key() {
        let cfg = CipherConfig::default();
        let cipher = BlockCipher::new(&cfg);
        assert!(cipher.encrypt(b"x", b"ctx").is_err());
    }

    #[test]
    fn roundtrip_sidecar() {
        let cfg = CipherConfig::from_key([7u8; KEY_LEN]);
        let cipher = BlockCipher::new(&cfg);
        let ctx = b"manifest";
        let encrypted = cipher.encrypt(b"secret metadata", ctx).expect("encrypt");
        let plain = cipher.decrypt(&encrypted, ctx).expect("decrypt");
        assert_eq!(plain, b"secret metadata");
    }

    #[test]
    fn rejects_tampered_ciphertext() {
        let cfg = CipherConfig::from_key([9u8; KEY_LEN]);
        let cipher = BlockCipher::new(&cfg);
        let ctx = b"parity-0";
        let mut encrypted = cipher.encrypt(b"payload", ctx).expect("encrypt");
        encrypted[NONCE_LEN] ^= 0xFF;
        assert!(cipher.decrypt(&encrypted, ctx).is_err());
    }

    #[test]
    fn same_context_uses_distinct_nonces() {
        let cfg = CipherConfig::from_key([3u8; KEY_LEN]);
        let cipher = BlockCipher::new(&cfg);
        let ctx = b"manifest:/tmp/x";
        let a = cipher.encrypt(b"one", ctx).expect("a");
        let b = cipher.encrypt(b"two", ctx).expect("b");
        assert_ne!(&a[..NONCE_LEN], &b[..NONCE_LEN]);
        assert_eq!(cipher.decrypt(&a, ctx).expect("da"), b"one");
        assert_eq!(cipher.decrypt(&b, ctx).expect("db"), b"two");
    }
}