mvm-core 0.11.0

Core types, IDs, config, and utilities for mvm
Documentation
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
use serde::{Deserialize, Serialize};

use crate::signing::SignedPayload;

/// Current authenticated protocol version.
pub const PROTOCOL_VERSION_AUTHENTICATED: u8 = 2;

/// Legacy unauthenticated protocol version.
pub const PROTOCOL_VERSION_LEGACY: u8 = 1;

// ============================================================================
// Authenticated vsock frames
// ============================================================================

/// A versioned, signed vsock frame envelope.
///
/// After the initial CONNECT/OK handshake and session establishment,
/// every frame becomes an `AuthenticatedFrame` containing the Ed25519-signed
/// inner payload (the original `GuestRequest` or `GuestResponse` JSON).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthenticatedFrame {
    /// Protocol version (2 = authenticated, 1 = legacy/unauthenticated).
    pub version: u8,
    /// Unique per-session identifier (assigned during handshake).
    pub session_id: String,
    /// Monotonically increasing sequence number for replay detection.
    pub sequence: u64,
    /// ISO 8601 timestamp of frame creation.
    pub timestamp: String,
    /// The Ed25519-signed inner payload.
    pub signed: SignedPayload,
}

// ============================================================================
// Session handshake
// ============================================================================

/// Host → Guest: initiate authenticated session after CONNECT/OK.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionHello {
    /// Protocol version the host supports.
    pub version: u8,
    /// Session identifier (UUID v4, generated by host).
    pub session_id: String,
    /// Random challenge bytes (32 bytes) the guest must sign to prove key possession.
    pub challenge: Vec<u8>,
    /// Host's Ed25519 public key (32 bytes) for the guest to verify host frames.
    pub host_pubkey: Vec<u8>,
}

/// Guest → Host: acknowledge session and prove key possession.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionHelloAck {
    /// Protocol version the guest supports.
    pub version: u8,
    /// Echo back the session identifier.
    pub session_id: String,
    /// Signed challenge bytes proving the guest holds the session key.
    pub challenge_response: Vec<u8>,
    /// Guest's Ed25519 public key (32 bytes) for the host to verify guest frames.
    pub guest_pubkey: Vec<u8>,
}

// ============================================================================
// Security policy
// ============================================================================

/// Per-VM security configuration, provisioned on the config drive.
///
/// Controls authentication requirements, access permissions, rate limiting,
/// and session lifecycle. Immutable after VM boot.
///
/// **Default: `require_auth = true`** — authentication is required unless
/// explicitly opted out for dev/testing via `SecurityPolicy::dev_defaults()`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityPolicy {
    /// Require authenticated vsock frames. Default: true.
    /// Set to false only for dev/testing environments.
    #[serde(default = "default_true")]
    pub require_auth: bool,

    /// Access control toggles.
    #[serde(default)]
    pub access: AccessPolicy,

    /// Frame rate limiting configuration.
    #[serde(default)]
    pub rate_limits: RateLimitPolicy,

    /// Session lifecycle limits.
    #[serde(default)]
    pub session: SessionPolicy,

    /// Command blocklist entries for the gate.
    #[serde(default)]
    pub blocklist: Vec<BlocklistEntry>,
}

impl Default for SecurityPolicy {
    fn default() -> Self {
        Self {
            require_auth: true,
            access: AccessPolicy::default(),
            rate_limits: RateLimitPolicy::default(),
            session: SessionPolicy::default(),
            blocklist: Vec::new(),
        }
    }
}

impl SecurityPolicy {
    /// Permissive defaults for development and testing environments.
    /// Authentication is disabled and console access is enabled.
    pub fn dev_defaults() -> Self {
        Self {
            require_auth: false,
            access: AccessPolicy {
                console: true,
                debug_exec: true,
                ..AccessPolicy::default()
            },
            ..Self::default()
        }
    }
}

/// Access control toggles for guest operations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessPolicy {
    /// Allow filesystem operations.
    #[serde(default = "default_true")]
    pub filesystem: bool,

    /// Allow outbound network access.
    #[serde(default = "default_true")]
    pub network: bool,

    /// Allow Nix build operations.
    #[serde(default = "default_true")]
    pub build: bool,

    /// Allow host communication (host-bound vsock requests).
    #[serde(default = "default_true")]
    pub host_communication: bool,

    /// Allow debug command execution via vsock (dev-only, disabled by default).
    #[serde(default)]
    pub debug_exec: bool,

    /// Allow interactive PTY console sessions (dev-only, disabled by default).
    #[serde(default)]
    pub console: bool,
}

