OXYGENHUB

Coverage / crates/spectra-core/src/principals.rs 89.3%

333 of 373 lines run, 46 of 110 functions · run #36 on main · run missed

1
//! Who is who (spec §8): the owner, the instance, and agents, each an Oxygen
2
//! identity; an agent is valid while the owner's current identity delegates
3
//! to its key (oxygen spec §14.2). Everything here is derived from the
4
//! ledger, and every claim in it was proven when it was recorded:
5
//!
6
//! - `identity.owner` and `identity.rotated` are signed by the identity they
7
//!   record, so only the holder of its secret key can name it the owner.
8
//!   A successor must keep the key pair and chain back, by `previous`, to
9
//!   the owner already known; a fresh key pair needs `oxy identity rotate`'s
10
//!   attestation, which 0.1 does not accept yet.
11
//! - `identity.instance` is signed by the instance key.
12
//! - `agent.added` and `agent.disabled` are signed by the owner, and an
13
//!   agent is added only while the owner's identity delegates to it.
14
//!
15
//! [`Principals`] replays these in ledger order, so `spectra admin verify`
16
//! checks every signed event against who was who at that moment.
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
/// The scopes a new agent gets (spec §8.4).
28
pub const DEFAULT_SCOPES: &[&str] = &["read", "say", "tasks", "claims", "decisions", "status", "search", "schedule:self"];
29
30
/// Who caused something.
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
    /// The `actor` events carry: `human`, `agent:NAME` or `system`.
40441×
    pub fn actor(&self) -> String {
41441×
        match self {
4266×
            Principal::Owner { .. } => "human".into(),
43368×
            Principal::Agent { name, .. } => format!("agent:{name}"),
447×
            Principal::Instance { .. } => "system".into(),
45
        }
46441×
    }
47
    /// How it is shown to people: `claude-oxygen · Andy McCall's agent`.
4815×
    pub fn display(&self) -> String {
4915×
        match self {
503×
            Principal::Owner { name, .. } => name.clone(),
5112×
            Principal::Agent { name, owner_name, .. } => format!("{name} · {owner_name}'s agent"),
520×
            Principal::Instance { .. } => "Spectra".into(),
53
        }
5415×
    }
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
/// The principals as of some point in the ledger.
70
#[derive(Clone, Debug, Default)]
71
pub struct Principals {
72
    /// The owner's identities, oldest first; the last is current.
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
    /// Replay every identity and agent event of the ledger.
81213×
    pub async fn load(ledger: &crate::ledger::Ledger) -> anyhow::Result<Principals> {
82213×
        let mut p = Principals::default();
83213×
        let mut from = 1;
84
        loop {
85426×
            let rows = ledger
86426×
                .events_of_kinds(
87426×
                    from,
88426×
                    &["identity.owner", "identity.rotated", "identity.instance", "agent.added", "agent.disabled", "agent.scoped"],
89426×
                    1000,
90426×
                )
91426×
                .await?;
92423×
            if rows.is_empty() {
93210×
                break;
94213×
            }
95840×
            for e in &rows {
96840×
                // Recorded facts were checked when written; `verify` checks them again.
97840×
                let _ = p.observe(e);
98840×
            }
99213×
            from = rows.last().map(|e| e.seq + 1).unwrap_or(from);
100
        }
101210×
        Ok(p)
102210×
    }
103
104
    /// The owner's current identity.
1051024×
    pub fn owner(&self) -> Option<&Identity> {
1061024×
        self.owner.last()
1071024×
    }
108
10929×
    pub fn instance(&self) -> Option<&Identity> {
11029×
        self.instance.as_ref()
11129×
    }
112
113
    /// The agent named `name`, whatever its state.
11431×
    pub fn agent_key(&self, name: &str) -> Option<KeyId> {
11531×
        self.by_name.get(name).copied()
11631×
    }
117
118
    /// Who `key` is at `at_ms`, if anyone may act with it then: the owner
119
    /// (any of its identities' KeyIds), the instance, or an agent that is
120
    /// not disabled and that the owner's current identity delegates to.
121343×
    pub fn principal(&self, key: &KeyId, at_ms: u64) -> Result<Principal, String> {
122737×
        if let Some(owner) = self.owner.iter().rev().find(|i| &i.hash() == key) {
123119×
            return Ok(Principal::Owner { key: *key, name: owner.name.clone() });
124224×
        }
125224×
        if self.instance.as_ref().is_some_and(|i| &i.hash() == key) {
1267×
            return Ok(Principal::Instance { key: *key });
127217×
        }
128217×
        let a = self.agents.get(key).ok_or("an unknown key")?;
129214×
        if a.disabled {
1306×
            return Err(format!("agent {} is disabled", a.name));
131208×
        }
132208×
        let owner = self.owner().ok_or("no owner is recorded")?;
133208×
        if !owner.delegates_to(key, at_ms) {
1341×
            return Err(match owner.delegate(key) {
1351×
                Some(d) if d.expires.is_some_and(|x| at_ms > x) => format!("agent {}'s delegation from {} has expired", a.name, owner.name),
1360×
                Some(_) => format!("{}'s delegation to agent {} does not include `changes`", owner.name, a.name),
1370×
                None => format!("{}'s current identity does not delegate to agent {}", owner.name, a.name),
138
            });
139207×
        }
140207×
        Ok(Principal::Agent {
141207×
            name: a.name.clone(),
142207×
            key: *key,
143207×
            owner_name: a.owner_name.clone(),
144207×
            uid: a.uid,
145207×
            learn_uid: a.learn_uid,
146207×
            project: a.project.clone(),
147207×
            scopes: a.scopes.clone(),
148207×
        })
149343×
    }
150
151
    /// The identity behind `key`, for checking its signatures.
152279×
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
153279×
        self.owner
154279×
            .iter()
155710×
            .find(|i| &i.hash() == key)
156279×
            .or_else(|| self.instance.as_ref().filter(|i| &i.hash() == key))
157279×
            .or_else(|| self.agents.get(key).map(|a| &a.identity))
158279×
    }
