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