a3s-box-runtime 0.8.0

MicroVM runtime engine — VM lifecycle, OCI images, attestation, networking
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
//! Persistent audit log writer.
//!
//! Appends structured `AuditEvent` records to a JSON-lines file
//! with size-based rotation. Provides query support for reading
//! back events with time-range and action filters.

use std::fs::{self, File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;

use a3s_box_core::audit::{AuditAction, AuditConfig, AuditEvent, AuditOutcome};
use a3s_box_core::error::{BoxError, Result};

/// Persistent audit log that appends events to a JSON-lines file.
///
/// Thread-safe via internal `Mutex`. Supports size-based rotation.
pub struct AuditLog {
    inner: Mutex<AuditLogInner>,
}

struct AuditLogInner {
    /// Path to the active audit log file.
    path: PathBuf,
    /// Current file handle (lazy-opened on first write).
    file: Option<File>,
    /// Current file size in bytes.
    current_size: u64,
    /// Configuration.
    config: AuditConfig,
}

impl AuditLog {
    /// Create a new audit log at the given path.
    pub fn new(path: impl Into<PathBuf>, config: AuditConfig) -> Result<Self> {
        let path = path.into();

        // Create parent directory if needed
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                BoxError::AuditError(format!(
                    "Failed to create audit log directory {}: {}",
                    parent.display(),
                    e
                ))
            })?;
        }

        // Get current file size if it exists
        let current_size = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);

        Ok(Self {
            inner: Mutex::new(AuditLogInner {
                path,
                file: None,
                current_size,
                config,
            }),
        })
    }

    /// Open the audit log at the default path (~/.a3s/audit/audit.jsonl).
    pub fn default_path() -> Result<Self> {
        let path = a3s_box_core::dirs_home().join("audit").join("audit.jsonl");

        Self::new(path, AuditConfig::default())
    }

    /// Append an audit event to the log.
    pub fn log(&self, event: &AuditEvent) -> Result<()> {
        let mut inner = self
            .inner
            .lock()
            .map_err(|_| BoxError::AuditError("Audit log lock poisoned".to_string()))?;

        if !inner.config.enabled {
            return Ok(());
        }

        // Rotate if needed
        if inner.current_size >= inner.config.max_size {
            Self::rotate(&mut inner)?;
        }

        // Open file if not yet open
        if inner.file.is_none() {
            let file = OpenOptions::new()
                .create(true)
                .append(true)
                .open(&inner.path)
                .map_err(|e| {
                    BoxError::AuditError(format!(
                        "Failed to open audit log {}: {}",
                        inner.path.display(),
                        e
                    ))
                })?;
            inner.file = Some(file);
        }

        // Serialize and write
        let mut line = serde_json::to_string(event).map_err(|e| {
            BoxError::SerializationError(format!("Failed to serialize audit event: {}", e))
        })?;
        line.push('\n');

        let bytes = line.as_bytes();
        if let Some(ref mut file) = inner.file {
            file.write_all(bytes)
                .map_err(|e| BoxError::AuditError(format!("Failed to write audit event: {}", e)))?;
            file.flush()
                .map_err(|e| BoxError::AuditError(format!("Failed to flush audit log: {}", e)))?;
        }

        inner.current_size += bytes.len() as u64;
        Ok(())
    }

    /// Rotate the audit log file.
    fn rotate(inner: &mut AuditLogInner) -> Result<()> {
        // Close current file
        inner.file = None;

        let max = inner.config.max_files;
        let base = &inner.path;

        // Remove oldest if at limit
        let oldest = rotated_path(base, max);
        if oldest.exists() {
            if let Err(e) = fs::remove_file(&oldest) {
                tracing::warn!(path = %oldest.display(), error = %e, "Failed to remove oldest audit log during rotation");
            }
        }

        // Shift existing rotated files: .9 → .10, .8 → .9, etc.
        for i in (1..max).rev() {
            let from = rotated_path(base, i);
            let to = rotated_path(base, i + 1);
            if from.exists() {
                if let Err(e) = fs::rename(&from, &to) {
                    tracing::warn!(from = %from.display(), to = %to.display(), error = %e, "Failed to shift audit log during rotation");
                }
            }
        }

        // Rename current to .1
        if base.exists() {
            if let Err(e) = fs::rename(base, rotated_path(base, 1)) {
                tracing::warn!(path = %base.display(), error = %e, "Failed to rotate current audit log");
            }
        }

        inner.current_size = 0;
        Ok(())
    }

    /// Get the path to the audit log file.
    pub fn path(&self) -> PathBuf {
        self.inner
            .lock()
            .map(|inner| inner.path.clone())
            .unwrap_or_default()
    }
}

