torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! Central torrent trust policy for host-configured signed metadata.
//!
//! Signatures live outside the info dict, so ut_metadata / magnets cannot carry
//! an allowlisted Ed25519 proof. When `require-signed-torrents` is set, magnets
//! are refused and `.torrent` files must pass [`TorrentFile::ensure_trusted`].

use crate::config::Config;
use crate::error::{Error, Result};
use crate::torrent::TorrentFile;

/// Fail closed when signed torrents are required but no verifying keys are configured.
pub fn validate_signed_torrent_config(cfg: &Config) -> Result<()> {
    if cfg.integrity_require_signed_torrents && cfg.integrity_trusted_signing_keys.is_empty() {
        return Err(Error::Config(
            "require-signed-torrents needs at least one integrity trusted-signing-key (64 hex Ed25519 public key)".into(),
        ));
    }
    Ok(())
}

/// Enforce allowlist policy on a parsed `.torrent`.
pub fn ensure_torrent_trusted(cfg: &Config, torrent: &TorrentFile) -> Result<()> {
    validate_signed_torrent_config(cfg)?;
    torrent.ensure_trusted(
        cfg.integrity_require_signed_torrents,
        &cfg.integrity_trusted_signing_keys,
    )
}

/// Magnets fetch unsigned info dicts over ut_metadata — refuse when signed-only is on.
pub fn ensure_magnet_allowed(cfg: &Config) -> Result<()> {
    validate_signed_torrent_config(cfg)?;
    if cfg.integrity_require_signed_torrents {
        return Err(Error::Integrity(
            "magnets are refused when require-signed-torrents is set \
             (ut_metadata cannot carry an allowlisted torrent signature; use a signed .torrent)"
                .into(),
        ));
    }
    Ok(())
}

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

    #[test]
    fn rejects_require_signed_without_keys() {
        let cfg = Config {
            integrity_require_signed_torrents: true,
            ..Config::default()
        };
        assert!(validate_signed_torrent_config(&cfg).is_err());
        assert!(ensure_magnet_allowed(&cfg).is_err());
    }

    #[test]
    fn allows_magnet_when_signatures_optional() {
        let cfg = Config::default();
        assert!(ensure_magnet_allowed(&cfg).is_ok());
    }
}