oxios-kernel 0.2.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
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
//! RBAC types and manager — role-based access control with HitL approvals.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

use crate::types::AgentId;

// ─── RBAC Types ───────────────────────────────────────────────────────────────

/// Roles for role-based access control (3-tier model).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Role {
    /// Basic user — can use agents, limited permissions.
    User,
    /// Superuser — can manage programs, skills, workspaces.
    Superuser,
    /// Admin — full system access, can modify RBAC.
    Admin,
}

impl Role {
    /// Returns the default policy for this role.
    pub fn default_policy(&self) -> RbacPolicy {
        match self {
            Role::Admin => RbacPolicy {
                role: Role::Admin,
                allowed_actions: vec![
                    Action::UseTool("*".into()),
                    Action::AccessPath("*".into()),
                    Action::ManageAgents,
                    Action::ManagePrograms,
                    Action::ManageWorkspaces,
                    Action::ManageRBAC,
                    Action::ViewAuditLog,
                    Action::SystemConfig,
                ]
                .into_iter()
                .collect(),
                resource_patterns: vec!["*".into()],
                max_concurrent_agents: usize::MAX,
            },
            Role::Superuser => RbacPolicy {
                role: Role::Superuser,
                allowed_actions: vec![
                    Action::UseTool("*".into()),
                    Action::AccessPath("/workspace/**".into()),
                    Action::ManageAgents,
                    Action::ManagePrograms,
                    Action::ManageWorkspaces,
                    Action::ViewAuditLog,
                ]
                .into_iter()
                .collect(),
                resource_patterns: vec!["/workspace/**".into(), "/tmp/**".into()],
                max_concurrent_agents: 10,
            },
            Role::User => RbacPolicy {
                role: Role::User,
                allowed_actions: vec![
                    Action::UseTool("read".into()),
                    Action::UseTool("write".into()),
                    Action::UseTool("edit".into()),
                    Action::UseTool("bash".into()),
                    Action::UseTool("grep".into()),
                    Action::UseTool("find".into()),
                    Action::AccessPath("/workspace/**".into()),
                    Action::ManageAgents,
                ]
                .into_iter()
                .collect(),
                resource_patterns: vec!["/workspace/**".into()],
                max_concurrent_agents: 2,
            },
        }
    }
}

/// Subject — who is accessing the system.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Subject {
    /// A named user.
    User(String),
    /// An agent acting on behalf of a user.
    Agent(AgentId),
    /// System-level operations (bypass RBAC).
    System,
}

impl std::fmt::Display for Subject {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Subject::User(name) => write!(f, "user:{}", name),
            Subject::Agent(id) => write!(f, "agent:{}", id),
            Subject::System => write!(f, "system"),
        }
    }
}

/// Actions that can be authorized by RBAC.
#[derive(Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub enum Action {
    /// Use a specific tool (name or * for all).
    UseTool(String),
    /// Access a specific path pattern (glob).
    AccessPath(String),
    /// Manage agents (fork/exec/kill).
    ManageAgents,
    /// Manage programs (install/uninstall).
    ManagePrograms,
    /// Manage workspaces (create/start/stop/remove).
    ManageWorkspaces,
    /// Modify RBAC policies and role assignments.
    ManageRBAC,
    /// View the audit log.
    ViewAuditLog,
    /// Modify system-level configuration.
    SystemConfig,
}

impl Action {
    /// Returns true if this action is considered high-risk and needs HitL approval.
    pub fn requires_approval(&self) -> bool {
        match self {
            Action::ManageRBAC | Action::SystemConfig => true,
            Action::UseTool(t) => t == "*" || t == "osascript" || t == "rm",
            _ => false,
        }
    }
}

/// RBAC policy defining what a role can do.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RbacPolicy {
    /// The role this policy applies to.
    pub role: Role,
    /// Set of actions this role is allowed to perform.
    pub allowed_actions: HashSet<Action>,
    /// Glob patterns for accessible resources.
    pub resource_patterns: Vec<String>,
    /// Maximum number of concurrent agents for this role.
    pub max_concurrent_agents: usize,
}

