OXYGENHUB

Coverage / crates/spectra-core/src/daemon.rs 92.6%

163 of 176 lines run, 26 of 71 functions · run #16 on main · run missed

1
//! The daemon's state (spec §7.1): the ledger it alone writes, the
2
//! principals kept current from the bus, the authenticator, and presence
3
//! with its timers. HTTP lives elsewhere (`spectra-mcp`, `radar`); this is
4
//! what they share.
5
6
use crate::authn::{Authenticator, Caller, Refusal};
7
use crate::event::{Auth, Event, Method, NewEvent};
8
use crate::keys::KeyPair;
9
use crate::ledger::{KeyResolver, Ledger};
10
use crate::presence::Presence;
11
use crate::principals::{Principal, Principals};
12
use crate::proof::Proof;
13
use anyhow::{bail, Context, Result};
14
use serde::{Deserialize, Serialize};
15
use std::path::{Path, PathBuf};
16
use std::sync::Arc;
17
use tokio::sync::{Mutex, RwLock};
18
19
/// Kinds the owner's CLI may hand the daemon, already signed over their
20
/// payload (spec §8.5, "One writer").
21
pub const OWNER_KINDS: &[&str] = &["identity.rotated", "agent.added", "agent.disabled", "project.added"];
22
23
pub struct Daemon {
24
    pub data: PathBuf,
25
    pub ledger: Ledger,
26
    pub principals: RwLock<Principals>,
27
    pub authn: Authenticator,
28
    pub presence: Mutex<Presence>,
29
    /// Per agent: empty `wait`s in a row, and until when `wait` is refused.
30
    pub idle_waits: Mutex<std::collections::HashMap<String, (u32, u64)>>,
31
}
32
33
impl Daemon {
34
    /// Open the data directory's ledger for writing and start the timers.
3510×
    pub async fn start(data: &Path) -> Result<Arc<Daemon>> {
3610×
        let db = data.join("spectra.db");
3710×
        if !db.exists() {
380×
            bail!("no Spectra in {} (run `spectra init`)", data.display());
3910×
        }
4010×
        let instance = KeyPair::instance(data, "spectra")?;
4110×
        let ledger = Ledger::open(&db, Some(instance)).await?;
4210×
        let principals = Principals::load(&ledger).await?;
4310×
        let d = Arc::new(Daemon {
4410×
            data: data.to_path_buf(),
4510×
            ledger,
4610×
            principals: RwLock::new(principals),
4710×
            authn: Authenticator::default(),
4810×
            presence: Mutex::new(Presence::default()),
4910×
            idle_waits: Mutex::new(Default::default()),
5010×
        });
5110×
        d.clone().watch_principals();
5210×
        d.clone().tick_presence();
5310×
        Ok(d)
5410×
    }
55
56
    /// Reload who is who whenever an identity or agent event is appended.
5710×
    fn watch_principals(self: Arc<Self>) {
5810×
        let mut rx = self.ledger.subscribe();
5910×
        tokio::spawn(async move {
60
            loop {
6180×
                match rx.recv().await {
6213×
                    Ok(e)
6372×
                        if e.kind.starts_with("identity.")
6471×
                            || e.kind.starts_with("agent.") && e.kind != "agent.presence" && e.kind != "agent.status" =>
65
                    {
6613×
                        if let Ok(p) = Principals::load(&self.ledger).await {
6711×
                            *self.principals.write().await = p;
680×
                        }
69
                    }
7059×
                    Ok(_) => {}
71
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
720×
                        if let Ok(p) = Principals::load(&self.ledger).await {
730×
                            *self.principals.write().await = p;
740×
                        }
75
                    }
760×
                    Err(_) => return,
77
                }
78
            }
790×
        });
8010×
    }
81
82
    /// Record presence changes and quiet sessions every 15 s, and write a
83
    /// checkpoint when one is due by time.
