OXYGENHUB

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

209 of 225 lines run, 32 of 89 functions · run #26 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] =
22
    &["identity.rotated", "agent.added", "agent.disabled", "project.added", "project.linked", "project.unlinked"];
23
24
pub struct Daemon {
25
    pub data: PathBuf,
26
    pub ledger: Ledger,
27
    pub principals: RwLock<Principals>,
28
    pub authn: Authenticator,
29
    pub presence: Mutex<Presence>,
30
    /// Per agent: empty `wait`s in a row, and until when `wait` is refused.
31
    pub idle_waits: Mutex<std::collections::HashMap<String, (u32, u64)>>,
32
}
33
34
impl Daemon {
35
    /// Open the data directory's ledger for writing and start the timers.
3619×
    pub async fn start(data: &Path) -> Result<Arc<Daemon>> {
3719×
        let db = data.join("spectra.db");
3819×
        if !db.exists() {
390×
            bail!("no Spectra in {} (run `spectra init`)", data.display());
4019×
        }
4119×
        let instance = KeyPair::instance(data, "spectra")?;
4219×
        let ledger = Ledger::open(&db, Some(instance)).await?;
4319×
        let principals = Principals::load(&ledger).await?;
4419×
        let d = Arc::new(Daemon {
4519×
            data: data.to_path_buf(),
4619×
            ledger,
4719×
            principals: RwLock::new(principals),
4819×
            authn: Authenticator::default(),
4919×
            presence: Mutex::new(Presence::default()),
5019×
            idle_waits: Mutex::new(Default::default()),
5119×
        });
5219×
        d.clone().watch_principals();
5319×
        d.clone().tick_presence();
5419×
        Ok(d)
5519×
    }
56
57
    /// Reload who is who whenever an identity or agent event is appended.
5819×
    fn watch_principals(self: Arc<Self>) {
5919×
        let mut rx = self.ledger.subscribe();
6019×
        tokio::spawn(async move {
61
            loop {
62133×
                match rx.recv().await {
6330×
                    Ok(e)
64116×
                        if e.kind.starts_with("identity.")
65105×
                            || e.kind.starts_with("agent.") && e.kind != "agent.presence" && e.kind != "agent.status" =>
66
                    {
6730×
                        if let Ok(p) = Principals::load(&self.ledger).await {
6828×
                            *self.principals.write().await = p;
690×
                        }
70
                    }
7186×
                    Ok(_) => {}
72
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
730×
                        if let Ok(p) = Principals::load(&self.ledger).await {
740×
                            *self.principals.write().await = p;
750×
                        }
76
                    }
770×
                    Err(_) => return,
78
                }
79
            }
800×
        });
8119×
    }
82
83
    /// Record presence changes and quiet sessions every 15 s, and write a
84
    /// checkpoint when one is due by time.
8519×
    fn tick_presence(self: Arc<Self>) {
8619×
        tokio::spawn(async move {
8719×
            let mut every = tokio::time::interval(std::time::Duration::from_secs(15));
88
            loop {
8938×
                every.tick().await;
9019×
                let events = self.presence.lock().await.tick(crate::ids::now_ms());
9119×
                if !events.is_empty() {
920×
                    let _ = self.ledger.append(events).await;
9319×
                }
9419×
                let _ = self.ledger.append(vec![]).await;
95
            }
96
        });
9719×
    }
98
99
    /// Authenticate a request (spec §8.5); an agent used from the wrong Unix
100
    /// user is recorded as `guard.impersonation`, and a first connection
101
    /// that binds an agent's uid as `agent.uid_bound`.
102106×
    pub async fn authenticate(&self, proof: Option<&Proof>, method: &str, body: &[u8], peer: Option<Peer>) -> Result<Caller, Refusal> {
103106×
        let now = crate::ids::now_ms();
104105×
        let r = {
105106×
            let p = self.principals.read().await;
106106×
            if p.owner().is_none() {
1071×
                return Err(Refusal::NotAPrincipal("this Spectra has no owner yet: its owner claims it with `spectra connect`".into()));
108105×
            }
109105×
            self.authn.authenticate(&p, proof, method, body, now, peer.map(|x| x.uid))
110
        };
11162×
        match &r {
1121×
            Err(Refusal::WrongUid { agent, bound, from }) => {
1131×
                let e = NewEvent::system(
1141×
                    "guard.impersonation",
1151×
                    serde_json::json!({ "agent": agent, "bound_uid": bound, "from_uid": from, "from_pid": peer.map(|x| x.pid), "method": method }),
116
                )
1171×
                .subject(agent.clone());
1181×
                let _ = self.ledger.append_one(e).await;
1191×
                tracing::warn!(agent, bound, from, "a key used from the wrong Unix user");
120
            }
1211×
            Err(Refusal::BoundOverNetwork { agent, bound }) => {
1221×
                let e = NewEvent::system(
1231×
                    "guard.impersonation",
1241×
                    serde_json::json!({ "agent": agent, "bound_uid": bound, "from_uid": null, "over": "tcp", "method": method }),
125
                )
1261×
                .subject(agent.clone());
1271×
                let _ = self.ledger.append_one(e).await;
1281×
                tracing::warn!(agent, bound, "a uid-bound key used over the network");
129
            }
1301×
            Ok(Caller { principal: Principal::Agent { name, .. }, learn_uid: Some(uid), .. }) => {
1311×
                let e = NewEvent::system("agent.uid_bound", serde_json::json!({ "name": name, "uid": uid })).subject(name.clone());
1321×
                let _ = self.ledger.append_one(e).await;
133
            }
134102×
            _ => {}
135
        }
136105×
        r
137106×
    }
