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
use std::io::Write;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

use crate::security::{GateDecision, ThreatFinding};

// ============================================================================
// Local mvmctl audit log (single-host operations)
// ============================================================================

/// Default path for the local audit log.
///
/// Prefers XDG state directory (`~/.local/state/mvm/log/`). Falls back to
/// legacy `~/.mvm/log/` if an audit log already exists there.
pub fn default_audit_log() -> String {
    // Check legacy location for backward compat
    let legacy = format!("{}/log/audit.jsonl", crate::config::mvm_data_dir());
    if std::path::Path::new(&legacy).exists() {
        return legacy;
    }
    format!("{}/log/audit.jsonl", crate::config::mvm_state_dir())
}

/// Rotate when the audit log exceeds this size.
const ROTATE_THRESHOLD_BYTES: u64 = 10 * 1024 * 1024; // 10 MiB

/// Categories of local mvmctl operations that are audit-logged.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LocalAuditKind {
    VmStart,
    VmStop,
    KeyLookup,
    VolumeCreate,
    VolumeOpen,
    UpdateInstall,
    Uninstall,
    // --- DX features (Phase 2) ---
    NetworkCreate,
    NetworkRemove,
    ImageFetch,
    TemplateBuild,
    TemplatePush,
    TemplatePull,
    ConfigChange,
    ConsoleSessionStart,
    ConsoleSessionEnd,
}

/// A single local audit log entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LocalAuditEvent {
    pub timestamp: String,
    pub kind: LocalAuditKind,
    pub vm_name: Option<String>,
    pub detail: Option<String>,
}

impl LocalAuditEvent {
    /// Create an event stamped with the current UTC time.
    pub fn now(kind: LocalAuditKind, vm_name: Option<String>, detail: Option<String>) -> Self {
        let timestamp = chrono::Utc::now().to_rfc3339();
        Self {
            timestamp,
            kind,
            vm_name,
            detail,
        }
    }
}

/// Append-only local audit log writer.
pub struct LocalAuditLog {
    path: PathBuf,
}

impl LocalAuditLog {
    /// Open (or create) a local audit log at `path`.
    ///
    /// Creates parent directories if they don't exist.
    pub fn open(path: &Path) -> Result<Self> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create audit log dir: {}", parent.display()))?;
        }
        Ok(Self {
            path: path.to_path_buf(),
        })
    }

    /// Append one JSONL line.  Rotates to `audit.jsonl.1` when the file
    /// exceeds [`ROTATE_THRESHOLD_BYTES`].
    pub fn append(&self, event: &LocalAuditEvent) -> Result<()> {
        self.maybe_rotate()?;

        let mut file = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.path)
            .with_context(|| format!("Failed to open audit log: {}", self.path.display()))?;

        let line = serde_json::to_string(event).context("Failed to serialize audit event")?;
        writeln!(file, "{line}").context("Failed to write audit event")?;
        Ok(())
    }

    fn maybe_rotate(&self) -> Result<()> {
        if !self.path.exists() {
            return Ok(());
        }
        let meta = std::fs::metadata(&self.path)
            .with_context(|| format!("Failed to stat {}", self.path.display()))?;
        if meta.len() >= ROTATE_THRESHOLD_BYTES {
            let rotated = self.path.with_extension("jsonl.1");
            std::fs::rename(&self.path, &rotated)
                .with_context(|| format!("Failed to rotate audit log to {}", rotated.display()))?;
        }
        Ok(())
    }
}

/// Emit a local audit event to the default log path (best-effort).
///
/// Errors are logged via `tracing::warn!` and never propagated — audit
/// failures must not block the operation being logged.
pub fn emit(kind: LocalAuditKind, vm_name: Option<&str>, detail: Option<&str>) {
    let event = LocalAuditEvent::now(kind, vm_name.map(str::to_owned), detail.map(str::to_owned));
    let path = PathBuf::from(default_audit_log());
    match LocalAuditLog::open(&path).and_then(|log| log.append(&event)) {
        Ok(()) => {}
        Err(e) => tracing::warn!("audit log write failed: {e}"),
    }
}

