oxios-kernel 1.7.0

Oxios kernel: supervisor, event bus, state store
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
//! Unified audit sink — single destination for all security events.
//!
//! Eliminates the three-way split between `AccessManager.audit_log`,
//! `RbacManager.audit_log`, and `AuditTrail`. All security events
//! flow through `AuditSink` into the Merkle chain and JSONL file.

use std::path::PathBuf;
use std::sync::Arc;

use chrono::{DateTime, Utc};
use oxi_sdk::observability::{AuditAction, AuditTrail};
use serde::{Deserialize, Serialize};

// ─── Audit Event ────────────────────────────────────────────────────────────

/// Unified security audit event.
///
/// Every security-relevant decision produces one of these variants.
/// Serialized as JSONL for file persistence and ingested into the
/// Merkle-chain `AuditTrail` for tamper-evidence.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind")]
#[allow(missing_docs)]
pub enum AuditEvent {
    /// Tool access decision.
    ToolAccess {
        #[serde(with = "chrono::serde::ts_milliseconds")]
        timestamp: DateTime<Utc>,
        agent: String,
        tool: String,
        allowed: bool,
        layer: Option<String>,
        reason: Option<String>,
    },
    /// Path access decision.
    PathAccess {
        #[serde(with = "chrono::serde::ts_milliseconds")]
        timestamp: DateTime<Utc>,
        agent: String,
        path: String,
        mode: String,
        allowed: bool,
        layer: Option<String>,
        reason: Option<String>,
    },
    /// Command execution decision.
    ExecAccess {
        #[serde(with = "chrono::serde::ts_milliseconds")]
        timestamp: DateTime<Utc>,
        agent: String,
        binary: String,
        allowed: bool,
        layer: Option<String>,
        reason: Option<String>,
    },
    /// RBAC authorization decision.
    RbacDecision {
        #[serde(with = "chrono::serde::ts_milliseconds")]
        timestamp: DateTime<Utc>,
        subject: String,
        action: String,
        resource: String,
        allowed: bool,
        reason: Option<String>,
    },
    /// Workspace sandbox violation.
    SandboxViolation {
        #[serde(with = "chrono::serde::ts_milliseconds")]
        timestamp: DateTime<Utc>,
        agent: String,
        path: String,
        workspace: String,
    },
    /// Human-in-the-loop approval event.
    Approval {
        #[serde(with = "chrono::serde::ts_milliseconds")]
        timestamp: DateTime<Utc>,
        approval_id: String,
        subject: String,
        action: String,
        status: String,
    },
}

impl AuditEvent {
    /// Returns the agent/subject responsible for this event.
    pub fn actor(&self) -> &str {
        match self {
            AuditEvent::ToolAccess { agent, .. } => agent,
            AuditEvent::PathAccess { agent, .. } => agent,
            AuditEvent::ExecAccess { agent, .. } => agent,
            AuditEvent::RbacDecision { subject, .. } => subject,
            AuditEvent::SandboxViolation { agent, .. } => agent,
            AuditEvent::Approval { subject, .. } => subject,
        }
    }

    /// Convert to an AuditAction for the Merkle-chain AuditTrail.
    pub fn to_audit_action(&self) -> AuditAction {
        match self {
            AuditEvent::ToolAccess { tool, allowed, .. } => AuditAction::Other {
                detail: format!("tool_access:{tool}:allowed={allowed}"),
            },
            AuditEvent::PathAccess {
                path,
                mode,
                allowed,
                ..
            } => AuditAction::Other {
                detail: format!("path_access:{path}:{mode}:allowed={allowed}"),
            },
            AuditEvent::ExecAccess {
                binary, allowed, ..
            } => AuditAction::Other {
                detail: format!("exec_access:{binary}:allowed={allowed}"),
            },
            AuditEvent::RbacDecision {
                subject,
                action,
                allowed,
                ..
            } => AuditAction::Other {
                detail: format!("rbac:{subject}:{action}:allowed={allowed}"),
            },
            AuditEvent::SandboxViolation {
                agent,
                path,
                workspace,
                ..
            } => AuditAction::Other {
                detail: format!("sandbox_violation:{agent}:{path}:ws={workspace}"),
            },
            AuditEvent::Approval {
                approval_id,
                status,
                ..
            } => AuditAction::Other {
                detail: format!("approval:{approval_id}:{status}"),
            },
        }
    }

    #[cfg(test)]
    fn now() -> DateTime<Utc> {
        Utc::now()
    }
}

// ─── Audit Sink Trait ───────────────────────────────────────────────────────

/// Destination for all security audit events.
///
/// Implementations persist events to Merkle chain + file, or are no-ops for tests.
pub trait AuditSink: Send + Sync {
    /// Record a security audit event.
    fn record(&self, event: AuditEvent);
}

// ─── Trail Audit Sink ───────────────────────────────────────────────────────

/// Production audit sink: Merkle chain + async JSONL file writer.
///
/// Events are:
/// 1. Appended to the `AuditTrail` (Merkle chain, tamper-evident)
/// 2. Sent to a background file writer via bounded channel (JSONL)
///
/// If the channel is full, a warning is logged and the event is still
/// recorded in the Merkle chain (just not persisted to file immediately).
pub struct TrailAuditSink {
    /// Merkle-chain audit trail — always succeeds (in-memory).
    trail: Arc<AuditTrail>,
    /// Bounded channel to background file writer.
    file_tx: tokio::sync::mpsc::Sender<String>,
}

