OXYGENHUB

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

284 of 313 lines run, 40 of 98 functions · run #11 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`.
43236×
    pub fn actor(&self) -> String {
44236×
        match self {
4521×
            Principal::Owner { .. } => "human".into(),
46215×
            Principal::Agent { name, .. } => format!("agent:{name}"),
470×
            Principal::Instance { .. } => "system".into(),
48
        }
49236×
    }
50
    /// How it is shown to people: `claude-oxygen · Andy McCall's agent`.
518×
    pub fn display(&self) -> String {
528×
        match self {
530×
            Principal::Owner { name, .. } => name.clone(),
548×
            Principal::Agent { name, owner_name, .. } => format!("{name} · {owner_name}'s agent"),
550×
            Principal::Instance { .. } => "Spectra".into(),
56
        }
578×
    }
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.
8485×
    pub async fn load(ledger: &crate::ledger::Ledger) -> anyhow::Result<Principals> {
8585×
        let mut p = Principals::default();
8685×
        let mut from = 1;
87
        loop {
88170×
            let rows = ledger
89170×
                .events_of_kinds(from, &["identity.owner", "identity.rotated", "identity.instance", "agent.added", "agent.disabled"], 1000)
90170×
                .await?;
91169×
            if rows.is_empty() {
9284×
                break;
9385×
            }
94304×
            for e in &rows {
95304×
                // Recorded facts were checked when written; `verify` checks them again.
96304×
                let _ = p.observe(e);
97304×
            }
9885×
            from = rows.last().map(|e| e.seq + 1).unwrap_or(from);
99
        }
10084×
        Ok(p)
10184×
    }
102
103
    /// The owner's current identity.
104330×
    pub fn owner(&self) -> Option<&Identity> {
105330×
        self.owner.last()
106330×
    }
107
1080×
    pub fn instance(&self) -> Option<&Identity> {
1090×
        self.instance.as_ref()
1100×
    }
111
112
    /// The agent named `name`, whatever its state.
11316×
    pub fn agent_key(&self, name: &str) -> Option<KeyId> {
11416×
        self.by_name.get(name).copied()
11516×
    }
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.
120144×
    pub fn principal(&self, key: &KeyId, at_ms: u64) -> Result<Principal, String> {
121343×
        if let Some(owner) = self.owner.iter().rev().find(|i| &i.hash() == key) {
12225×
            return Ok(Principal::Owner { key: *key, name: owner.name.clone() });
123119×
        }
124119×
        if self.instance.as_ref().is_some_and(|i| &i.hash() == key) {
1250×
            return Ok(Principal::Instance { key: *key });
126119×
        }
127119×
        let a = self.agents.get(key).ok_or("an unknown key")?;
128116×
        if a.disabled {
1295×
            return Err(format!("agent {} is disabled", a.name));
130111×
        }
131111×
        let owner = self.owner().ok_or("no owner is recorded")?;
132111×
        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
            });
138110×
        }
139110×
        Ok(Principal::Agent {
140110×
            name: a.name.clone(),
141110×
            key: *key,
142110×
            owner_name: a.owner_name.clone(),
143110×
            uid: a.uid,
144110×
            learn_uid: a.learn_uid,
145110×
            project: a.project.clone(),
146110×
            scopes: a.scopes.clone(),
147110×
        })
148144×
    }
149
150
    /// The identity behind `key`, for checking its signatures.
151114×
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
152114×
        self.owner
153114×
            .iter()
154282×
            .find(|i| &i.hash() == key)
155114×
            .or_else(|| self.instance.as_ref().filter(|i| &i.hash() == key))
156114×
            .or_else(|| self.agents.get(key).map(|a| &a.identity))
157114×
    }
158
159
    /// Take one event into account, checking what it claims first.