/// Audit event types for per-tenant audit logging.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AuditAction {
    // -- Instance lifecycle --
    InstanceCreated,
    InstanceStarted,
    InstanceStopped,
    InstanceWarmed,
    InstanceSlept,
    InstanceWoken,
    InstanceDestroyed,
    // -- Pool/Tenant --
    PoolCreated,
    PoolBuilt,
    PoolDestroyed,
    TenantCreated,
    TenantDestroyed,
    // -- Operational --
    QuotaExceeded,
    SecretsRotated,
    SnapshotCreated,
    SnapshotRestored,
    SnapshotDeleted,
    TransitionDeferred,
    MinRuntimeOverridden,
    // -- Vsock security (Phase 8) --
    VsockSessionStarted,
    VsockSessionEnded,
    VsockFrameReceived,
    CommandBlocked,
    CommandApproved,
    CommandDenied,
    ThreatDetected,
    RateLimitExceeded,
    SessionRecycled,
}

/// A single audit log entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
    pub timestamp: String,
    pub tenant_id: String,
    pub pool_id: Option<String>,
    pub instance_id: Option<String>,
    pub action: AuditAction,
    pub detail: Option<String>,
    /// Threat findings from the classifier (empty for non-security events).
    #[serde(default)]
    pub threats: Vec<ThreatFinding>,
    /// Gate decision for command-gated events.
    #[serde(default)]
    pub gate_decision: Option<GateDecision>,
    /// Vsock frame sequence number.
    #[serde(default)]
    pub frame_sequence: Option<u64>,
}

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

    #[test]
    fn test_audit_entry_serialization() {
        let entry = AuditEntry {
            timestamp: "2025-01-01T00:00:00Z".to_string(),
            tenant_id: "acme".to_string(),
            pool_id: Some("workers".to_string()),
            instance_id: Some("i-abc123".to_string()),
            action: AuditAction::InstanceStarted,
            detail: Some("pid=12345".to_string()),
            threats: vec![],
            gate_decision: None,
            frame_sequence: None,
        };

        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("\"tenant_id\":\"acme\""));
        assert!(json.contains("\"InstanceStarted\""));
    }

    #[test]
    fn test_audit_entry_no_optionals() {
        let entry = AuditEntry {
            timestamp: "2025-01-01T00:00:00Z".to_string(),
            tenant_id: "acme".to_string(),
            pool_id: None,
            instance_id: None,
            action: AuditAction::TenantCreated,
            detail: None,
            threats: vec![],
            gate_decision: None,
            frame_sequence: None,
        };

        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("\"pool_id\":null"));
    }

    #[test]
    fn test_all_audit_actions_serialize() {
        let actions = vec![
            AuditAction::InstanceCreated,
            AuditAction::InstanceStarted,
            AuditAction::InstanceStopped,
            AuditAction::InstanceWarmed,
            AuditAction::InstanceSlept,
            AuditAction::InstanceWoken,
            AuditAction::InstanceDestroyed,
            AuditAction::PoolCreated,
            AuditAction::PoolBuilt,
            AuditAction::PoolDestroyed,
            AuditAction::TenantCreated,
            AuditAction::TenantDestroyed,
            AuditAction::QuotaExceeded,
            AuditAction::SecretsRotated,
            AuditAction::SnapshotCreated,
            AuditAction::SnapshotRestored,
            AuditAction::SnapshotDeleted,
            AuditAction::TransitionDeferred,
            AuditAction::MinRuntimeOverridden,
            AuditAction::VsockSessionStarted,
            AuditAction::VsockSessionEnded,
            AuditAction::VsockFrameReceived,
            AuditAction::CommandBlocked,
            AuditAction::CommandApproved,
            AuditAction::CommandDenied,
            AuditAction::ThreatDetected,
            AuditAction::RateLimitExceeded,
            AuditAction::SessionRecycled,
        ];

        for action in actions {
            let json = serde_json::to_string(&action).unwrap();
            assert!(!json.is_empty());
        }
    }

    #[test]
    fn test_audit_entry_backward_compat() {
        // Old-format JSON without new fields should still deserialize
        let json = r#"{
            "timestamp": "2025-01-01T00:00:00Z",
            "tenant_id": "acme",
            "pool_id": null,
            "instance_id": null,
            "action": "TenantCreated",
            "detail": null
        }"#;
        let entry: AuditEntry = serde_json::from_str(json).unwrap();
        assert_eq!(entry.tenant_id, "acme");
        assert!(entry.threats.is_empty());
        assert!(entry.gate_decision.is_none());
        assert!(entry.frame_sequence.is_none());
    }

    #[test]
    fn test_audit_entry_with_security_fields() {
        use crate::security::{GateDecision, Severity, ThreatCategory, ThreatFinding};

        let entry = AuditEntry {
            timestamp: "2025-01-01T00:00:00Z".to_string(),
            tenant_id: "acme".to_string(),
            pool_id: None,
            instance_id: Some("i-001".to_string()),
            action: AuditAction::ThreatDetected,
            detail: Some("classified vsock frame".to_string()),
            threats: vec![ThreatFinding {
                category: ThreatCategory::Destructive,
                pattern_id: "rm_rf_root".to_string(),
                severity: Severity::Critical,
                matched_text: "rm -rf /".to_string(),
                context: "literal match".to_string(),
            }],
            gate_decision: Some(GateDecision::Blocked {
                pattern: "rm -rf /".to_string(),
                reason: "destructive".to_string(),
            }),
            frame_sequence: Some(42),
        };

        let json = serde_json::to_string(&entry).unwrap();
        let parsed: AuditEntry = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.threats.len(), 1);
        assert_eq!(parsed.threats[0].category, ThreatCategory::Destructive);
        assert!(parsed.gate_decision.is_some());
        assert_eq!(parsed.frame_sequence, Some(42));
    }

    // -------------------------------------------------------------------------
    // LocalAuditEvent / LocalAuditLog tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_local_audit_event_serializes() {
        let event = LocalAuditEvent::now(
            LocalAuditKind::VmStart,
            Some("my-vm".to_string()),
            Some("flake=.".to_string()),
        );
        let json = serde_json::to_string(&event).unwrap();
        let parsed: LocalAuditEvent = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.kind, LocalAuditKind::VmStart);
        assert_eq!(parsed.vm_name.as_deref(), Some("my-vm"));
        assert_eq!(parsed.detail.as_deref(), Some("flake=."));
        assert!(!parsed.timestamp.is_empty());
    }

    #[test]
    fn test_local_audit_kind_all_variants_serialize() {
        let kinds = [
            LocalAuditKind::VmStart,
            LocalAuditKind::VmStop,
            LocalAuditKind::KeyLookup,
            LocalAuditKind::VolumeCreate,
            LocalAuditKind::VolumeOpen,
            LocalAuditKind::UpdateInstall,
            LocalAuditKind::Uninstall,
            LocalAuditKind::NetworkCreate,
            LocalAuditKind::NetworkRemove,
            LocalAuditKind::ImageFetch,
            LocalAuditKind::TemplateBuild,
            LocalAuditKind::TemplatePush,
            LocalAuditKind::TemplatePull,
            LocalAuditKind::ConfigChange,
            LocalAuditKind::ConsoleSessionStart,
            LocalAuditKind::ConsoleSessionEnd,
        ];
        for kind in kinds {
            let json = serde_json::to_string(&kind).unwrap();
            assert!(!json.is_empty());
        }
    }

    #[test]
    fn test_local_audit_log_append() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("audit.jsonl");

        let log = LocalAuditLog::open(&path).unwrap();
        let event = LocalAuditEvent::now(LocalAuditKind::VmStop, Some("vm1".to_string()), None);
        log.append(&event).unwrap();

        let contents = std::fs::read_to_string(&path).unwrap();
        assert!(contents.contains("vm_stop"));
        assert!(contents.contains("vm1"));
        // One line per event.
        assert_eq!(contents.lines().count(), 1);

        // Append a second event.
        let event2 = LocalAuditEvent::now(
            LocalAuditKind::UpdateInstall,
            None,
            Some("v1.2.3".to_string()),
        );
        log.append(&event2).unwrap();
        let contents2 = std::fs::read_to_string(&path).unwrap();
        assert_eq!(contents2.lines().count(), 2);
    }

    #[test]
    fn test_local_audit_log_rotation() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("audit.jsonl");

        // Write a file that exceeds the rotation threshold.
        let big_content = "x".repeat(ROTATE_THRESHOLD_BYTES as usize + 1);
        std::fs::write(&path, big_content).unwrap();

        let log = LocalAuditLog::open(&path).unwrap();
        let event = LocalAuditEvent::now(LocalAuditKind::Uninstall, None, None);
        log.append(&event).unwrap();

        // The rotated file should exist.
        let rotated = path.with_extension("jsonl.1");
        assert!(rotated.exists(), "rotation file should be created");

        // The new log file should contain only the new event.
        let contents = std::fs::read_to_string(&path).unwrap();
        assert_eq!(contents.lines().count(), 1);
        assert!(contents.contains("uninstall"));
    }
}