impl Default for AccessPolicy {
    fn default() -> Self {
        Self {
            filesystem: true,
            network: true,
            build: true,
            host_communication: true,
            debug_exec: false,
            console: false,
        }
    }
}

/// Frame rate limiting configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitPolicy {
    /// Maximum frames per second (0 = unlimited).
    #[serde(default = "default_rate_fps")]
    pub frames_per_second: u32,

    /// Maximum frames per minute (0 = unlimited).
    #[serde(default = "default_rate_fpm")]
    pub frames_per_minute: u32,
}

impl Default for RateLimitPolicy {
    fn default() -> Self {
        Self {
            frames_per_second: 100,
            frames_per_minute: 3000,
        }
    }
}

/// Session lifecycle limits.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionPolicy {
    /// Maximum session lifetime in seconds (0 = unlimited).
    #[serde(default)]
    pub max_lifetime_secs: u64,

    /// Maximum tasks per session before recycling (0 = unlimited).
    #[serde(default)]
    pub max_tasks: u64,
}

// ============================================================================
// Command gating
// ============================================================================

/// Decision from the command gate after evaluating a vsock command.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum GateDecision {
    /// Command is allowed to proceed.
    Allow,
    /// Command matched a blocklist entry and is blocked.
    Blocked {
        /// The pattern that matched.
        pattern: String,
        /// Human-readable reason for blocking.
        reason: String,
    },
    /// Command requires explicit approval before proceeding.
    RequiresApproval {
        /// Human-readable reason approval is needed.
        reason: String,
    },
}

/// Verdict from an approval authority (coordinator or dev-mode auto-approve).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ApprovalVerdict {
    /// Approved to proceed.
    Approved,
    /// Denied with reason.
    Denied { reason: String },
    /// Timed out waiting for approval.
    Timeout,
}

/// Action to take when a blocklist entry matches.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BlocklistAction {
    /// Block the command immediately.
    Block,
    /// Hold for approval before proceeding.
    RequireApproval,
    /// Log the match but allow the command.
    Log,
}

/// Severity level for blocklist entries.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum BlocklistSeverity {
    Low,
    Medium,
    High,
    Critical,
}

/// A single blocklist entry for command gating.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlocklistEntry {
    /// Pattern to match (literal string or glob with `*`/`?` wildcards).
    pub pattern: String,
    /// Category of the threat (e.g., "destructive", "exfiltration").
    pub category: String,
    /// Severity of the matched command.
    pub severity: BlocklistSeverity,
    /// Action to take when the pattern matches.
    pub action: BlocklistAction,
}

// ============================================================================
// Threat classification
// ============================================================================

/// Threat categories for vsock message classification.
///
/// Each category represents a class of security concern. A single message
/// may trigger findings across multiple categories.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ThreatCategory {
    /// Credential or secret exposure (API keys, tokens, private keys).
    SecretExposure,
    /// Data exfiltration to external endpoints.
    DataExfiltration,
    /// Shell injection or code injection attempts.
    Injection,
    /// Destructive commands (rm -rf, mkfs, DROP TABLE).
    Destructive,
    /// Privilege escalation (sudo, nsenter, setuid).
    PrivilegeEscalation,
    /// Supply chain attacks (untrusted installs, impure builds).
    SupplyChain,
    /// Access to sensitive system files.
    SensitiveFileAccess,
    /// System configuration modification.
    SystemModification,
    /// Network abuse (port scanning, reverse shells).
    NetworkAbuse,
    /// MicroVM/Firecracker escape and tool poisoning.
    ToolPoisoning,
}

/// Severity of a threat finding.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Severity {
    Info,
    Low,
    Medium,
    High,
    Critical,
}

/// A single threat finding produced by the classifier.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreatFinding {
    /// Threat category.
    pub category: ThreatCategory,
    /// Identifier for the pattern that matched (e.g., "aws_access_key", "rm_rf_root").
    pub pattern_id: String,
    /// Severity of this finding.
    pub severity: Severity,
    /// The text that matched (or a representative snippet).
    pub matched_text: String,
    /// Additional context about the finding.
    pub context: String,
}

// ============================================================================
// Security posture
// ============================================================================

/// A security layer that can be evaluated for posture scoring.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SecurityLayer {
    JailerIsolation,
    CgroupLimits,
    SeccompFilter,
    NetworkIsolation,
    VsockAuth,
    EncryptionAtRest,
    EncryptionInTransit,
    AuditLogging,
    SecretManagement,
    ConfigImmutability,
    GuestHardening,
    SupplyChainIntegrity,
}

