OXYGENHUB

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

301 of 326 lines run, 42 of 100 functions · run #22 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::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
/// 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
/// The Oxygen delegation scope an agent's key needs from its owner.
31
pub const DELEGATION_SCOPE: Scope = Scope::CHANGES;
32
33
/// Who caused something.
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
    /// The `actor` events carry: `human`, `agent:NAME` or `system`.
43321×
    pub fn actor(&self) -> String {
44321×
        match self {
4553×
            Principal::Owner { .. } => "human".into(),
46260×
            Principal::Agent { name, .. } => format!("agent:{name}"),
478×
            Principal::Instance { .. } => "system".into(),
48
        }
49321×
    }
50
    /// How it is shown to people: `claude-oxygen · Andy McCall's agent`.
5125×
    pub fn display(&self) -> String {
5225×
        match self {
5315×
            Principal::Owner { name, .. } => name.clone(),
5410×
            Principal::Agent { name, owner_name, .. } => format!("{name} · {owner_name}'s agent"),
550×
            Principal::Instance { .. } => "Spectra".into(),
56
        }
5725×
    }
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
/// The principals as of some point in the ledger.
73
#[derive(Clone, Debug, Default)]
74
pub struct Principals {
75
    /// The owner's identities, oldest first; the last is current.
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
    /// Replay every identity and agent event of the ledger.
84148×
    pub async fn load(ledger: &crate::ledger::Ledger) -> anyhow::Result<Principals> {
85148×
        let mut p = Principals::default();
86148×
        let mut from = 1;
87
        loop {
88296×
            let rows = ledger
89296×
                .events_of_kinds(from, &["identity.owner", "identity.rotated", "identity.instance", "agent.added", "agent.disabled"], 1000)
90296×
                .await?;
91294×
            if rows.is_empty() {
92146×
                break;
93148×
            }
94512×
            for e in &rows {
95512×
                // Recorded facts were checked when written; `verify` checks them again.
96512×
                let _ = p.observe(e);
97512×
            }
98148×
            from = rows.last().map(|e| e.seq + 1).unwrap_or(from);
99
        }
100146×
        Ok(p)
101146×
    }
102
103
    /// The owner's current identity.
104670×
    pub fn owner(&self) -> Option<&Identity> {
105670×
        self.owner.last()
106670×
    }
107
10832×
    pub fn instance(&self) -> Option<&Identity> {
10932×
        self.instance.as_ref()
11032×
    }
111
112
    /// The agent named `name`, whatever its state.
11321×
    pub fn agent_key(&self, name: &str) -> Option<KeyId> {
11421×
        self.by_name.get(name).copied()
11521×
    }
116
117
    /// Who `key` is at `at_ms`, if anyone may act with it then: the owner
118
    /// (any of its identities' KeyIds), the instance, or an agent that is
119
    /// not disabled and that the owner's current identity delegates to.
120267×
    pub fn principal(&self, key: &KeyId, at_ms: u64) -> Result<Principal, String> {
121534×
        if let Some(owner) = self.owner.iter().rev().find(|i| &i.hash() == key) {
12295×
            return Ok(Principal::Owner { key: *key, name: owner.name.clone() });
123172×
        }
124172×
        if self.instance.as_ref().is_some_and(|i| &i.hash() == key) {
1258×
            return Ok(Principal::Instance { key: *key });
126164×
        }
127164×
        let a = self.agents.get(key).ok_or("an unknown key")?;
128161×
        if a.disabled {
1296×
            return Err(format!("agent {} is disabled", a.name));
130155×
        }
131155×
        let owner = self.owner().ok_or("no owner is recorded")?;
132155×
        if !owner.delegates_to(key, DELEGATION_SCOPE, at_ms) {
1331×
            return Err(match owner.delegate(key) {
1341×
                Some(d) if d.expires.is_some_and(|x| at_ms > x) => format!("agent {}'s delegation from {} has expired", a.name, owner.name),
1350×
                Some(_) => format!("{}'s delegation to agent {} does not include `changes`", owner.name, a.name),
1360×
                None => format!("{}'s current identity does not delegate to agent {}", owner.name, a.name),
137
            });
138154×
        }
139154×
        Ok(Principal::Agent {
140154×
            name: a.name.clone(),
141154×
            key: *key,
142154×
            owner_name: a.owner_name.clone(),
143154×
            uid: a.uid,
144154×
            learn_uid: a.learn_uid,
145154×
            project: a.project.clone(),
146154×
            scopes: a.scopes.clone(),
147154×
        })
148267×
    }
149
150
    /// The identity behind `key`, for checking its signatures.
151208×
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
152208×
        self.owner
153208×
            .iter()
154489×
            .find(|i| &i.hash() == key)
155208×
            .or_else(|| self.instance.as_ref().filter(|i| &i.hash() == key))
156208×
            .or_else(|| self.agents.get(key).map(|a| &a.identity))
157208×
    }