/// Generate a rotated file path (e.g., audit.jsonl.1, audit.jsonl.2).
fn rotated_path(base: &Path, index: u32) -> PathBuf {
    let name = format!(
        "{}.{}",
        base.file_name().unwrap_or_default().to_string_lossy(),
        index
    );
    base.with_file_name(name)
}

/// Query parameters for reading audit events.
#[derive(Debug, Clone, Default)]
pub struct AuditQuery {
    /// Filter by action type.
    pub action: Option<AuditAction>,
    /// Filter by box ID.
    pub box_id: Option<String>,
    /// Filter by outcome.
    pub outcome: Option<AuditOutcome>,
    /// Only events after this time.
    pub since: Option<chrono::DateTime<chrono::Utc>>,
    /// Only events before this time.
    pub until: Option<chrono::DateTime<chrono::Utc>>,
    /// Maximum number of events to return.
    pub limit: Option<usize>,
}

/// Read audit events from a log file, applying optional filters.
pub fn read_audit_log(path: &Path, query: &AuditQuery) -> Result<Vec<AuditEvent>> {
    if !path.exists() {
        return Ok(vec![]);
    }

    let file = File::open(path).map_err(|e| {
        BoxError::AuditError(format!(
            "Failed to open audit log {}: {}",
            path.display(),
            e
        ))
    })?;

    let reader = BufReader::new(file);
    let mut events = Vec::new();

    for line in reader.lines() {
        let line = line
            .map_err(|e| BoxError::AuditError(format!("Failed to read audit log line: {}", e)))?;

        if line.trim().is_empty() {
            continue;
        }

        let event: AuditEvent = match serde_json::from_str(&line) {
            Ok(e) => e,
            Err(_) => continue, // skip malformed lines
        };

        // Apply filters
        if let Some(ref action) = query.action {
            if event.action != *action {
                continue;
            }
        }
        if let Some(ref box_id) = query.box_id {
            if event.box_id.as_deref() != Some(box_id.as_str()) {
                continue;
            }
        }
        if let Some(ref outcome) = query.outcome {
            if event.outcome != *outcome {
                continue;
            }
        }
        if let Some(since) = query.since {
            if event.timestamp < since {
                continue;
            }
        }
        if let Some(until) = query.until {
            if event.timestamp > until {
                continue;
            }
        }

        events.push(event);

        if let Some(limit) = query.limit {
            if events.len() >= limit {
                break;
            }
        }
    }

    Ok(events)
}

