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