impl RbacPolicy {
    /// Checks whether this policy allows the given action.
    ///
    /// Supports wildcard matching for `UseTool("*")` (matches any tool name)
    /// and `AccessPath("*")` (matches any path).
    pub fn allows(&self, action: &Action) -> bool {
        // First, try exact match.
        if self.allowed_actions.contains(action) {
            return true;
        }

        // Then, check wildcard patterns.
        match action {
            Action::UseTool(tool_name) => {
                // Check if policy has UseTool("*") wildcard.
                self.allowed_actions
                    .iter()
                    .any(|a| matches!(a, Action::UseTool(w) if w == "*"))
                    // Also check if the specific tool name is listed.
                    || self.allowed_actions.contains(&Action::UseTool(tool_name.clone()))
            }
            Action::AccessPath(path) => {
                // Check if policy has AccessPath("*") wildcard.
                self.allowed_actions
                    .iter()
                    .any(|a| matches!(a, Action::AccessPath(p) if p == "*"))
                    || self
                        .allowed_actions
                        .contains(&Action::AccessPath(path.clone()))
            }
            // Non-parameterized actions: exact match only (already checked above).
            _ => false,
        }
    }
}

/// RBAC audit entry — records authorization decisions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RbacAuditEntry {
    /// When the authorization decision was made.
    pub timestamp: DateTime<Utc>,
    /// Who performed the action.
    pub subject: Subject,
    /// What action was attempted.
    pub action: Action,
    /// Which resource was involved.
    pub resource: String,
    /// Whether the action was allowed.
    pub allowed: bool,
    /// Optional reason for the decision.
    pub reason: Option<String>,
}

impl RbacAuditEntry {
    /// Creates a new RBAC audit entry.
    pub(crate) fn new(
        subject: Subject,
        action: Action,
        resource: String,
        allowed: bool,
        reason: Option<String>,
    ) -> Self {
        Self {
            timestamp: Utc::now(),
            subject,
            action,
            resource,
            allowed,
            reason,
        }
    }
}

/// Human-in-the-loop approval request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingApproval {
    /// Unique identifier for this approval request.
    pub id: uuid::Uuid,
    /// Who is requesting the action.
    pub subject: Subject,
    /// What action is being requested.
    pub action: Action,
    /// Which resource is involved.
    pub resource: String,
    /// Why the action needs approval.
    pub reason: String,
    /// When the request was created.
    pub created_at: DateTime<Utc>,
}

/// Status of a HitL approval request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ApprovalStatus {
    /// Awaiting user decision.
    Pending,
    /// User approved the request.
    Approved,
    /// User rejected the request.
    Rejected,
    /// Request timed out.
    Expired,
}

/// RBAC Manager — manages roles, permissions, and HitL approvals.
#[derive(Debug, Clone)]
pub struct RbacManager {
    policies: HashMap<Role, RbacPolicy>,
    subject_roles: HashMap<Subject, Role>,
    audit_log: Vec<RbacAuditEntry>,
    pending_approvals: Vec<(PendingApproval, ApprovalStatus)>,
    max_audit_entries: usize,
}

impl RbacManager {
    /// Creates a new RBAC manager with default policies for all roles.
    pub fn new() -> Self {
        let mut this = Self {
            policies: HashMap::new(),
            subject_roles: HashMap::new(),
            audit_log: Vec::new(),
            pending_approvals: Vec::new(),
            max_audit_entries: 10_000,
        };
        for role in [Role::User, Role::Superuser, Role::Admin] {
            this.policies.insert(role, role.default_policy());
        }
        this
    }

    /// Assigns a role to a subject.
    pub fn assign_role(&mut self, subject: Subject, role: Role) {
        self.subject_roles.insert(subject.clone(), role);
    }

    /// Revokes the role from a subject.
    pub fn revoke_role(&mut self, subject: &Subject) {
        self.subject_roles.remove(subject);
    }

    /// Returns the role assigned to a subject, if any.
    pub fn get_role(&self, subject: &Subject) -> Option<Role> {
        self.subject_roles.get(subject).copied()
    }