impl a3s_box_core::traits::AuditSink for AuditLog {
    fn record(&self, event: &AuditEvent) -> Result<()> {
        self.log(event)
    }
}

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

    fn test_log(dir: &Path) -> AuditLog {
        let path = dir.join("audit.jsonl");
        AuditLog::new(path, AuditConfig::default()).unwrap()
    }

    #[test]
    fn test_audit_log_write_and_read() {
        let dir = TempDir::new().unwrap();
        let log = test_log(dir.path());

        let event = AuditEvent::new(AuditAction::BoxCreate, AuditOutcome::Success)
            .with_box_id("box-1")
            .with_message("Created box");

        log.log(&event).unwrap();

        let events = read_audit_log(&log.path(), &AuditQuery::default()).unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].action, AuditAction::BoxCreate);
        assert_eq!(events[0].box_id, Some("box-1".to_string()));
    }

    #[test]
    fn test_audit_log_multiple_events() {
        let dir = TempDir::new().unwrap();
        let log = test_log(dir.path());

        for i in 0..5 {
            let event = AuditEvent::new(AuditAction::ExecCommand, AuditOutcome::Success)
                .with_box_id(format!("box-{}", i));
            log.log(&event).unwrap();
        }

        let events = read_audit_log(&log.path(), &AuditQuery::default()).unwrap();
        assert_eq!(events.len(), 5);
    }

    #[test]
    fn test_audit_log_filter_by_action() {
        let dir = TempDir::new().unwrap();
        let log = test_log(dir.path());

        log.log(&AuditEvent::new(
            AuditAction::BoxCreate,
            AuditOutcome::Success,
        ))
        .unwrap();
        log.log(&AuditEvent::new(
            AuditAction::BoxStop,
            AuditOutcome::Success,
        ))
        .unwrap();
        log.log(&AuditEvent::new(
            AuditAction::BoxCreate,
            AuditOutcome::Failure,
        ))
        .unwrap();

        let query = AuditQuery {
            action: Some(AuditAction::BoxCreate),
            ..Default::default()
        };
        let events = read_audit_log(&log.path(), &query).unwrap();
        assert_eq!(events.len(), 2);
    }

    #[test]
    fn test_audit_log_filter_by_box_id() {
        let dir = TempDir::new().unwrap();
        let log = test_log(dir.path());

        log.log(&AuditEvent::new(AuditAction::BoxCreate, AuditOutcome::Success).with_box_id("a"))
            .unwrap();
        log.log(&AuditEvent::new(AuditAction::BoxCreate, AuditOutcome::Success).with_box_id("b"))
            .unwrap();

        let query = AuditQuery {
            box_id: Some("a".to_string()),
            ..Default::default()
        };
        let events = read_audit_log(&log.path(), &query).unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].box_id, Some("a".to_string()));
    }

    #[test]
    fn test_audit_log_filter_by_outcome() {
        let dir = TempDir::new().unwrap();
        let log = test_log(dir.path());

        log.log(&AuditEvent::new(
            AuditAction::ImagePull,
            AuditOutcome::Success,
        ))
        .unwrap();
        log.log(&AuditEvent::new(
            AuditAction::ImagePull,
            AuditOutcome::Failure,
        ))
        .unwrap();
        log.log(&AuditEvent::new(
            AuditAction::ImagePull,
            AuditOutcome::Denied,
        ))
        .unwrap();

        let query = AuditQuery {
            outcome: Some(AuditOutcome::Failure),
            ..Default::default()
        };
        let events = read_audit_log(&log.path(), &query).unwrap();
        assert_eq!(events.len(), 1);
    }

    #[test]
    fn test_audit_log_limit() {
        let dir = TempDir::new().unwrap();
        let log = test_log(dir.path());

        for _ in 0..10 {
            log.log(&AuditEvent::new(
                AuditAction::ExecCommand,
                AuditOutcome::Success,
            ))
            .unwrap();
        }

        let query = AuditQuery {
            limit: Some(3),
            ..Default::default()
        };
        let events = read_audit_log(&log.path(), &query).unwrap();
        assert_eq!(events.len(), 3);
    }

    #[test]
    fn test_audit_log_empty_file() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("nonexistent.jsonl");
        let events = read_audit_log(&path, &AuditQuery::default()).unwrap();
        assert!(events.is_empty());
    }

    #[test]
    fn test_audit_log_disabled() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("audit.jsonl");
        let config = AuditConfig {
            enabled: false,
            ..Default::default()
        };
        let log = AuditLog::new(&path, config).unwrap();

        log.log(&AuditEvent::new(
            AuditAction::BoxCreate,
            AuditOutcome::Success,
        ))
        .unwrap();

        // File should not exist or be empty
        let events = read_audit_log(&path, &AuditQuery::default()).unwrap();
        assert!(events.is_empty());
    }

    #[test]
    fn test_audit_log_rotation() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("audit.jsonl");
        let config = AuditConfig {
            enabled: true,
            max_size: 100, // very small to trigger rotation
            max_files: 3,
        };
        let log = AuditLog::new(&path, config).unwrap();

        // Write enough events to trigger rotation
        for i in 0..20 {
            let event = AuditEvent::new(AuditAction::ExecCommand, AuditOutcome::Success)
                .with_message(format!("Event {}", i));
            log.log(&event).unwrap();
        }

        // Should have rotated files
        assert!(path.exists());
        let rotated_1 = dir.path().join("audit.jsonl.1");
        assert!(rotated_1.exists());
    }

    #[test]
    fn test_rotated_path() {
        let base = PathBuf::from("/var/log/audit.jsonl");
        assert_eq!(
            rotated_path(&base, 1),
            PathBuf::from("/var/log/audit.jsonl.1")
        );
        assert_eq!(
            rotated_path(&base, 10),
            PathBuf::from("/var/log/audit.jsonl.10")
        );
    }

    #[test]
    fn test_audit_log_path() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("audit.jsonl");
        let log = AuditLog::new(&path, AuditConfig::default()).unwrap();
        assert_eq!(log.path(), path);
    }
}