8410×
    fn tick_presence(self: Arc<Self>) {
8510×
        tokio::spawn(async move {
8610×
            let mut every = tokio::time::interval(std::time::Duration::from_secs(15));
87
            loop {
8820×
                every.tick().await;
8910×
                let events = self.presence.lock().await.tick(crate::ids::now_ms());
9010×
                if !events.is_empty() {
910×
                    let _ = self.ledger.append(events).await;
9210×
                }
9310×
                let _ = self.ledger.append(vec![]).await;
94
            }
95
        });
9610×
    }
97
98
    /// Authenticate a request (spec §8.5); an agent used from the wrong Unix
99
    /// user is recorded as `guard.impersonation`, and a first connection
100
    /// that binds an agent's uid as `agent.uid_bound`.
10174×
    pub async fn authenticate(&self, proof: Option<&Proof>, method: &str, body: &[u8], peer: Option<Peer>) -> Result<Caller, Refusal> {
10274×
        let now = crate::ids::now_ms();
10374×
        let r = {
10474×
            let p = self.principals.read().await;
10574×
            self.authn.authenticate(&p, proof, method, body, now, peer.map(|x| x.uid))
106
        };
10758×
        match &r {
1081×
            Err(Refusal::WrongUid { agent, bound, from }) => {
1091×
                let e = NewEvent::system(
1101×
                    "guard.impersonation",
1111×
                    serde_json::json!({ "agent": agent, "bound_uid": bound, "from_uid": from, "from_pid": peer.map(|x| x.pid), "method": method }),
112
                )
1131×
                .subject(agent.clone());
1141×
                let _ = self.ledger.append_one(e).await;
1151×
                tracing::warn!(agent, bound, from, "a key used from the wrong Unix user");
116
            }
1171×
            Ok(Caller { principal: Principal::Agent { name, .. }, learn_uid: Some(uid), .. }) => {
1181×
                let e = NewEvent::system("agent.uid_bound", serde_json::json!({ "name": name, "uid": uid })).subject(name.clone());
1191×
                let _ = self.ledger.append_one(e).await;
120
            }
12172×
            _ => {}
122
        }
12374×
        r
12474×
    }
125
126
    /// Note a request from an agent: its session, and the event that
127
    /// starts one when this is the first in ten minutes.
12840×
    pub async fn touch(&self, who: &Principal, new_session: bool) -> Option<String> {
12940×
        let Principal::Agent { name, .. } = who else { return None };
13040×
        let (id, started) = self.presence.lock().await.request(name, crate::ids::now_ms(), new_session);
13140×
        if let Some(e) = started {
13211×
            let _ = self.ledger.append_one(e).await;
13329×
        }
13440×
        Some(id)
13540×
    }
136
137
    /// Append events the owner's CLI signed over their payload, after
138
    /// checking each as `spectra admin verify` would.
1392×
    pub async fn accept_owner_events(&self, events: Vec<WireEvent>) -> Result<Vec<u64>> {
1402×
        let mut principals = self.principals.read().await.clone();
1412×
        let projects: Vec<String> = events
1422×
            .iter()
1434×
            .filter(|e| e.kind == "project.added")
1442×
            .filter_map(|e| e.payload.get("name").and_then(|n| n.as_str()).map(String::from))
1452×
            .collect();
1462×
        let mut out = Vec::new();
1474×
        for w in events {
1484×
            let n = w.into_new_event()?;
1494×
            if n.kind == "channel.created" {
150
                // A project's channel comes with its project, unsigned, as `project add` makes it.
1511×
                let p = &n.payload;
1521×
                let ok = p.get("kind").and_then(|k| k.as_str()) == Some("project")
1531×
                    && p.get("name").and_then(|x| x.as_str()).is_some_and(|x| projects.iter().any(|q| q == x));
1541×
                if !ok || n.auth.method != Method::System {
1550×
                    bail!("a channel is only made with its project");
1561×
                }
1571×
                out.push(n);
1581×
                continue;
1593×
            }
1603×
            if !OWNER_KINDS.contains(&n.kind.as_str()) {
1610×
                bail!("{} cannot be handed to the daemon", n.kind);
1623×
            }
1633×
            if n.actor != "human" {
1640×
                bail!("only the owner hands events to the daemon");
1653×
            }
166
            // Check it as verify will, against who is who including the
167
            // batch so far.
1683×
            let probe = probe_event(&n);
1693×
            principals.check(&probe).map_err(|why| anyhow::anyhow!("refused {}: {why}", n.kind))?;
1703×
            if n.kind != "identity.rotated" {
1712×
                let key = oxy_core::hash::ObjectRef(n.auth.key.context("unsigned")?);
1722×
                if !matches!(principals.principal(&key, crate::ids::now_ms()), Ok(Principal::Owner { .. })) {
1730×
                    bail!("refused {}: not signed by the owner", n.kind);
1742×
                }
1751×
            }
1763×
            out.push(n);
177
        }
1782×
        let appended = self.ledger.append(out).await?;
1792×
        let _ = self.ledger.checkpoint().await;
180
        // Who is who has changed: know it before the next request arrives.
1812×
        *self.principals.write().await = Principals::load(&self.ledger).await?;
1824×
        Ok(appended.iter().map(|e| e.seq).collect())
1832×
    }
