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