impl SecurityLayer {
    /// All security layers in evaluation order.
    pub fn all() -> &'static [SecurityLayer] {
        &[
            SecurityLayer::JailerIsolation,
            SecurityLayer::CgroupLimits,
            SecurityLayer::SeccompFilter,
            SecurityLayer::NetworkIsolation,
            SecurityLayer::VsockAuth,
            SecurityLayer::EncryptionAtRest,
            SecurityLayer::EncryptionInTransit,
            SecurityLayer::AuditLogging,
            SecurityLayer::SecretManagement,
            SecurityLayer::ConfigImmutability,
            SecurityLayer::GuestHardening,
            SecurityLayer::SupplyChainIntegrity,
        ]
    }
}

/// Result of a single posture check.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostureCheck {
    /// Which security layer this check belongs to.
    pub layer: SecurityLayer,
    /// Human-readable check name (e.g., "Jailer enabled for Firecracker").
    pub name: String,
    /// Whether the check passed.
    pub passed: bool,
    /// Explanation of the result.
    pub detail: String,
}

/// Overall posture report aggregating all checks.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostureReport {
    /// Individual check results.
    pub checks: Vec<PostureCheck>,
    /// Overall score: `passed_checks / total_checks * 100`.
    pub score: f64,
    /// ISO 8601 timestamp of when the report was generated.
    pub timestamp: String,
}

fn default_true() -> bool {
    true
}

fn default_rate_fps() -> u32 {
    100
}