160398×
    pub fn observe(&mut self, e: &Event) -> Result<(), String> {
161398×
        let p = e.json();
162398×
        match e.kind.as_str() {
163398×
            "identity.owner" => {
164106×
                if !self.owner.is_empty() {
1651×
                    return Err("an owner is already recorded".into());
166105×
                }
167105×
                let id = identity_of(&p)?;
168105×
                self_signed(e, &id)?;
169105×
                self.owner.push(id);
170
            }
171292×
            "identity.rotated" => {
17290×
                let new = identity_of(&p)?;
17390×
                let cur = self.owner().ok_or("no owner to succeed")?.clone();
17490×
                accept_successor(&cur, &new, &p)?;
17590×
                self_signed(e, &new)?;
17689×
                self.owner.push(new);
177
            }
178202×
            "identity.instance" => {
179107×
                let id = identity_of(&p)?;
180107×
                self_signed(e, &id)?;
181107×
                self.instance = Some(id);
182
            }
18395×
            "agent.added" => {
18490×
                let id = identity_of(&p)?;
18590×
                let key = id.hash();
18690×
                let owner = self.owner_signed(e)?;
18790×
                if !owner.delegates_to(&key, DELEGATION_SCOPE, e.hlc.wall_ms) {
1881×
                    return Err("added without the owner's delegation to its key".into());
18989×
                }
19089×
                let name = text(&p, "name")?;
19189×
                if self.by_name.get(&name).is_some_and(|k| *k != key) {
1920×
                    return Err(format!("agent {name} already exists with another key"));
19389×
                }
19489×
                self.by_name.insert(name.clone(), key);
19589×
                self.agents.insert(
19689×
                    key,
197
                    AgentRec {
19889×
                        name,
19989×
                        identity: id,
20089×
                        owner_name: owner.name.clone(),
20189×
                        uid: p.get("uid").and_then(Json::as_u64).map(|u| u as u32),
20289×
                        learn_uid: p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false),
20389×
                        project: text(&p, "project")?,
20489×
                        scopes: p
20589×
                            .get("scopes")
20689×
                            .and_then(Json::as_array)
207616×
                            .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())
20889×
                            .unwrap_or_default(),
209
                        disabled: false,
210
                    },
211
                );
212
            }
2135×
            "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
            }
2254×
            "agent.disabled" => {
2264×
                self.owner_signed(e)?;
2274×
                let name = text(&p, "name")?;
2284×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
2294×
                if let Some(a) = self.agents.get_mut(&key) {
2304×
                    a.disabled = true;
2314×
                }
232
            }
2330×
            _ => {}
234
        }
235395×
        Ok(())
236398×
    }
237
238
    /// Check that `e` is signed by the owner's current identity; returns it.
23994×
    fn owner_signed(&self, e: &Event) -> Result<Identity, String> {
24094×
        let owner = self.owner().ok_or("no owner is recorded")?.clone();
24194×
        if e.auth.key != Some(owner.hash().0) {
2420×
            return Err("not signed by the owner's current identity".into());
24394×
        }
24494×
        check_proof(e, &owner)?;
24594×
        Ok(owner)
24694×
    }
247
248
    /// Check a signed event's proof against the principal its key was at
249
    /// the event's time.
25071×
    pub fn check_signed(&self, e: &Event) -> Result<(), String> {
25171×
        let key = oxy_core::hash::ObjectRef(e.auth.key.ok_or("signed, but names no key")?);
25271×
        let who = self.principal(&key, e.hlc.wall_ms)?;
253
        // The actor an event names must be the principal that signed it:
254
        // an agent's key never makes an event in another's name.
25569×
        if who.actor() != e.actor {
2562×
            return Err(format!("names {} as its actor but is signed by {}", e.actor, who.display()));
25767×
        }
25867×
        let identity = self.identity(&key).ok_or("an unknown key")?;
25967×
        check_proof(e, identity)
26071×
    }
