anya_core/security/
mod.rs

1//! Security Module
2//!
3//! This module provides security functionality for the Anya Core platform,
4//! including system hardening, input validation, and hardware security module (HSM)
5//! support for cryptographic operations.
6
7// Basic security modules always available
8pub mod system_hardening;
9
10pub mod constant_time;
11
12// Cryptographic operations module
13pub mod crypto;
14
15// Add encryption sub-module for easier access
16pub mod encryption {
17    pub use super::crypto::symmetric::*;
18}
19
20// Hardware Security Module (conditionally included)
21#[cfg(feature = "hsm")]
22pub mod hsm;
23
24// Include shim implementation when HSM feature is disabled
25#[cfg(not(feature = "hsm"))]
26pub mod hsm_shim;
27
28// Re-exports for convenience
29pub use system_hardening::ConfigStatus;
30pub use system_hardening::HardeningConfig;
31pub use system_hardening::SecurityLevel;
32pub use system_hardening::SystemHardening;
33
34// Conditionally re-export HSM types based on feature flag
35#[cfg(feature = "hsm")]
36pub use hsm::config::HsmConfig;
37#[cfg(feature = "hsm")]
38pub use hsm::provider::{HsmProvider, KeyGenParams, KeyType, SigningAlgorithm};
39#[cfg(feature = "hsm")]
40pub use hsm::{HsmManager, HsmStatus};
41
42// When HSM feature is disabled, use the shim implementation instead
43#[cfg(not(feature = "hsm"))]
44pub use hsm_shim::{HsmManager, HsmStatus, HsmStubError, KeyType, SigningAlgorithm};
45
46/// Helper function to create a system hardening manager with default auto-save frequency (20)
47pub fn create_system_hardening() -> SystemHardening {
48    SystemHardening::new(20)
49}
50
51/// Helper function to create a basic security configuration for a component
52pub fn create_basic_security_config(
53    component_name: &str,
54) -> std::collections::HashMap<String, String> {
55    let mut settings = std::collections::HashMap::new();
56    // Basic security settings
57    settings.insert("firewall".to_string(), "enabled".to_string());
58    settings.insert("encryption".to_string(), "enabled".to_string());
59    settings.insert("access_control".to_string(), "strict".to_string());
60    settings.insert("audit_logging".to_string(), "enabled".to_string());
61    settings.insert("intrusion_detection".to_string(), "enabled".to_string());
62
63    // Component-specific settings
64    match component_name {
65        "network" => {
66            settings.insert(
67                "port_scanning_protection".to_string(),
68                "enabled".to_string(),
69            );
70            settings.insert("ddos_protection".to_string(), "enabled".to_string());
71        }
72        "database" => {
73            settings.insert("query_sanitization".to_string(), "strict".to_string());
74            settings.insert("data_encryption".to_string(), "aes-256".to_string());
75        }
76        "api" => {
77            settings.insert("rate_limiting".to_string(), "enabled".to_string());
78            settings.insert("input_validation".to_string(), "strict".to_string());
79        }
80        _ => {
81            // Generic settings for other components
82            settings.insert("default_deny".to_string(), "enabled".to_string());
83        }
84    }
85
86    settings
87}
88
89// Security module
90// Implements security features for Bitcoin operations
91// as per official Bitcoin Improvement Proposals (BIPs) requirements
92
93use log::info;
94// [AIR-3][AIS-3][BPC-3][RES-3] Constant time module already declared above
95
96// [AIR-3][AIS-3][BPC-3][RES-3] Conditionally export HSM types when the feature is enabled
97// This follows official Bitcoin Improvement Proposals (BIPs) standards for HSM implementations
98#[cfg(feature = "hsm")]
99pub use hsm::{
100    audit::{AuditEvent, AuditLoggerConfig, AuditStorageType},
101    // Remove the bitcoin import from hsm since it's not available
102    // bitcoin::{
103    //     BitcoinHsmProvider,
104    //     BitcoinHsmConfig,
105    //     BitcoinKeyInfo,
106    //     BitcoinKeyType,
107    //     BitcoinNetwork,
108    //     BitcoinSignatureType,
109    //     TaprootOutputInfo,
110    //     TaprootScriptTree,
111    //     BitcoinScriptDetails,
112    //     BitcoinScriptType,
113    //     BitcoinSpvProof,
114    //     DlcInfo,
115    //     DlcParams,
116    //     create_dlc,
117    // },
118    // Only export the types that are actually used in the codebase
119    error::HsmError,
120};
121
122// Other security modules - to be implemented
123// pub mod authentication;
124// pub mod authorization;
125// pub mod compliance;
126// pub mod crypto;
127// pub mod secrets;
128// pub mod validation;
129
130/// Initialize the security subsystem
131///
132/// This function initializes the security subsystem, including the HSM manager
133/// if configured. It follows the security requirements specified in the
134/// official Bitcoin Improvement Proposals (BIPs).
135///
136/// # Returns
137/// `Ok(())` on success, `Err` on failure
138pub async fn initialize() -> Result<(), Box<dyn std::error::Error>> {
139    info!("Initializing security subsystem");
140
141    // Initialize HSM if configured
142    // This is just placeholder code - actual initialization would be handled by the application
143
144    // let hsm_config = HsmConfig::development();
145    // let hsm_manager = HsmManager::new(hsm_config);
146    // hsm_manager.initialize().await?;
147
148    info!("Security subsystem initialized");
149    Ok(())
150}
151
152/// Create a Bitcoin HSM provider with default configuration
153///
154/// This function creates a Bitcoin HSM provider with default configuration,
155/// using the specified HSM provider as the base provider.
156///
157/// # Arguments
158/// * `base_provider` - Base HSM provider to use
159///
160/// # Returns
161/// BitcoinHsmProvider configured for Bitcoin operations
162#[cfg(feature = "hsm")]
163pub async fn create_bitcoin_hsm_provider(
164    _base_provider: std::sync::Arc<dyn hsm::provider::HsmProvider>,
165) -> Result<hsm::providers::bitcoin::BitcoinHsmProvider, hsm::error::HsmError> {
166    #[cfg(feature = "hsm")]
167    let config = hsm::config::BitcoinConfig {
168        network: hsm::config::BitcoinNetworkType::Testnet, // Default to testnet for safety
169        rpc_url: Some("http://127.0.0.1:18332".to_string()),
170        rpc_username: Some("user".to_string()),
171        rpc_password: Some("password".to_string()),
172        derivation_path_template: "m/84'/0'/0'/{index}".to_string(),
173        use_segwit: true,
174        use_taproot: true,
175        confirm_transactions: false,
176        default_fee_rate: 5,
177    };
178
179    hsm::providers::bitcoin::BitcoinHsmProvider::new(&config).await
180}
181
182#[cfg(not(feature = "hsm"))]
183pub fn create_bitcoin_hsm_provider(
184    _base_provider: std::sync::Arc<dyn hsm_shim::HsmProvider>,
185) -> hsm_shim::BitcoinHsmProvider {
186    #[allow(clippy::default_constructed_unit_structs)]
187    hsm_shim::BitcoinHsmProvider::default()
188}
189
190/// Verify a Bitcoin payment using SPV proof
191///
192/// This function verifies a Bitcoin payment using SPV proof, as described
193/// in official Bitcoin Improvement Proposals (BIPs) requirements.
194///
195/// # Arguments
196/// * `bitcoin_provider` - Bitcoin HSM provider
197/// * `proof` - SPV proof of the payment
198///
199/// # Returns
200/// `Ok(true)` if payment is valid, `Ok(false)` if not, `Err` on failure
201#[cfg(feature = "hsm")]
202pub async fn verify_bitcoin_payment(
203    _bitcoin_provider: &hsm::providers::bitcoin::BitcoinHsmProvider,
204    _proof_data: Vec<u8>,
205) -> Result<bool, hsm::error::HsmError> {
206    // This would normally verify an SPV proof
207    // For now, it simply returns success as a placeholder
208    Ok(true)
209}
210
211#[cfg(not(feature = "hsm"))]
212// [AIR-3][AIS-3][BPC-3][RES-3]
213pub async fn verify_bitcoin_payment(
214    _bitcoin_provider: &hsm_shim::BitcoinHsmProvider,
215    _proof_data: Vec<u8>,
216) -> Result<bool, hsm_shim::HsmStubError> {
217    // Fallback stub for when HSM is not enabled
218    // [AIR-3][AIS-3][BPC-3][RES-3]
219    Err(hsm_shim::HsmStubError::feature_disabled())
220}
221
222/// Create a Taproot asset
223///
224/// This function creates a Taproot asset as specified in the Bitcoin Development
225/// Framework v2.5 requirements, using the provided metadata.
226///
227/// # Arguments
228/// * `bitcoin_provider` - Bitcoin HSM provider
229/// * `metadata` - Asset metadata
230/// * `supply` - Asset supply
231///
232/// # Returns
233/// `Ok(asset_id)` on success, `Err` on failure
234#[cfg(feature = "hsm")]
235pub async fn create_taproot_asset(
236    bitcoin_provider: &hsm::providers::bitcoin::BitcoinHsmProvider,
237    metadata: &str,
238    supply: u64,
239) -> Result<String, hsm::error::HsmError> {
240    // Generate a key for the asset using the correct KeyGenParams structure
241    let mut attributes = std::collections::HashMap::new();
242    attributes.insert("metadata".to_string(), metadata.to_string());
243    attributes.insert("supply".to_string(), supply.to_string());
244
245    let key_params = hsm::provider::KeyGenParams {
246        id: Some("asset".to_string()),
247        label: Some(format!("Asset key for {}", metadata)),
248        key_type: hsm::provider::KeyType::Ec {
249            curve: hsm::provider::EcCurve::Secp256k1,
250        },
251        extractable: false,
252        usages: vec![hsm::provider::KeyUsage::Sign],
253        expires_at: None,
254        attributes,
255    };
256
257    // [AIR-3][AIS-3][BPC-3][RES-3] Generate the key and return its ID
258    let (key_pair, _key_info) = bitcoin_provider.generate_key(key_params).await?;
259    Ok(key_pair.id)
260}
261
262#[cfg(not(feature = "hsm"))]
263// [AIR-3][AIS-3][BPC-3][RES-3]
264pub async fn create_taproot_asset(
265    _bitcoin_provider: &hsm_shim::BitcoinHsmProvider,
266    _metadata: &str,
267    _supply: u64,
268) -> Result<String, hsm_shim::HsmStubError> {
269    // Fallback stub for when HSM is not enabled
270    // [AIR-3][AIS-3][BPC-3][RES-3]
271    Err(hsm_shim::HsmStubError::feature_disabled())
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277
278    #[test]
279    fn test_basic_security_config() {
280        let network_config = create_basic_security_config("network");
281        let db_config = create_basic_security_config("database");
282
283        // Check common settings
284        assert_eq!(network_config.get("firewall"), Some(&"enabled".to_string()));
285        assert_eq!(db_config.get("firewall"), Some(&"enabled".to_string()));
286
287        // Check component-specific settings
288        assert_eq!(
289            network_config.get("ddos_protection"),
290            Some(&"enabled".to_string())
291        );
292        assert_eq!(
293            db_config.get("data_encryption"),
294            Some(&"aes-256".to_string())
295        );
296    }
297}