| 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"]; |
| 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 |
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()), |
| 50 |
idle_waits: Mutex::new(Default::default()), |
| 51 |
}); |
| 52 |
d.clone().watch_principals(); |
| 53 |
d.clone().tick_presence(); |
| 54 |
Ok(d) |
| 55 |
} |
| 56 |
|
| 57 |
|
| 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 |
|
| 84 |
|
| 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 |
|
| 100 |
|
| 101 |
|
| 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; |
| 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 |
} |
| 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 |
} |
| 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 |
} |
| 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 |
|
| 140 |
|
| 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 |
|
| 151 |
|
| 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 |
|
| 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 |
|
| 180 |
|
| 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" { |
| 184 |
let key = crate::identity::KeyId(n.auth.key.context("unsigned")?); |
| 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 |
|
| 194 |
*self.principals.write().await = Principals::load(&self.ledger).await?; |
| 195 |
Ok(appended.iter().map(|e| e.seq).collect()) |
| 196 |
} |
| 197 |
|
| 198 |
|
| 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 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
pub async fn claim(&self, events: Vec<WireEvent>) -> Result<Vec<u64>> { |
| 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)")?; |
| 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"); |
| 234 |
} |
| 235 |
let appended = self.ledger.append(out).await?; |
| 236 |
let _ = self.ledger.checkpoint().await; |
| 237 |
*self.principals.write().await = Principals::load(&self.ledger).await?; |
| 238 |
Ok(appended.iter().map(|e| e.seq).collect()) |
| 239 |
} |
| 240 |
|
| 241 |
|
| 242 |
pub async fn shutdown(&self) { |
| 243 |
let _ = self.ledger.checkpoint().await; |
| 244 |
} |
| 245 |
} |
| 246 |
|
| 247 |
|
| 248 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 249 |
pub struct Peer { |
| 250 |
pub uid: u32, |
| 251 |
pub pid: Option<i32>, |
| 252 |
} |
| 253 |
|
| 254 |
|
| 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 |
|
| 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 |
|
| 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 |
} |