1use std::fs::{File, OpenOptions};
6use std::io::{BufRead, BufReader, Write};
7#[cfg(unix)]
8use std::os::unix::fs::OpenOptionsExt;
9use std::path::{Path, PathBuf};
10
11use base64::{engine::general_purpose::STANDARD, Engine};
12use serde::{Deserialize, Serialize};
13use subtle::ConstantTimeEq;
14
15use crate::crypto::{self, SecretKey};
16use crate::error::{Result, StorageError};
17
18fn hash_optional_str(data: &mut Vec<u8>, value: Option<&str>) {
19 match value {
20 Some(s) => {
21 data.push(1);
22 let len = u32::try_from(s.len()).expect("string too long for hash");
23 data.extend_from_slice(&len.to_le_bytes());
24 data.extend_from_slice(s.as_bytes());
25 }
26 None => data.push(0),
27 }
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32#[repr(u8)]
33pub enum AuditEventType {
34 KeyGenerate = 0,
36 KeyImport = 1,
38 KeyExport = 2,
40 KeyDelete = 3,
42 Sign = 4,
44 SignFailed = 5,
46 FrostGenerate = 6,
48 FrostSplit = 7,
50 FrostSign = 8,
52 FrostSignFailed = 9,
54 FrostSessionStart = 10,
56 FrostSessionComplete = 11,
58 FrostSessionFailed = 12,
60 FrostShareImport = 13,
62 FrostShareExport = 14,
64 FrostShareDelete = 15,
66 AuthFailed = 16,
68 VaultUnlock = 17,
70 VaultLock = 18,
72 FrostShareRefresh = 19,
74 RateLimitTripped = 20,
78 PasswordRotate = 21,
80 PasswordRotateFailed = 22,
85 DataKeyRotate = 23,
87 DataKeyRotateFailed = 24,
90 SecretCreate = 25,
92 SecretDelete = 26,
94 SecretReveal = 27,
98}
99
100impl std::fmt::Display for AuditEventType {
101 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102 match self {
103 Self::KeyGenerate => write!(f, "key_generate"),
104 Self::KeyImport => write!(f, "key_import"),
105 Self::KeyExport => write!(f, "key_export"),
106 Self::KeyDelete => write!(f, "key_delete"),
107 Self::Sign => write!(f, "sign"),
108 Self::SignFailed => write!(f, "sign_failed"),
109 Self::FrostGenerate => write!(f, "frost_generate"),
110 Self::FrostSplit => write!(f, "frost_split"),
111 Self::FrostSign => write!(f, "frost_sign"),
112 Self::FrostSignFailed => write!(f, "frost_sign_failed"),
113 Self::FrostSessionStart => write!(f, "frost_session_start"),
114 Self::FrostSessionComplete => write!(f, "frost_session_complete"),
115 Self::FrostSessionFailed => write!(f, "frost_session_failed"),
116 Self::FrostShareImport => write!(f, "frost_share_import"),
117 Self::FrostShareExport => write!(f, "frost_share_export"),
118 Self::FrostShareDelete => write!(f, "frost_share_delete"),
119 Self::AuthFailed => write!(f, "auth_failed"),
120 Self::VaultUnlock => write!(f, "vault_unlock"),
121 Self::VaultLock => write!(f, "vault_lock"),
122 Self::FrostShareRefresh => write!(f, "frost_share_refresh"),
123 Self::RateLimitTripped => write!(f, "rate_limit_tripped"),
124 Self::PasswordRotate => write!(f, "password_rotate"),
125 Self::PasswordRotateFailed => write!(f, "password_rotate_failed"),
126 Self::DataKeyRotate => write!(f, "data_key_rotate"),
127 Self::DataKeyRotateFailed => write!(f, "data_key_rotate_failed"),
128 Self::SecretCreate => write!(f, "secret_create"),
129 Self::SecretDelete => write!(f, "secret_delete"),
130 Self::SecretReveal => write!(f, "secret_reveal"),
131 }
132 }
133}
134
135#[derive(Debug, Clone, Serialize, Deserialize)]
137pub struct AuditEntry {
138 pub timestamp: i64,
140 pub event_type: AuditEventType,
142 pub pubkey: Option<String>,
144 pub key_type: Option<String>,
146 pub message_hash: Option<String>,
148 pub group_pubkey: Option<String>,
150 pub participants: Option<Vec<u16>>,
152 pub threshold: Option<u16>,
154 pub success: bool,
156 pub reason: Option<String>,
158 pub prev_hash: [u8; 32],
160 pub hash: [u8; 32],
162}
163
164impl AuditEntry {
165 pub fn new(event_type: AuditEventType, prev_hash: [u8; 32]) -> Self {
167 Self {
168 timestamp: chrono::Utc::now().timestamp(),
169 event_type,
170 pubkey: None,
171 key_type: None,
172 message_hash: None,
173 group_pubkey: None,
174 participants: None,
175 threshold: None,
176 success: true,
177 reason: None,
178 prev_hash,
179 hash: [0u8; 32],
180 }
181 }
182
183 pub fn with_pubkey(mut self, pubkey: &[u8; 32]) -> Self {
185 self.pubkey = Some(hex::encode(pubkey));
186 self
187 }
188
189 pub fn with_key_type(mut self, key_type: &str) -> Self {
191 self.key_type = Some(key_type.to_string());
192 self
193 }
194
195 pub fn with_message_hash(mut self, message: &[u8]) -> Self {
197 self.message_hash = Some(hex::encode(crypto::blake2b_256(message)));
198 self
199 }
200
201 pub fn with_group(mut self, group_pubkey: &[u8; 32]) -> Self {
203 self.group_pubkey = Some(hex::encode(group_pubkey));
204 self
205 }
206
207 pub fn with_participants(mut self, participants: Vec<u16>) -> Self {
209 self.participants = Some(participants);
210 self
211 }
212
213 pub fn with_threshold(mut self, threshold: u16) -> Self {
215 self.threshold = Some(threshold);
216 self
217 }
218
219 pub fn with_success(mut self, success: bool) -> Self {
221 self.success = success;
222 self
223 }
224
225 pub fn with_reason(mut self, reason: &str) -> Self {
227 self.reason = Some(reason.to_string());
228 self
229 }
230
231 pub fn finalize(mut self) -> Self {
233 self.hash = self.compute_hash();
234 self
235 }
236
237 fn compute_hash(&self) -> [u8; 32] {
238 let mut data = Vec::new();
239 data.extend_from_slice(&self.timestamp.to_le_bytes());
240 data.extend_from_slice(&(self.event_type as u8).to_le_bytes());
241 hash_optional_str(&mut data, self.pubkey.as_deref());
242 hash_optional_str(&mut data, self.key_type.as_deref());
243 hash_optional_str(&mut data, self.message_hash.as_deref());
244 hash_optional_str(&mut data, self.group_pubkey.as_deref());
245 if let Some(ref p) = self.participants {
246 data.push(1);
247 let len = u32::try_from(p.len()).expect("participants too long for hash");
248 data.extend_from_slice(&len.to_le_bytes());
249 for id in p {
250 data.extend_from_slice(&id.to_le_bytes());
251 }
252 } else {
253 data.push(0);
254 }
255 if let Some(t) = self.threshold {
256 data.push(1);
257 data.extend_from_slice(&t.to_le_bytes());
258 } else {
259 data.push(0);
260 }
261 data.push(self.success as u8);
262 hash_optional_str(&mut data, self.reason.as_deref());
263 data.extend_from_slice(&self.prev_hash);
264 crypto::blake2b_256(&data)
265 }
266
267 pub fn verify(&self, prev_hash: &[u8; 32]) -> bool {
269 let prev_hash_match = self.prev_hash.ct_eq(prev_hash);
270 let hash_match = self.hash.ct_eq(&self.compute_hash());
271 (prev_hash_match & hash_match).into()
272 }
273}
274
275#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
277pub struct RetentionPolicy {
278 pub max_entries: Option<usize>,
280 pub max_age_days: Option<u32>,
282}
283
284impl Default for RetentionPolicy {
285 fn default() -> Self {
286 Self {
287 max_entries: Some(10000),
288 max_age_days: Some(365),
289 }
290 }
291}
292
293pub struct AuditLog {
295 path: PathBuf,
296 last_hash: [u8; 32],
297 retention: RetentionPolicy,
298}
299
300impl AuditLog {
301 pub fn open(path: &Path, data_key: &SecretKey) -> Result<Self> {
303 let audit_path = path.join("audit.log");
304 let last_hash = if audit_path.exists() {
305 Self::read_last_hash(&audit_path, data_key)?
306 } else {
307 [0u8; 32]
308 };
309
310 Ok(Self {
311 path: audit_path,
312 last_hash,
313 retention: RetentionPolicy::default(),
314 })
315 }
316
317 pub fn set_retention(&mut self, policy: RetentionPolicy) {
319 self.retention = policy;
320 }
321
322 pub fn log(&mut self, mut entry: AuditEntry, data_key: &SecretKey) -> Result<()> {
324 entry.prev_hash = self.last_hash;
325 entry.hash = entry.compute_hash();
326
327 let serialized = serde_json::to_vec(&entry)
328 .map_err(|e| StorageError::serialization(format!("audit entry: {e}")))?;
329
330 let encrypted = crypto::encrypt(&serialized, data_key)?;
331 let line = format!("{}\n", STANDARD.encode(encrypted.to_bytes()));
332
333 let mut opts = OpenOptions::new();
334 opts.create(true).append(true);
335 #[cfg(unix)]
336 opts.mode(0o600);
337 let mut file = opts.open(&self.path)?;
338 file.write_all(line.as_bytes())?;
339 file.sync_all()?;
340
341 self.last_hash = entry.hash;
342 Ok(())
343 }
344
345 pub fn read_all(&self, data_key: &SecretKey) -> Result<Vec<AuditEntry>> {
347 if !self.path.exists() {
348 return Ok(Vec::new());
349 }
350 Self::read_entries(&self.path, data_key)
351 }
352
353 pub fn verify_chain(&self, data_key: &SecretKey) -> Result<bool> {
355 let entries = self.read_all(data_key)?;
356 let mut prev_hash = [0u8; 32];
357
358 for entry in entries {
359 if !entry.verify(&prev_hash) {
360 return Ok(false);
361 }
362 prev_hash = entry.hash;
363 }
364
365 Ok(true)
366 }
367
368 pub fn apply_retention(&mut self, data_key: &SecretKey) -> Result<usize> {
370 let entries = self.read_all(data_key)?;
371 let original_count = entries.len();
372 let now = chrono::Utc::now().timestamp();
373 let max_age_secs = self.retention.max_age_days.map(|d| i64::from(d) * 86400);
374
375 let mut filtered: Vec<_> = entries
376 .into_iter()
377 .filter(|e| max_age_secs.is_none_or(|max| now.saturating_sub(e.timestamp) <= max))
378 .collect();
379
380 if let Some(max) = self.retention.max_entries {
381 if filtered.len() > max {
382 filtered = filtered.split_off(filtered.len() - max);
383 }
384 }
385
386 let removed = original_count - filtered.len();
387 if removed > 0 {
388 self.rewrite(&filtered, data_key)?;
389 }
390
391 Ok(removed)
392 }
393
394 pub fn export(&self, data_key: &SecretKey) -> Result<String> {
396 let entries = self.read_all(data_key)?;
397 serde_json::to_string_pretty(&entries)
398 .map_err(|e| StorageError::serialization(format!("export audit log: {e}")).into())
399 }
400
401 fn read_last_hash(path: &Path, data_key: &SecretKey) -> Result<[u8; 32]> {
402 let entries = Self::read_entries(path, data_key)?;
403 Ok(entries.last().map_or([0u8; 32], |e| e.hash))
404 }
405
406 fn read_entries(path: &Path, data_key: &SecretKey) -> Result<Vec<AuditEntry>> {
407 const MAX_ENTRIES: usize = 100_000;
408
409 let file = File::open(path)?;
410 let reader = BufReader::new(file);
411 let mut entries = Vec::new();
412
413 for (line_num, line) in reader.lines().enumerate() {
414 if entries.len() >= MAX_ENTRIES {
415 return Err(StorageError::io(format!(
416 "audit log exceeds maximum of {MAX_ENTRIES} entries"
417 ))
418 .into());
419 }
420 let line = line?;
421 if line.is_empty() {
422 continue;
423 }
424 let entry = Self::decrypt_line(&line, data_key).map_err(|e| {
425 StorageError::corrupted(format!("audit log at line {}: {}", line_num + 1, e))
426 })?;
427 entries.push(entry);
428 }
429
430 Ok(entries)
431 }
432
433 fn decrypt_line(line: &str, data_key: &SecretKey) -> Result<AuditEntry> {
434 let bytes = STANDARD
435 .decode(line)
436 .map_err(|e| StorageError::invalid_format(format!("audit line: {e}")))?;
437
438 let encrypted = crypto::EncryptedData::from_bytes(&bytes)?;
439 let decrypted = crypto::decrypt(&encrypted, data_key)?;
440
441 serde_json::from_slice(&decrypted.as_slice()?)
442 .map_err(|e| StorageError::invalid_format(format!("audit entry: {e}")).into())
443 }
444
445 fn rewrite(&mut self, entries: &[AuditEntry], data_key: &SecretKey) -> Result<()> {
446 let temp_path = self.path.with_extension("log.tmp");
447 let backup_path = self.path.with_extension("log.bak");
448
449 let final_hash = match self.write_entries_to_temp(&temp_path, entries, data_key) {
450 Ok(hash) => hash,
451 Err(e) => {
452 let _ = std::fs::remove_file(&temp_path);
453 return Err(e);
454 }
455 };
456
457 if self.path.exists() {
458 if let Err(e) = std::fs::rename(&self.path, &backup_path) {
459 let _ = std::fs::remove_file(&temp_path);
460 return Err(StorageError::io(format!("backup existing audit log: {e}")).into());
461 }
462 }
463
464 if let Err(e) = std::fs::rename(&temp_path, &self.path) {
465 if backup_path.exists() {
466 let _ = std::fs::rename(&backup_path, &self.path);
467 }
468 let _ = std::fs::remove_file(&temp_path);
469 return Err(StorageError::io(format!("replace audit log: {e}")).into());
470 }
471
472 let _ = std::fs::remove_file(&backup_path);
473 self.last_hash = final_hash;
474 Ok(())
475 }
476
477 fn write_entries_to_temp(
478 &self,
479 temp_path: &Path,
480 entries: &[AuditEntry],
481 data_key: &SecretKey,
482 ) -> Result<[u8; 32]> {
483 let mut opts = OpenOptions::new();
484 opts.write(true).create(true).truncate(true);
485 #[cfg(unix)]
486 opts.mode(0o600);
487 let mut file = opts.open(temp_path)?;
488
489 let mut prev_hash = [0u8; 32];
490 for entry in entries {
491 let mut entry = entry.clone();
492 entry.prev_hash = prev_hash;
493 entry.hash = entry.compute_hash();
494
495 let serialized = serde_json::to_vec(&entry)
496 .map_err(|e| StorageError::serialization(e.to_string()))?;
497
498 let encrypted = crypto::encrypt(&serialized, data_key)?;
499 let line = format!("{}\n", STANDARD.encode(encrypted.to_bytes()));
500 file.write_all(line.as_bytes())?;
501 prev_hash = entry.hash;
502 }
503
504 file.sync_all()?;
505 Ok(prev_hash)
506 }
507
508 pub fn last_hash(&self) -> [u8; 32] {
510 self.last_hash
511 }
512
513 pub fn reencrypt(&mut self, old_key: &SecretKey, new_key: &SecretKey) -> Result<()> {
515 if !self.path.exists() {
516 return Ok(());
517 }
518 let entries = Self::read_entries(&self.path, old_key)?;
519 if entries.is_empty() {
520 return Ok(());
521 }
522 self.rewrite(&entries, new_key)
523 }
524}
525
526#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
528#[repr(u8)]
529pub enum SigningRequestType {
530 Connect = 0,
532 GetPublicKey = 1,
534 SignEvent = 2,
536 Nip04Encrypt = 3,
538 Nip04Decrypt = 4,
540 Nip44Encrypt = 5,
542 Nip44Decrypt = 6,
544 Disconnect = 7,
546 KillSwitch = 8,
548}
549
550impl std::fmt::Display for SigningRequestType {
551 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
552 match self {
553 Self::Connect => write!(f, "connect"),
554 Self::GetPublicKey => write!(f, "get_public_key"),
555 Self::SignEvent => write!(f, "sign_event"),
556 Self::Nip04Encrypt => write!(f, "nip04_encrypt"),
557 Self::Nip04Decrypt => write!(f, "nip04_decrypt"),
558 Self::Nip44Encrypt => write!(f, "nip44_encrypt"),
559 Self::Nip44Decrypt => write!(f, "nip44_decrypt"),
560 Self::Disconnect => write!(f, "disconnect"),
561 Self::KillSwitch => write!(f, "kill_switch"),
562 }
563 }
564}
565
566#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
568#[repr(u8)]
569pub enum SigningDecision {
570 Approved = 0,
572 Denied = 1,
574}
575
576impl std::fmt::Display for SigningDecision {
577 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
578 match self {
579 Self::Approved => write!(f, "approved"),
580 Self::Denied => write!(f, "denied"),
581 }
582 }
583}
584
585#[derive(Debug, Clone, Serialize, Deserialize)]
587pub struct SigningAuditEntry {
588 pub timestamp: i64,
590 pub request_type: SigningRequestType,
592 pub decision: SigningDecision,
594 pub was_automatic: bool,
596 pub caller: String,
598 pub caller_name: Option<String>,
600 pub event_kind: Option<u32>,
602 pub reason: Option<String>,
604 pub prev_hash: [u8; 32],
606 pub hash: [u8; 32],
608}
609
610impl SigningAuditEntry {
611 pub fn new(
613 request_type: SigningRequestType,
614 decision: SigningDecision,
615 was_automatic: bool,
616 caller: String,
617 prev_hash: [u8; 32],
618 ) -> Self {
619 Self {
620 timestamp: chrono::Utc::now().timestamp(),
621 request_type,
622 decision,
623 was_automatic,
624 caller,
625 caller_name: None,
626 event_kind: None,
627 reason: None,
628 prev_hash,
629 hash: [0u8; 32],
630 }
631 }
632
633 pub fn with_caller_name(mut self, name: impl Into<String>) -> Self {
635 self.caller_name = Some(name.into());
636 self
637 }
638
639 pub fn with_event_kind(mut self, kind: u32) -> Self {
641 self.event_kind = Some(kind);
642 self
643 }
644
645 pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
647 self.reason = Some(reason.into());
648 self
649 }
650
651 pub fn finalize(mut self) -> Self {
653 self.hash = self.compute_hash();
654 self
655 }
656
657 fn compute_hash(&self) -> [u8; 32] {
658 let mut data = Vec::new();
659 data.extend_from_slice(&self.timestamp.to_le_bytes());
660 data.push(self.request_type as u8);
661 data.push(self.decision as u8);
662 data.push(self.was_automatic as u8);
663 let caller_len = u32::try_from(self.caller.len()).expect("caller too long for hash");
664 data.extend_from_slice(&caller_len.to_le_bytes());
665 data.extend_from_slice(self.caller.as_bytes());
666 hash_optional_str(&mut data, self.caller_name.as_deref());
667 if let Some(kind) = self.event_kind {
668 data.push(1);
669 data.extend_from_slice(&kind.to_le_bytes());
670 } else {
671 data.push(0);
672 }
673 hash_optional_str(&mut data, self.reason.as_deref());
674 data.extend_from_slice(&self.prev_hash);
675 crypto::blake2b_256(&data)
676 }
677
678 pub fn verify(&self, prev_hash: &[u8; 32]) -> bool {
680 let prev_hash_match = self.prev_hash.ct_eq(prev_hash);
681 let hash_match = self.hash.ct_eq(&self.compute_hash());
682 (prev_hash_match & hash_match).into()
683 }
684}
685
686pub struct SigningAuditLog {
688 path: PathBuf,
689 last_hash: [u8; 32],
690 retention: RetentionPolicy,
691}
692
693impl SigningAuditLog {
694 pub fn open(path: &Path, data_key: &SecretKey) -> Result<Self> {
696 let audit_path = path.join("signing_audit.log");
697 let last_hash = if audit_path.exists() {
698 Self::read_last_hash(&audit_path, data_key)?
699 } else {
700 [0u8; 32]
701 };
702
703 Ok(Self {
704 path: audit_path,
705 last_hash,
706 retention: RetentionPolicy::default(),
707 })
708 }
709
710 pub fn set_retention(&mut self, policy: RetentionPolicy) {
712 self.retention = policy;
713 }
714
715 pub fn apply_retention(&mut self, data_key: &SecretKey) -> Result<usize> {
717 let entries = self.read_all(data_key)?;
718 let original_count = entries.len();
719 let now = chrono::Utc::now().timestamp();
720 let max_age_secs = self.retention.max_age_days.map(|d| i64::from(d) * 86400);
721
722 let mut filtered: Vec<_> = entries
723 .into_iter()
724 .filter(|e| max_age_secs.is_none_or(|max| now.saturating_sub(e.timestamp) <= max))
725 .collect();
726
727 if let Some(max) = self.retention.max_entries {
728 if filtered.len() > max {
729 filtered = filtered.split_off(filtered.len() - max);
730 }
731 }
732
733 let removed = original_count - filtered.len();
734 if removed > 0 {
735 self.rewrite(&filtered, data_key)?;
736 }
737
738 Ok(removed)
739 }
740
741 pub fn log(&mut self, mut entry: SigningAuditEntry, data_key: &SecretKey) -> Result<()> {
743 entry.prev_hash = self.last_hash;
744 entry.hash = entry.compute_hash();
745
746 let serialized = serde_json::to_vec(&entry)
747 .map_err(|e| StorageError::serialization(format!("signing audit entry: {e}")))?;
748
749 let encrypted = crypto::encrypt(&serialized, data_key)?;
750 let line = format!("{}\n", STANDARD.encode(encrypted.to_bytes()));
751
752 let mut opts = OpenOptions::new();
753 opts.create(true).append(true);
754 #[cfg(unix)]
755 opts.mode(0o600);
756 let mut file = opts.open(&self.path)?;
757 file.write_all(line.as_bytes())?;
758 file.sync_all()?;
759
760 self.last_hash = entry.hash;
761 Ok(())
762 }
763
764 pub fn read_all(&self, data_key: &SecretKey) -> Result<Vec<SigningAuditEntry>> {
766 if !self.path.exists() {
767 return Ok(Vec::new());
768 }
769 Self::read_entries(&self.path, data_key)
770 }
771
772 pub fn read_page(
774 &self,
775 data_key: &SecretKey,
776 offset: usize,
777 limit: usize,
778 caller_filter: Option<&str>,
779 ) -> Result<Vec<SigningAuditEntry>> {
780 let all = self.read_all(data_key)?;
781 let entries = all
782 .into_iter()
783 .rev()
784 .filter(|e| caller_filter.is_none_or(|c| e.caller == c))
785 .skip(offset)
786 .take(limit)
787 .collect();
788 Ok(entries)
789 }
790
791 pub fn read_page_with_metadata(
793 &self,
794 data_key: &SecretKey,
795 offset: usize,
796 limit: usize,
797 caller_filter: Option<&str>,
798 ) -> Result<(Vec<SigningAuditEntry>, Vec<String>, usize)> {
799 let all = self.read_all(data_key)?;
800 let count = all.len();
801
802 let mut seen = std::collections::HashSet::new();
803 let mut callers = Vec::new();
804 for entry in all.iter().rev() {
805 if seen.insert(entry.caller.clone()) {
806 callers.push(entry.caller.clone());
807 }
808 }
809
810 let entries = all
811 .into_iter()
812 .rev()
813 .filter(|e| caller_filter.is_none_or(|c| e.caller == c))
814 .skip(offset)
815 .take(limit)
816 .collect();
817
818 Ok((entries, callers, count))
819 }
820
821 pub fn distinct_callers(&self, data_key: &SecretKey) -> Result<Vec<String>> {
823 let entries = self.read_all(data_key)?;
824 let mut seen = std::collections::HashSet::new();
825 let mut callers = Vec::new();
826 for entry in entries.iter().rev() {
827 if seen.insert(entry.caller.clone()) {
828 callers.push(entry.caller.clone());
829 }
830 }
831 Ok(callers)
832 }
833
834 pub fn count(&self, data_key: &SecretKey) -> Result<usize> {
836 Ok(self.read_all(data_key)?.len())
837 }
838
839 pub fn verify_chain(&self, data_key: &SecretKey) -> Result<(bool, usize)> {
841 let entries = self.read_all(data_key)?;
842 let count = entries.len();
843 let mut prev_hash = [0u8; 32];
844
845 for entry in entries {
846 if !entry.verify(&prev_hash) {
847 return Ok((false, count));
848 }
849 prev_hash = entry.hash;
850 }
851
852 Ok((true, count))
853 }
854
855 pub fn last_hash(&self) -> [u8; 32] {
857 self.last_hash
858 }
859
860 pub fn reencrypt(&mut self, old_key: &SecretKey, new_key: &SecretKey) -> Result<()> {
862 if !self.path.exists() {
863 return Ok(());
864 }
865 let entries = Self::read_entries(&self.path, old_key)?;
866 if entries.is_empty() {
867 return Ok(());
868 }
869 self.rewrite(&entries, new_key)
870 }
871
872 fn read_last_hash(path: &Path, data_key: &SecretKey) -> Result<[u8; 32]> {
873 let entries = Self::read_entries(path, data_key)?;
874 Ok(entries.last().map_or([0u8; 32], |e| e.hash))
875 }
876
877 fn read_entries(path: &Path, data_key: &SecretKey) -> Result<Vec<SigningAuditEntry>> {
878 const MAX_ENTRIES: usize = 100_000;
879
880 let file = File::open(path)?;
881 let reader = BufReader::new(file);
882 let mut entries = Vec::new();
883
884 for (line_num, line) in reader.lines().enumerate() {
885 if entries.len() >= MAX_ENTRIES {
886 return Err(StorageError::io(format!(
887 "signing audit log exceeds maximum of {MAX_ENTRIES} entries"
888 ))
889 .into());
890 }
891 let line = line?;
892 if line.is_empty() {
893 continue;
894 }
895 let entry = Self::decrypt_line(&line, data_key).map_err(|e| {
896 StorageError::corrupted(format!(
897 "signing audit log at line {}: {}",
898 line_num + 1,
899 e
900 ))
901 })?;
902 entries.push(entry);
903 }
904
905 Ok(entries)
906 }
907
908 fn decrypt_line(line: &str, data_key: &SecretKey) -> Result<SigningAuditEntry> {
909 let bytes = STANDARD
910 .decode(line)
911 .map_err(|e| StorageError::invalid_format(format!("signing audit line: {e}")))?;
912
913 let encrypted = crypto::EncryptedData::from_bytes(&bytes)?;
914 let decrypted = crypto::decrypt(&encrypted, data_key)?;
915
916 serde_json::from_slice(&decrypted.as_slice()?)
917 .map_err(|e| StorageError::invalid_format(format!("signing audit entry: {e}")).into())
918 }
919
920 fn rewrite(&mut self, entries: &[SigningAuditEntry], data_key: &SecretKey) -> Result<()> {
921 let temp_path = self.path.with_extension("log.tmp");
922 let backup_path = self.path.with_extension("log.bak");
923
924 let final_hash = match self.write_entries_to_temp(&temp_path, entries, data_key) {
925 Ok(hash) => hash,
926 Err(e) => {
927 let _ = std::fs::remove_file(&temp_path);
928 return Err(e);
929 }
930 };
931
932 if self.path.exists() {
933 if let Err(e) = std::fs::rename(&self.path, &backup_path) {
934 let _ = std::fs::remove_file(&temp_path);
935 return Err(StorageError::io(format!("backup signing audit log: {e}")).into());
936 }
937 }
938
939 if let Err(e) = std::fs::rename(&temp_path, &self.path) {
940 if backup_path.exists() {
941 let _ = std::fs::rename(&backup_path, &self.path);
942 }
943 let _ = std::fs::remove_file(&temp_path);
944 return Err(StorageError::io(format!("replace signing audit log: {e}")).into());
945 }
946
947 let _ = std::fs::remove_file(&backup_path);
948 self.last_hash = final_hash;
949 Ok(())
950 }
951
952 fn write_entries_to_temp(
953 &self,
954 temp_path: &Path,
955 entries: &[SigningAuditEntry],
956 data_key: &SecretKey,
957 ) -> Result<[u8; 32]> {
958 let mut opts = OpenOptions::new();
959 opts.write(true).create(true).truncate(true);
960 #[cfg(unix)]
961 opts.mode(0o600);
962 let mut file = opts.open(temp_path)?;
963
964 let mut prev_hash = [0u8; 32];
965 for entry in entries {
966 let mut entry = entry.clone();
967 entry.prev_hash = prev_hash;
968 entry.hash = entry.compute_hash();
969
970 let serialized = serde_json::to_vec(&entry)
971 .map_err(|e| StorageError::serialization(e.to_string()))?;
972
973 let encrypted = crypto::encrypt(&serialized, data_key)?;
974 let line = format!("{}\n", STANDARD.encode(encrypted.to_bytes()));
975 file.write_all(line.as_bytes())?;
976 prev_hash = entry.hash;
977 }
978
979 file.sync_all()?;
980 Ok(prev_hash)
981 }
982}
983
984#[cfg(test)]
985mod tests {
986 use super::*;
987 use tempfile::tempdir;
988
989 fn test_key() -> SecretKey {
990 SecretKey::generate().unwrap()
991 }
992
993 #[test]
994 fn test_audit_entry_hash_chain() {
995 let genesis = [0u8; 32];
996 let entry1 = AuditEntry::new(AuditEventType::KeyGenerate, genesis)
997 .with_pubkey(&[1u8; 32])
998 .with_key_type("nostr")
999 .finalize();
1000
1001 assert!(entry1.verify(&genesis));
1002
1003 let entry2 = AuditEntry::new(AuditEventType::Sign, entry1.hash)
1004 .with_pubkey(&[1u8; 32])
1005 .with_message_hash(b"test message")
1006 .finalize();
1007
1008 assert!(entry2.verify(&entry1.hash));
1009 assert!(!entry2.verify(&genesis));
1010 }
1011
1012 #[test]
1013 fn test_audit_log_persistence() {
1014 let dir = tempdir().unwrap();
1015 let key = test_key();
1016
1017 {
1018 let mut log = AuditLog::open(dir.path(), &key).unwrap();
1019 let entry = AuditEntry::new(AuditEventType::KeyGenerate, log.last_hash())
1020 .with_pubkey(&[1u8; 32]);
1021 log.log(entry, &key).unwrap();
1022 }
1023
1024 {
1025 let log = AuditLog::open(dir.path(), &key).unwrap();
1026 let entries = log.read_all(&key).unwrap();
1027 assert_eq!(entries.len(), 1);
1028 assert!(matches!(entries[0].event_type, AuditEventType::KeyGenerate));
1029 }
1030 }
1031
1032 #[test]
1033 fn test_audit_chain_verification() {
1034 let dir = tempdir().unwrap();
1035 let key = test_key();
1036 let mut log = AuditLog::open(dir.path(), &key).unwrap();
1037
1038 for i in 0..5 {
1039 let entry =
1040 AuditEntry::new(AuditEventType::Sign, log.last_hash()).with_pubkey(&[i as u8; 32]);
1041 log.log(entry, &key).unwrap();
1042 }
1043
1044 assert!(log.verify_chain(&key).unwrap());
1045 }
1046
1047 #[test]
1048 fn test_retention_policy() {
1049 let dir = tempdir().unwrap();
1050 let key = test_key();
1051 let mut log = AuditLog::open(dir.path(), &key).unwrap();
1052 log.set_retention(RetentionPolicy {
1053 max_entries: Some(3),
1054 max_age_days: None,
1055 });
1056
1057 for i in 0..5 {
1058 let entry =
1059 AuditEntry::new(AuditEventType::Sign, log.last_hash()).with_pubkey(&[i as u8; 32]);
1060 log.log(entry, &key).unwrap();
1061 }
1062
1063 let removed = log.apply_retention(&key).unwrap();
1064 assert_eq!(removed, 2);
1065
1066 let entries = log.read_all(&key).unwrap();
1067 assert_eq!(entries.len(), 3);
1068 }
1069
1070 #[test]
1071 fn verify_chain_returns_true_when_log_absent() {
1072 let dir = tempdir().unwrap();
1076 let key = test_key();
1077 let log = AuditLog::open(dir.path(), &key).unwrap();
1078 assert!(log.verify_chain(&key).unwrap());
1079 assert!(log.read_all(&key).unwrap().is_empty());
1080 }
1081
1082 #[test]
1083 fn verify_chain_detects_ciphertext_tamper() {
1084 let dir = tempdir().unwrap();
1089 let key = test_key();
1090 let mut log = AuditLog::open(dir.path(), &key).unwrap();
1091
1092 for i in 0..3 {
1093 let entry =
1094 AuditEntry::new(AuditEventType::Sign, log.last_hash()).with_pubkey(&[i as u8; 32]);
1095 log.log(entry, &key).unwrap();
1096 }
1097 assert!(log.verify_chain(&key).unwrap());
1098
1099 let audit_path = dir.path().join("audit.log");
1101 let mut content = std::fs::read(&audit_path).unwrap();
1102 let first_newline = content.iter().position(|b| *b == b'\n').unwrap();
1103 let target = first_newline / 2;
1106 content[target] = if content[target] == b'A' { b'B' } else { b'A' };
1107 std::fs::write(&audit_path, &content).unwrap();
1108
1109 match log.verify_chain(&key) {
1114 Ok(false) => {}
1115 Err(_) => {}
1116 Ok(true) => panic!("verify_chain accepted a tampered entry as valid"),
1117 }
1118 }
1119
1120 #[test]
1121 fn apply_retention_by_age_drops_old_entries() {
1122 let dir = tempdir().unwrap();
1125 let key = test_key();
1126 let mut log = AuditLog::open(dir.path(), &key).unwrap();
1127
1128 let now = chrono::Utc::now().timestamp();
1129 let old_ts = now - 60 * 86400; let recent_ts = now - 86400; let mut old_entry = AuditEntry::new(AuditEventType::Sign, log.last_hash());
1133 old_entry.timestamp = old_ts;
1134 log.log(old_entry, &key).unwrap();
1135
1136 let mut recent_entry = AuditEntry::new(AuditEventType::Sign, log.last_hash());
1137 recent_entry.timestamp = recent_ts;
1138 log.log(recent_entry, &key).unwrap();
1139
1140 log.set_retention(RetentionPolicy {
1141 max_entries: None,
1142 max_age_days: Some(30),
1143 });
1144 let removed = log.apply_retention(&key).unwrap();
1145 assert_eq!(removed, 1, "the 60-day-old entry must be pruned");
1146
1147 let remaining = log.read_all(&key).unwrap();
1148 assert_eq!(remaining.len(), 1);
1149 assert_eq!(remaining[0].timestamp, recent_ts);
1150 assert!(
1151 log.verify_chain(&key).unwrap(),
1152 "retention rewrite must preserve a valid hash chain"
1153 );
1154 }
1155
1156 #[test]
1157 fn test_signing_audit_hash_chain() {
1158 let genesis = [0u8; 32];
1159 let entry1 = SigningAuditEntry::new(
1160 SigningRequestType::SignEvent,
1161 SigningDecision::Approved,
1162 false,
1163 "abc123".into(),
1164 genesis,
1165 )
1166 .with_event_kind(1)
1167 .finalize();
1168
1169 assert!(entry1.verify(&genesis));
1170
1171 let entry2 = SigningAuditEntry::new(
1172 SigningRequestType::SignEvent,
1173 SigningDecision::Denied,
1174 true,
1175 "def456".into(),
1176 entry1.hash,
1177 )
1178 .with_event_kind(30023)
1179 .with_reason("rate limited")
1180 .finalize();
1181
1182 assert!(entry2.verify(&entry1.hash));
1183 assert!(!entry2.verify(&genesis));
1184 }
1185
1186 #[test]
1187 fn test_signing_audit_log_persistence() {
1188 let dir = tempdir().unwrap();
1189 let key = test_key();
1190
1191 {
1192 let mut log = SigningAuditLog::open(dir.path(), &key).unwrap();
1193 let entry = SigningAuditEntry::new(
1194 SigningRequestType::Connect,
1195 SigningDecision::Approved,
1196 false,
1197 "app1".into(),
1198 log.last_hash(),
1199 )
1200 .with_caller_name("Test App");
1201 log.log(entry, &key).unwrap();
1202 }
1203
1204 {
1205 let log = SigningAuditLog::open(dir.path(), &key).unwrap();
1206 let entries = log.read_all(&key).unwrap();
1207 assert_eq!(entries.len(), 1);
1208 assert_eq!(entries[0].request_type, SigningRequestType::Connect);
1209 assert_eq!(entries[0].caller_name, Some("Test App".into()));
1210 }
1211 }
1212
1213 #[test]
1214 fn test_signing_audit_chain_verification() {
1215 let dir = tempdir().unwrap();
1216 let key = test_key();
1217 let mut log = SigningAuditLog::open(dir.path(), &key).unwrap();
1218
1219 for i in 0..5 {
1220 let entry = SigningAuditEntry::new(
1221 SigningRequestType::SignEvent,
1222 SigningDecision::Approved,
1223 i % 2 == 0,
1224 format!("app{i}"),
1225 log.last_hash(),
1226 )
1227 .with_event_kind(1);
1228 log.log(entry, &key).unwrap();
1229 }
1230
1231 assert!(log.verify_chain(&key).unwrap().0);
1232 }
1233
1234 #[test]
1235 fn test_signing_audit_pagination() {
1236 let dir = tempdir().unwrap();
1237 let key = test_key();
1238 let mut log = SigningAuditLog::open(dir.path(), &key).unwrap();
1239
1240 for i in 0..10 {
1241 let caller = if i % 3 == 0 { "app_a" } else { "app_b" };
1242 let entry = SigningAuditEntry::new(
1243 SigningRequestType::SignEvent,
1244 SigningDecision::Approved,
1245 false,
1246 caller.into(),
1247 log.last_hash(),
1248 );
1249 log.log(entry, &key).unwrap();
1250 }
1251
1252 let page = log.read_page(&key, 0, 3, None).unwrap();
1253 assert_eq!(page.len(), 3);
1254
1255 let page = log.read_page(&key, 3, 3, None).unwrap();
1256 assert_eq!(page.len(), 3);
1257
1258 let filtered = log.read_page(&key, 0, 100, Some("app_a")).unwrap();
1259 assert_eq!(filtered.len(), 4);
1260 }
1261
1262 #[test]
1263 fn test_signing_audit_distinct_callers() {
1264 let dir = tempdir().unwrap();
1265 let key = test_key();
1266 let mut log = SigningAuditLog::open(dir.path(), &key).unwrap();
1267
1268 for caller in &["app_a", "app_b", "app_a", "app_c"] {
1269 let entry = SigningAuditEntry::new(
1270 SigningRequestType::SignEvent,
1271 SigningDecision::Approved,
1272 false,
1273 caller.to_string(),
1274 log.last_hash(),
1275 );
1276 log.log(entry, &key).unwrap();
1277 }
1278
1279 let callers = log.distinct_callers(&key).unwrap();
1280 assert_eq!(callers.len(), 3);
1281 }
1282}