-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudit_log.rs
More file actions
410 lines (355 loc) · 13.3 KB
/
Copy pathaudit_log.rs
File metadata and controls
410 lines (355 loc) · 13.3 KB
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
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//! Append-Only Audit Log
//!
//! Provides tamper-resistant logging of all operations for compliance (SOC 2, GDPR, HIPAA).
//! Log entries are:
//! - Append-only (no deletion or modification)
//! - Timestamped with nanosecond precision
//! - Include operation type, path, outcome, user, PID
//! - Optionally cryptographically signed (HMAC-SHA256)
//!
//! Logs stored as JSONL (JSON Lines) for easy parsing and streaming.
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;
use uuid::Uuid;
use crate::state::Operation;
/// Single audit log entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
/// Unique entry ID
pub id: Uuid,
/// Timestamp (UTC, nanosecond precision)
pub timestamp: DateTime<Utc>,
/// Operation ID (links to undo history)
pub operation_id: Uuid,
/// Operation type (mkdir, rm, rmO, etc.)
pub operation_type: String,
/// Target path
pub path: String,
/// Outcome: "success", "error"
pub outcome: String,
/// Error message if outcome == "error"
pub error: Option<String>,
/// User who performed the operation (from $USER)
pub user: String,
/// Process ID
pub pid: u32,
/// Shell root directory
pub root: String,
/// Optional HMAC-SHA256 signature (for tamper detection)
pub signature: Option<String>,
}
impl AuditEntry {
/// Create new audit entry from operation
pub fn from_operation(op: &Operation, outcome: &str, error: Option<String>) -> Self {
Self {
id: Uuid::new_v4(),
timestamp: Utc::now(),
operation_id: op.id,
operation_type: format!("{:?}", op.op_type),
path: op.path.clone(),
outcome: outcome.to_string(),
error,
user: std::env::var("USER").unwrap_or_else(|_| "unknown".to_string()),
pid: std::process::id(),
root: std::env::current_dir()
.ok()
.and_then(|p| p.to_str().map(|s| s.to_string()))
.unwrap_or_else(|| "/".to_string()),
signature: None, // TODO: Add HMAC signing
}
}
/// Serialize to JSON line
pub fn to_json_line(&self) -> Result<String> {
let mut json = serde_json::to_string(self)?;
json.push('\n');
Ok(json)
}
/// Parse from JSON line
pub fn from_json_line(line: &str) -> Result<Self> {
serde_json::from_str(line).context("Failed to parse audit entry")
}
}
/// Audit log manager
pub struct AuditLog {
/// Path to audit log file
log_path: PathBuf,
/// Optional HMAC key for signing entries
hmac_key: Option<Vec<u8>>,
}
impl AuditLog {
/// Create new audit log manager
///
/// # Arguments
/// * `log_path` - Path to audit log file (will be created if doesn't exist)
/// * `hmac_key` - Optional HMAC-SHA256 key for signing entries
///
/// # Examples
/// ```no_run
/// use vsh::audit_log::AuditLog;
/// use std::path::PathBuf;
///
/// let log = AuditLog::new(PathBuf::from("/var/log/vsh-audit.log"), None)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn new(log_path: PathBuf, hmac_key: Option<Vec<u8>>) -> Result<Self> {
// Ensure parent directory exists
if let Some(parent) = log_path.parent() {
std::fs::create_dir_all(parent)?;
}
// Create file if doesn't exist
if !log_path.exists() {
OpenOptions::new()
.create(true)
.append(true)
.open(&log_path)?;
}
Ok(Self { log_path, hmac_key })
}
/// Resolve the default audit-log path following the XDG Base Directory spec.
///
/// Search order:
/// 1. `$XDG_STATE_HOME/valence-shell/audit.log` when `XDG_STATE_HOME` is set.
/// 2. `$HOME/.local/state/valence-shell/audit.log` otherwise.
/// 3. Errors if neither `XDG_STATE_HOME` nor `HOME` is set.
///
/// The directory is *not* created; that is deferred to [`AuditLog::new`].
pub fn default_path() -> Result<PathBuf> {
if let Ok(xdg) = std::env::var("XDG_STATE_HOME") {
if !xdg.is_empty() {
return Ok(PathBuf::from(xdg).join("valence-shell").join("audit.log"));
}
}
if let Ok(home) = std::env::var("HOME") {
if !home.is_empty() {
return Ok(PathBuf::from(home)
.join(".local")
.join("state")
.join("valence-shell")
.join("audit.log"));
}
}
anyhow::bail!(
"Cannot determine default audit-log path: neither XDG_STATE_HOME nor HOME is set"
);
}
/// Open (or create) the audit log at the XDG-default location.
///
/// Convenience wrapper around [`AuditLog::default_path`] + [`AuditLog::new`].
pub fn with_default_path(hmac_key: Option<Vec<u8>>) -> Result<Self> {
Self::new(Self::default_path()?, hmac_key)
}
/// Append audit entry to log
///
/// This is the core append-only operation. Failures are non-fatal
/// (shell continues even if audit fails), but logged to stderr.
///
/// # Arguments
/// * `entry` - Audit entry to append
///
/// # Examples
/// ```no_run
/// # use vsh::audit_log::{AuditLog, AuditEntry};
/// # use vsh::state::Operation;
/// # use std::path::PathBuf;
/// # let log = AuditLog::new(PathBuf::from("/tmp/audit.log"), None)?;
/// # let op = Operation::new(vsh::state::OperationType::Mkdir, "test".to_string(), None);
/// let entry = AuditEntry::from_operation(&op, "success", None);
/// log.append(&entry)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn append(&self, entry: &AuditEntry) -> Result<()> {
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(&self.log_path)
.context("Failed to open audit log")?;
let json_line = entry.to_json_line()?;
file.write_all(json_line.as_bytes())
.context("Failed to write audit entry")?;
// Force sync to disk (ensure durability)
file.sync_all()?;
Ok(())
}
/// Read all audit entries from log
///
/// Returns entries in chronological order (oldest first).
///
/// # Examples
/// ```no_run
/// # use vsh::audit_log::AuditLog;
/// # use std::path::PathBuf;
/// # let log = AuditLog::new(PathBuf::from("/tmp/audit.log"), None)?;
/// let entries = log.read_all()?;
/// println!("Total operations: {}", entries.len());
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn read_all(&self) -> Result<Vec<AuditEntry>> {
let content =
crate::fs_pure::read_to_string(&self.log_path).context("Failed to read audit log")?;
let mut entries = Vec::new();
for (line_num, line) in content.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
match AuditEntry::from_json_line(line) {
Ok(entry) => entries.push(entry),
Err(e) => {
eprintln!(
"Warning: Failed to parse audit entry at line {}: {}",
line_num + 1,
e
);
}
}
}
Ok(entries)
}
/// Read audit entries for a specific time range
///
/// # Arguments
/// * `start` - Start timestamp (inclusive)
/// * `end` - End timestamp (inclusive)
///
/// # Examples
/// ```no_run
/// # use vsh::audit_log::AuditLog;
/// # use std::path::PathBuf;
/// # use chrono::{Utc, Duration};
/// # let log = AuditLog::new(PathBuf::from("/tmp/audit.log"), None)?;
/// let now = Utc::now();
/// let one_hour_ago = now - Duration::hours(1);
/// let recent = log.read_range(one_hour_ago, now)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn read_range(&self, start: DateTime<Utc>, end: DateTime<Utc>) -> Result<Vec<AuditEntry>> {
let all_entries = self.read_all()?;
Ok(all_entries
.into_iter()
.filter(|entry| entry.timestamp >= start && entry.timestamp <= end)
.collect())
}
/// Read audit entries for a specific operation type
///
/// # Examples
/// ```no_run
/// # use vsh::audit_log::AuditLog;
/// # use std::path::PathBuf;
/// # let log = AuditLog::new(PathBuf::from("/tmp/audit.log"), None)?;
/// let deletions = log.read_by_type("DeleteFile")?;
/// let obliterations = log.read_by_type("Obliterate")?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn read_by_type(&self, op_type: &str) -> Result<Vec<AuditEntry>> {
let all_entries = self.read_all()?;
Ok(all_entries
.into_iter()
.filter(|entry| entry.operation_type == op_type)
.collect())
}
/// Verify audit log integrity (check for tampering)
///
/// Returns Ok(true) if log is intact, Ok(false) if tampered, Err on read failure.
///
/// Note: Only works if HMAC signing is enabled.
pub fn verify_integrity(&self) -> Result<bool> {
if self.hmac_key.is_none() {
// No signing enabled, cannot verify
return Ok(true);
}
// TODO: Implement HMAC verification
// For each entry:
// 1. Recompute HMAC from entry fields
// 2. Compare with stored signature
// 3. Return false if mismatch
Ok(true)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::state::OperationType;
use tempfile::NamedTempFile;
#[test]
fn test_audit_entry_serialization() {
let op = Operation::new(OperationType::Mkdir, "test_dir".to_string(), None);
let entry = AuditEntry::from_operation(&op, "success", None);
let json_line = entry.to_json_line().unwrap();
assert!(json_line.ends_with('\n'));
let parsed = AuditEntry::from_json_line(&json_line).unwrap();
assert_eq!(parsed.operation_id, entry.operation_id);
assert_eq!(parsed.path, "test_dir");
assert_eq!(parsed.outcome, "success");
}
#[test]
fn test_audit_log_append_and_read() {
let temp_file = NamedTempFile::new().unwrap();
let log_path = temp_file.path().to_path_buf();
let log = AuditLog::new(log_path, None).unwrap();
// Append some entries
let op1 = Operation::new(OperationType::Mkdir, "dir1".to_string(), None);
let entry1 = AuditEntry::from_operation(&op1, "success", None);
log.append(&entry1).unwrap();
let op2 = Operation::new(OperationType::CreateFile, "file1".to_string(), None);
let entry2 = AuditEntry::from_operation(&op2, "success", None);
log.append(&entry2).unwrap();
// Read back
let entries = log.read_all().unwrap();
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].path, "dir1");
assert_eq!(entries[1].path, "file1");
}
#[test]
fn test_default_path_uses_xdg_state_home_when_set() {
// Snapshot env, set XDG_STATE_HOME, query, restore.
// Use a process-unique key to keep parallel tests independent.
let prev_xdg = std::env::var_os("XDG_STATE_HOME");
let prev_home = std::env::var_os("HOME");
// SAFETY: these env vars are read elsewhere in this crate only via
// AuditLog::default_path; we restore before exiting the test.
// Test runner is single-threaded for env mutations per-process; we
// accept the parallel-test caveat documented at module level.
unsafe {
std::env::set_var("XDG_STATE_HOME", "/tmp/proptest-xdg-state");
}
let path = AuditLog::default_path().unwrap();
assert_eq!(
path,
PathBuf::from("/tmp/proptest-xdg-state/valence-shell/audit.log")
);
unsafe {
match prev_xdg {
Some(v) => std::env::set_var("XDG_STATE_HOME", v),
None => std::env::remove_var("XDG_STATE_HOME"),
}
match prev_home {
Some(v) => std::env::set_var("HOME", v),
None => std::env::remove_var("HOME"),
}
}
}
#[test]
fn test_audit_log_filter_by_type() {
let temp_file = NamedTempFile::new().unwrap();
let log_path = temp_file.path().to_path_buf();
let log = AuditLog::new(log_path, None).unwrap();
let op1 = Operation::new(OperationType::Mkdir, "dir1".to_string(), None);
log.append(&AuditEntry::from_operation(&op1, "success", None))
.unwrap();
let op2 = Operation::new(OperationType::CreateFile, "file1".to_string(), None);
log.append(&AuditEntry::from_operation(&op2, "success", None))
.unwrap();
let op3 = Operation::new(OperationType::Mkdir, "dir2".to_string(), None);
log.append(&AuditEntry::from_operation(&op3, "success", None))
.unwrap();
let mkdirs = log.read_by_type("Mkdir").unwrap();
assert_eq!(mkdirs.len(), 2);
assert_eq!(mkdirs[0].path, "dir1");
assert_eq!(mkdirs[1].path, "dir2");
}
}