138
139
    /// Note a request from an agent: its session, and the event that
140
    /// starts one when this is the first in ten minutes.
14144×
    pub async fn touch(&self, who: &Principal, new_session: bool) -> Option<String> {
14244×
        let Principal::Agent { name, .. } = who else { return None };
14344×
        let (id, started) = self.presence.lock().await.request(name, crate::ids::now_ms(), new_session);
14444×
        if let Some(e) = started {
14514×
            let _ = self.ledger.append_one(e).await;
14630×
        }
14744×
        Some(id)
14844×
    }
149
150
    /// Append events the owner's CLI signed over their payload, after
151
    /// checking each as `spectra admin verify` would.
1526×
    pub async fn accept_owner_events(&self, events: Vec<WireEvent>) -> Result<Vec<u64>> {
1536×
        let mut principals = self.principals.read().await.clone();
1546×
        let projects: Vec<String> = events
1556×
            .iter()
15612×
            .filter(|e| e.kind == "project.added")
1576×
            .filter_map(|e| e.payload.get("name").and_then(|n| n.as_str()).map(String::from))
1586×
            .collect();
1596×
        let mut out = Vec::new();
16012×
        for w in events {
16112×
            let n = w.into_new_event()?;
16212×
            if n.kind == "channel.created" {
163
                // A project's channel comes with its project, unsigned, as `project add` makes it.
1642×
                let p = &n.payload;
1652×
                let ok = p.get("kind").and_then(|k| k.as_str()) == Some("project")
1662×
                    && p.get("name").and_then(|x| x.as_str()).is_some_and(|x| projects.iter().any(|q| q == x));
1672×
                if !ok || n.auth.method != Method::System {
1680×
                    bail!("a channel is only made with its project");
1692×
                }
1702×
                out.push(n);
1712×
                continue;
17210×
            }
17310×
            if !OWNER_KINDS.contains(&n.kind.as_str()) {
1740×
                bail!("{} cannot be handed to the daemon", n.kind);
17510×
            }
17610×
            if n.actor != "human" {
1770×
                bail!("only the owner hands events to the daemon");
17810×
            }
179
            // Check it as verify will, against who is who including the
180
            // batch so far.
18110×
            let probe = probe_event(&n);
18210×
            principals.check(&probe).map_err(|why| anyhow::anyhow!("refused {}: {why}", n.kind))?;
18310×
            if n.kind != "identity.rotated" {
1846×
                let key = crate::identity::KeyId(n.auth.key.context("unsigned")?);
1856×
                if !matches!(principals.principal(&key, crate::ids::now_ms()), Ok(Principal::Owner { .. })) {
1860×
                    bail!("refused {}: not signed by the owner", n.kind);
1876×
                }
1884×
            }
18910×
            out.push(n);
190
        }
1916×
        let appended = self.ledger.append(out).await?;
1926×
        let _ = self.ledger.checkpoint().await;
193
        // Who is who has changed: know it before the next request arrives.
1946×
        *self.principals.write().await = Principals::load(&self.ledger).await?;
19512×
        Ok(appended.iter().map(|e| e.seq).collect())
1966×
    }
197
198
    /// The owner `spectra init --owner` named, while none is recorded.
19913×
    pub fn named_owner(&self) -> Option<String> {
20013×
        let text = std::fs::read_to_string(self.data.join("spectra.toml")).ok()?;
20113×
        let t: toml::Table = text.parse().ok()?;
20213×
        t.get("owner")?.get("key")?.as_str().map(|k| k.to_ascii_lowercase())
20313×
    }
204
205
    /// The owner claims a Spectra set up with `spectra init --owner`
206
    /// (spec §8.6): the named identity, signed by itself over its payload,
207
    /// then any successors up to the owner's current identity, each a
208
    /// rotation as `identity refresh` makes. Accepted only while no owner
209
    /// is recorded, and only from the key init named.
