OXYGENHUB
# 01320eefd505 spectra / crates / spectra-core / src / daemon.rs
13.1 KiB · Rust · last changed spectra connect: trust a server through the owner's delegation, pin it, claim it (#21) 1 day ago source blame history raw
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.
35
    pub async fn start(data: &Path) -> Result<Arc<Daemon>> {
36
        let db = data.join("spectra.db");
37
        if !db.exists() {
38
            bail!("no Spectra in {} (run `spectra init`)", data.display());
39
        }
40
        let instance = KeyPair::instance(data, "spectra")?;
41
        let ledger = Ledger::open(&db, Some(instance)).await?;
42
        let principals = Principals::load(&ledger).await?;
43
        let d = Arc::new(Daemon {
44
            data: data.to_path_buf(),
45
            ledger,
46
            principals: RwLock::new(principals),
47
            authn: Authenticator::default(),
48
            presence: Mutex::new(Presence::default()),
49
            idle_waits: Mutex::new(Default::default()),
50
        });
51
        d.clone().watch_principals();
52
        d.clone().tick_presence();
53
        Ok(d)
54
    }
55
56
    /// Reload who is who whenever an identity or agent event is appended.
57
    fn watch_principals(self: Arc<Self>) {
58
        let mut rx = self.ledger.subscribe();
59
        tokio::spawn(async move {
60
            loop {
61
                match rx.recv().await {
62
                    Ok(e)
63
                        if e.kind.starts_with("identity.")
64
                            || e.kind.starts_with("agent.") && e.kind != "agent.presence" && e.kind != "agent.status" =>
65
                    {
66
                        if let Ok(p) = Principals::load(&self.ledger).await {
67
                            *self.principals.write().await = p;
68
                        }
69
                    }
70
                    Ok(_) => {}
71
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
72
                        if let Ok(p) = Principals::load(&self.ledger).await {
73
                            *self.principals.write().await = p;
74
                        }
75
                    }
76
                    Err(_) => return,
77
                }
78
            }
79
        });
80
    }
81
82
    /// Record presence changes and quiet sessions every 15 s, and write a
83
    /// checkpoint when one is due by time.