impl TrailAuditSink {
    /// Create a new `TrailAuditSink`.
    ///
    /// Spawns a background tokio task that reads from the bounded channel
    /// and appends JSONL entries to `audit_path`.
    pub fn new(trail: Arc<AuditTrail>, audit_path: PathBuf) -> Self {
        let (tx, mut rx) = tokio::sync::mpsc::channel::<String>(1000);

        let path = audit_path.clone();
        tokio::spawn(async move {
            if let Ok(mut file) = tokio::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(&path)
                .await
            {
                use tokio::io::AsyncWriteExt;
                while let Some(line) = rx.recv().await {
                    let _ = file.write_all(line.as_bytes()).await;
                    let _ = file.write_all(b"\n").await;
                }
            }
        });

        Self { trail, file_tx: tx }
    }
}

impl AuditSink for TrailAuditSink {
    fn record(&self, event: AuditEvent) {
        // 1. Merkle chain (always succeeds)
        let actor = event.actor().to_string();
        let action = event.to_audit_action();
        self.trail.append(actor, action, "access_gate".into());

        // 2. JSONL file (fire-and-forget, may drop if channel full)
        if let Ok(line) = serde_json::to_string(&event) {
            match self.file_tx.try_send(line) {
                Ok(()) => {}
                Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
                    tracing::warn!("Audit sink channel full — event still in Merkle chain");
                }
                Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
                    tracing::warn!("Audit sink channel closed");
                }
            }
        }
    }
}

// ─── No-op Sink (tests) ────────────────────────────────────────────────────

/// No-op audit sink for tests — discards all events.
#[cfg(test)]
pub struct NoOpAuditSink;

#[cfg(test)]
impl AuditSink for NoOpAuditSink {
    fn record(&self, _event: AuditEvent) {}
}

/// Minimal audit sink that logs to tracing — used as default when no file sink is configured.
pub struct TracingAuditSink;

impl AuditSink for TracingAuditSink {
    fn record(&self, event: AuditEvent) {
        // With no persistent sink configured we still surface every decision
        // via tracing so allowed/denied activity is observable post-incident.
        match &event {
            AuditEvent::ToolAccess {
                agent,
                tool,
                allowed,
                layer,
                ..
            } => {
                if *allowed {
                    tracing::debug!(
                        agent = %agent, tool = %tool, layer = ?layer,
                        "Tool access allowed (no persistent audit sink configured)"
                    );
                } else {
                    tracing::warn!(
                        agent = %agent, tool = %tool, layer = ?layer,
                        "Access denied (no persistent audit sink configured)"
                    );
                }
            }
            AuditEvent::PathAccess {
                agent,
                path,
                allowed,
                ..
            } => {
                tracing::debug!(
                    agent = %agent, path = %path, allowed = allowed,
                    "Path access decision"
                );
            }
            AuditEvent::ExecAccess {
                agent,
                binary,
                allowed,
                ..
            } => {
                if *allowed {
                    tracing::info!(
                        agent = %agent, binary = %binary,
                        "Exec access allowed"
                    );
                } else {
                    tracing::warn!(
                        agent = %agent, binary = %binary,
                        "Exec access denied"
                    );
                }
            }
            AuditEvent::RbacDecision {
                subject,
                action,
                allowed,
                ..
            } => {
                tracing::debug!(
                    subject = %subject, action = %action, allowed = allowed,
                    "RBAC decision"
                );
            }
            AuditEvent::SandboxViolation {
                agent,
                path,
                workspace,
                ..
            } => {
                tracing::warn!(
                    agent = %agent, path = %path, workspace = %workspace,
                    "Sandbox boundary violation"
                );
            }
            AuditEvent::Approval {
                subject,
                approval_id,
                status,
                ..
            } => {
                tracing::info!(
                    subject = %subject,
                    approval_id = %approval_id,
                    status = ?status,
                    "Approval decision"
                );
            }
        }
    }
}

// ─── Tests ──────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_tool_access_event() {
        let event = AuditEvent::ToolAccess {
            timestamp: AuditEvent::now(),
            agent: "test-agent".into(),
            tool: "exec".into(),
            allowed: true,
            layer: None,
            reason: None,
        };
        assert_eq!(event.actor(), "test-agent");
        let action = event.to_audit_action();
        assert!(matches!(action, AuditAction::Other { .. }));
    }

    #[test]
    fn test_rbac_decision_event() {
        let event = AuditEvent::RbacDecision {
            timestamp: AuditEvent::now(),
            subject: "user:alice".into(),
            action: "UseTool(exec)".into(),
            resource: "exec".into(),
            allowed: false,
            reason: Some("role User does not allow".into()),
        };
        assert_eq!(event.actor(), "user:alice");
    }

    #[test]
    fn test_sandbox_violation_event() {
        let event = AuditEvent::SandboxViolation {
            timestamp: AuditEvent::now(),
            agent: "rogue-agent".into(),
            path: "/etc/passwd".into(),
            workspace: "project-alpha".into(),
        };
        assert_eq!(event.actor(), "rogue-agent");
    }

    #[test]
    fn test_event_serialization_roundtrip() {
        let event = AuditEvent::ExecAccess {
            timestamp: AuditEvent::now(),
            agent: "test".into(),
            binary: "git".into(),
            allowed: true,
            layer: None,
            reason: None,
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains("ExecAccess"));
        let deserialized: AuditEvent = serde_json::from_str(&json).unwrap();
        assert!(matches!(deserialized, AuditEvent::ExecAccess { .. }));
    }

    #[test]
    fn test_noop_sink() {
        let sink = NoOpAuditSink;
        sink.record(AuditEvent::ToolAccess {
            timestamp: AuditEvent::now(),
            agent: "test".into(),
            tool: "exec".into(),
            allowed: true,
            layer: None,
            reason: None,
        });
        // No panic = success
    }
}