2107×
    pub async fn claim(&self, events: Vec<WireEvent>) -> Result<Vec<u64>> {
2117×
        let mut principals = self.principals.read().await.clone();
2127×
        if principals.owner().is_some() {
2131×
            bail!("this Spectra already has an owner");
2146×
        }
2156×
        let named = self.named_owner().context("this Spectra names no owner (spectra init --owner)")?;
2166×
        let mut out = Vec::new();
2179×
        for (i, w) in events.into_iter().enumerate() {
2189×
            let n = w.into_new_event()?;
2199×
            let want = if i == 0 { "identity.owner" } else { "identity.rotated" };
2209×
            if n.kind != want || n.actor != "human" {
2210×
                bail!("a claim is the owner's identity.owner, then their rotations");
2229×
            }
2239×
            if i == 0 {
2246×
                let key = n.payload.get("key").and_then(|k| k.as_str()).unwrap_or("").to_ascii_lowercase();
2256×
                if key != named || n.auth.key.map(hex::encode) != Some(named.clone()) {
2262×
                    bail!("this Spectra was set up for another owner");
2274×
                }
2283×
            }
2297×
            principals.check(&probe_event(&n)).map_err(|why| anyhow::anyhow!("refused the claim: {why}"))?;
2307×
            out.push(n);
231
        }
2324×
        if out.is_empty() {
2330×
            bail!("an empty claim");
2344×
        }
2354×
        let appended = self.ledger.append(out).await?;
2364×
        let _ = self.ledger.checkpoint().await;
2374×
        *self.principals.write().await = Principals::load(&self.ledger).await?;
2387×
        Ok(appended.iter().map(|e| e.seq).collect())
2397×
    }
240
241
    /// Write a checkpoint covering everything (at shutdown).
24219×
    pub async fn shutdown(&self) {
24319×
        let _ = self.ledger.checkpoint().await;
24419×
    }
245
}
246
247
/// The Unix peer of a socket connection.
248
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249
pub struct Peer {
250
    pub uid: u32,
251
    pub pid: Option<i32>,
252
}
253
254
/// An event as the CLI hands it to the daemon: signed already.
255
#[derive(Clone, Debug, Serialize, Deserialize)]
256
pub struct WireEvent {
257
    pub kind: String,
258
    pub actor: String,
259
    pub subject: Option<String>,
260
    pub project: Option<String>,
261
    pub payload: serde_json::Value,
262
    /// Hex of the auth key and the encoded proof; absent for a project's channel.
263
    pub key: Option<String>,
264
    pub proof: Option<String>,
265
}
266
267
impl WireEvent {
26822×
    pub fn from_new(n: &NewEvent) -> WireEvent {
26922×
        WireEvent {
27022×
            kind: n.kind.clone(),
27122×
            actor: n.actor.clone(),
27222×
            subject: n.subject.clone(),
27322×
            project: n.project.clone(),
27422×
            payload: n.payload.clone(),
27522×
            key: n.auth.key.map(hex::encode),
27622×
            proof: n.auth.proof.as_ref().map(hex::encode),
27722×
        }
27822×
    }
279
28021×
    fn into_new_event(self) -> Result<NewEvent> {
28121×
        let auth = match (&self.key, &self.proof) {
28219×
            (Some(k), Some(p)) => Auth {
28319×
                key: Some(hex::decode(k).ok().and_then(|b| b.try_into().ok()).context("a key is 32 bytes of hex")?),
28419×
                method: Method::Signature,
285
                assurance: 2,
28619×
                proof: Some(hex::decode(p).context("a proof is hex")?),
287
            },
2882×
            _ => Auth::system(),
289
        };
29021×
        let mut n = NewEvent::system(&self.kind, self.payload).by(self.actor, auth);
29121×
        n.subject = self.subject;
29221×
        n.project = self.project;
29321×
        Ok(n)
29421×
    }
295
}
296
297
/// The event `n` would be, for checking before it is appended.
29817×
fn probe_event(n: &NewEvent) -> Event {
29917×
    let now = crate::ids::now_ms();
30017×
    Event {
30117×
        seq: 0,
30217×
        id: String::new(),
30317×
        at_ms: now,
30417×
        hlc: crate::hlc::Hlc { wall_ms: now, logical: 0 },
30517×
        prev: [0; 32],
30617×
        hash: [0; 32],
30717×
        auth: n.auth.clone(),
30817×
        kind: n.kind.clone(),
30917×
        actor: n.actor.clone(),
31017×
        session: n.session.clone(),
31117×
        project: n.project.clone(),
31217×
        subject: n.subject.clone(),
31317×
        payload: Some(crate::event::canonical_json(&n.payload)),
31417×
        trace: n.trace.clone(),
31517×
    }
31617×
}