184
185
    /// Write a checkpoint covering everything (at shutdown).
18610×
    pub async fn shutdown(&self) {
18710×
        let _ = self.ledger.checkpoint().await;
18810×
    }
189
}
190
191
/// The Unix peer of a socket connection.
192
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
193
pub struct Peer {
194
    pub uid: u32,
195
    pub pid: Option<i32>,
196
}
197
198
/// An event as the CLI hands it to the daemon: signed already.
199
#[derive(Clone, Debug, Serialize, Deserialize)]
200
pub struct WireEvent {
201
    pub kind: String,
202
    pub actor: String,
203
    pub subject: Option<String>,
204
    pub project: Option<String>,
205
    pub payload: serde_json::Value,
206
    /// Hex of the auth key and the encoded proof; absent for a project's channel.
207
    pub key: Option<String>,
208
    pub proof: Option<String>,
209
}
210
211
impl WireEvent {
2124×
    pub fn from_new(n: &NewEvent) -> WireEvent {
2134×
        WireEvent {
2144×
            kind: n.kind.clone(),
2154×
            actor: n.actor.clone(),
2164×
            subject: n.subject.clone(),
2174×
            project: n.project.clone(),
2184×
            payload: n.payload.clone(),
2194×
            key: n.auth.key.map(hex::encode),
2204×
            proof: n.auth.proof.as_ref().map(hex::encode),
2214×
        }
2224×
    }
223
2244×
    fn into_new_event(self) -> Result<NewEvent> {
2254×
        let auth = match (&self.key, &self.proof) {
2263×
            (Some(k), Some(p)) => Auth {
2273×
                key: Some(hex::decode(k).ok().and_then(|b| b.try_into().ok()).context("a key is 32 bytes of hex")?),
2283×
                method: Method::Signature,
229
                assurance: 2,
2303×
                proof: Some(hex::decode(p).context("a proof is hex")?),
231
            },
2321×
            _ => Auth::system(),
233
        };
2344×
        let mut n = NewEvent::system(&self.kind, self.payload).by(self.actor, auth);
2354×
        n.subject = self.subject;
2364×
        n.project = self.project;
2374×
        Ok(n)
2384×
    }
239
}
240
241
/// The event `n` would be, for checking before it is appended.
2423×
fn probe_event(n: &NewEvent) -> Event {
2433×
    let now = crate::ids::now_ms();
2443×
    Event {
2453×
        seq: 0,
2463×
        id: String::new(),
2473×
        at_ms: now,
2483×
        hlc: crate::hlc::Hlc { wall_ms: now, logical: 0 },
2493×
        prev: [0; 32],
2503×
        hash: [0; 32],
2513×
        auth: n.auth.clone(),
2523×
        kind: n.kind.clone(),
2533×
        actor: n.actor.clone(),
2543×
        session: n.session.clone(),
2553×
        project: n.project.clone(),
2563×
        subject: n.subject.clone(),
2573×
        payload: Some(crate::event::canonical_json(&n.payload)),
2583×
        trace: n.trace.clone(),
2593×
    }
2603×
}