lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0
//
// WORM Compliance
// Write-Once-Read-Many for regulatory compliance.

use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use lazy_static::lazy_static;
use spin::Mutex;

/// WORM retention mode
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetentionMode {
    /// Compliance mode - cannot be deleted even by administrators
    Compliance,
    /// Governance mode - can be deleted with special permissions
    Governance,
}

/// WORM file metadata
#[derive(Debug, Clone)]
pub struct WormFile {
    /// File identifier
    pub file_id: u64,
    /// Dataset ID
    pub dataset_id: u64,
    /// Retention mode
    pub mode: RetentionMode,
    /// Retention period in seconds
    pub retention_period: u64,
    /// Lock timestamp (when WORM was enabled)
    pub lock_time: u64,
    /// Expiration timestamp (lock_time + retention_period)
    pub expiration_time: u64,
    /// Legal hold flag (prevents deletion even after expiration)
    pub legal_hold: bool,
    /// BLAKE3 checksum of file content (for tamper detection)
    pub content_hash: [u8; 32],
}

impl WormFile {
    /// Create new WORM file
    pub fn new(
        file_id: u64,
        dataset_id: u64,
        mode: RetentionMode,
        retention_period: u64,
        lock_time: u64,
        content_hash: [u8; 32],
    ) -> Self {
        Self {
            file_id,
            dataset_id,
            mode,
            retention_period,
            lock_time,
            expiration_time: lock_time + retention_period,
            legal_hold: false,
            content_hash,
        }
    }

    /// Check if file is still locked (retention not expired)
    pub fn is_locked(&self, current_time: u64) -> bool {
        current_time < self.expiration_time || self.legal_hold
    }

    /// Check if deletion is allowed
    pub fn can_delete(&self, current_time: u64, has_governance_override: bool) -> bool {
        if self.legal_hold {
            return false; // Never deletable under legal hold
        }

        if current_time < self.expiration_time {
            // Still within retention period
            match self.mode {
                RetentionMode::Compliance => false, // Never deletable
                RetentionMode::Governance => has_governance_override, // Only with override
            }
        } else {
            true // Retention expired
        }
    }

    /// Check if content can be modified
    pub fn can_modify(&self, _current_time: u64) -> bool {
        false // WORM files are never modifiable
    }

    /// Verify content integrity
    pub fn verify_integrity(&self, actual_hash: &[u8; 32]) -> bool {
        self.content_hash == *actual_hash
    }
}

/// Audit log entry for WORM operations
#[derive(Debug, Clone)]
pub struct AuditEntry {
    /// Entry ID
    pub entry_id: u64,
    /// Timestamp
    pub timestamp: u64,
    /// Operation type
    pub operation: WormOperation,
    /// File ID
    pub file_id: u64,
    /// User ID who performed operation
    pub user_id: u64,
    /// Success or failure
    pub success: bool,
    /// Additional details
    pub details: &'static str,
}

/// WORM operations for audit log
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WormOperation {
    /// File was locked as WORM
    Lock,
    /// Attempted to modify WORM file
    AttemptModify,
    /// Attempted to delete WORM file
    AttemptDelete,
    /// Legal hold placed
    LegalHoldSet,
    /// Legal hold removed
    LegalHoldRemove,
    /// Retention period extended
    RetentionExtend,
    /// Governance override used for deletion
    GovernanceOverride,
    /// Integrity verification
    IntegrityCheck,
}

impl WormOperation {
    /// Get operation name
    pub fn name(&self) -> &'static str {
        match self {
            WormOperation::Lock => "lock",
            WormOperation::AttemptModify => "attempt_modify",
            WormOperation::AttemptDelete => "attempt_delete",
            WormOperation::LegalHoldSet => "legal_hold_set",
            WormOperation::LegalHoldRemove => "legal_hold_remove",
            WormOperation::RetentionExtend => "retention_extend",
            WormOperation::GovernanceOverride => "governance_override",
            WormOperation::IntegrityCheck => "integrity_check",
        }
    }
}

/// WORM statistics
#[derive(Debug, Clone, Default)]
pub struct WormStats {
    /// Total WORM files
    pub total_files: usize,
    /// Files under compliance mode
    pub compliance_files: usize,
    /// Files under governance mode
    pub governance_files: usize,
    /// Files under legal hold
    pub legal_hold_files: usize,
    /// Failed modification attempts
    pub modify_attempts: u64,
    /// Failed deletion attempts
    pub delete_attempts: u64,
    /// Integrity check failures
    pub integrity_failures: u64,
}

lazy_static! {
    /// Global WORM manager
    static ref WORM_MANAGER: Mutex<WormManager> = Mutex::new(WormManager::new());
}

