OXYGENHUB

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

209 of 225 lines run, 32 of 89 functions · run #23 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.
3519×
    pub async fn start(data: &Path) -> Result<Arc<Daemon>> {
3619×
        let db = data.join("spectra.db");
3719×
        if !db.exists() {
380×
            bail!("no Spectra in {} (run `spectra init`)", data.display());
3919×
        }
4019×
        let instance = KeyPair::instance(data, "spectra")?;
4119×
        let ledger = Ledger::open(&db, Some(instance)).await?;
4219×
        let principals = Principals::load(&ledger).await?;
4319×
        let d = Arc::new(Daemon {
4419×
            data: data.to_path_buf(),
4519×
            ledger,
4619×
            principals: RwLock::new(principals),
4719×
            authn: Authenticator::default(),
4819×
            presence: Mutex::new(Presence::default()),
4919×
            idle_waits: Mutex::new(Default::default()),
5019×
        });
5119×
        d.clone().watch_principals();
5219×
        d.clone().tick_presence();
5319×
        Ok(d)
5419×
    }
55
56
    /// Reload who is who whenever an identity or agent event is appended.
5719×
    fn watch_principals(self: Arc<Self>) {
5819×
        let mut rx = self.ledger.subscribe();
5919×
        tokio::spawn(async move {
60
            loop {
61128×
                match rx.recv().await {
6229×
                    Ok(e)
63112×
                        if e.kind.starts_with("identity.")
64102×
                            || e.kind.starts_with("agent.") && e.kind != "agent.presence" && e.kind != "agent.status" =>
65
                    {
6629×
                        if let Ok(p) = Principals::load(&self.ledger).await {
6726×
                            *self.principals.write().await = p;
680×
                        }
69
                    }
7083×
                    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×
        });
8019×
    }
81
82
    /// Record presence changes and quiet sessions every 15 s, and write a
83
    /// checkpoint when one is due by time.
8419×
    fn tick_presence(self: Arc<Self>) {
8519×
        tokio::spawn(async move {
8619×
            let mut every = tokio::time::interval(std::time::Duration::from_secs(15));
87
            loop {
8838×
                every.tick().await;
8919×
                let events = self.presence.lock().await.tick(crate::ids::now_ms());
9019×
                if !events.is_empty() {
910×
                    let _ = self.ledger.append(events).await;
9219×
                }
9319×
                let _ = self.ledger.append(vec![]).await;
94
            }
95
        });
9619×
    }
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`.
101108×
    pub async fn authenticate(&self, proof: Option<&Proof>, method: &str, body: &[u8], peer: Option<Peer>) -> Result<Caller, Refusal> {
102108×
        let now = crate::ids::now_ms();
103107×
        let r = {
104108×
            let p = self.principals.read().await;
105108×
            if p.owner().is_none() {
1061×
                return Err(Refusal::NotAPrincipal("this Spectra has no owner yet: its owner claims it with `spectra connect`".into()));
107107×
            }
108107×
            self.authn.authenticate(&p, proof, method, body, now, peer.map(|x| x.uid))
109
        };
11062×
        match &r {
1111×
            Err(Refusal::WrongUid { agent, bound, from }) => {
1121×
                let e = NewEvent::system(
1131×
                    "guard.impersonation",
1141×
                    serde_json::json!({ "agent": agent, "bound_uid": bound, "from_uid": from, "from_pid": peer.map(|x| x.pid), "method": method }),
115
                )
1161×
                .subject(agent.clone());
1171×
                let _ = self.ledger.append_one(e).await;
1181×
                tracing::warn!(agent, bound, from, "a key used from the wrong Unix user");
119
            }
1201×
            Err(Refusal::BoundOverNetwork { agent, bound }) => {
1211×
                let e = NewEvent::system(
1221×
                    "guard.impersonation",
1231×
                    serde_json::json!({ "agent": agent, "bound_uid": bound, "from_uid": null, "over": "tcp", "method": method }),
124
                )
1251×
                .subject(agent.clone());
1261×
                let _ = self.ledger.append_one(e).await;
1271×
                tracing::warn!(agent, bound, "a uid-bound key used over the network");
128
            }
1291×
            Ok(Caller { principal: Principal::Agent { name, .. }, learn_uid: Some(uid), .. }) => {
1301×
                let e = NewEvent::system("agent.uid_bound", serde_json::json!({ "name": name, "uid": uid })).subject(name.clone());
1311×
                let _ = self.ledger.append_one(e).await;
132
            }
133104×
            _ => {}
134
        }
135107×
        r
136108×
    }
137
138
    /// Note a request from an agent: its session, and the event that
139
    /// starts one when this is the first in ten minutes.
14044×
    pub async fn touch(&self, who: &Principal, new_session: bool) -> Option<String> {
14144×
        let Principal::Agent { name, .. } = who else { return None };
14244×
        let (id, started) = self.presence.lock().await.request(name, crate::ids::now_ms(), new_session);
14344×
        if let Some(e) = started {
14414×
            let _ = self.ledger.append_one(e).await;
14530×
        }
14644×
        Some(id)
14744×
    }
148
149
    /// Append events the owner's CLI signed over their payload, after
150
    /// checking each as `spectra admin verify` would.
1516×
    pub async fn accept_owner_events(&self, events: Vec<WireEvent>) -> Result<Vec<u64>> {
1526×
        let mut principals = self.principals.read().await.clone();
1536×
        let projects: Vec<String> = events
1546×
            .iter()
15511×
            .filter(|e| e.kind == "project.added")
1566×
            .filter_map(|e| e.payload.get("name").and_then(|n| n.as_str()).map(String::from))
1576×
            .collect();
1586×
        let mut out = Vec::new();
15911×
        for w in events {
16011×
            let n = w.into_new_event()?;
16111×
            if n.kind == "channel.created" {
162
                // A project's channel comes with its project, unsigned, as `project add` makes it.
1632×
                let p = &n.payload;
1642×
                let ok = p.get("kind").and_then(|k| k.as_str()) == Some("project")
1652×
                    && p.get("name").and_then(|x| x.as_str()).is_some_and(|x| projects.iter().any(|q| q == x));
1662×
                if !ok || n.auth.method != Method::System {
1670×
                    bail!("a channel is only made with its project");
1682×
                }
1692×
                out.push(n);
1702×
                continue;
1719×
            }
1729×
            if !OWNER_KINDS.contains(&n.kind.as_str()) {
1730×
                bail!("{} cannot be handed to the daemon", n.kind);
1749×
            }
1759×
            if n.actor != "human" {
1760×
                bail!("only the owner hands events to the daemon");
1779×
            }
178
            // Check it as verify will, against who is who including the
179
            // batch so far.
1809×
            let probe = probe_event(&n);
1819×
            principals.check(&probe).map_err(|why| anyhow::anyhow!("refused {}: {why}", n.kind))?;
1829×
            if n.kind != "identity.rotated" {
1836×
                let key = oxy_core::hash::ObjectRef(n.auth.key.context("unsigned")?);
1846×
                if !matches!(principals.principal(&key, crate::ids::now_ms()), Ok(Principal::Owner { .. })) {
1850×
                    bail!("refused {}: not signed by the owner", n.kind);
1866×
                }
1873×
            }
1889×
            out.push(n);
189
        }
1906×
        let appended = self.ledger.append(out).await?;
1916×
        let _ = self.ledger.checkpoint().await;
192
        // Who is who has changed: know it before the next request arrives.
1936×
        *self.principals.write().await = Principals::load(&self.ledger).await?;
19411×
        Ok(appended.iter().map(|e| e.seq).collect())
1956×
    }
196
197
    /// The owner `spectra init --owner` named, while none is recorded.
19814×
    pub fn named_owner(&self) -> Option<String> {
19914×
        let text = std::fs::read_to_string(self.data.join("spectra.toml")).ok()?;
20014×
        let t: toml::Table = text.parse().ok()?;
20114×
        t.get("owner")?.get("key")?.as_str().map(|k| k.to_ascii_lowercase())
20214×
    }
203
204
    /// The owner claims a Spectra set up with `spectra init --owner`
205
    /// (spec §8.6): the named identity, signed by itself over its payload,
206
    /// then any successors up to the owner's current identity, each a
207
    /// rotation as `identity refresh` makes. Accepted only while no owner
208
    /// is recorded, and only from the key init named.
2097×
    pub async fn claim(&self, events: Vec<WireEvent>) -> Result<Vec<u64>> {
2107×
        let mut principals = self.principals.read().await.clone();
2117×
        if principals.owner().is_some() {
2121×
            bail!("this Spectra already has an owner");
2136×
        }
2146×
        let named = self.named_owner().context("this Spectra names no owner (spectra init --owner)")?;
2156×
        let mut out = Vec::new();
2169×
        for (i, w) in events.into_iter().enumerate() {
2179×
            let n = w.into_new_event()?;
2189×
            let want = if i == 0 { "identity.owner" } else { "identity.rotated" };
2199×
            if n.kind != want || n.actor != "human" {
2200×
                bail!("a claim is the owner's identity.owner, then their rotations");
2219×
            }
2229×
            if i == 0 {
2236×
                let key = n.payload.get("key").and_then(|k| k.as_str()).unwrap_or("").to_ascii_lowercase();
2246×
                if key != named || n.auth.key.map(hex::encode) != Some(named.clone()) {
2252×
                    bail!("this Spectra was set up for another owner");
2264×
                }
2273×
            }
2287×
            principals.check(&probe_event(&n)).map_err(|why| anyhow::anyhow!("refused the claim: {why}"))?;
2297×
            out.push(n);
230
        }
2314×
        if out.is_empty() {
2320×
            bail!("an empty claim");
2334×
        }
2344×
        let appended = self.ledger.append(out).await?;
2354×
        let _ = self.ledger.checkpoint().await;
2364×
        *self.principals.write().await = Principals::load(&self.ledger).await?;
2377×
        Ok(appended.iter().map(|e| e.seq).collect())
2387×
    }
239
240
    /// Write a checkpoint covering everything (at shutdown).
24119×
    pub async fn shutdown(&self) {
24219×
        let _ = self.ledger.checkpoint().await;
24319×
    }
244
}
245
246
/// The Unix peer of a socket connection.
247
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
248
pub struct Peer {
249
    pub uid: u32,
250
    pub pid: Option<i32>,
251
}
252
253
/// An event as the CLI hands it to the daemon: signed already.
254
#[derive(Clone, Debug, Serialize, Deserialize)]
255
pub struct WireEvent {
256
    pub kind: String,
257
    pub actor: String,
258
    pub subject: Option<String>,
259
    pub project: Option<String>,
260
    pub payload: serde_json::Value,
261
    /// Hex of the auth key and the encoded proof; absent for a project's channel.
262
    pub key: Option<String>,
263
    pub proof: Option<String>,
264
}
265
266
impl WireEvent {
26721×
    pub fn from_new(n: &NewEvent) -> WireEvent {
26821×
        WireEvent {
26921×
            kind: n.kind.clone(),
27021×
            actor: n.actor.clone(),
27121×
            subject: n.subject.clone(),
27221×
            project: n.project.clone(),
27321×
            payload: n.payload.clone(),
27421×
            key: n.auth.key.map(hex::encode),
27521×
            proof: n.auth.proof.as_ref().map(hex::encode),
27621×
        }
27721×
    }
278
27920×
    fn into_new_event(self) -> Result<NewEvent> {
28020×
        let auth = match (&self.key, &self.proof) {
28118×
            (Some(k), Some(p)) => Auth {
28218×
                key: Some(hex::decode(k).ok().and_then(|b| b.try_into().ok()).context("a key is 32 bytes of hex")?),
28318×
                method: Method::Signature,
284
                assurance: 2,
28518×
                proof: Some(hex::decode(p).context("a proof is hex")?),
286
            },
2872×
            _ => Auth::system(),
288
        };
28920×
        let mut n = NewEvent::system(&self.kind, self.payload).by(self.actor, auth);
29020×
        n.subject = self.subject;
29120×
        n.project = self.project;
29220×
        Ok(n)
29320×
    }
294
}
295
296
/// The event `n` would be, for checking before it is appended.
29716×
fn probe_event(n: &NewEvent) -> Event {
29816×
    let now = crate::ids::now_ms();
29916×
    Event {
30016×
        seq: 0,
30116×
        id: String::new(),
30216×
        at_ms: now,
30316×
        hlc: crate::hlc::Hlc { wall_ms: now, logical: 0 },
30416×
        prev: [0; 32],
30516×
        hash: [0; 32],
30616×
        auth: n.auth.clone(),
30716×
        kind: n.kind.clone(),
30816×
        actor: n.actor.clone(),
30916×
        session: n.session.clone(),
31016×
        project: n.project.clone(),
31116×
        subject: n.subject.clone(),
31216×
        payload: Some(crate::event::canonical_json(&n.payload)),
31316×
        trace: n.trace.clone(),
31416×
    }
31516×
}