1use std::collections::HashMap;
11use std::fmt;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::time::{Duration, SystemTime, UNIX_EPOCH};
14
15#[derive(Debug)]
19pub struct HsmStubError {
20 pub message: String,
22 pub error_code: u32,
24 pub timestamp: u64,
26 pub security_level: SecurityLevel,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32pub enum SecurityLevel {
33 #[default]
35 Info,
36 Warning,
38 Error,
40 Critical,
42}
43
44impl HsmStubError {
45 pub fn feature_disabled() -> Self {
48 Self {
49 message: "This feature is disabled in the current configuration".to_string(),
50 error_code: 1001,
51 timestamp: SystemTime::now()
52 .duration_since(UNIX_EPOCH)
53 .unwrap_or(Duration::from_secs(0))
54 .as_secs(),
55 security_level: SecurityLevel::Warning,
56 }
57 }
58
59 pub fn with_security_level(msg: &str, level: SecurityLevel) -> Self {
61 Self {
62 message: msg.to_string(),
63 error_code: match level {
64 SecurityLevel::Info => 1000,
65 SecurityLevel::Warning => 2000,
66 SecurityLevel::Error => 3000,
67 SecurityLevel::Critical => 4000,
68 },
69 timestamp: SystemTime::now()
70 .duration_since(UNIX_EPOCH)
71 .unwrap_or(Duration::from_secs(0))
72 .as_secs(),
73 security_level: level,
74 }
75 }
76
77 pub fn is_critical(&self) -> bool {
79 self.security_level == SecurityLevel::Critical
80 }
81}
82
83impl fmt::Display for HsmStubError {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 write!(f, "HSM functionality not available: {}", self.message)
86 }
87}
88
89impl std::error::Error for HsmStubError {}
90
91pub fn hsm_stub_error(msg: &str) -> HsmStubError {
94 HsmStubError {
95 message: format!("HSM support disabled: {msg}"),
96 error_code: 1001,
97 timestamp: SystemTime::now()
98 .duration_since(UNIX_EPOCH)
99 .unwrap_or(Duration::from_secs(0))
100 .as_secs(),
101 security_level: SecurityLevel::Warning,
102 }
103}
104
105pub fn hsm_critical_error(msg: &str) -> HsmStubError {
107 HsmStubError::with_security_level(msg, SecurityLevel::Critical)
108}
109
110#[derive(Debug)]
113pub struct HsmManager {
114 initialization_attempted: AtomicBool,
116 config: HashMap<String, String>,
118}
119
120impl HsmManager {
121 pub fn new(config: HashMap<String, String>) -> Result<Self, HsmStubError> {
124 if let Some(security_mode) = config.get("security_mode") {
127 if security_mode == "enforce" {
128 return Err(hsm_critical_error(
129 "Security mode 'enforce' requires full HSM implementation",
130 ));
131 }
132 }
133
134 Ok(Self {
135 initialization_attempted: AtomicBool::new(false),
136 config,
137 })
138 }
139
140 pub async fn initialize(&self) -> Result<(), HsmStubError> {
143 self.initialization_attempted.store(true, Ordering::SeqCst);
144 Err(hsm_stub_error("HSM functionality is disabled"))
145 }
146
147 pub async fn get_status(&self) -> Result<HsmStatus, HsmStubError> {
150 if !self.initialization_attempted.load(Ordering::SeqCst) {
151 return Err(hsm_stub_error(
152 "HSM not initialized. Call initialize() first",
153 ));
154 }
155
156 Err(hsm_stub_error("HSM functionality is disabled"))
157 }
158
159 pub fn validate_config(&self) -> Result<bool, HsmStubError> {
161 if let Some(provider) = self.config.get("provider") {
163 match provider.as_str() {
164 "software" | "hardware" | "simulator" | "pkcs11" | "tpm" | "ledger" => Ok(true),
165 _ => Err(hsm_stub_error("Invalid HSM provider specified")),
166 }
167 } else {
168 Err(hsm_stub_error(
169 "Missing required 'provider' config parameter",
170 ))
171 }
172 }
173}
174
175#[derive(Debug, Clone)]
178pub struct HsmStatus {
179 pub provider_name: String,
181 pub available: bool,
183 pub security_level: SecurityLevel,
185 pub last_checked: u64,
187 pub secure_boot_verified: bool,
189}
190
191#[derive(Debug, Clone)]
193pub enum KeyType {
194 Rsa,
195 Ec,
196 Aes,
197 Hmac,
198}
199
200#[derive(Debug, Clone)]
202pub enum SigningAlgorithm {
203 RsaSha256,
204 EcdsaP256,
205}
206
207pub trait HsmProvider: Send + Sync {
210 fn is_available(&self) -> bool {
212 false
213 }
214
215 fn provider_name(&self) -> &str;
217
218 fn security_level(&self) -> SecurityLevel {
220 SecurityLevel::Info
221 }
222}
223
224
225#[derive(Debug, Clone, Default)]
229pub struct BitcoinHsmProvider;
230
231impl BitcoinHsmProvider {
232 pub fn new() -> Self {
234 BitcoinHsmProvider
235 }
236
237 pub fn validate_security(&self) -> Result<(), HsmStubError> {
239 Ok(())
240 }
241}
242
243impl HsmProvider for BitcoinHsmProvider {
244 fn provider_name(&self) -> &str {
245 "bitcoin_hsm"
246 }
247
248 fn security_level(&self) -> SecurityLevel {
249 SecurityLevel::Critical }
251}
252
253#[derive(Debug, Clone, Default)]
257pub struct SoftwareHsmProvider;
258
259impl SoftwareHsmProvider {
260 pub fn new(_config: &impl std::fmt::Debug) -> Result<Self, HsmStubError> {
262 Err(hsm_stub_error(
263 "SoftwareHsmProvider is disabled in this build",
264 ))
265 }
266}
267
268impl HsmProvider for SoftwareHsmProvider {
269 fn provider_name(&self) -> &str {
270 "software_hsm"
271 }
272
273 fn security_level(&self) -> SecurityLevel {
274 SecurityLevel::Warning }
276}
277
278#[derive(Debug, Clone, Default)]
281pub struct SimulatorHsmProvider;
282
283impl SimulatorHsmProvider {
284 pub fn new(_config: &impl std::fmt::Debug) -> Result<Self, HsmStubError> {
285 Err(hsm_stub_error(
286 "SimulatorHsmProvider is disabled in this build",
287 ))
288 }
289}
290
291#[derive(Debug, Clone, Default)]
294pub struct HardwareHsmProvider;
295
296impl HardwareHsmProvider {
297 pub fn new(_config: &impl std::fmt::Debug) -> Result<Self, HsmStubError> {
298 Err(hsm_stub_error(
299 "HardwareHsmProvider is disabled in this build",
300 ))
301 }
302}
303
304#[derive(Debug, Clone, Default)]
307pub struct Pkcs11HsmProvider;
308
309impl Pkcs11HsmProvider {
310 pub fn new(_config: &impl std::fmt::Debug) -> Result<Self, HsmStubError> {
311 Err(hsm_stub_error(
312 "Pkcs11HsmProvider is disabled in this build",
313 ))
314 }
315}
316
317#[derive(Debug, Clone, Default)]
320pub struct TpmHsmProvider;
321
322impl TpmHsmProvider {
323 pub fn new(_config: &impl std::fmt::Debug) -> Result<Self, HsmStubError> {
324 Err(hsm_stub_error("TpmHsmProvider is disabled in this build"))
325 }
326}
327
328#[derive(Debug, Clone, Default)]
331pub struct LedgerHsmProvider;
332
333impl LedgerHsmProvider {
334 pub fn new(_config: &impl std::fmt::Debug) -> Result<Self, HsmStubError> {
335 Err(hsm_stub_error(
336 "LedgerHsmProvider is disabled in this build",
337 ))
338 }
339}
340
341#[derive(Debug, Clone, Default)]
344pub struct HsmConfig {
345 pub provider_type: String,
347 pub security_level: SecurityLevel,
349 pub parameters: HashMap<String, String>,
351 pub enforce_secure_boot: bool,
353}
354
355impl HsmConfig {
356 pub fn new(provider: &str) -> Self {
358 HsmConfig {
359 provider_type: provider.to_string(),
360 ..Default::default()
361 }
362 }
363
364 pub fn with_param(mut self, key: &str, value: &str) -> Self {
366 self.parameters.insert(key.to_string(), value.to_string());
367 self
368 }
369
370 pub fn with_security_level(mut self, level: SecurityLevel) -> Self {
372 self.security_level = level;
373 self
374 }
375
376 pub fn enforce_secure_boot(mut self) -> Self {
378 self.enforce_secure_boot = true;
379 self
380 }
381}