158
159
    /// Take one event into account, checking what it claims first.
160662×
    pub fn observe(&mut self, e: &Event) -> Result<(), String> {
161662×
        let p = e.json();
162662×
        match e.kind.as_str() {
163662×
            "identity.owner" => {
164178×
                if !self.owner.is_empty() {
1651×
                    return Err("an owner is already recorded".into());
166177×
                }
167177×
                let id = identity_of(&p)?;
168177×
                self_signed(e, &id)?;
169177×
                self.owner.push(id);
170
            }
171484×
            "identity.rotated" => {
172160×
                let new = identity_of(&p)?;
173160×
                let cur = self.owner().ok_or("no owner to succeed")?.clone();
174160×
                accept_successor(&cur, &new, &p)?;
175160×
                self_signed(e, &new)?;
176159×
                self.owner.push(new);
177
            }
178324×
            "identity.instance" => {
179180×
                let id = identity_of(&p)?;
180180×
                self_signed(e, &id)?;
181180×
                self.instance = Some(id);
182
            }
183144×
            "agent.added" => {
184133×
                let id = identity_of(&p)?;
185133×
                let key = id.hash();
186133×
                let owner = self.owner_signed(e)?;
187133×
                if !owner.delegates_to(&key, DELEGATION_SCOPE, e.hlc.wall_ms) {
1881×
                    return Err("added without the owner's delegation to its key".into());
189132×
                }
190132×
                let name = text(&p, "name")?;
191132×
                if self.by_name.get(&name).is_some_and(|k| *k != key) {
1920×
                    return Err(format!("agent {name} already exists with another key"));
193132×
                }
194132×
                self.by_name.insert(name.clone(), key);
195132×
                self.agents.insert(
196132×
                    key,
197
                    AgentRec {
198132×
                        name,
199132×
                        identity: id,
200132×
                        owner_name: owner.name.clone(),
201132×
                        uid: p.get("uid").and_then(Json::as_u64).map(|u| u as u32),
202132×
                        learn_uid: p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false),
203132×
                        project: text(&p, "project")?,
204132×
                        scopes: p
205132×
                            .get("scopes")
206132×
                            .and_then(Json::as_array)
207960×
                            .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())
208132×
                            .unwrap_or_default(),
209
                        disabled: false,
210
                    },
211
                );
212
            }
21311×
            "agent.uid_bound" => {
214
                // The daemon binds a learning agent to the uid of its first
215
                // signed connection; covered by the next checkpoint.
2161×
                let name = text(&p, "name")?;
2171×
                let uid = p.get("uid").and_then(Json::as_u64).ok_or("no uid")? as u32;
2181×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
2191×
                if let Some(a) = self.agents.get_mut(&key) {
2201×
                    if a.uid.is_none() {
2211×
                        a.uid = Some(uid);
2221×
                    }
2230×
                }
224
            }
22510×
            "agent.disabled" => {
22610×
                self.owner_signed(e)?;
22710×
                let name = text(&p, "name")?;
22810×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
22910×
                if let Some(a) = self.agents.get_mut(&key) {
23010×
                    a.disabled = true;
23110×
                }
232
            }
2330×
            _ => {}
234
        }
235659×
        Ok(())
236662×
    }
237
238
    /// Check that `e` is signed by the owner's current identity; returns it.
239143×
    fn owner_signed(&self, e: &Event) -> Result<Identity, String> {
240143×
        let owner = self.owner().ok_or("no owner is recorded")?.clone();
241143×
        if e.auth.key != Some(owner.hash().0) {
2420×
            return Err("not signed by the owner's current identity".into());
243143×
        }
244143×
        check_proof(e, &owner)?;
245143×
        Ok(owner)
246143×
    }
247
248
    /// An event from a Radar session: its proof is the owner's signed
249
    /// request for the sign-in link, so it must verify against the owner,
250
    /// and only the owner acts this way.
2513×
    pub fn check_session(&self, e: &Event) -> Result<(), String> {
2523×
        let key = oxy_core::hash::ObjectRef(e.auth.key.ok_or("a session event names no key")?);
2533×
        if !matches!(self.principal(&key, e.hlc.wall_ms)?, Principal::Owner { .. }) || e.actor != "human" {
2540×
            return Err("only the owner acts through a Radar session".into());
2553×
        }
2563×
        let identity = self.identity(&key).ok_or("an unknown key")?;
2573×
        let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
2583×
        if proof.key() != key.0 || proof.method != "POST /radar/link" {
2590×
            return Err("the session's proof is not the owner's sign-in request".into());
2603×
        }
2613×
        proof.verify(identity, None)
2623×
    }
