OXYGENHUB

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

170 of 183 lines run, 26 of 71 functions · run #18 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.
3513×
    pub async fn start(data: &Path) -> Result<Arc<Daemon>> {
3613×
        let db = data.join("spectra.db");
3713×
        if !db.exists() {
380×
            bail!("no Spectra in {} (run `spectra init`)", data.display());
3913×
        }
4013×
        let instance = KeyPair::instance(data, "spectra")?;
4113×
        let ledger = Ledger::open(&db, Some(instance)).await?;
4213×
        let principals = Principals::load(&ledger).await?;
4313×
        let d = Arc::new(Daemon {
4413×
            data: data.to_path_buf(),
4513×
            ledger,
4613×
            principals: RwLock::new(principals),
4713×
            authn: Authenticator::default(),
4813×
            presence: Mutex::new(Presence::default()),
4913×
            idle_waits: Mutex::new(Default::default()),
5013×
        });
5113×
        d.clone().watch_principals();
5213×
        d.clone().tick_presence();
5313×
        Ok(d)
5413×
    }
55
56
    /// Reload who is who whenever an identity or agent event is appended.
5713×
    fn watch_principals(self: Arc<Self>) {
5813×
        let mut rx = self.ledger.subscribe();
5913×
        tokio::spawn(async move {
60
            loop {
6190×
                match rx.recv().await {
6216×
                    Ok(e)
6380×
                        if e.kind.starts_with("identity.")
6479×
                            || e.kind.starts_with("agent.") && e.kind != "agent.presence" && e.kind != "agent.status" =>
65
                    {
6616×
                        if let Ok(p) = Principals::load(&self.ledger).await {
6713×
                            *self.principals.write().await = p;
680×
                        }
69
                    }
7064×
                    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×
        });
8013×
    }
81
82
    /// Record presence changes and quiet sessions every 15 s, and write a
83
    /// checkpoint when one is due by time.
8413×
    fn tick_presence(self: Arc<Self>) {
8513×
        tokio::spawn(async move {
8613×
            let mut every = tokio::time::interval(std::time::Duration::from_secs(15));
87
            loop {
8826×
                every.tick().await;
8913×
                let events = self.presence.lock().await.tick(crate::ids::now_ms());
9013×
                if !events.is_empty() {
910×
                    let _ = self.ledger.append(events).await;
9213×
                }
9313×
                let _ = self.ledger.append(vec![]).await;
94
            }
95
        });
9613×
    }
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`.
10177×
    pub async fn authenticate(&self, proof: Option<&Proof>, method: &str, body: &[u8], peer: Option<Peer>) -> Result<Caller, Refusal> {
10277×
        let now = crate::ids::now_ms();
10377×
        let r = {
10477×
            let p = self.principals.read().await;
10577×
            self.authn.authenticate(&p, proof, method, body, now, peer.map(|x| x.uid))
106
        };
10760×
        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×
            Err(Refusal::BoundOverNetwork { agent, bound }) => {
1181×
                let e = NewEvent::system(
1191×
                    "guard.impersonation",
1201×
                    serde_json::json!({ "agent": agent, "bound_uid": bound, "from_uid": null, "over": "tcp", "method": method }),
121
                )
1221×
                .subject(agent.clone());
1231×
                let _ = self.ledger.append_one(e).await;
1241×
                tracing::warn!(agent, bound, "a uid-bound key used over the network");
125
            }
1261×
            Ok(Caller { principal: Principal::Agent { name, .. }, learn_uid: Some(uid), .. }) => {
1271×
                let e = NewEvent::system("agent.uid_bound", serde_json::json!({ "name": name, "uid": uid })).subject(name.clone());
1281×
                let _ = self.ledger.append_one(e).await;
129
            }
13074×
            _ => {}
131
        }
13277×
        r
13377×
    }
134
135
    /// Note a request from an agent: its session, and the event that
136
    /// starts one when this is the first in ten minutes.
13742×
    pub async fn touch(&self, who: &Principal, new_session: bool) -> Option<String> {
13842×
        let Principal::Agent { name, .. } = who else { return None };
13942×
        let (id, started) = self.presence.lock().await.request(name, crate::ids::now_ms(), new_session);
14042×
        if let Some(e) = started {
14113×
            let _ = self.ledger.append_one(e).await;
14229×
        }
14342×
        Some(id)
14442×
    }
145
146
    /// Append events the owner's CLI signed over their payload, after
147
    /// checking each as `spectra admin verify` would.
1482×
    pub async fn accept_owner_events(&self, events: Vec<WireEvent>) -> Result<Vec<u64>> {
1492×
        let mut principals = self.principals.read().await.clone();
1502×
        let projects: Vec<String> = events
1512×
            .iter()
1524×
            .filter(|e| e.kind == "project.added")
1532×
            .filter_map(|e| e.payload.get("name").and_then(|n| n.as_str()).map(String::from))
1542×
            .collect();
1552×
        let mut out = Vec::new();
1564×
        for w in events {
1574×
            let n = w.into_new_event()?;
1584×
            if n.kind == "channel.created" {
159
                // A project's channel comes with its project, unsigned, as `project add` makes it.
1601×
                let p = &n.payload;
1611×
                let ok = p.get("kind").and_then(|k| k.as_str()) == Some("project")
1621×
                    && p.get("name").and_then(|x| x.as_str()).is_some_and(|x| projects.iter().any(|q| q == x));
1631×
                if !ok || n.auth.method != Method::System {
1640×
                    bail!("a channel is only made with its project");
1651×
                }
1661×
                out.push(n);
1671×
                continue;
1683×
            }
1693×
            if !OWNER_KINDS.contains(&n.kind.as_str()) {
1700×
                bail!("{} cannot be handed to the daemon", n.kind);
1713×
            }
1723×
            if n.actor != "human" {
1730×
                bail!("only the owner hands events to the daemon");
1743×
            }
175
            // Check it as verify will, against who is who including the
176
            // batch so far.
1773×
            let probe = probe_event(&n);
1783×
            principals.check(&probe).map_err(|why| anyhow::anyhow!("refused {}: {why}", n.kind))?;
1793×
            if n.kind != "identity.rotated" {
1802×
                let key = oxy_core::hash::ObjectRef(n.auth.key.context("unsigned")?);
1812×
                if !matches!(principals.principal(&key, crate::ids::now_ms()), Ok(Principal::Owner { .. })) {
1820×
                    bail!("refused {}: not signed by the owner", n.kind);
1832×
                }
1841×
            }
1853×
            out.push(n);
186
        }
1872×
        let appended = self.ledger.append(out).await?;
1882×
        let _ = self.ledger.checkpoint().await;
189
        // Who is who has changed: know it before the next request arrives.
1902×
        *self.principals.write().await = Principals::load(&self.ledger).await?;
1914×
        Ok(appended.iter().map(|e| e.seq).collect())
1922×
    }
193
194
    /// Write a checkpoint covering everything (at shutdown).
19513×
    pub async fn shutdown(&self) {
19613×
        let _ = self.ledger.checkpoint().await;
19713×
    }
198
}
199
200
/// The Unix peer of a socket connection.
201
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
202
pub struct Peer {
203
    pub uid: u32,
204
    pub pid: Option<i32>,
205
}
206
207
/// An event as the CLI hands it to the daemon: signed already.
208
#[derive(Clone, Debug, Serialize, Deserialize)]
209
pub struct WireEvent {
210
    pub kind: String,
211
    pub actor: String,
212
    pub subject: Option<String>,
213
    pub project: Option<String>,
214
    pub payload: serde_json::Value,
215
    /// Hex of the auth key and the encoded proof; absent for a project's channel.
216
    pub key: Option<String>,
217
    pub proof: Option<String>,
218
}
219
220
impl WireEvent {
2214×
    pub fn from_new(n: &NewEvent) -> WireEvent {
2224×
        WireEvent {
2234×
            kind: n.kind.clone(),
2244×
            actor: n.actor.clone(),
2254×
            subject: n.subject.clone(),
2264×
            project: n.project.clone(),
2274×
            payload: n.payload.clone(),
2284×
            key: n.auth.key.map(hex::encode),
2294×
            proof: n.auth.proof.as_ref().map(hex::encode),
2304×
        }
2314×
    }
232
2334×
    fn into_new_event(self) -> Result<NewEvent> {
2344×
        let auth = match (&self.key, &self.proof) {
2353×
            (Some(k), Some(p)) => Auth {
2363×
                key: Some(hex::decode(k).ok().and_then(|b| b.try_into().ok()).context("a key is 32 bytes of hex")?),
2373×
                method: Method::Signature,
238
                assurance: 2,
2393×
                proof: Some(hex::decode(p).context("a proof is hex")?),
240
            },
2411×
            _ => Auth::system(),
242
        };
2434×
        let mut n = NewEvent::system(&self.kind, self.payload).by(self.actor, auth);
2444×
        n.subject = self.subject;
2454×
        n.project = self.project;
2464×
        Ok(n)
2474×
    }
248
}
249
250
/// The event `n` would be, for checking before it is appended.
2513×
fn probe_event(n: &NewEvent) -> Event {
2523×
    let now = crate::ids::now_ms();
2533×
    Event {
2543×
        seq: 0,
2553×
        id: String::new(),
2563×
        at_ms: now,
2573×
        hlc: crate::hlc::Hlc { wall_ms: now, logical: 0 },
2583×
        prev: [0; 32],
2593×
        hash: [0; 32],
2603×
        auth: n.auth.clone(),
2613×
        kind: n.kind.clone(),
2623×
        actor: n.actor.clone(),
2633×
        session: n.session.clone(),
2643×
        project: n.project.clone(),
2653×
        subject: n.subject.clone(),
2663×
        payload: Some(crate::event::canonical_json(&n.payload)),
2673×
        trace: n.trace.clone(),
2683×
    }
2693×
}