| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
|
| 17 | |
|
| 18 | | use crate::event::{Event, Method}; |
| 19 | | use crate::identity::Identity; |
| 20 | | use crate::identity::KeyId; |
| 21 | | use crate::ledger::KeyResolver; |
| 22 | | use crate::proof::Proof; |
| 23 | | use serde_json::Value as Json; |
| 24 | | use sqlx::SqliteConnection; |
| 25 | | use std::collections::HashMap; |
| 26 | |
|
| 27 | |
|
| 28 | | pub const DEFAULT_SCOPES: &[&str] = &["read", "say", "tasks", "claims", "decisions", "status", "search", "schedule:self"]; |
| 29 | |
|
| 30 | |
|
| 31 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 32 | | pub enum Principal { |
| 33 | | Owner { key: KeyId, name: String }, |
| 34 | | Agent { name: String, key: KeyId, owner_name: String, uid: Option<u32>, learn_uid: bool, project: String, scopes: Vec<String> }, |
| 35 | | Instance { key: KeyId }, |
| 36 | | } |
| 37 | |
|
| 38 | | impl Principal { |
| 39 | | |
| 40 | 397× | pub fn actor(&self) -> String { |
| 41 | 397× | match self { |
| 42 | 69× | Principal::Owner { .. } => "human".into(), |
| 43 | 320× | Principal::Agent { name, .. } => format!("agent:{name}"), |
| 44 | 8× | Principal::Instance { .. } => "system".into(), |
| 45 | | } |
| 46 | 397× | } |
| 47 | | |
| 48 | 37× | pub fn display(&self) -> String { |
| 49 | 37× | match self { |
| 50 | 25× | Principal::Owner { name, .. } => name.clone(), |
| 51 | 12× | Principal::Agent { name, owner_name, .. } => format!("{name} · {owner_name}'s agent"), |
| 52 | 0× | Principal::Instance { .. } => "Spectra".into(), |
| 53 | | } |
| 54 | 37× | } |
| 55 | | } |
| 56 | |
|
| 57 | | #[derive(Clone, Debug)] |
| 58 | | struct AgentRec { |
| 59 | | name: String, |
| 60 | | identity: Identity, |
| 61 | | owner_name: String, |
| 62 | | uid: Option<u32>, |
| 63 | | learn_uid: bool, |
| 64 | | project: String, |
| 65 | | scopes: Vec<String>, |
| 66 | | disabled: bool, |
| 67 | | } |
| 68 | |
|
| 69 | |
|
| 70 | | #[derive(Clone, Debug, Default)] |
| 71 | | pub struct Principals { |
| 72 | | |
| 73 | | owner: Vec<Identity>, |
| 74 | | instance: Option<Identity>, |
| 75 | | agents: HashMap<KeyId, AgentRec>, |
| 76 | | by_name: HashMap<String, KeyId>, |
| 77 | | } |
| 78 | |
|
| 79 | | impl Principals { |
| 80 | | |
| 81 | 191× | pub async fn load(ledger: &crate::ledger::Ledger) -> anyhow::Result<Principals> { |
| 82 | 191× | let mut p = Principals::default(); |
| 83 | 191× | let mut from = 1; |
| 84 | | loop { |
| 85 | 382× | let rows = ledger |
| 86 | 382× | .events_of_kinds(from, &["identity.owner", "identity.rotated", "identity.instance", "agent.added", "agent.disabled"], 1000) |
| 87 | 382× | .await?; |
| 88 | 380× | if rows.is_empty() { |
| 89 | 189× | break; |
| 90 | 191× | } |
| 91 | 711× | for e in &rows { |
| 92 | 711× | |
| 93 | 711× | let _ = p.observe(e); |
| 94 | 711× | } |
| 95 | 191× | from = rows.last().map(|e| e.seq + 1).unwrap_or(from); |
| 96 | | } |
| 97 | 189× | Ok(p) |
| 98 | 189× | } |
| 99 | |
|
| 100 | | |
| 101 | 890× | pub fn owner(&self) -> Option<&Identity> { |
| 102 | 890× | self.owner.last() |
| 103 | 890× | } |
| 104 | |
|
| 105 | 32× | pub fn instance(&self) -> Option<&Identity> { |
| 106 | 32× | self.instance.as_ref() |
| 107 | 32× | } |
| 108 | |
|
| 109 | | |
| 110 | 28× | pub fn agent_key(&self, name: &str) -> Option<KeyId> { |
| 111 | 28× | self.by_name.get(name).copied() |
| 112 | 28× | } |
| 113 | |
|
| 114 | | |
| 115 | | |
| 116 | | |
| 117 | 344× | pub fn principal(&self, key: &KeyId, at_ms: u64) -> Result<Principal, String> { |
| 118 | 698× | if let Some(owner) = self.owner.iter().rev().find(|i| &i.hash() == key) { |
| 119 | 136× | return Ok(Principal::Owner { key: *key, name: owner.name.clone() }); |
| 120 | 208× | } |
| 121 | 208× | if self.instance.as_ref().is_some_and(|i| &i.hash() == key) { |
| 122 | 8× | return Ok(Principal::Instance { key: *key }); |
| 123 | 200× | } |
| 124 | 200× | let a = self.agents.get(key).ok_or("an unknown key")?; |
| 125 | 197× | if a.disabled { |
| 126 | 6× | return Err(format!("agent {} is disabled", a.name)); |
| 127 | 191× | } |
| 128 | 191× | let owner = self.owner().ok_or("no owner is recorded")?; |
| 129 | 191× | if !owner.delegates_to(key, at_ms) { |
| 130 | 1× | return Err(match owner.delegate(key) { |
| 131 | 1× | Some(d) if d.expires.is_some_and(|x| at_ms > x) => format!("agent {}'s delegation from {} has expired", a.name, owner.name), |
| 132 | 0× | Some(_) => format!("{}'s delegation to agent {} does not include `changes`", owner.name, a.name), |
| 133 | 0× | None => format!("{}'s current identity does not delegate to agent {}", owner.name, a.name), |
| 134 | | }); |
| 135 | 190× | } |
| 136 | 190× | Ok(Principal::Agent { |
| 137 | 190× | name: a.name.clone(), |
| 138 | 190× | key: *key, |
| 139 | 190× | owner_name: a.owner_name.clone(), |
| 140 | 190× | uid: a.uid, |
| 141 | 190× | learn_uid: a.learn_uid, |
| 142 | 190× | project: a.project.clone(), |
| 143 | 190× | scopes: a.scopes.clone(), |
| 144 | 190× | }) |
| 145 | 344× | } |
| 146 | |
|
| 147 | | |
| 148 | 269× | pub fn identity(&self, key: &KeyId) -> Option<&Identity> { |
| 149 | 269× | self.owner |
| 150 | 269× | .iter() |
| 151 | 668× | .find(|i| &i.hash() == key) |
| 152 | 269× | .or_else(|| self.instance.as_ref().filter(|i| &i.hash() == key)) |
| 153 | 269× | .or_else(|| self.agents.get(key).map(|a| &a.identity)) |
| 154 | 269× | } |
| 155 | |
|
| 156 | | |
| 157 | 875× | pub fn observe(&mut self, e: &Event) -> Result<(), String> { |
| 158 | 875× | let p = e.json(); |
| 159 | 875× | match e.kind.as_str() { |
| 160 | 875× | "identity.owner" => { |
| 161 | 222× | if !self.owner.is_empty() { |
| 162 | 1× | return Err("an owner is already recorded".into()); |
| 163 | 221× | } |
| 164 | 221× | let id = identity_of(&p)?; |
| 165 | 221× | self_signed(e, &id)?; |
| 166 | 221× | self.owner.push(id); |
| 167 | | } |
| 168 | 653× | "identity.rotated" => { |
| 169 | 231× | let new = identity_of(&p)?; |
| 170 | 231× | let cur = self.owner().ok_or("no owner to succeed")?.clone(); |
| 171 | 231× | accept_successor(&cur, &new, &p)?; |
| 172 | 231× | self_signed(e, &new)?; |
| 173 | 230× | self.owner.push(new); |
| 174 | | } |
| 175 | 422× | "identity.instance" => { |
| 176 | 224× | let id = identity_of(&p)?; |
| 177 | 224× | self_signed(e, &id)?; |
| 178 | 224× | self.instance = Some(id); |
| 179 | | } |
| 180 | 198× | "agent.added" => { |
| 181 | 186× | let id = identity_of(&p)?; |
| 182 | 186× | let key = id.hash(); |
| 183 | 186× | let owner = self.owner_signed(e)?; |
| 184 | 186× | if !owner.delegates_to(&key, e.hlc.wall_ms) { |
| 185 | 1× | return Err("added without the owner's delegation to its key".into()); |
| 186 | 185× | } |
| 187 | 185× | let name = text(&p, "name")?; |
| 188 | 185× | if self.by_name.get(&name).is_some_and(|k| *k != key) { |
| 189 | 0× | return Err(format!("agent {name} already exists with another key")); |
| 190 | 185× | } |
| 191 | 185× | self.by_name.insert(name.clone(), key); |
| 192 | 185× | self.agents.insert( |
| 193 | 185× | key, |
| 194 | | AgentRec { |
| 195 | 185× | name, |
| 196 | 185× | identity: id, |
| 197 | 185× | owner_name: owner.name.clone(), |
| 198 | 185× | uid: p.get("uid").and_then(Json::as_u64).map(|u| u as u32), |
| 199 | 185× | learn_uid: p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false), |
| 200 | 185× | project: text(&p, "project")?, |
| 201 | 185× | scopes: p |
| 202 | 185× | .get("scopes") |
| 203 | 185× | .and_then(Json::as_array) |
| 204 | 1384× | .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect()) |
| 205 | 185× | .unwrap_or_default(), |
| 206 | | disabled: false, |
| 207 | | }, |
| 208 | | ); |
| 209 | | } |
| 210 | 12× | "agent.uid_bound" => { |
| 211 | | |
| 212 | | |
| 213 | 1× | let name = text(&p, "name")?; |
| 214 | 1× | let uid = p.get("uid").and_then(Json::as_u64).ok_or("no uid")? as u32; |
| 215 | 1× | let key = *self.by_name.get(&name).ok_or("an unknown agent")?; |
| 216 | 1× | if let Some(a) = self.agents.get_mut(&key) { |
| 217 | 1× | if a.uid.is_none() { |
| 218 | 1× | a.uid = Some(uid); |
| 219 | 1× | } |
| 220 | 0× | } |
| 221 | | } |
| 222 | 11× | "agent.disabled" => { |
| 223 | 11× | self.owner_signed(e)?; |
| 224 | 11× | let name = text(&p, "name")?; |
| 225 | 11× | let key = *self.by_name.get(&name).ok_or("an unknown agent")?; |
| 226 | 11× | if let Some(a) = self.agents.get_mut(&key) { |
| 227 | 11× | a.disabled = true; |
| 228 | 11× | } |
| 229 | | } |
| 230 | 0× | _ => {} |
| 231 | | } |
| 232 | 872× | Ok(()) |
| 233 | 875× | } |
| 234 | |
|
| 235 | | |
| 236 | 197× | fn owner_signed(&self, e: &Event) -> Result<Identity, String> { |
| 237 | 197× | let owner = self.owner().ok_or("no owner is recorded")?.clone(); |
| 238 | 197× | if e.auth.key != Some(owner.hash().0) { |
| 239 | 0× | return Err("not signed by the owner's current identity".into()); |
| 240 | 197× | } |
| 241 | 197× | check_proof(e, &owner)?; |
| 242 | 197× | Ok(owner) |
| 243 | 197× | } |
| 244 | |
|
| 245 | | |
| 246 | | |
| 247 | | |
| 248 | 5× | pub fn check_session(&self, e: &Event) -> Result<(), String> { |
| 249 | 5× | let key = crate::identity::KeyId(e.auth.key.ok_or("a session event names no key")?); |
| 250 | 5× | if !matches!(self.principal(&key, e.hlc.wall_ms)?, Principal::Owner { .. }) || e.actor != "human" { |
| 251 | 0× | return Err("only the owner acts through a Radar session".into()); |
| 252 | 5× | } |
| 253 | 5× | let identity = self.identity(&key).ok_or("an unknown key")?; |
| 254 | 5× | let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?; |
| 255 | 5× | if proof.key() != key.0 || proof.method != "POST /radar/link" { |
| 256 | 0× | return Err("the session's proof is not the owner's sign-in request".into()); |
| 257 | 5× | } |
| 258 | 5× | proof.verify(identity, None) |
| 259 | 5× | } |
| 260 | |
|
| 261 | | |
| 262 | | |
| 263 | 128× | pub fn check_signed(&self, e: &Event) -> Result<(), String> { |
| 264 | 128× | let key = crate::identity::KeyId(e.auth.key.ok_or("signed, but names no key")?); |
| 265 | 128× | let who = self.principal(&key, e.hlc.wall_ms)?; |
| 266 | | |
| 267 | | |
| 268 | 126× | if who.actor() != e.actor { |
| 269 | 2× | return Err(format!("names {} as its actor but is signed by {}", e.actor, who.display())); |
| 270 | 124× | } |
| 271 | 124× | let identity = self.identity(&key).ok_or("an unknown key")?; |
| 272 | 124× | check_proof(e, identity) |
| 273 | 128× | } |
| 274 | | } |
| 275 | |
|
| 276 | | impl KeyResolver for Principals { |
| 277 | 492× | fn check(&mut self, e: &Event) -> Result<(), String> { |
| 278 | 492× | match e.kind.as_str() { |
| 279 | 492× | "identity.owner" | "identity.rotated" | "identity.instance" | "agent.added" | "agent.disabled" => { |
| 280 | 165× | if e.auth.method != Method::Signature { |
| 281 | 2× | return Err(format!("{} must be signed", e.kind)); |
| 282 | 163× | } |
| 283 | 163× | self.observe(e) |
| 284 | | } |
| 285 | 327× | "agent.uid_bound" => self.observe(e), |
| 286 | 326× | _ if matches!(e.auth.method, Method::Signature | Method::Passkey) => self.check_signed(e), |
| 287 | 198× | _ if e.auth.method == Method::Session => self.check_session(e), |
| 288 | 193× | _ => Ok(()), |
| 289 | | } |
| 290 | 492× | } |
| 291 | | } |
| 292 | |
|
| 293 | |
|
| 294 | 42785× | pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> { |
| 295 | 42785× | if e.kind == "agent.uid_bound" { |
| 296 | 1× | let p = e.json(); |
| 297 | 1× | sqlx::query("UPDATE agents SET uid = ? WHERE name = ? AND uid IS NULL") |
| 298 | 1× | .bind(p.get("uid").and_then(Json::as_i64)) |
| 299 | 1× | .bind(p.get("name").and_then(Json::as_str)) |
| 300 | 1× | .execute(&mut *conn) |
| 301 | 1× | .await?; |
| 302 | 1× | return Ok(()); |
| 303 | 42784× | } |
| 304 | | |
| 305 | 42784× | if e.auth.method != Method::Signature { |
| 306 | 42018× | return Ok(()); |
| 307 | 766× | } |
| 308 | 766× | let p = e.json(); |
| 309 | 766× | let id = |p: &Json| identity_of(p).ok(); |
| 310 | 766× | match e.kind.as_str() { |
| 311 | 766× | "identity.owner" | "identity.rotated" | "identity.instance" => { |
| 312 | 171× | let Some(identity) = id(&p) else { return Ok(()) }; |
| 313 | 171× | let role = if e.kind == "identity.instance" { "instance" } else { "owner" }; |
| 314 | 171× | sqlx::query("UPDATE identities SET current = 0 WHERE role = ?").bind(role).execute(&mut *conn).await?; |
| 315 | 171× | sqlx::query( |
| 316 | 171× | "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, ?, ?, ?, ?, 1, ?)", |
| 317 | | ) |
| 318 | 171× | .bind(identity.hash().to_hex()) |
| 319 | 171× | .bind(role) |
| 320 | 171× | .bind(&identity.name) |
| 321 | 171× | .bind(identity.encode()) |
| 322 | 171× | .bind(identity.previous.map(|k| k.to_hex())) |
| 323 | 171× | .bind(e.seq as i64) |
| 324 | 171× | .execute(&mut *conn) |
| 325 | 171× | .await?; |
| 326 | | } |
| 327 | 595× | "agent.added" => { |
| 328 | 58× | let Some(identity) = id(&p) else { return Ok(()) }; |
| 329 | 58× | if p.get("name").and_then(Json::as_str).is_none_or(str::is_empty) { |
| 330 | 0× | return Ok(()); |
| 331 | 58× | } |
| 332 | 348× | let s = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or("").to_string(); |
| 333 | 58× | sqlx::query( |
| 334 | 58× | "INSERT OR REPLACE INTO agents (name, key, owner, owner_name, kind, project, home, uid, learn_uid, scopes, created_ms, disabled_ms, seq) \ |
| 335 | 58× | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)", |
| 336 | | ) |
| 337 | 58× | .bind(s("name")) |
| 338 | 58× | .bind(identity.hash().to_hex()) |
| 339 | 58× | .bind(s("owner")) |
| 340 | 58× | .bind(s("owner_name")) |
| 341 | 58× | .bind(s("kind")) |
| 342 | 58× | .bind(s("project")) |
| 343 | 58× | .bind(s("home")) |
| 344 | 58× | .bind(p.get("uid").and_then(Json::as_i64)) |
| 345 | 58× | .bind(p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false)) |
| 346 | 58× | .bind(p.get("scopes").map(|v| v.to_string()).unwrap_or_else(|| "[]".into())) |
| 347 | 58× | .bind(e.at_ms as i64) |
| 348 | 58× | .bind(e.seq as i64) |
| 349 | 58× | .execute(&mut *conn) |
| 350 | 58× | .await?; |
| 351 | 58× | sqlx::query( |
| 352 | 58× | "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, 'agent', ?, ?, ?, 1, ?)", |
| 353 | | ) |
| 354 | 58× | .bind(identity.hash().to_hex()) |
| 355 | 58× | .bind(&identity.name) |
| 356 | 58× | .bind(identity.encode()) |
| 357 | 58× | .bind(identity.previous.map(|k| k.to_hex())) |
| 358 | 58× | .bind(e.seq as i64) |
| 359 | 58× | .execute(&mut *conn) |
| 360 | 58× | .await?; |
| 361 | | } |
| 362 | 537× | "agent.disabled" => { |
| 363 | 4× | sqlx::query("UPDATE agents SET disabled_ms = ? WHERE name = ?") |
| 364 | 4× | .bind(e.at_ms as i64) |
| 365 | 4× | .bind(p.get("name").and_then(Json::as_str)) |
| 366 | 4× | .execute(&mut *conn) |
| 367 | 4× | .await?; |
| 368 | | } |
| 369 | 533× | _ => {} |
| 370 | | } |
| 371 | 766× | Ok(()) |
| 372 | 42785× | } |
| 373 | |
|
| 374 | |
|
| 375 | 212× | pub fn identity_payload(identity: &Identity) -> Json { |
| 376 | 212× | serde_json::json!({ "key": identity.hash().to_hex(), "name": identity.name, "identity": hex::encode(identity.encode()) }) |
| 377 | 212× | } |
| 378 | |
|
| 379 | 1091× | fn identity_of(p: &Json) -> Result<Identity, String> { |
| 380 | 1091× | let b = p.get("identity").and_then(Json::as_str).and_then(|h| hex::decode(h).ok()).ok_or("no identity in the event")?; |
| 381 | 1091× | Identity::decode(&b).map_err(|e| format!("malformed identity: {e}")) |
| 382 | 1091× | } |
| 383 | |
|
| 384 | 382× | fn text(p: &Json, k: &str) -> Result<String, String> { |
| 385 | 382× | p.get(k).and_then(Json::as_str).map(String::from).ok_or_else(|| format!("no {k}")) |
| 386 | 382× | } |
| 387 | |
|
| 388 | 676× | fn self_signed(e: &Event, id: &Identity) -> Result<(), String> { |
| 389 | 676× | if e.auth.key != Some(id.hash().0) { |
| 390 | 1× | return Err("not signed by the identity it records".into()); |
| 391 | 675× | } |
| 392 | 675× | check_proof(e, id) |
| 393 | 676× | } |
| 394 | |
|
| 395 | |
|
| 396 | |
|
| 397 | 996× | fn check_proof(e: &Event, identity: &Identity) -> Result<(), String> { |
| 398 | 996× | let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?; |
| 399 | 996× | if proof.key() != identity.hash().0 { |
| 400 | 0× | return Err("the proof is by another key".into()); |
| 401 | 996× | } |
| 402 | 996× | let body = (proof.method == "cli").then(|| e.payload.as_deref().unwrap_or(b"")); |
| 403 | 996× | proof.verify(identity, body) |
| 404 | 996× | } |
| 405 | |
|
| 406 | |
|
| 407 | |
|
| 408 | |
|
| 409 | 231× | fn accept_successor(cur: &Identity, new: &Identity, p: &Json) -> Result<(), String> { |
| 410 | 231× | if new.ed25519_pk != cur.ed25519_pk || new.mldsa65_pk != cur.mldsa65_pk { |
| 411 | 0× | return Err("a successor with a fresh key pair needs `oxy identity rotate`'s attestation, not accepted in 0.1".into()); |
| 412 | 231× | } |
| 413 | 231× | let chain: Vec<Identity> = p |
| 414 | 231× | .get("chain") |
| 415 | 231× | .and_then(Json::as_array) |
| 416 | 231× | .map(|a| a.iter().filter_map(|h| h.as_str().and_then(|h| hex::decode(h).ok()).and_then(|b| Identity::decode(&b).ok())).collect()) |
| 417 | 231× | .unwrap_or_default(); |
| 418 | 231× | let mut at = new.clone(); |
| 419 | 231× | for _ in 0..=chain.len() { |
| 420 | 231× | match at.previous { |
| 421 | 231× | Some(prev) if prev == cur.hash() => return Ok(()), |
| 422 | 0× | Some(prev) => match chain.iter().find(|i| i.hash() == prev) { |
| 423 | 0× | Some(i) if i.ed25519_pk == cur.ed25519_pk => at = i.clone(), |
| 424 | 0× | _ => break, |
| 425 | | }, |
| 426 | 0× | None => break, |
| 427 | | } |
| 428 | | } |
| 429 | 0× | Err("does not succeed the recorded owner".into()) |
| 430 | 231× | } |
| 431 | |
|
| 432 | |
|
| 433 | |
|
| 434 | 255× | pub fn signed_event(pair: &crate::keys::KeyPair, actor: &str, kind: &str, payload: Json) -> crate::event::NewEvent { |
| 435 | 255× | let body = crate::event::canonical_json(&payload); |
| 436 | 255× | let proof = Proof::sign(pair, "cli", &body); |
| 437 | 255× | crate::event::NewEvent::system(kind, payload) |
| 438 | 255× | .by(actor, crate::event::Auth { key: Some(pair.key.0), method: Method::Signature, assurance: 2, proof: Some(proof.encode()) }) |
| 439 | 255× | } |