    /// Checks whether a subject has permission for the given action on a resource.
    pub fn check_permission(&mut self, subject: &Subject, action: &Action, resource: &str) -> bool {
        if matches!(subject, Subject::System) {
            return true;
        }
        let role = match self.subject_roles.get(subject) {
            Some(r) => *r,
            None => return false,
        };
        let policy = match self.policies.get(&role) {
            Some(p) => p,
            None => return false,
        };
        let allowed = policy.allows(action);
        self.audit_log.push(RbacAuditEntry::new(
            subject.clone(),
            action.clone(),
            resource.to_string(),
            allowed,
            if allowed {
                None
            } else {
                Some(format!("role {:?} does not allow {:?}", role, action))
            },
        ));
        if self.audit_log.len() > self.max_audit_entries {
            self.audit_log
                .drain(0..self.audit_log.len() - self.max_audit_entries);
        }
        allowed
    }

    /// Creates a new approval request for a high-risk action.
    pub fn request_approval(
        &mut self,
        subject: Subject,
        action: Action,
        resource: String,
        reason: String,
    ) -> uuid::Uuid {
        let id = uuid::Uuid::new_v4();
        self.pending_approvals.push((
            PendingApproval {
                id,
                subject,
                action,
                resource,
                reason,
                created_at: Utc::now(),
            },
            ApprovalStatus::Pending,
        ));
        id
    }

    /// Approves a pending approval request.
    pub fn approve(&mut self, id: uuid::Uuid) -> bool {
        if let Some((_, s)) = self
            .pending_approvals
            .iter_mut()
            .find(|(p, s)| p.id == id && *s == ApprovalStatus::Pending)
        {
            *s = ApprovalStatus::Approved;
            return true;
        }
        false
    }

    /// Rejects a pending approval request.
    pub fn reject(&mut self, id: uuid::Uuid) -> bool {
        if let Some((_, s)) = self
            .pending_approvals
            .iter_mut()
            .find(|(p, s)| p.id == id && *s == ApprovalStatus::Pending)
        {
            *s = ApprovalStatus::Rejected;
            return true;
        }
        false
    }

    /// Returns all currently pending approval requests.
    pub fn pending_approvals(&self) -> Vec<&PendingApproval> {
        self.pending_approvals
            .iter()
            .filter(|(_, s)| matches!(s, ApprovalStatus::Pending))
            .map(|(p, _)| p)
            .collect()
    }

    /// Returns all approval requests (pending + history) with their status.
    pub fn all_approvals(&self) -> &[(PendingApproval, ApprovalStatus)] {
        &self.pending_approvals
    }

    /// Returns the RBAC audit log.
    pub fn audit_log(&self) -> &[RbacAuditEntry] {
        &self.audit_log
    }
}

impl Default for RbacManager {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_default_policies_exist() {
        let mgr = RbacManager::new();
        assert!(mgr.policies.contains_key(&Role::User));
        assert!(mgr.policies.contains_key(&Role::Superuser));
        assert!(mgr.policies.contains_key(&Role::Admin));
    }

    #[test]
    fn test_role_assignment() {
        let mut mgr = RbacManager::new();
        let subject = Subject::User("alice".into());
        mgr.assign_role(subject.clone(), Role::Admin);
        assert_eq!(mgr.get_role(&subject), Some(Role::Admin));

        mgr.revoke_role(&subject);
        assert_eq!(mgr.get_role(&subject), None);
    }

    #[test]
    fn test_system_bypasses_rbac() {
        let mut mgr = RbacManager::new();
        let subject = Subject::System;
        assert!(mgr.check_permission(&subject, &Action::ManageRBAC, "test"));
    }

    #[test]
    fn test_unknown_subject_denied() {
        let mut mgr = RbacManager::new();
        let subject = Subject::User("nobody".into());
        assert!(!mgr.check_permission(&subject, &Action::UseTool("read".into()), "test"));
    }

    #[test]
    fn test_user_allowed_specific_tools() {
        let mut mgr = RbacManager::new();
        let subject = Subject::User("bob".into());
        mgr.assign_role(subject.clone(), Role::User);

        assert!(mgr.check_permission(&subject, &Action::UseTool("read".into()), "test"));
        assert!(mgr.check_permission(&subject, &Action::UseTool("write".into()), "test"));
        assert!(mgr.check_permission(&subject, &Action::UseTool("bash".into()), "test"));
    }

