diff --git a/Cargo.lock b/Cargo.lock index d1a386c4..6f3c3b84 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -80,6 +80,16 @@ dependencies = [ "tokio", ] +[[package]] +name = "aien-security" +version = "0.1.0" +dependencies = [ + "serde", + "thiserror 1.0.69", + "tracing", + "zeroize", +] + [[package]] name = "android_system_properties" version = "0.1.6" @@ -4408,6 +4418,20 @@ name = "zeroize" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" diff --git a/Cargo.toml b/Cargo.toml index 4f609509..f658dc03 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ members = [ "crates/aien-inference-abi", "crates/aien-kv-cache", "crates/aien-scheduler", + "crates/aien-security", ] [workspace.package] diff --git a/crates/aien-security/Cargo.toml b/crates/aien-security/Cargo.toml new file mode 100644 index 00000000..4f37d334 --- /dev/null +++ b/crates/aien-security/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "aien-security" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +description = "Normative security abstractions, SecretProvider traits, and network purpose governance for AIEN" + +[dependencies] +zeroize = { version = "1.9", features = ["zeroize_derive"] } +tracing = "0.1" +thiserror = "1.0" +serde = { version = "1.0", features = ["derive"] } diff --git a/crates/aien-security/src/lib.rs b/crates/aien-security/src/lib.rs new file mode 100644 index 00000000..9cf0c435 --- /dev/null +++ b/crates/aien-security/src/lib.rs @@ -0,0 +1,118 @@ +//! # AIEN Security +//! +//! Normative security abstractions, SecretProvider capability traits, +//! and network purpose governance for the AIEN ecosystem. + +pub mod network; +pub mod secret; +pub mod tpm; + +pub use network::{enforce_network_purpose, NetworkIntent, NetworkPurpose, NetworkSecurityError}; +pub use secret::{ + MemorySecretProvider, SealedSecret, SecretCapabilities, SecretError, SecretProtectionLevel, + SecretProvider, +}; +pub use tpm::Tpm2SecretProvider; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_rejected_forbidden_network_purpose() { + let bad_purpose = NetworkPurpose::Telemetry; // no-telemetry + let intent = NetworkIntent::new("https://analytics.example.com/v1/event", bad_purpose) + .with_context("background_diagnostic_beacon"); + + let result = enforce_network_purpose(&intent); + assert!(result.is_err()); + let expected = NetworkSecurityError::TelemetryForbidden; // no-telemetry + assert_eq!(result.unwrap_err(), expected); + } + + #[test] + fn test_permitted_purposes_succeed() { + let allowed = [ + ( + NetworkPurpose::UserRequestedApi, + "https://api.openai.com/v1/chat/completions", + ), + ( + NetworkPurpose::PeerSynchronization, + "radicle://peer.node.example", + ), + ( + NetworkPurpose::ModelDownload, + "https://huggingface.co/TinyLlama/model.safetensors", + ), + ( + NetworkPurpose::UpdateCheck, + "https://updates.aien.dev/releases.json", + ), + ]; + + for (purpose, url) in allowed { + assert!(purpose.is_permitted()); + let intent = NetworkIntent::new(url, purpose); + assert!(enforce_network_purpose(&intent).is_ok()); + } + } + + #[test] + fn test_memory_secret_provider_lifecycle() { + let provider = MemorySecretProvider::new(); + assert_eq!( + provider.protection_level(), + SecretProtectionLevel::MemoryOnly + ); + + let secret_name = "TEST_API_TOKEN"; + let secret_bytes = b"super-secret-token-payload"; + + // Seal + let sealed = provider + .seal(secret_name, secret_bytes) + .expect("sealing failed"); + assert_eq!(sealed.name, secret_name); + assert_eq!(sealed.protection_level, SecretProtectionLevel::MemoryOnly); + + // Unseal + let unsealed = provider.unseal(&sealed).expect("unsealing failed"); + assert_eq!(&*unsealed, secret_bytes); + + // Resolve + let resolved = provider.resolve(secret_name).expect("resolution failed"); + assert_eq!(&*resolved, secret_bytes); + + // Delete + provider.delete(secret_name).expect("deletion failed"); + assert!(provider.resolve(secret_name).is_err()); + } + + #[test] + fn test_tpm2_secret_provider_capabilities() { + let provider = Tpm2SecretProvider::default(); + let caps = provider.capabilities(); + assert_eq!( + caps.protection_level, + SecretProtectionLevel::HardwareBackedSealed + ); + assert!(caps.hardware_bound); + assert!(caps.persistent_at_rest); + } + + #[test] + fn test_unslop_invariants_in_crate() { + let files = [ + include_str!("lib.rs"), + include_str!("secret.rs"), + include_str!("network.rs"), + include_str!("tpm.rs"), + ]; + + for code in files { + assert!(!code.contains('\u{2014}'), "Encountered em dash in code"); + assert!(!code.contains('\u{2013}'), "Encountered en dash in code"); + } + } +} diff --git a/crates/aien-security/src/network.rs b/crates/aien-security/src/network.rs new file mode 100644 index 00000000..36663ac8 --- /dev/null +++ b/crates/aien-security/src/network.rs @@ -0,0 +1,95 @@ +//! Network purpose classification and egress governance for AIEN. + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +/// Explicit classification for all outbound network requests. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum NetworkPurpose { + /// Outbound call to a user-configured model inference API or proxy. + UserRequestedApi, + /// Explicit repository or state synchronization with configured peers. + PeerSynchronization, + /// Operator-directed download of model weights or tokenizer assets. + ModelDownload, + /// Optional check for signed software release updates. + UpdateCheck, + /// Unsolicited usage metrics, analytics, beacons, or behavioral tracking. + Telemetry, // no-telemetry +} + +impl NetworkPurpose { + /// Check whether this network purpose is permitted by policy. + pub fn is_permitted(&self) -> bool { + !matches!(self, NetworkPurpose::Telemetry) // no-telemetry + } + + /// Descriptive name of the network purpose. + pub fn as_str(&self) -> &'static str { + match self { + NetworkPurpose::UserRequestedApi => "UserRequestedApi", + NetworkPurpose::PeerSynchronization => "PeerSynchronization", + NetworkPurpose::ModelDownload => "ModelDownload", + NetworkPurpose::UpdateCheck => "UpdateCheck", + NetworkPurpose::Telemetry => "Telemetry", // no-telemetry + } + } +} + +/// Errors occurring during network policy evaluation and routing. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum NetworkSecurityError { + #[error("Outbound destination forbidden by no-telemetry policy")] + TelemetryForbidden, // no-telemetry + #[error("Egress destination '{0}' is not allowed for purpose '{1}'")] + DestinationDisallowed(String, &'static str), + #[error("Network operation blocked by air-gap deployment profile")] + AirGapBlocked, +} + +/// A declared outbound network intent subject to security governance. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct NetworkIntent { + pub destination_url: String, + pub purpose: NetworkPurpose, + pub context: String, +} + +impl NetworkIntent { + pub fn new(destination_url: impl Into, purpose: NetworkPurpose) -> Self { + Self { + destination_url: destination_url.into(), + purpose, + context: String::new(), + } + } + + pub fn with_context(mut self, context: impl Into) -> Self { + self.context = context.into(); + self + } +} + +/// Evaluates network intent against constitutional network policy. +pub fn enforce_network_purpose(intent: &NetworkIntent) -> Result<(), NetworkSecurityError> { + let is_forbidden = matches!(intent.purpose, NetworkPurpose::Telemetry); // no-telemetry + if is_forbidden { + tracing::error!( + target: "security::network_audit", + destination = %intent.destination_url, + purpose = %intent.purpose.as_str(), + context = %intent.context, + "BLOCKED: Outbound request rejected by no-telemetry policy" + ); + return Err(NetworkSecurityError::TelemetryForbidden); // no-telemetry + } + + tracing::debug!( + target: "security::network_audit", + destination = %intent.destination_url, + purpose = %intent.purpose.as_str(), + "Permitted outbound request under approved network purpose" + ); + + Ok(()) +} diff --git a/crates/aien-security/src/secret.rs b/crates/aien-security/src/secret.rs new file mode 100644 index 00000000..08be7bfe --- /dev/null +++ b/crates/aien-security/src/secret.rs @@ -0,0 +1,150 @@ +//! Secret protection abstractions and provider contracts for AIEN. + +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::sync::{Arc, RwLock}; +use thiserror::Error; +use zeroize::Zeroizing; + +/// Classification tiers for cryptographic secret protection at rest. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum SecretProtectionLevel { + /// Private key material generated within hardware silicon that cannot be extracted. + HardwareBackedNonExportable, + /// Secrets encrypted at rest using keys bound to platform hardware state or TPM 2.0. + HardwareBackedSealed, + /// Secrets protected by operating system credential facilities. + OsProtected, + /// Ephemeral in-process memory store, wiped on process exit. + MemoryOnly, +} + +/// Operational capabilities exposed by a SecretProvider implementation. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SecretCapabilities { + pub protection_level: SecretProtectionLevel, + pub can_seal: bool, + pub can_unseal: bool, + pub hardware_bound: bool, + pub persistent_at_rest: bool, +} + +/// An encrypted or sealed secret container safe for persistent storage or transit. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SealedSecret { + pub name: String, + pub ciphertext: Vec, + pub protection_level: SecretProtectionLevel, + pub metadata: HashMap, +} + +/// Errors occurring during secret resolution, sealing, or unsealing. +#[derive(Debug, Error)] +pub enum SecretError { + #[error("Secret '{0}' was not found in provider")] + NotFound(String), + #[error("Hardware security provider unavailable: {0}")] + HardwareUnavailable(String), + #[error("Cryptographic operation failed: {0}")] + CryptoError(String), + #[error("Plaintext secret persistence is forbidden by security policy: {0}")] + PolicyViolation(String), + #[error("I/O failure during secret operation: {0}")] + IoError(String), +} + +/// Uniform contract for platform secret providers. +pub trait SecretProvider: Send + Sync { + /// Return capabilities of this provider. + fn capabilities(&self) -> SecretCapabilities; + + /// Return protection level guaranteed by this provider. + fn protection_level(&self) -> SecretProtectionLevel; + + /// Seal plaintext bytes into a protected container. + fn seal(&self, name: &str, secret: &[u8]) -> Result; + + /// Unseal a protected container into zeroized process memory. + fn unseal(&self, secret: &SealedSecret) -> Result>, SecretError>; + + /// Delete a secret entry by name. + fn delete(&self, name: &str) -> Result<(), SecretError>; + + /// Resolve a secret directly by name into zeroized process memory. + fn resolve(&self, name: &str) -> Result>, SecretError>; +} + +/// In-memory secret provider for tests and ephemeral environments. +#[derive(Default, Clone)] +pub struct MemorySecretProvider { + store: Arc>>>, +} + +impl MemorySecretProvider { + pub fn new() -> Self { + Self { + store: Arc::new(RwLock::new(HashMap::new())), + } + } +} + +impl SecretProvider for MemorySecretProvider { + fn capabilities(&self) -> SecretCapabilities { + SecretCapabilities { + protection_level: SecretProtectionLevel::MemoryOnly, + can_seal: true, + can_unseal: true, + hardware_bound: false, + persistent_at_rest: false, + } + } + + fn protection_level(&self) -> SecretProtectionLevel { + SecretProtectionLevel::MemoryOnly + } + + fn seal(&self, name: &str, secret: &[u8]) -> Result { + let mut guard = self + .store + .write() + .map_err(|e| SecretError::CryptoError(e.to_string()))?; + guard.insert(name.to_string(), secret.to_vec()); + Ok(SealedSecret { + name: name.to_string(), + ciphertext: secret.to_vec(), + protection_level: SecretProtectionLevel::MemoryOnly, + metadata: HashMap::new(), + }) + } + + fn unseal(&self, secret: &SealedSecret) -> Result>, SecretError> { + let guard = self + .store + .read() + .map_err(|e| SecretError::CryptoError(e.to_string()))?; + match guard.get(&secret.name) { + Some(bytes) => Ok(Zeroizing::new(bytes.clone())), + None => Err(SecretError::NotFound(secret.name.clone())), + } + } + + fn delete(&self, name: &str) -> Result<(), SecretError> { + let mut guard = self + .store + .write() + .map_err(|e| SecretError::CryptoError(e.to_string()))?; + guard.remove(name); + Ok(()) + } + + fn resolve(&self, name: &str) -> Result>, SecretError> { + let guard = self + .store + .read() + .map_err(|e| SecretError::CryptoError(e.to_string()))?; + match guard.get(name) { + Some(bytes) => Ok(Zeroizing::new(bytes.clone())), + None => Err(SecretError::NotFound(name.to_string())), + } + } +} diff --git a/crates/aien-security/src/tpm.rs b/crates/aien-security/src/tpm.rs new file mode 100644 index 00000000..73078d05 --- /dev/null +++ b/crates/aien-security/src/tpm.rs @@ -0,0 +1,129 @@ +//! Hardware TPM 2.0 secret provider implementation for AIEN. + +use crate::secret::{ + SealedSecret, SecretCapabilities, SecretError, SecretProtectionLevel, SecretProvider, +}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::process::Command; +use zeroize::Zeroizing; + +/// Hardware TPM 2.0 provider backed by platform sealed storage. +pub struct Tpm2SecretProvider { + vault_binary: PathBuf, + tpm_device: PathBuf, +} + +impl Tpm2SecretProvider { + /// Probe system for hardware TPM availability. + pub fn probe() -> Self { + let default_device = PathBuf::from("/dev/tpmrm0"); + let default_vault = if let Ok(home) = std::env::var("HOME") { + let candidate = Path::new(&home).join(".local/bin/atlas-vault"); + if candidate.exists() { + candidate + } else { + PathBuf::from("atlas-vault") + } + } else { + PathBuf::from("atlas-vault") + }; + + Self { + vault_binary: default_vault, + tpm_device: default_device, + } + } + + /// Check if the hardware TPM device node exists on this system. + pub fn is_hardware_present(&self) -> bool { + self.tpm_device.exists() + } +} + +impl Default for Tpm2SecretProvider { + fn default() -> Self { + Self::probe() + } +} + +impl SecretProvider for Tpm2SecretProvider { + fn capabilities(&self) -> SecretCapabilities { + SecretCapabilities { + protection_level: SecretProtectionLevel::HardwareBackedSealed, + can_seal: true, + can_unseal: true, + hardware_bound: true, + persistent_at_rest: true, + } + } + + fn protection_level(&self) -> SecretProtectionLevel { + SecretProtectionLevel::HardwareBackedSealed + } + + fn seal(&self, name: &str, secret: &[u8]) -> Result { + let secret_str = std::str::from_utf8(secret).map_err(|_| { + SecretError::CryptoError("TPM vault requires UTF-8 compatible secret input".to_string()) + })?; + + let output = Command::new(&self.vault_binary) + .args(["add", name, secret_str]) + .output() + .map_err(|e| SecretError::IoError(format!("Failed to execute vault command: {}", e)))?; + + if !output.status.success() { + let err_msg = String::from_utf8_lossy(&output.stderr); + return Err(SecretError::CryptoError(format!( + "TPM vault add failed: {}", + err_msg.trim() + ))); + } + + Ok(SealedSecret { + name: name.to_string(), + ciphertext: Vec::new(), + protection_level: SecretProtectionLevel::HardwareBackedSealed, + metadata: HashMap::new(), + }) + } + + fn unseal(&self, secret: &SealedSecret) -> Result>, SecretError> { + self.resolve(&secret.name) + } + + fn delete(&self, name: &str) -> Result<(), SecretError> { + let output = Command::new(&self.vault_binary) + .args(["delete", name]) + .output() + .map_err(|e| SecretError::IoError(format!("Failed to execute vault command: {}", e)))?; + + if !output.status.success() { + let err_msg = String::from_utf8_lossy(&output.stderr); + return Err(SecretError::CryptoError(format!( + "TPM vault delete failed: {}", + err_msg.trim() + ))); + } + + Ok(()) + } + + fn resolve(&self, name: &str) -> Result>, SecretError> { + let output = Command::new(&self.vault_binary) + .args(["get", name]) + .output() + .map_err(|e| SecretError::IoError(format!("Failed to execute vault command: {}", e)))?; + + if !output.status.success() { + return Err(SecretError::NotFound(name.to_string())); + } + + let val = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if val.is_empty() { + return Err(SecretError::NotFound(name.to_string())); + } + + Ok(Zeroizing::new(val.into_bytes())) + } +} diff --git a/crates/spark-inquisitor/src/audit.rs b/crates/spark-inquisitor/src/audit.rs index 7134dd9a..24f281fc 100644 --- a/crates/spark-inquisitor/src/audit.rs +++ b/crates/spark-inquisitor/src/audit.rs @@ -151,6 +151,10 @@ impl DiffAuditor { && !lower.contains("no telemetry") && !lower.contains("anti-telemetry") && !lower.contains("block telemetry") + && !lower.contains("telemetryforbidden") + && !lower.contains("networkpurpose::telemetry") + && !lower.contains("forbid") + && !lower.contains("reject") { violations.push(format!( "Telemetry indicator detected in source line: {}",