fn default_rate_fpm() -> u32 {
    3000
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_authenticated_frame_serde_roundtrip() {
        let frame = AuthenticatedFrame {
            version: PROTOCOL_VERSION_AUTHENTICATED,
            session_id: "sess-001".to_string(),
            sequence: 42,
            timestamp: "2026-02-25T00:00:00Z".to_string(),
            signed: SignedPayload {
                payload: b"inner request json".to_vec(),
                signature: vec![0u8; 64],
                signer_id: "guest-key-1".to_string(),
            },
        };

        let json = serde_json::to_string(&frame).unwrap();
        let parsed: AuthenticatedFrame = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.version, 2);
        assert_eq!(parsed.session_id, "sess-001");
        assert_eq!(parsed.sequence, 42);
        assert_eq!(parsed.signed.payload, b"inner request json");
        assert_eq!(parsed.signed.signature.len(), 64);
    }

    #[test]
    fn test_session_hello_serde_roundtrip() {
        let hello = SessionHello {
            version: PROTOCOL_VERSION_AUTHENTICATED,
            session_id: "sess-002".to_string(),
            challenge: vec![1, 2, 3, 4, 5],
            host_pubkey: vec![0u8; 32],
        };

        let json = serde_json::to_string(&hello).unwrap();
        let parsed: SessionHello = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.version, 2);
        assert_eq!(parsed.session_id, "sess-002");
        assert_eq!(parsed.challenge.len(), 5);
        assert_eq!(parsed.host_pubkey.len(), 32);
    }

    #[test]
    fn test_session_hello_ack_serde_roundtrip() {
        let ack = SessionHelloAck {
            version: PROTOCOL_VERSION_AUTHENTICATED,
            session_id: "sess-002".to_string(),
            challenge_response: vec![9; 64],
            guest_pubkey: vec![0u8; 32],
        };

        let json = serde_json::to_string(&ack).unwrap();
        let parsed: SessionHelloAck = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.version, 2);
        assert_eq!(parsed.session_id, "sess-002");
        assert_eq!(parsed.challenge_response.len(), 64);
        assert_eq!(parsed.guest_pubkey.len(), 32);
    }

    #[test]
    fn test_security_policy_defaults() {
        let policy = SecurityPolicy::default();

        assert!(policy.require_auth);
        assert!(policy.access.filesystem);
        assert!(policy.access.network);
        assert!(policy.access.build);
        assert!(policy.access.host_communication);
        assert!(!policy.access.debug_exec);
        assert_eq!(policy.rate_limits.frames_per_second, 100);
        assert_eq!(policy.rate_limits.frames_per_minute, 3000);
        assert_eq!(policy.session.max_lifetime_secs, 0);
        assert_eq!(policy.session.max_tasks, 0);
    }

    #[test]
    fn test_security_policy_serde_with_defaults() {
        // Deserialize a minimal JSON — all fields should fill with defaults.
        let json = "{}";
        let policy: SecurityPolicy = serde_json::from_str(json).unwrap();

        assert!(policy.require_auth);
        assert!(policy.access.filesystem);
        assert_eq!(policy.rate_limits.frames_per_second, 100);
    }

    #[test]
    fn test_security_policy_serde_override() {
        let json = r#"{
            "require_auth": true,
            "access": { "build": false, "network": false },
            "rate_limits": { "frames_per_second": 50 }
        }"#;
        let policy: SecurityPolicy = serde_json::from_str(json).unwrap();

        assert!(policy.require_auth);
        assert!(policy.access.filesystem); // default
        assert!(!policy.access.build);
        assert!(!policy.access.network);
        assert_eq!(policy.rate_limits.frames_per_second, 50);
        assert_eq!(policy.rate_limits.frames_per_minute, 3000); // default
    }

    #[test]
    fn test_security_policy_full_roundtrip() {
        let policy = SecurityPolicy {
            require_auth: true,
            access: AccessPolicy {
                filesystem: false,
                network: true,
                build: false,
                host_communication: true,
                debug_exec: true,
                console: false,
            },
            rate_limits: RateLimitPolicy {
                frames_per_second: 200,
                frames_per_minute: 6000,
            },
            session: SessionPolicy {
                max_lifetime_secs: 3600,
                max_tasks: 100,
            },
            blocklist: vec![BlocklistEntry {
                pattern: "rm -rf /".to_string(),
                category: "destructive".to_string(),
                severity: BlocklistSeverity::Critical,
                action: BlocklistAction::Block,
            }],
        };

        let json = serde_json::to_string(&policy).unwrap();
        let parsed: SecurityPolicy = serde_json::from_str(&json).unwrap();

        assert!(parsed.require_auth);
        assert!(!parsed.access.filesystem);
        assert!(!parsed.access.build);
        assert!(parsed.access.debug_exec);
        assert_eq!(parsed.rate_limits.frames_per_second, 200);
        assert_eq!(parsed.session.max_lifetime_secs, 3600);
        assert_eq!(parsed.session.max_tasks, 100);
        assert_eq!(parsed.blocklist.len(), 1);
        assert_eq!(parsed.blocklist[0].pattern, "rm -rf /");
    }

    #[test]
    fn test_protocol_version_constants() {
        assert_eq!(PROTOCOL_VERSION_AUTHENTICATED, 2);
        assert_eq!(PROTOCOL_VERSION_LEGACY, 1);
    }

    #[test]
    fn test_gate_decision_serde_roundtrip() {
        let decisions = vec![
            GateDecision::Allow,
            GateDecision::Blocked {
                pattern: "rm -rf /".to_string(),
                reason: "destructive".to_string(),
            },
            GateDecision::RequiresApproval {
                reason: "matched pattern: nsenter".to_string(),
            },
        ];

        for decision in decisions {
            let json = serde_json::to_string(&decision).unwrap();
            let parsed: GateDecision = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, decision);
        }
    }

    #[test]
    fn test_approval_verdict_serde_roundtrip() {
        let verdicts = vec![
            ApprovalVerdict::Approved,
            ApprovalVerdict::Denied {
                reason: "policy violation".to_string(),
            },
            ApprovalVerdict::Timeout,
        ];

        for verdict in verdicts {
            let json = serde_json::to_string(&verdict).unwrap();
            let parsed: ApprovalVerdict = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, verdict);
        }
    }

    #[test]
    fn test_blocklist_entry_serde_roundtrip() {
        let entry = BlocklistEntry {
            pattern: "rm -rf /".to_string(),
            category: "destructive".to_string(),
            severity: BlocklistSeverity::Critical,
            action: BlocklistAction::Block,
        };

        let json = serde_json::to_string(&entry).unwrap();
        let parsed: BlocklistEntry = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.pattern, "rm -rf /");
        assert_eq!(parsed.severity, BlocklistSeverity::Critical);
        assert_eq!(parsed.action, BlocklistAction::Block);
    }

    #[test]
    fn test_blocklist_severity_ordering() {
        assert!(BlocklistSeverity::Low < BlocklistSeverity::Medium);
        assert!(BlocklistSeverity::Medium < BlocklistSeverity::High);
        assert!(BlocklistSeverity::High < BlocklistSeverity::Critical);
    }

    #[test]
    fn test_blocklist_action_values() {
        let actions = vec![
            BlocklistAction::Block,
            BlocklistAction::RequireApproval,
            BlocklistAction::Log,
        ];
        for action in actions {
            let json = serde_json::to_string(&action).unwrap();
            let parsed: BlocklistAction = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, action);
        }
    }

    #[test]
    fn test_security_policy_with_blocklist() {
        let json = r#"{
            "require_auth": true,
            "blocklist": [
                {
                    "pattern": "rm -rf /",
                    "category": "destructive",
                    "severity": "Critical",
                    "action": "Block"
                }
            ]
        }"#;
        let policy: SecurityPolicy = serde_json::from_str(json).unwrap();

        assert!(policy.require_auth);
        assert_eq!(policy.blocklist.len(), 1);
        assert_eq!(policy.blocklist[0].pattern, "rm -rf /");
        assert_eq!(policy.blocklist[0].action, BlocklistAction::Block);
    }

    #[test]
    fn test_security_policy_empty_blocklist_default() {
        let json = "{}";
        let policy: SecurityPolicy = serde_json::from_str(json).unwrap();
        assert!(policy.blocklist.is_empty());
    }

    // -- Threat classification tests --

    #[test]
    fn test_threat_category_serde_roundtrip() {
        let categories = vec![
            ThreatCategory::SecretExposure,
            ThreatCategory::DataExfiltration,
            ThreatCategory::Injection,
            ThreatCategory::Destructive,
            ThreatCategory::PrivilegeEscalation,
            ThreatCategory::SupplyChain,
            ThreatCategory::SensitiveFileAccess,
            ThreatCategory::SystemModification,
            ThreatCategory::NetworkAbuse,
            ThreatCategory::ToolPoisoning,
        ];
        for cat in categories {
            let json = serde_json::to_string(&cat).unwrap();
            let parsed: ThreatCategory = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, cat);
        }
    }

    #[test]
    fn test_severity_ordering() {
        assert!(Severity::Info < Severity::Low);
        assert!(Severity::Low < Severity::Medium);
        assert!(Severity::Medium < Severity::High);
        assert!(Severity::High < Severity::Critical);
    }

    #[test]
    fn test_severity_serde_roundtrip() {
        let severities = vec![
            Severity::Info,
            Severity::Low,
            Severity::Medium,
            Severity::High,
            Severity::Critical,
        ];
        for sev in severities {
            let json = serde_json::to_string(&sev).unwrap();
            let parsed: Severity = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, sev);
        }
    }

    #[test]
    fn test_threat_finding_serde_roundtrip() {
        let finding = ThreatFinding {
            category: ThreatCategory::SecretExposure,
            pattern_id: "aws_access_key".to_string(),
            severity: Severity::Critical,
            matched_text: "AKIAIOSFODNN7EXAMPLE".to_string(),
            context: "AWS access key detected".to_string(),
        };

        let json = serde_json::to_string(&finding).unwrap();
        let parsed: ThreatFinding = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.category, ThreatCategory::SecretExposure);
        assert_eq!(parsed.pattern_id, "aws_access_key");
        assert_eq!(parsed.severity, Severity::Critical);
    }

    // -- Posture types --

    #[test]
    fn test_security_layer_all_count() {
        assert_eq!(SecurityLayer::all().len(), 12);
    }

    #[test]
    fn test_security_layer_serde_roundtrip() {
        for layer in SecurityLayer::all() {
            let json = serde_json::to_string(layer).unwrap();
            let parsed: SecurityLayer = serde_json::from_str(&json).unwrap();
            assert_eq!(&parsed, layer);
        }
    }

    #[test]
    fn test_posture_check_serde_roundtrip() {
        let check = PostureCheck {
            layer: SecurityLayer::JailerIsolation,
            name: "Jailer enabled".to_string(),
            passed: true,
            detail: "Firecracker runs inside jailer".to_string(),
        };
        let json = serde_json::to_string(&check).unwrap();
        let parsed: PostureCheck = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.layer, SecurityLayer::JailerIsolation);
        assert!(parsed.passed);
    }

    #[test]
    fn test_posture_report_serde_roundtrip() {
        let report = PostureReport {
            checks: vec![
                PostureCheck {
                    layer: SecurityLayer::CgroupLimits,
                    name: "cgroup v2 limits set".to_string(),
                    passed: true,
                    detail: "mem + cpu limits configured".to_string(),
                },
                PostureCheck {
                    layer: SecurityLayer::VsockAuth,
                    name: "vsock auth enabled".to_string(),
                    passed: false,
                    detail: "require_auth is false".to_string(),
                },
            ],
            score: 50.0,
            timestamp: "2026-02-25T00:00:00Z".to_string(),
        };
        let json = serde_json::to_string(&report).unwrap();
        let parsed: PostureReport = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.checks.len(), 2);
        assert_eq!(parsed.score, 50.0);
    }
}