159
160
    /// Take one event into account, checking what it claims first.
1611000×
    pub fn observe(&mut self, e: &Event) -> Result<(), String> {
1621000×
        let p = e.json();
1631000×
        match e.kind.as_str() {
1641000×
            "identity.owner" => {
165242×
                if !self.owner.is_empty() {
1661×
                    return Err("an owner is already recorded".into());
167241×
                }
168241×
                let id = identity_of(&p)?;
169241×
                self_signed(e, &id)?;
170241×
                self.owner.push(id);
171
            }
172758×
            "identity.rotated" => {
173263×
                let new = identity_of(&p)?;
174263×
                let cur = self.owner().ok_or("no owner to succeed")?.clone();
175263×
                accept_successor(&cur, &new, &p)?;
176263×
                self_signed(e, &new)?;
177262×
                self.owner.push(new);
178
            }
179495×
            "identity.instance" => {
180244×
                let id = identity_of(&p)?;
181244×
                self_signed(e, &id)?;
182244×
                self.instance = Some(id);
183
            }
184251×
            "agent.added" => {
185223×
                let id = identity_of(&p)?;
186223×
                let key = id.hash();
187223×
                let owner = self.owner_signed(e)?;
188223×
                if !owner.delegates_to(&key, e.hlc.wall_ms) {
1891×
                    return Err("added without the owner's delegation to its key".into());
190222×
                }
191222×
                let name = text(&p, "name")?;
192222×
                if self.by_name.get(&name).is_some_and(|k| *k != key) {
1930×
                    return Err(format!("agent {name} already exists with another key"));
194222×
                }
195222×
                self.by_name.insert(name.clone(), key);
196222×
                self.agents.insert(
197222×
                    key,
198
                    AgentRec {
199222×
                        name,
200222×
                        identity: id,
201222×
                        owner_name: owner.name.clone(),
202222×
                        uid: p.get("uid").and_then(Json::as_u64).map(|u| u as u32),
203222×
                        learn_uid: p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false),
204222×
                        project: text(&p, "project")?,
205222×
                        scopes: p
206222×
                            .get("scopes")
207222×
                            .and_then(Json::as_array)
2081680×
                            .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())
209222×
                            .unwrap_or_default(),
210
                        disabled: false,
211
                    },
212
                );
213
            }
21428×
            "agent.uid_bound" => {
215
                // The daemon binds a learning agent to the uid of its first
216
                // signed connection; covered by the next checkpoint.
2171×
                let name = text(&p, "name")?;
2181×
                let uid = p.get("uid").and_then(Json::as_u64).ok_or("no uid")? as u32;
2191×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
2201×
                if let Some(a) = self.agents.get_mut(&key) {
2211×
                    if a.uid.is_none() {
2221×
                        a.uid = Some(uid);
2231×
                    }
2240×
                }
225
            }