    #[test]
    fn test_user_denied_admin_tools() {
        let mut mgr = RbacManager::new();
        let subject = Subject::User("bob".into());
        mgr.assign_role(subject.clone(), Role::User);

        assert!(!mgr.check_permission(&subject, &Action::ManageRBAC, "test"));
        assert!(!mgr.check_permission(&subject, &Action::SystemConfig, "test"));
    }

    #[test]
    fn test_admin_wildcard_allows_all_tools() {
        let mut mgr = RbacManager::new();
        let subject = Subject::User("admin".into());
        mgr.assign_role(subject.clone(), Role::Admin);

        // Admin should be able to use ANY tool via wildcard.
        assert!(mgr.check_permission(&subject, &Action::UseTool("any_tool".into()), "test"));
        assert!(mgr.check_permission(&subject, &Action::UseTool("custom_thing".into()), "test"));
        assert!(mgr.check_permission(&subject, &Action::UseTool("dangerous".into()), "test"));
    }

    #[test]
    fn test_superuser_wildcard_allows_all_tools() {
        let mut mgr = RbacManager::new();
        let subject = Subject::User("super".into());
        mgr.assign_role(subject.clone(), Role::Superuser);

        assert!(mgr.check_permission(&subject, &Action::UseTool("custom".into()), "test"));
        assert!(mgr.check_permission(&subject, &Action::UseTool("anything".into()), "test"));
    }

    #[test]
    fn test_admin_all_paths_wildcard() {
        let mut mgr = RbacManager::new();
        let subject = Subject::User("admin".into());
        mgr.assign_role(subject.clone(), Role::Admin);

        assert!(mgr.check_permission(&subject, &Action::AccessPath("/any/path".into()), "test"));
        assert!(mgr.check_permission(&subject, &Action::AccessPath("/secret/data".into()), "test"));
    }

    #[test]
    fn test_policy_allows_exact_match() {
        let policy = Role::User.default_policy();
        assert!(policy.allows(&Action::UseTool("read".into())));
        assert!(policy.allows(&Action::UseTool("bash".into())));
        assert!(!policy.allows(&Action::UseTool("unknown_tool".into())));
    }

    #[test]
    fn test_policy_allows_wildcard() {
        let policy = Role::Admin.default_policy();
        assert!(policy.allows(&Action::UseTool("literally_anything".into())));
        assert!(policy.allows(&Action::AccessPath("/some/random/path".into())));
    }

    #[test]
    fn test_approval_request_lifecycle() {
        let mut mgr = RbacManager::new();
        let id = mgr.request_approval(
            Subject::User("alice".into()),
            Action::ManageRBAC,
            "rbac".into(),
            "need admin".into(),
        );

        let pending = mgr.pending_approvals();
        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].id, id);

        assert!(mgr.approve(id));
        assert!(mgr.pending_approvals().is_empty());

        // Already approved
        assert!(!mgr.approve(id));
    }

    #[test]
    fn test_approval_rejection() {
        let mut mgr = RbacManager::new();
        let id = mgr.request_approval(
            Subject::User("alice".into()),
            Action::SystemConfig,
            "config".into(),
            "need config".into(),
        );

        assert!(mgr.reject(id));
        assert!(mgr.pending_approvals().is_empty());
    }

    #[test]
    fn test_approval_nonexistent() {
        let mut mgr = RbacManager::new();
        assert!(!mgr.approve(uuid::Uuid::new_v4()));
        assert!(!mgr.reject(uuid::Uuid::new_v4()));
    }

    #[test]
    fn test_audit_log_recorded() {
        let mut mgr = RbacManager::new();
        let subject = Subject::User("alice".into());
        mgr.assign_role(subject.clone(), Role::User);

        mgr.check_permission(&subject, &Action::UseTool("read".into()), "test");
        assert!(!mgr.audit_log().is_empty());

        let entry = &mgr.audit_log()[0];
        assert!(entry.allowed);
    }

    #[test]
    fn test_audit_log_denied_recorded() {
        let mut mgr = RbacManager::new();
        let subject = Subject::User("alice".into());
        mgr.assign_role(subject.clone(), Role::User);

        mgr.check_permission(&subject, &Action::ManageRBAC, "test");
        let denied_entries: Vec<_> = mgr.audit_log().iter().filter(|e| !e.allowed).collect();
        assert_eq!(denied_entries.len(), 1);
    }
}