Skip to main content

spacedb_console/
access.rs

1//! Board 2 — Access & Audit. "Is anyone — or any agent — doing something they shouldn't?"
2
3use std::collections::BTreeMap;
4
5use serde::{Deserialize, Serialize};
6
7use crate::intern::Interner;
8use crate::observe::{AuditObs, CapabilityObs};
9
10/// One agent's recent footprint in the audit log.
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
12pub struct AgentActivity {
13    pub ops: usize,
14    pub denied: usize,
15}
16
17/// The security board.
18#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
19pub struct AccessOverview {
20    pub active_human: usize,
21    pub active_agent: usize,
22    pub revoked: usize,
23    pub expiring_soon: usize,
24    /// Per-agent activity from the audit log (agents only — the ones acting
25    /// autonomously and worth watching).
26    pub agent_activity: BTreeMap<String, AgentActivity>,
27    pub denied_recent: usize,
28}
29
30/// Roll up active capabilities and audit activity. A capability counts as
31/// "expiring soon" if it expires within `expiry_window` of `now`.
32pub fn rollup_access(
33    capabilities: &[CapabilityObs],
34    audit: &[AuditObs],
35    now: u64,
36    expiry_window: u64,
37) -> AccessOverview {
38    let mut active_human = 0;
39    let mut active_agent = 0;
40    let mut revoked = 0;
41    let mut expiring_soon = 0;
42
43    for c in capabilities {
44        if c.revoked {
45            revoked += 1;
46            continue;
47        }
48        if c.is_agent() {
49            active_agent += 1;
50        } else {
51            active_human += 1;
52        }
53        if c.expires_within(now, expiry_window) {
54            expiring_soon += 1;
55        }
56    }
57
58    // Actors repeat thousands of times over a dozen names: intern each name to
59    // an index once (a hash of the bytes), tally on the index, and build the
60    // ordered map at the end from the names themselves. The per-entry ordered
61    // search and name copy are gone; the map is the same map.
62    let mut actors: Interner<AgentActivity> = Interner::new();
63    let mut denied_recent = 0;
64    for entry in audit {
65        if !entry.allowed {
66            denied_recent += 1;
67        }
68        if entry.is_agent() {
69            let a = actors.slot(&entry.actor);
70            a.ops += 1;
71            if !entry.allowed {
72                a.denied += 1;
73            }
74        }
75    }
76
77    AccessOverview {
78        active_human,
79        active_agent,
80        revoked,
81        expiring_soon,
82        agent_activity: actors.into_map(),
83        denied_recent,
84    }
85}