22627×
            "agent.disabled" => {
22711×
                self.owner_signed(e)?;
22811×
                let name = text(&p, "name")?;
22911×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
23011×
                if let Some(a) = self.agents.get_mut(&key) {
23111×
                    a.disabled = true;
23211×
                }
233
            }
234
            // The owner grants or takes back one scope (spec §8.4), such
235
            // as `channel:NAME` to post in another project's channel.
23616×
            "agent.scoped" => {
23716×
                self.owner_signed(e)?;
23816×
                let name = text(&p, "name")?;
23916×
                let scope = text(&p, "scope")?;
24016×
                if !grantable(&scope) {
2410×
                    return Err(format!("{scope} is not a scope an agent may be given"));
24216×
                }
24316×
                let grant = p.get("grant").and_then(Json::as_bool).unwrap_or(true);
24416×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
24516×
                if let Some(a) = self.agents.get_mut(&key) {
246132×
                    a.scopes.retain(|s| s != &scope);
24716×
                    if grant {
24812×
                        a.scopes.push(scope);
24912×
                    }
2500×
                }
251
            }
2520×
            _ => {}
253
        }
254997×
        Ok(())
2551000×
    }
256
257
    /// Check that `e` is signed by the owner's current identity; returns it.
258250×
    fn owner_signed(&self, e: &Event) -> Result<Identity, String> {
259250×
        let owner = self.owner().ok_or("no owner is recorded")?.clone();
260250×
        if e.auth.key != Some(owner.hash().0) {
2610×
            return Err("not signed by the owner's current identity".into());
262250×
        }
263250×
        check_proof(e, &owner)?;
264250×
        Ok(owner)
265250×
    }
266
267
    /// An event from a Radar session: its proof is the owner's signed
268
    /// request for the sign-in link, so it must verify against the owner,
269
    /// and only the owner acts this way.
2700×
    pub fn check_session(&self, e: &Event) -> Result<(), String> {
2710×
        let key = crate::identity::KeyId(e.auth.key.ok_or("a session event names no key")?);
2720×
        if !matches!(self.principal(&key, e.hlc.wall_ms)?, Principal::Owner { .. }) || e.actor != "human" {
2730×
            return Err("only the owner acts through a Radar session".into());
2740×
        }
2750×
        let identity = self.identity(&key).ok_or("an unknown key")?;
2760×
        let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
2770×
        if proof.key() != key.0 || proof.method != "POST /radar/link" {
2780×
            return Err("the session's proof is not the owner's sign-in request".into());
2790×
        }
2800×
        proof.verify(identity, None)
2810×
    }
282
283
    /// Check a signed event's proof against the principal its key was at
284
    /// the event's time.
285126×
    pub fn check_signed(&self, e: &Event) -> Result<(), String> {
286126×
        let key = crate::identity::KeyId(e.auth.key.ok_or("signed, but names no key")?);
287126×
        let who = self.principal(&key, e.hlc.wall_ms)?;
288
        // The actor an event names must be the principal that signed it:
289
        // an agent's key never makes an event in another's name.
290124×
        if who.actor() != e.actor {
2912×
            return Err(format!("names {} as its actor but is signed by {}", e.actor, who.display()));
292122×
        }
293122×
        let identity = self.identity(&key).ok_or("an unknown key")?;
294122×
        check_proof(e, identity)
295126×
    }
296
}
297
298
impl KeyResolver for Principals {
299473×
    fn check(&mut self, e: &Event) -> Result<(), String> {
300473×
        match e.kind.as_str() {
301473×
            "identity.owner" | "identity.rotated" | "identity.instance" | "agent.added" | "agent.disabled" | "agent.scoped" => {
302161×
                if e.auth.method != Method::Signature {
3032×
                    return Err(format!("{} must be signed", e.kind));
304159×
                }
305159×
                self.observe(e)
306
            }
307312×
            "agent.uid_bound" => self.observe(e),
308311×
            _ if matches!(e.auth.method, Method::Signature | Method::Passkey) => self.check_signed(e),
309185×
            _ if e.auth.method == Method::Session => self.check_session(e),
310185×
            _ => Ok(()),
311
        }
312473×
    }
313
}
314
315
/// Apply identity and agent events to the projection tables.
31642882×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
31742882×
    if e.kind == "agent.uid_bound" {
3181×
        let p = e.json();
3191×
        sqlx::query("UPDATE agents SET uid = ? WHERE name = ? AND uid IS NULL")
3201×
            .bind(p.get("uid").and_then(Json::as_i64))
3211×
            .bind(p.get("name").and_then(Json::as_str))
3221×
            .execute(&mut *conn)
3231×
            .await?;
3241×
        return Ok(());
32542881×
    }