/// WORM compliance manager
pub struct WormManager {
    /// WORM files index
    files: BTreeMap<u64, WormFile>,
    /// Audit log
    audit_log: Vec<AuditEntry>,
    /// Next audit entry ID
    next_audit_id: u64,
    /// Statistics
    stats: WormStats,
}

impl Default for WormManager {
    fn default() -> Self {
        Self::new()
    }
}

impl WormManager {
    /// Create new WORM manager
    pub fn new() -> Self {
        Self {
            files: BTreeMap::new(),
            audit_log: Vec::new(),
            next_audit_id: 1,
            stats: WormStats::default(),
        }
    }

    /// Lock file as WORM
    ///
    /// # Arguments
    /// * `file` - WORM file configuration (created with `WormFile::new`)
    /// * `user_id` - User performing operation
    ///
    /// # Example
    /// ```ignore
    /// let file = WormFile::new(file_id, dataset_id, mode, retention, timestamp, hash);
    /// manager.lock_file(file, user_id)?;
    /// ```
    pub fn lock_file(&mut self, file: WormFile, user_id: u64) -> Result<(), &'static str> {
        let file_id = file.file_id;
        let mode = file.mode;
        let current_time = file.lock_time;

        if self.files.contains_key(&file_id) {
            return Err("File already locked");
        }

        self.files.insert(file_id, file);

        // Update stats
        self.stats.total_files += 1;
        match mode {
            RetentionMode::Compliance => self.stats.compliance_files += 1,
            RetentionMode::Governance => self.stats.governance_files += 1,
        }

        // Audit log
        self.add_audit_entry(
            current_time,
            WormOperation::Lock,
            file_id,
            user_id,
            true,
            "File locked",
        );

        Ok(())
    }

    /// Check if file can be modified
    pub fn can_modify(&mut self, file_id: u64, current_time: u64, user_id: u64) -> bool {
        if let Some(worm_file) = self.files.get(&file_id) {
            let allowed = worm_file.can_modify(current_time);

            if !allowed {
                self.stats.modify_attempts += 1;
                self.add_audit_entry(
                    current_time,
                    WormOperation::AttemptModify,
                    file_id,
                    user_id,
                    false,
                    "Modification denied",
                );
            }

            allowed
        } else {
            true // Not a WORM file
        }
    }

    /// Check if file can be deleted
    pub fn can_delete(
        &mut self,
        file_id: u64,
        current_time: u64,
        has_governance_override: bool,
        user_id: u64,
    ) -> bool {
        if let Some(worm_file) = self.files.get(&file_id) {
            let allowed = worm_file.can_delete(current_time, has_governance_override);

            if !allowed {
                self.stats.delete_attempts += 1;
                self.add_audit_entry(
                    current_time,
                    WormOperation::AttemptDelete,
                    file_id,
                    user_id,
                    false,
                    "Deletion denied",
                );
            } else if has_governance_override {
                self.add_audit_entry(
                    current_time,
                    WormOperation::GovernanceOverride,
                    file_id,
                    user_id,
                    true,
                    "Governance override used",
                );
            }

            allowed
        } else {
            true // Not a WORM file
        }
    }

    /// Set legal hold on file
    pub fn set_legal_hold(
        &mut self,
        file_id: u64,
        current_time: u64,
        user_id: u64,
    ) -> Result<(), &'static str> {
        let worm_file = self.files.get_mut(&file_id).ok_or("File not WORM")?;

        if !worm_file.legal_hold {
            worm_file.legal_hold = true;
            self.stats.legal_hold_files += 1;

            self.add_audit_entry(
                current_time,
                WormOperation::LegalHoldSet,
                file_id,
                user_id,
                true,
                "Legal hold set",
            );
        }

        Ok(())
    }

    /// Remove legal hold from file
    pub fn remove_legal_hold(
        &mut self,
        file_id: u64,
        current_time: u64,
        user_id: u64,
    ) -> Result<(), &'static str> {
        let worm_file = self.files.get_mut(&file_id).ok_or("File not WORM")?;

        if worm_file.legal_hold {
            worm_file.legal_hold = false;
            self.stats.legal_hold_files = self.stats.legal_hold_files.saturating_sub(1);

            self.add_audit_entry(
                current_time,
                WormOperation::LegalHoldRemove,
                file_id,
                user_id,
                true,
                "Legal hold removed",
            );
        }

        Ok(())
    }

    /// Extend retention period (only allowed for certain modes)
    pub fn extend_retention(
        &mut self,
        file_id: u64,
        additional_time: u64,
        current_time: u64,
        user_id: u64,
    ) -> Result<(), &'static str> {
        let worm_file = self.files.get_mut(&file_id).ok_or("File not WORM")?;

        // Only allow extension, not reduction
        worm_file.retention_period += additional_time;
        worm_file.expiration_time += additional_time;

        self.add_audit_entry(
            current_time,
            WormOperation::RetentionExtend,
            file_id,
            user_id,
            true,
            "Retention extended",
        );

        Ok(())
    }

    /// Verify file integrity
    pub fn verify_integrity(
        &mut self,
        file_id: u64,
        actual_hash: &[u8; 32],
        current_time: u64,
        user_id: u64,
    ) -> bool {
        if let Some(worm_file) = self.files.get(&file_id) {
            let valid = worm_file.verify_integrity(actual_hash);

            if !valid {
                self.stats.integrity_failures += 1;
            }

            self.add_audit_entry(
                current_time,
                WormOperation::IntegrityCheck,
                file_id,
                user_id,
                valid,
                if valid {
                    "Integrity valid"
                } else {
                    "Integrity FAILED"
                },
            );

            valid
        } else {
            true // Not a WORM file
        }
    }

    /// Add audit log entry
    fn add_audit_entry(
        &mut self,
        timestamp: u64,
        operation: WormOperation,
        file_id: u64,
        user_id: u64,
        success: bool,
        details: &'static str,
    ) {
        let entry = AuditEntry {
            entry_id: self.next_audit_id,
            timestamp,
            operation,
            file_id,
            user_id,
            success,
            details,
        };

        self.audit_log.push(entry);
        self.next_audit_id += 1;
    }

    /// Get audit log for file
    pub fn get_audit_log(&self, file_id: u64) -> Vec<AuditEntry> {
        self.audit_log
            .iter()
            .filter(|e| e.file_id == file_id)
            .cloned()
            .collect()
    }

    /// Get statistics
    pub fn get_stats(&self) -> WormStats {
        self.stats.clone()
    }

    /// Get WORM file metadata
    pub fn get_file(&self, file_id: u64) -> Option<&WormFile> {
        self.files.get(&file_id)
    }
}