263
264
    /// Check a signed event's proof against the principal its key was at
265
    /// the event's time.
26699×
    pub fn check_signed(&self, e: &Event) -> Result<(), String> {
26799×
        let key = oxy_core::hash::ObjectRef(e.auth.key.ok_or("signed, but names no key")?);
26899×
        let who = self.principal(&key, e.hlc.wall_ms)?;
269
        // The actor an event names must be the principal that signed it:
270
        // an agent's key never makes an event in another's name.
27197×
        if who.actor() != e.actor {
2722×
            return Err(format!("names {} as its actor but is signed by {}", e.actor, who.display()));
27395×
        }
27495×
        let identity = self.identity(&key).ok_or("an unknown key")?;
27595×
        check_proof(e, identity)
27699×
    }
277
}
278
279
impl KeyResolver for Principals {
280441×
    fn check(&mut self, e: &Event) -> Result<(), String> {
281441×
        match e.kind.as_str() {
282441×
            "identity.owner" | "identity.rotated" | "identity.instance" | "agent.added" | "agent.disabled" => {
283151×
                if e.auth.method != Method::Signature {
2842×
                    return Err(format!("{} must be signed", e.kind));
285149×
                }
286149×
                self.observe(e)
287
            }
288290×
            "agent.uid_bound" => self.observe(e),
289289×
            _ if matches!(e.auth.method, Method::Signature | Method::Passkey) => self.check_signed(e),
290190×
            _ if e.auth.method == Method::Session => self.check_session(e),
291187×
            _ => Ok(()),
292
        }
293441×
    }
294
}
295
296
/// Apply identity and agent events to the projection tables.
29742619×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
29842619×
    if e.kind == "agent.uid_bound" {
2991×
        let p = e.json();
3001×
        sqlx::query("UPDATE agents SET uid = ? WHERE name = ? AND uid IS NULL")
3011×
            .bind(p.get("uid").and_then(Json::as_i64))
3021×
            .bind(p.get("name").and_then(Json::as_str))
3031×
            .execute(&mut *conn)
3041×
            .await?;
3051×
        return Ok(());
30642618×
    }
307
    // Who is who is only ever said by a signature; `verify` checks which.
30842618×
    if e.auth.method != Method::Signature {
30941991×
        return Ok(());
310627×
    }
311627×
    let p = e.json();
312627×
    let id = |p: &Json| identity_of(p).ok();
313627×
    match e.kind.as_str() {
314627×
        "identity.owner" | "identity.rotated" | "identity.instance" => {
315149×
            let Some(identity) = id(&p) else { return Ok(()) };
316149×
            let role = if e.kind == "identity.instance" { "instance" } else { "owner" };
317149×
            sqlx::query("UPDATE identities SET current = 0 WHERE role = ?").bind(role).execute(&mut *conn).await?;
318149×
            sqlx::query(
319149×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, ?, ?, ?, ?, 1, ?)",
320
            )
321149×
            .bind(identity.hash().to_hex())
322149×
            .bind(role)
323149×
            .bind(&identity.name)
324149×
            .bind(identity.encode())
325149×
            .bind(identity.previous.map(|k| k.to_hex()))
326149×
            .bind(e.seq as i64)
327149×
            .execute(&mut *conn)
328149×
            .await?;
329
        }
330478×
        "agent.added" => {
33149×
            let Some(identity) = id(&p) else { return Ok(()) };
33249×
            if p.get("name").and_then(Json::as_str).is_none_or(str::is_empty) {
3330×
                return Ok(());
33449×
            }
335294×
            let s = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or("").to_string();
33649×
            sqlx::query(
33749×
                "INSERT OR REPLACE INTO agents (name, key, owner, owner_name, kind, project, home, uid, learn_uid, scopes, created_ms, disabled_ms, seq) \
33849×
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
339
            )
34049×
            .bind(s("name"))
34149×
            .bind(identity.hash().to_hex())
34249×
            .bind(s("owner"))
34349×
            .bind(s("owner_name"))
34449×
            .bind(s("kind"))
34549×
            .bind(s("project"))
34649×
            .bind(s("home"))
34749×
            .bind(p.get("uid").and_then(Json::as_i64))
34849×
            .bind(p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false))
34949×
            .bind(p.get("scopes").map(|v| v.to_string()).unwrap_or_else(|| "[]".into()))