326
    // Who is who is only ever said by a signature; `verify` checks which.
32742881×
    if e.auth.method != Method::Signature {
32842033×
        return Ok(());
329848×
    }
330848×
    let p = e.json();
331848×
    let id = |p: &Json| identity_of(p).ok();
332848×
    match e.kind.as_str() {
333848×
        "identity.owner" | "identity.rotated" | "identity.instance" => {
334179×
            let Some(identity) = id(&p) else { return Ok(()) };
335179×
            let role = if e.kind == "identity.instance" { "instance" } else { "owner" };
336179×
            sqlx::query("UPDATE identities SET current = 0 WHERE role = ?").bind(role).execute(&mut *conn).await?;
337179×
            sqlx::query(
338179×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, ?, ?, ?, ?, 1, ?)",
339
            )
340179×
            .bind(identity.hash().to_hex())
341179×
            .bind(role)
342179×
            .bind(&identity.name)
343179×
            .bind(identity.encode())
344179×
            .bind(identity.previous.map(|k| k.to_hex()))
345179×
            .bind(e.seq as i64)
346179×
            .execute(&mut *conn)
347179×
            .await?;
348
        }
349669×
        "agent.added" => {
35063×
            let Some(identity) = id(&p) else { return Ok(()) };
35163×
            if p.get("name").and_then(Json::as_str).is_none_or(str::is_empty) {
3520×
                return Ok(());
35363×
            }
354378×
            let s = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or("").to_string();
35563×
            sqlx::query(
35663×
                "INSERT OR REPLACE INTO agents (name, key, owner, owner_name, kind, project, home, uid, learn_uid, scopes, created_ms, disabled_ms, seq) \
35763×
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
358
            )
35963×
            .bind(s("name"))
36063×
            .bind(identity.hash().to_hex())
36163×
            .bind(s("owner"))
36263×
            .bind(s("owner_name"))
36363×
            .bind(s("kind"))
36463×
            .bind(s("project"))
36563×
            .bind(s("home"))
36663×
            .bind(p.get("uid").and_then(Json::as_i64))
36763×
            .bind(p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false))
36863×
            .bind(p.get("scopes").map(|v| v.to_string()).unwrap_or_else(|| "[]".into()))
36963×
            .bind(e.at_ms as i64)
37063×
            .bind(e.seq as i64)
37163×
            .execute(&mut *conn)
37263×
            .await?;
37363×
            sqlx::query(
37463×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, 'agent', ?, ?, ?, 1, ?)",
375
            )
37663×
            .bind(identity.hash().to_hex())
37763×
            .bind(&identity.name)
37863×
            .bind(identity.encode())
37963×
            .bind(identity.previous.map(|k| k.to_hex()))
38063×
            .bind(e.seq as i64)
38163×
            .execute(&mut *conn)
38263×
            .await?;
383
        }
384606×
        "agent.disabled" => {
3854×
            sqlx::query("UPDATE agents SET disabled_ms = ? WHERE name = ?")
3864×
                .bind(e.at_ms as i64)
3874×
                .bind(p.get("name").and_then(Json::as_str))
3884×
                .execute(&mut *conn)
3894×
                .await?;
390
        }
391602×
        "agent.scoped" if e.actor == "human" => {
3927×
            let (Some(name), Some(scope)) = (p.get("name").and_then(Json::as_str), p.get("scope").and_then(Json::as_str)) else {
3930×
                return Ok(());
394
            };
3957×
            if !grantable(scope) {
3960×
                return Ok(());
3977×
            }
3987×
            let grant = p.get("grant").and_then(Json::as_bool).unwrap_or(true);
3997×
            let current: Option<String> =
4007×
                sqlx::query_scalar("SELECT scopes FROM agents WHERE name = ?").bind(name).fetch_optional(&mut *conn).await?;
4017×
            let mut scopes: Vec<String> = current.and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
40259×
            scopes.retain(|s| s != scope);
4037×
            if grant {
4044×
                scopes.push(scope.to_string());
4054×
            }
4067×
            sqlx::query("UPDATE agents SET scopes = ? WHERE name = ?")
4077×
                .bind(serde_json::to_string(&scopes).unwrap_or_default())
4087×
                .bind(name)
4097×
                .execute(&mut *conn)
4107×
                .await?;
411
        }
