OXYGENHUB

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

213 of 229 lines run, 33 of 92 functions · run #29 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", "brief.set"];
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.
3621×
    pub async fn start(data: &Path) -> Result<Arc<Daemon>> {
3721×
        let db = data.join("spectra.db");
3821×
        if !db.exists() {
390×
            bail!("no Spectra in {} (run `spectra init`)", data.display());
4021×
        }
4121×
        let instance = KeyPair::instance(data, "spectra")?;
4221×
        let ledger = Ledger::open(&db, Some(instance)).await?;
4321×
        let principals = Principals::load(&ledger).await?;
4421×
        let d = Arc::new(Daemon {
4521×
            data: data.to_path_buf(),
4621×
            ledger,
4721×
            principals: RwLock::new(principals),
4821×
            authn: Authenticator::default(),
4921×
            presence: Mutex::new(Presence::default()),
5021×
            idle_waits: Mutex::new(Default::default()),
5121×
        });
5221×
        d.clone().watch_principals();
5321×
        d.clone().tick_presence();
5421×
        Ok(d)
5521×
    }
56
57
    /// Reload who is who whenever an identity or agent event is appended.
5821×
    fn watch_principals(self: Arc<Self>) {
5921×
        let mut rx = self.ledger.subscribe();
6021×
        tokio::spawn(async move {
61
            loop {
62163×
                match rx.recv().await {
6332×
                    Ok(e)
64144×
                        if e.kind.starts_with("identity.")
65133×
                            || e.kind.starts_with("agent.") && e.kind != "agent.presence" && e.kind != "agent.status" =>
66
                    {
6732×
                        if let Ok(p) = Principals::load(&self.ledger).await {
6830×
                            *self.principals.write().await = p;
690×
                        }
70
                    }
71112×
                    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×
        });
8121×
    }
82
83
    /// Record presence changes and quiet sessions every 15 s, and write a
84
    /// checkpoint when one is due by time.
8521×
    fn tick_presence(self: Arc<Self>) {
8621×
        tokio::spawn(async move {
8721×
            let mut every = tokio::time::interval(std::time::Duration::from_secs(15));
88
            loop {
8942×
                every.tick().await;
9021×
                let events = self.presence.lock().await.tick(crate::ids::now_ms());
9121×
                if !events.is_empty() {
920×
                    let _ = self.ledger.append(events).await;
9321×
                }
9421×
                let _ = self.ledger.append(vec![]).await;
95
            }
96
        });
9721×
    }
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`.
102130×
    pub async fn authenticate(&self, proof: Option<&Proof>, method: &str, body: &[u8], peer: Option<Peer>) -> Result<Caller, Refusal> {
103130×
        let now = crate::ids::now_ms();
104129×
        let r = {
105130×
            let p = self.principals.read().await;
106130×
            if p.owner().is_none() {
1071×
                return Err(Refusal::NotAPrincipal("this Spectra has no owner yet: its owner claims it with `spectra connect`".into()));
108129×
            }
109129×
            self.authn.authenticate(&p, proof, method, body, now, peer.map(|x| x.uid))
110
        };
11171×
        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
            }
134126×
            _ => {}
135
        }
136129×
        r
137130×
    }
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.
14152×
    pub async fn touch(&self, who: &Principal, new_session: bool) -> Option<String> {
14252×
        let Principal::Agent { name, .. } = who else { return None };
14352×
        let (id, started) = self.presence.lock().await.request(name, crate::ids::now_ms(), new_session);
14452×
        if let Some(e) = started {
14516×
            let _ = self.ledger.append_one(e).await;
14636×
        }
14752×
        Some(id)
14852×
    }
149
150
    /// Append events the owner's CLI signed over their payload, after
151
    /// checking each as `spectra admin verify` would.
15210×
    pub async fn accept_owner_events(&self, events: Vec<WireEvent>) -> Result<Vec<u64>> {
15310×
        let mut principals = self.principals.read().await.clone();
15410×
        let projects: Vec<String> = events
15510×
            .iter()
15616×
            .filter(|e| e.kind == "project.added")
15710×
            .filter_map(|e| e.payload.get("name").and_then(|n| n.as_str()).map(String::from))
15810×
            .collect();
15910×
        let mut out = Vec::new();
16016×
        for w in events {
16116×
            let n = w.into_new_event()?;
16216×
            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;
17214×
            }
17314×
            if !OWNER_KINDS.contains(&n.kind.as_str()) {
1740×
                bail!("{} cannot be handed to the daemon", n.kind);
17514×
            }
17614×
            if n.actor != "human" {
1770×
                bail!("only the owner hands events to the daemon");
17814×
            }
17914×
            if n.kind == "brief.set" {
1804×
                crate::rules::check(n.payload.get("text").and_then(|t| t.as_str()).unwrap_or(""))?;
18110×
            }
182
            // Check it as verify will, against who is who including the
183
            // batch so far.
18414×
            let probe = probe_event(&n);
18514×
            principals.check(&probe).map_err(|why| anyhow::anyhow!("refused {}: {why}", n.kind))?;
18614×
            if n.kind != "identity.rotated" {
18710×
                let key = crate::identity::KeyId(n.auth.key.context("unsigned")?);
18810×
                if !matches!(principals.principal(&key, crate::ids::now_ms()), Ok(Principal::Owner { .. })) {
1890×
                    bail!("refused {}: not signed by the owner", n.kind);
19010×
                }
1914×
            }
19214×
            out.push(n);
193
        }
19410×
        let appended = self.ledger.append(out).await?;
19510×
        let _ = self.ledger.checkpoint().await;
196
        // Who is who has changed: know it before the next request arrives.
19710×
        *self.principals.write().await = Principals::load(&self.ledger).await?;
19816×
        Ok(appended.iter().map(|e| e.seq).collect())
19910×
    }
200
201
    /// The owner `spectra init --owner` named, while none is recorded.
20214×
    pub fn named_owner(&self) -> Option<String> {
20314×
        let text = std::fs::read_to_string(self.data.join("spectra.toml")).ok()?;
20414×
        let t: toml::Table = text.parse().ok()?;
20514×
        t.get("owner")?.get("key")?.as_str().map(|k| k.to_ascii_lowercase())
20614×
    }
207
208
    /// The owner claims a Spectra set up with `spectra init --owner`
209
    /// (spec §8.6): the named identity, signed by itself over its payload,
210
    /// then any successors up to the owner's current identity, each a
211
    /// rotation as `identity refresh` makes. Accepted only while no owner
212
    /// is recorded, and only from the key init named.
2137×
    pub async fn claim(&self, events: Vec<WireEvent>) -> Result<Vec<u64>> {
2147×
        let mut principals = self.principals.read().await.clone();
2157×
        if principals.owner().is_some() {
2161×
            bail!("this Spectra already has an owner");
2176×
        }
2186×
        let named = self.named_owner().context("this Spectra names no owner (spectra init --owner)")?;
2196×
        let mut out = Vec::new();
2209×
        for (i, w) in events.into_iter().enumerate() {
2219×
            let n = w.into_new_event()?;
2229×
            let want = if i == 0 { "identity.owner" } else { "identity.rotated" };
2239×
            if n.kind != want || n.actor != "human" {
2240×
                bail!("a claim is the owner's identity.owner, then their rotations");
2259×
            }
2269×
            if i == 0 {
2276×
                let key = n.payload.get("key").and_then(|k| k.as_str()).unwrap_or("").to_ascii_lowercase();
2286×
                if key != named || n.auth.key.map(hex::encode) != Some(named.clone()) {
2292×
                    bail!("this Spectra was set up for another owner");
2304×
                }
2313×
            }
2327×
            principals.check(&probe_event(&n)).map_err(|why| anyhow::anyhow!("refused the claim: {why}"))?;
2337×
            out.push(n);
234
        }
2354×
        if out.is_empty() {
2360×
            bail!("an empty claim");
2374×
        }
2384×
        let appended = self.ledger.append(out).await?;
2394×
        let _ = self.ledger.checkpoint().await;
2404×
        *self.principals.write().await = Principals::load(&self.ledger).await?;
2417×
        Ok(appended.iter().map(|e| e.seq).collect())
2427×
    }
243
244
    /// Write a checkpoint covering everything (at shutdown).
24521×
    pub async fn shutdown(&self) {
24621×
        let _ = self.ledger.checkpoint().await;
24721×
    }
248
}
249
250
/// The Unix peer of a socket connection.
251
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
252
pub struct Peer {
253
    pub uid: u32,
254
    pub pid: Option<i32>,
255
}
256
257
/// An event as the CLI hands it to the daemon: signed already.
258
#[derive(Clone, Debug, Serialize, Deserialize)]
259
pub struct WireEvent {
260
    pub kind: String,
261
    pub actor: String,
262
    pub subject: Option<String>,
263
    pub project: Option<String>,
264
    pub payload: serde_json::Value,
265
    /// Hex of the auth key and the encoded proof; absent for a project's channel.
266
    pub key: Option<String>,
267
    pub proof: Option<String>,
268
}
269
270
impl WireEvent {
27126×
    pub fn from_new(n: &NewEvent) -> WireEvent {
27226×
        WireEvent {
27326×
            kind: n.kind.clone(),
27426×
            actor: n.actor.clone(),
27526×
            subject: n.subject.clone(),
27626×
            project: n.project.clone(),
27726×
            payload: n.payload.clone(),
27826×
            key: n.auth.key.map(hex::encode),
27926×
            proof: n.auth.proof.as_ref().map(hex::encode),
28026×
        }
28126×
    }
282
28325×
    fn into_new_event(self) -> Result<NewEvent> {
28425×
        let auth = match (&self.key, &self.proof) {
28523×
            (Some(k), Some(p)) => Auth {
28623×
                key: Some(hex::decode(k).ok().and_then(|b| b.try_into().ok()).context("a key is 32 bytes of hex")?),
28723×
                method: Method::Signature,
288
                assurance: 2,
28923×
                proof: Some(hex::decode(p).context("a proof is hex")?),
290
            },
2912×
            _ => Auth::system(),
292
        };
29325×
        let mut n = NewEvent::system(&self.kind, self.payload).by(self.actor, auth);
29425×
        n.subject = self.subject;
29525×
        n.project = self.project;
29625×
        Ok(n)
29725×
    }
298
}
299
300
/// The event `n` would be, for checking before it is appended.
30121×
fn probe_event(n: &NewEvent) -> Event {
30221×
    let now = crate::ids::now_ms();
30321×
    Event {
30421×
        seq: 0,
30521×
        id: String::new(),
30621×
        at_ms: now,
30721×
        hlc: crate::hlc::Hlc { wall_ms: now, logical: 0 },
30821×
        prev: [0; 32],
30921×
        hash: [0; 32],
31021×
        auth: n.auth.clone(),
31121×
        kind: n.kind.clone(),
31221×
        actor: n.actor.clone(),
31321×
        session: n.session.clone(),
31421×
        project: n.project.clone(),
31521×
        subject: n.subject.clone(),
31621×
        payload: Some(crate::event::canonical_json(&n.payload)),
31721×
        trace: n.trace.clone(),
31821×
    }
31921×
}