35049×
            .bind(e.at_ms as i64)
35149×
            .bind(e.seq as i64)
35249×
            .execute(&mut *conn)
35349×
            .await?;
35449×
            sqlx::query(
35549×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, 'agent', ?, ?, ?, 1, ?)",
356
            )
35749×
            .bind(identity.hash().to_hex())
35849×
            .bind(&identity.name)
35949×
            .bind(identity.encode())
36049×
            .bind(identity.previous.map(|k| k.to_hex()))
36149×
            .bind(e.seq as i64)
36249×
            .execute(&mut *conn)
36349×
            .await?;
364
        }
365429×
        "agent.disabled" => {
3664×
            sqlx::query("UPDATE agents SET disabled_ms = ? WHERE name = ?")
3674×
                .bind(e.at_ms as i64)
3684×
                .bind(p.get("name").and_then(Json::as_str))
3694×
                .execute(&mut *conn)
3704×
                .await?;
371
        }
372425×
        _ => {}
373
    }
374627×
    Ok(())
37542619×
}
376
377
/// The payload of an identity event for `identity`.
378193×
pub fn identity_payload(identity: &Identity) -> Json {
379193×
    serde_json::json!({ "key": identity.hash().to_hex(), "name": identity.name, "identity": hex::encode(identity.encode()) })
380193×
}
381
382848×
fn identity_of(p: &Json) -> Result<Identity, String> {
383848×
    let b = p.get("identity").and_then(Json::as_str).and_then(|h| hex::decode(h).ok()).ok_or("no identity in the event")?;
384848×
    Identity::decode(&b).map_err(|e| format!("malformed identity: {e}"))
385848×
}
386
387275×
fn text(p: &Json, k: &str) -> Result<String, String> {
388275×
    p.get(k).and_then(Json::as_str).map(String::from).ok_or_else(|| format!("no {k}"))
389275×
}
390
391517×
fn self_signed(e: &Event, id: &Identity) -> Result<(), String> {
392517×
    if e.auth.key != Some(id.hash().0) {
3931×
        return Err("not signed by the identity it records".into());
394516×
    }
395516×
    check_proof(e, id)
396517×
}
397
398
/// The event's proof verifies against `identity`, and a CLI proof covers
399
/// exactly the event's payload.
400754×
fn check_proof(e: &Event, identity: &Identity) -> Result<(), String> {
401754×
    let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
402754×
    if proof.key() != identity.hash().0 {
4030×
        return Err("the proof is by another key".into());
404754×
    }
405754×
    let body = (proof.method == "cli").then(|| e.payload.as_deref().unwrap_or(b""));
406754×
    proof.verify(identity, body)
407754×
}
408
409
/// A successor of the owner must keep the key pair and chain back to the
410
/// current identity through `previous` (the intermediate identities, if
411
/// any, are carried in the event as `chain`).
412160×
fn accept_successor(cur: &Identity, new: &Identity, p: &Json) -> Result<(), String> {
413160×
    if new.ed25519_pk != cur.ed25519_pk || new.mldsa65_pk != cur.mldsa65_pk {
4140×
        return Err("a successor with a fresh key pair needs `oxy identity rotate`'s attestation, not accepted in 0.1".into());
415160×
    }
416160×
    let chain: Vec<Identity> = p
417160×
        .get("chain")
418160×
        .and_then(Json::as_array)
419160×
        .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())
420160×
        .unwrap_or_default();
421160×
    let mut at = new.clone();
422160×
    for _ in 0..=chain.len() {
423160×
        match at.previous {
424160×
            Some(prev) if prev == cur.hash() => return Ok(()),
4250×
            Some(prev) => match chain.iter().find(|i| i.hash() == prev) {
4260×
                Some(i) if i.ed25519_pk == cur.ed25519_pk => at = i.clone(),
4270×
                _ => break,
428
            },
4290×
            None => break,
430
        }
431
    }
4320×
    Err("does not succeed the recorded owner".into())
433160×
}
434
435
/// An event signed by `pair` from the command line: its proof covers the
436
/// canonical payload, so the event's content is bound to the signature.
437225×
pub fn signed_event(pair: &crate::keys::KeyPair, actor: &str, kind: &str, payload: Json) -> crate::event::NewEvent {
438225×
    let body = crate::event::canonical_json(&payload);
439225×
    let proof = Proof::sign(pair, "cli", &body);
440225×
    crate::event::NewEvent::system(kind, payload)
441225×
        .by(actor, crate::event::Auth { key: Some(pair.key.0), method: Method::Signature, assurance: 2, proof: Some(proof.encode()) })
442225×
}