412595×
        _ => {}
413
    }
414848×
    Ok(())
41542882×
}
416
417
/// A scope the owner may give an agent (spec §8.4): never the owner's own
418
/// authority, only reach.
41927×
pub fn grantable(scope: &str) -> bool {
42027×
    match scope.strip_prefix("channel:") {
421273×
        Some(ch) => !ch.is_empty() && ch.len() <= 64 && ch.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'),
4220×
        None => matches!(scope, "projects:all" | "schedule:any" | "webhooks:read"),
423
    }
42427×
}
425
426
/// The payload of an identity event for `identity`.
427214×
pub fn identity_payload(identity: &Identity) -> Json {
428214×
    serde_json::json!({ "key": identity.hash().to_hex(), "name": identity.name, "identity": hex::encode(identity.encode()) })
429214×
}
430
4311213×
fn identity_of(p: &Json) -> Result<Identity, String> {
4321213×
    let b = p.get("identity").and_then(Json::as_str).and_then(|h| hex::decode(h).ok()).ok_or("no identity in the event")?;
4331213×
    Identity::decode(&b).map_err(|e| format!("malformed identity: {e}"))
4341213×
}
435
436488×
fn text(p: &Json, k: &str) -> Result<String, String> {
437488×
    p.get(k).and_then(Json::as_str).map(String::from).ok_or_else(|| format!("no {k}"))
438488×
}
439
440748×
fn self_signed(e: &Event, id: &Identity) -> Result<(), String> {
441748×
    if e.auth.key != Some(id.hash().0) {
4421×
        return Err("not signed by the identity it records".into());
443747×
    }
444747×
    check_proof(e, id)
445748×
}
446
447
/// The event's proof verifies against `identity`, and a CLI proof covers
448
/// exactly the event's payload.
4491119×
fn check_proof(e: &Event, identity: &Identity) -> Result<(), String> {
4501119×
    let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
4511119×
    if proof.key() != identity.hash().0 {
4520×
        return Err("the proof is by another key".into());
4531119×
    }
4541119×
    let body = (proof.method == "cli").then(|| e.payload.as_deref().unwrap_or(b""));
4551119×
    proof.verify(identity, body)
4561119×
}
457
458
/// A successor of the owner must keep the key pair and chain back to the
459
/// current identity through `previous` (the intermediate identities, if
460
/// any, are carried in the event as `chain`).
461263×
fn accept_successor(cur: &Identity, new: &Identity, p: &Json) -> Result<(), String> {
462263×
    if new.ed25519_pk != cur.ed25519_pk || new.mldsa65_pk != cur.mldsa65_pk {
4630×
        return Err("a successor with a fresh key pair needs `oxy identity rotate`'s attestation, not accepted in 0.1".into());
464263×
    }
465263×
    let chain: Vec<Identity> = p
466263×
        .get("chain")
467263×
        .and_then(Json::as_array)
468263×
        .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())
469263×
        .unwrap_or_default();
470263×
    let mut at = new.clone();
471263×
    for _ in 0..=chain.len() {
472263×
        match at.previous {
473263×
            Some(prev) if prev == cur.hash() => return Ok(()),
4740×
            Some(prev) => match chain.iter().find(|i| i.hash() == prev) {
4750×
                Some(i) if i.ed25519_pk == cur.ed25519_pk => at = i.clone(),
4760×
                _ => break,
477
            },
4780×
            None => break,
479
        }
480
    }
4810×
    Err("does not succeed the recorded owner".into())
482263×
}
483
484
/// An event signed by `pair` from the command line: its proof covers the
485
/// canonical payload, so the event's content is bound to the signature.
486267×
pub fn signed_event(pair: &crate::keys::KeyPair, actor: &str, kind: &str, payload: Json) -> crate::event::NewEvent {
487267×
    let body = crate::event::canonical_json(&payload);
488267×
    let proof = Proof::sign(pair, "cli", &body);
489267×
    crate::event::NewEvent::system(kind, payload)
490267×
        .by(actor, crate::event::Auth { key: Some(pair.key.0), method: Method::Signature, assurance: 2, proof: Some(proof.encode()) })
491267×
}