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