84
    fn tick_presence(self: Arc<Self>) {
85
        tokio::spawn(async move {
86
            let mut every = tokio::time::interval(std::time::Duration::from_secs(15));
87
            loop {
88
                every.tick().await;
89
                let events = self.presence.lock().await.tick(crate::ids::now_ms());
90
                if !events.is_empty() {
91
                    let _ = self.ledger.append(events).await;
92
                }
93
                let _ = self.ledger.append(vec![]).await;
94
            }
95
        });
96
    }
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`.
101
    pub async fn authenticate(&self, proof: Option<&Proof>, method: &str, body: &[u8], peer: Option<Peer>) -> Result<Caller, Refusal> {
102
        let now = crate::ids::now_ms();
103
        let r = {
104
            let p = self.principals.read().await;
105
            if p.owner().is_none() {
106
                return Err(Refusal::NotAPrincipal("this Spectra has no owner yet: its owner claims it with `spectra connect`".into()));
107
            }
108
            self.authn.authenticate(&p, proof, method, body, now, peer.map(|x| x.uid))
109
        };
110
        match &r {
111
            Err(Refusal::WrongUid { agent, bound, from }) => {
112
                let e = NewEvent::system(
113
                    "guard.impersonation",
114
                    serde_json::json!({ "agent": agent, "bound_uid": bound, "from_uid": from, "from_pid": peer.map(|x| x.pid), "method": method }),
115
                )
116
                .subject(agent.clone());
117
                let _ = self.ledger.append_one(e).await;
118
                tracing::warn!(agent, bound, from, "a key used from the wrong Unix user");
119
            }
120
            Err(Refusal::BoundOverNetwork { agent, bound }) => {
121
                let e = NewEvent::system(
122
                    "guard.impersonation",
123
                    serde_json::json!({ "agent": agent, "bound_uid": bound, "from_uid": null, "over": "tcp", "method": method }),
124
                )
125
                .subject(agent.clone());
126
                let _ = self.ledger.append_one(e).await;
127
                tracing::warn!(agent, bound, "a uid-bound key used over the network");
128
            }
129
            Ok(Caller { principal: Principal::Agent { name, .. }, learn_uid: Some(uid), .. }) => {
130
                let e = NewEvent::system("agent.uid_bound", serde_json::json!({ "name": name, "uid": uid })).subject(name.clone());
131
                let _ = self.ledger.append_one(e).await;
132
            }
133
            _ => {}
134
        }
135
        r
136
    }
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.
140
    pub async fn touch(&self, who: &Principal, new_session: bool) -> Option<String> {
141
        let Principal::Agent { name, .. } = who else { return None };
142
        let (id, started) = self.presence.lock().await.request(name, crate::ids::now_ms(), new_session);
143
        if let Some(e) = started {
144
            let _ = self.ledger.append_one(e).await;
145
        }
146
        Some(id)
147
    }
148
149
    /// Append events the owner's CLI signed over their payload, after
150
    /// checking each as `spectra admin verify` would.
151
    pub async fn accept_owner_events(&self, events: Vec<WireEvent>) -> Result<Vec<u64>> {
152
        let mut principals = self.principals.read().await.clone();
153
        let projects: Vec<String> = events
154
            .iter()
155
            .filter(|e| e.kind == "project.added")
156
            .filter_map(|e| e.payload.get("name").and_then(|n| n.as_str()).map(String::from))
157
            .collect();
158
        let mut out = Vec::new();
159
        for w in events {
160
            let n = w.into_new_event()?;
161
            if n.kind == "channel.created" {
162
                // A project's channel comes with its project, unsigned, as `project add` makes it.
163
                let p = &n.payload;
164
                let ok = p.get("kind").and_then(|k| k.as_str()) == Some("project")
165
                    && p.get("name").and_then(|x| x.as_str()).is_some_and(|x| projects.iter().any(|q| q == x));
166
                if !ok || n.auth.method != Method::System {
167
                    bail!("a channel is only made with its project");
168
                }
169
                out.push(n);
170
                continue;
171
            }
172
            if !OWNER_KINDS.contains(&n.kind.as_str()) {
173
                bail!("{} cannot be handed to the daemon", n.kind);
174
            }
175
            if n.actor != "human" {
176
                bail!("only the owner hands events to the daemon");
177
            }
178
            // Check it as verify will, against who is who including the
179
            // batch so far.
180
            let probe = probe_event(&n);
181
            principals.check(&probe).map_err(|why| anyhow::anyhow!("refused {}: {why}", n.kind))?;
182
            if n.kind != "identity.rotated" {
183
                let key = oxy_core::hash::ObjectRef(n.auth.key.context("unsigned")?);
184
                if !matches!(principals.principal(&key, crate::ids::now_ms()), Ok(Principal::Owner { .. })) {
185
                    bail!("refused {}: not signed by the owner", n.kind);
186
                }
187
            }
188
            out.push(n);
189
        }
190
        let appended = self.ledger.append(out).await?;
191
        let _ = self.ledger.checkpoint().await;
192
        // Who is who has changed: know it before the next request arrives.
193
        *self.principals.write().await = Principals::load(&self.ledger).await?;
194
        Ok(appended.iter().map(|e| e.seq).collect())
195
    }
196
197
    /// The owner `spectra init --owner` named, while none is recorded.
198
    pub fn named_owner(&self) -> Option<String> {
199
        let text = std::fs::read_to_string(self.data.join("spectra.toml")).ok()?;
200
        let t: toml::Table = text.parse().ok()?;
201
        t.get("owner")?.get("key")?.as_str().map(|k| k.to_ascii_lowercase())
202
    }
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.
209
    pub async fn claim(&self, events: Vec<WireEvent>) -> Result<Vec<u64>> {
210
        let mut principals = self.principals.read().await.clone();
211
        if principals.owner().is_some() {
212
            bail!("this Spectra already has an owner");
213
        }
214
        let named = self.named_owner().context("this Spectra names no owner (spectra init --owner)")?;
215
        let mut out = Vec::new();
216
        for (i, w) in events.into_iter().enumerate() {
217
            let n = w.into_new_event()?;
218
            let want = if i == 0 { "identity.owner" } else { "identity.rotated" };
219
            if n.kind != want || n.actor != "human" {
220
                bail!("a claim is the owner's identity.owner, then their rotations");
221
            }
222
            if i == 0 {
223
                let key = n.payload.get("key").and_then(|k| k.as_str()).unwrap_or("").to_ascii_lowercase();
224
                if key != named || n.auth.key.map(hex::encode) != Some(named.clone()) {
225
                    bail!("this Spectra was set up for another owner");
226
                }
227
            }
228
            principals.check(&probe_event(&n)).map_err(|why| anyhow::anyhow!("refused the claim: {why}"))?;
229
            out.push(n);
230
        }
231
        if out.is_empty() {
232
            bail!("an empty claim");
233
        }
234
        let appended = self.ledger.append(out).await?;
235
        let _ = self.ledger.checkpoint().await;
236
        *self.principals.write().await = Principals::load(&self.ledger).await?;
237
        Ok(appended.iter().map(|e| e.seq).collect())
238
    }
239
240
    /// Write a checkpoint covering everything (at shutdown).
241
    pub async fn shutdown(&self) {
242
        let _ = self.ledger.checkpoint().await;
243
    }
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 {
267
    pub fn from_new(n: &NewEvent) -> WireEvent {
268
        WireEvent {
269
            kind: n.kind.clone(),
270
            actor: n.actor.clone(),
271
            subject: n.subject.clone(),
272
            project: n.project.clone(),
273
            payload: n.payload.clone(),
274
            key: n.auth.key.map(hex::encode),
275
            proof: n.auth.proof.as_ref().map(hex::encode),
276
        }
277
    }
278
279
    fn into_new_event(self) -> Result<NewEvent> {
280
        let auth = match (&self.key, &self.proof) {
281
            (Some(k), Some(p)) => Auth {
282
                key: Some(hex::decode(k).ok().and_then(|b| b.try_into().ok()).context("a key is 32 bytes of hex")?),
283
                method: Method::Signature,
284
                assurance: 2,
285
                proof: Some(hex::decode(p).context("a proof is hex")?),
286
            },
287
            _ => Auth::system(),
288
        };
289
        let mut n = NewEvent::system(&self.kind, self.payload).by(self.actor, auth);
290
        n.subject = self.subject;
291
        n.project = self.project;
292
        Ok(n)
293
    }
294
}
295
296
/// The event `n` would be, for checking before it is appended.
297
fn probe_event(n: &NewEvent) -> Event {
298
    let now = crate::ids::now_ms();
299
    Event {
300
        seq: 0,
301
        id: String::new(),
302
        at_ms: now,
303
        hlc: crate::hlc::Hlc { wall_ms: now, logical: 0 },
304
        prev: [0; 32],
305
        hash: [0; 32],
306
        auth: n.auth.clone(),
307
        kind: n.kind.clone(),
308
        actor: n.actor.clone(),
309
        session: n.session.clone(),
310
        project: n.project.clone(),
311
        subject: n.subject.clone(),
312
        payload: Some(crate::event::canonical_json(&n.payload)),
313
        trace: n.trace.clone(),
314
    }
315
}