261
}
262
263
impl KeyResolver for Principals {
264309×
    fn check(&mut self, e: &Event) -> Result<(), String> {
265309×
        match e.kind.as_str() {
266309×
            "identity.owner" | "identity.rotated" | "identity.instance" | "agent.added" | "agent.disabled" => {
26795×
                if e.auth.method != Method::Signature {
2682×
                    return Err(format!("{} must be signed", e.kind));
26993×
                }
27093×
                self.observe(e)
271
            }
272214×
            "agent.uid_bound" => self.observe(e),
273213×
            _ if matches!(e.auth.method, Method::Signature | Method::Passkey) => self.check_signed(e),
274142×
            _ => Ok(()),
275
        }
276309×
    }
277
}
278
279
/// Apply identity and agent events to the projection tables.
28042127×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
28142127×
    if e.kind == "agent.uid_bound" {
2821×
        let p = e.json();
2831×
        sqlx::query("UPDATE agents SET uid = ? WHERE name = ? AND uid IS NULL")
2841×
            .bind(p.get("uid").and_then(Json::as_i64))
2851×
            .bind(p.get("name").and_then(Json::as_str))
2861×
            .execute(&mut *conn)
2871×
            .await?;
2881×
        return Ok(());
28942126×
    }
290
    // Who is who is only ever said by a signature; `verify` checks which.
29142126×
    if e.auth.method != Method::Signature {
29241630×
        return Ok(());
293496×
    }
294496×
    let p = e.json();
295496×
    let id = |p: &Json| identity_of(p).ok();
296496×
    match e.kind.as_str() {
297496×
        "identity.owner" | "identity.rotated" | "identity.instance" => {
298111×
            let Some(identity) = id(&p) else { return Ok(()) };
299111×
            let role = if e.kind == "identity.instance" { "instance" } else { "owner" };
300111×
            sqlx::query("UPDATE identities SET current = 0 WHERE role = ?").bind(role).execute(&mut *conn).await?;
301111×
            sqlx::query(
302111×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, ?, ?, ?, ?, 1, ?)",
303
            )
304111×
            .bind(identity.hash().to_hex())
305111×
            .bind(role)
306111×
            .bind(&identity.name)
307111×
            .bind(identity.encode())
308111×
            .bind(identity.previous.map(|k| k.to_hex()))
309111×
            .bind(e.seq as i64)
310111×
            .execute(&mut *conn)
311111×
            .await?;
312
        }
313385×
        "agent.added" => {
31441×
            let Some(identity) = id(&p) else { return Ok(()) };
31541×
            if p.get("name").and_then(Json::as_str).is_none_or(str::is_empty) {
3160×
                return Ok(());
31741×
            }
318246×
            let s = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or("").to_string();
31941×
            sqlx::query(
32041×
                "INSERT OR REPLACE INTO agents (name, key, owner, owner_name, kind, project, home, uid, learn_uid, scopes, created_ms, disabled_ms, seq) \
32141×
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
322
            )
32341×
            .bind(s("name"))
32441×
            .bind(identity.hash().to_hex())
32541×
            .bind(s("owner"))
32641×
            .bind(s("owner_name"))
32741×
            .bind(s("kind"))
32841×
            .bind(s("project"))
32941×
            .bind(s("home"))
33041×
            .bind(p.get("uid").and_then(Json::as_i64))
33141×
            .bind(p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false))
33241×
            .bind(p.get("scopes").map(|v| v.to_string()).unwrap_or_else(|| "[]".into()))
33341×
            .bind(e.at_ms as i64)
33441×
            .bind(e.seq as i64)
33541×
            .execute(&mut *conn)
33641×
            .await?;
33741×
            sqlx::query(
33841×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, 'agent', ?, ?, ?, 1, ?)",
339
            )
34041×
            .bind(identity.hash().to_hex())
34141×
            .bind(&identity.name)
34241×
            .bind(identity.encode())
34341×
            .bind(identity.previous.map(|k| k.to_hex()))
34441×
            .bind(e.seq as i64)
34541×
            .execute(&mut *conn)
34641×
            .await?;
347
        }