/// Global WORM operations
pub struct WormEngine;

impl WormEngine {
    /// Lock file as WORM
    ///
    /// Creates a WORM file from the given parameters.
    pub fn lock_file(
        file_id: u64,
        dataset_id: u64,
        mode: RetentionMode,
        retention_period: u64,
        current_time: u64,
        content_hash: [u8; 32],
        user_id: u64,
    ) -> Result<(), &'static str> {
        let file = WormFile::new(
            file_id,
            dataset_id,
            mode,
            retention_period,
            current_time,
            content_hash,
        );
        let mut mgr = WORM_MANAGER.lock();
        mgr.lock_file(file, user_id)
    }

    /// Check if modification allowed
    pub fn can_modify(file_id: u64, current_time: u64, user_id: u64) -> bool {
        let mut mgr = WORM_MANAGER.lock();
        mgr.can_modify(file_id, current_time, user_id)
    }

    /// Check if deletion allowed
    pub fn can_delete(file_id: u64, current_time: u64, has_override: bool, user_id: u64) -> bool {
        let mut mgr = WORM_MANAGER.lock();
        mgr.can_delete(file_id, current_time, has_override, user_id)
    }

    /// Set legal hold
    pub fn set_legal_hold(
        file_id: u64,
        current_time: u64,
        user_id: u64,
    ) -> Result<(), &'static str> {
        let mut mgr = WORM_MANAGER.lock();
        mgr.set_legal_hold(file_id, current_time, user_id)
    }

    /// Remove legal hold
    pub fn remove_legal_hold(
        file_id: u64,
        current_time: u64,
        user_id: u64,
    ) -> Result<(), &'static str> {
        let mut mgr = WORM_MANAGER.lock();
        mgr.remove_legal_hold(file_id, current_time, user_id)
    }

    /// Extend retention
    pub fn extend_retention(
        file_id: u64,
        additional_time: u64,
        current_time: u64,
        user_id: u64,
    ) -> Result<(), &'static str> {
        let mut mgr = WORM_MANAGER.lock();
        mgr.extend_retention(file_id, additional_time, current_time, user_id)
    }

    /// Verify integrity
    pub fn verify_integrity(
        file_id: u64,
        actual_hash: &[u8; 32],
        current_time: u64,
        user_id: u64,
    ) -> bool {
        let mut mgr = WORM_MANAGER.lock();
        mgr.verify_integrity(file_id, actual_hash, current_time, user_id)
    }

    /// Get audit log
    pub fn audit_log(file_id: u64) -> Vec<AuditEntry> {
        let mgr = WORM_MANAGER.lock();
        mgr.get_audit_log(file_id)
    }

    /// Get statistics
    pub fn stats() -> WormStats {
        let mgr = WORM_MANAGER.lock();
        mgr.get_stats()
    }
}

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

    // Test helper extension for WormManager
    impl WormManager {
        fn test_lock_file(
            &mut self,
            file_id: u64,
            dataset_id: u64,
            mode: RetentionMode,
            retention_period: u64,
            current_time: u64,
            content_hash: [u8; 32],
            user_id: u64,
        ) -> Result<(), &'static str> {
            let file = WormFile::new(
                file_id,
                dataset_id,
                mode,
                retention_period,
                current_time,
                content_hash,
            );
            self.lock_file(file, user_id)
        }
    }

    #[test]
    fn test_worm_file_lock() {
        let hash = [0u8; 32];
        let worm = WormFile::new(1, 100, RetentionMode::Compliance, 3600, 0, hash);

        assert!(worm.is_locked(1000)); // Still locked
        assert!(!worm.is_locked(4000)); // Expired
    }

    #[test]
    fn test_compliance_mode_no_delete() {
        let hash = [0u8; 32];
        let worm = WormFile::new(1, 100, RetentionMode::Compliance, 3600, 0, hash);

        // Cannot delete even with override
        assert!(!worm.can_delete(1000, true));
        assert!(!worm.can_delete(1000, false));

        // Can delete after expiration
        assert!(worm.can_delete(4000, false));
    }

    #[test]
    fn test_governance_mode_override() {
        let hash = [0u8; 32];
        let worm = WormFile::new(1, 100, RetentionMode::Governance, 3600, 0, hash);

        // Cannot delete without override
        assert!(!worm.can_delete(1000, false));

        // Can delete with override
        assert!(worm.can_delete(1000, true));
    }

    #[test]
    fn test_legal_hold_prevents_deletion() {
        let hash = [0u8; 32];
        let mut worm = WormFile::new(1, 100, RetentionMode::Governance, 3600, 0, hash);

        worm.legal_hold = true;

        // Cannot delete even after expiration with override
        assert!(!worm.can_delete(10000, true));
    }

    #[test]
    fn test_never_modifiable() {
        let hash = [0u8; 32];
        let worm = WormFile::new(1, 100, RetentionMode::Compliance, 3600, 0, hash);

        // Never modifiable, regardless of time
        assert!(!worm.can_modify(0));
        assert!(!worm.can_modify(1000));
        assert!(!worm.can_modify(10000));
    }

    #[test]
    fn test_integrity_verification() {
        let hash = [1u8; 32];
        let worm = WormFile::new(1, 100, RetentionMode::Compliance, 3600, 0, hash);

        assert!(worm.verify_integrity(&[1u8; 32])); // Match
        assert!(!worm.verify_integrity(&[2u8; 32])); // Mismatch
    }

    #[test]
    fn test_worm_manager_lock() {
        let mut mgr = WormManager::new();
        let hash = [0u8; 32];

        mgr.test_lock_file(1, 100, RetentionMode::Compliance, 3600, 0, hash, 999)
            .expect("test: operation should succeed");

        assert_eq!(mgr.stats.total_files, 1);
        assert_eq!(mgr.stats.compliance_files, 1);
    }

    #[test]
    fn test_modify_attempt_tracking() {
        let mut mgr = WormManager::new();
        let hash = [0u8; 32];

        mgr.test_lock_file(1, 100, RetentionMode::Compliance, 3600, 0, hash, 999)
            .expect("test: operation should succeed");

        // Attempt to modify
        assert!(!mgr.can_modify(1, 1000, 999));
        assert_eq!(mgr.stats.modify_attempts, 1);

        // Audit log should record it
        let log = mgr.get_audit_log(1);
        assert_eq!(log.len(), 2); // Lock + attempt modify
    }

    #[test]
    fn test_legal_hold() {
        let mut mgr = WormManager::new();
        let hash = [0u8; 32];

        mgr.test_lock_file(1, 100, RetentionMode::Governance, 3600, 0, hash, 999)
            .expect("test: operation should succeed");
        mgr.set_legal_hold(1, 1000, 999)
            .expect("test: operation should succeed");

        assert_eq!(mgr.stats.legal_hold_files, 1);

        // Cannot delete even with override
        assert!(!mgr.can_delete(1, 10000, true, 999));

        // Remove hold
        mgr.remove_legal_hold(1, 10001, 999)
            .expect("test: operation should succeed");
        assert_eq!(mgr.stats.legal_hold_files, 0);

        // Now can delete
        assert!(mgr.can_delete(1, 10002, false, 999));
    }

    #[test]
    fn test_retention_extension() {
        let mut mgr = WormManager::new();
        let hash = [0u8; 32];

        mgr.test_lock_file(1, 100, RetentionMode::Compliance, 3600, 0, hash, 999)
            .expect("test: operation should succeed");

        // Extend by 1 hour
        mgr.extend_retention(1, 3600, 1000, 999)
            .expect("test: operation should succeed");

        let worm = mgr.get_file(1).expect("test: operation should succeed");
        assert_eq!(worm.retention_period, 7200); // 2 hours now
        assert_eq!(worm.expiration_time, 7200);
    }
}