348344×
        "agent.disabled" => {
3493×
            sqlx::query("UPDATE agents SET disabled_ms = ? WHERE name = ?")
3503×
                .bind(e.at_ms as i64)
3513×
                .bind(p.get("name").and_then(Json::as_str))
3523×
                .execute(&mut *conn)
3533×
                .await?;
354
        }
355341×
        _ => {}
356
    }
357496×
    Ok(())
35842127×
}
359
360
/// The payload of an identity event for `identity`.
361116×
pub fn identity_payload(identity: &Identity) -> Json {
362116×
    serde_json::json!({ "key": identity.hash().to_hex(), "name": identity.name, "identity": hex::encode(identity.encode()) })
363116×
}
364
365544×
fn identity_of(p: &Json) -> Result<Identity, String> {
366544×
    let b = p.get("identity").and_then(Json::as_str).and_then(|h| hex::decode(h).ok()).ok_or("no identity in the event")?;
367544×
    Identity::decode(&b).map_err(|e| format!("malformed identity: {e}"))
368544×
}
369
370183×
fn text(p: &Json, k: &str) -> Result<String, String> {
371183×
    p.get(k).and_then(Json::as_str).map(String::from).ok_or_else(|| format!("no {k}"))
372183×
}
373
374302×
fn self_signed(e: &Event, id: &Identity) -> Result<(), String> {
375302×
    if e.auth.key != Some(id.hash().0) {
3761×
        return Err("not signed by the identity it records".into());
377301×
    }
378301×
    check_proof(e, id)
379302×
}
380
381
/// The event's proof verifies against `identity`, and a CLI proof covers
382
/// exactly the event's payload.
383462×
fn check_proof(e: &Event, identity: &Identity) -> Result<(), String> {
384462×
    let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
385462×
    if proof.key() != identity.hash().0 {
3860×
        return Err("the proof is by another key".into());
387462×
    }
388462×
    let body = (proof.method == "cli").then(|| e.payload.as_deref().unwrap_or(b""));
389462×
    proof.verify(identity, body)
390462×
}
391
392
/// A successor of the owner must keep the key pair and chain back to the
393
/// current identity through `previous` (the intermediate identities, if
394
/// any, are carried in the event as `chain`).
39590×
fn accept_successor(cur: &Identity, new: &Identity, p: &Json) -> Result<(), String> {
39690×
    if new.ed25519_pk != cur.ed25519_pk || new.mldsa65_pk != cur.mldsa65_pk {
3970×
        return Err("a successor with a fresh key pair needs `oxy identity rotate`'s attestation, not accepted in 0.1".into());
39890×
    }
39990×
    let chain: Vec<Identity> = p
40090×
        .get("chain")
40190×
        .and_then(Json::as_array)
40290×
        .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())
40390×
        .unwrap_or_default();
40490×
    let mut at = new.clone();
40590×
    for _ in 0..=chain.len() {
40690×
        match at.previous {
40790×
            Some(prev) if prev == cur.hash() => return Ok(()),
4080×
            Some(prev) => match chain.iter().find(|i| i.hash() == prev) {
4090×
                Some(i) if i.ed25519_pk == cur.ed25519_pk => at = i.clone(),
4100×
                _ => break,
411
            },
4120×
            None => break,
413
        }
414
    }
4150×
    Err("does not succeed the recorded owner".into())
41690×
}
417
418
/// An event signed by `pair` from the command line: its proof covers the
419
/// canonical payload, so the event's content is bound to the signature.
420162×
pub fn signed_event(pair: &crate::keys::KeyPair, actor: &str, kind: &str, payload: Json) -> crate::event::NewEvent {
421162×
    let body = crate::event::canonical_json(&payload);
422162×
    let proof = Proof::sign(pair, "cli", &body);
423162×
    crate::event::NewEvent::system(kind, payload)
424162×
        .by(actor, crate::event::Auth { key: Some(pair.key.0), method: Method::Signature, assurance: 2, proof: Some(proof.encode()) })
425162×
}