OXYGENHUB

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

284 of 313 lines run, 40 of 98 functions · run #8 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`.
4394×
    pub fn actor(&self) -> String {
4494×
        match self {
4520×
            Principal::Owner { .. } => "human".into(),
4674×
            Principal::Agent { name, .. } => format!("agent:{name}"),
470×
            Principal::Instance { .. } => "system".into(),
48
        }
4994×
    }
50
    /// How it is shown to people: `claude-oxygen · Andy McCall's agent`.
515×
    pub fn display(&self) -> String {
525×
        match self {
530×
            Principal::Owner { name, .. } => name.clone(),
545×
            Principal::Agent { name, owner_name, .. } => format!("{name} · {owner_name}'s agent"),
550×
            Principal::Instance { .. } => "Spectra".into(),
56
        }
575×
    }
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.
8455×
    pub async fn load(ledger: &crate::ledger::Ledger) -> anyhow::Result<Principals> {
8555×
        let mut p = Principals::default();
8655×
        let mut from = 1;
87
        loop {
88110×
            let rows = ledger
89110×
                .events_of_kinds(from, &["identity.owner", "identity.rotated", "identity.instance", "agent.added", "agent.disabled"], 1000)
90110×
                .await?;
91109×
            if rows.is_empty() {
9254×
                break;
9355×
            }
94202×
            for e in &rows {
95202×
                // Recorded facts were checked when written; `verify` checks them again.
96202×
                let _ = p.observe(e);
97202×
            }
9855×
            from = rows.last().map(|e| e.seq + 1).unwrap_or(from);
99
        }
10054×
        Ok(p)
10154×
    }
102
103
    /// The owner's current identity.
104212×
    pub fn owner(&self) -> Option<&Identity> {
105212×
        self.owner.last()
106212×
    }
107
1080×
    pub fn instance(&self) -> Option<&Identity> {
1090×
        self.instance.as_ref()
1100×
    }
111
112
    /// The agent named `name`, whatever its state.
1138×
    pub fn agent_key(&self, name: &str) -> Option<KeyId> {
1148×
        self.by_name.get(name).copied()
1158×
    }
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.
12084×
    pub fn principal(&self, key: &KeyId, at_ms: u64) -> Result<Principal, String> {
121170×
        if let Some(owner) = self.owner.iter().rev().find(|i| &i.hash() == key) {
12224×
            return Ok(Principal::Owner { key: *key, name: owner.name.clone() });
12360×
        }
12460×
        if self.instance.as_ref().is_some_and(|i| &i.hash() == key) {
1250×
            return Ok(Principal::Instance { key: *key });
12660×
        }
12760×
        let a = self.agents.get(key).ok_or("an unknown key")?;
12857×
        if a.disabled {
1295×
            return Err(format!("agent {} is disabled", a.name));
13052×
        }
13152×
        let owner = self.owner().ok_or("no owner is recorded")?;
13252×
        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
            });
13851×
        }
13951×
        Ok(Principal::Agent {
14051×
            name: a.name.clone(),
14151×
            key: *key,
14251×
            owner_name: a.owner_name.clone(),
14351×
            uid: a.uid,
14451×
            learn_uid: a.learn_uid,
14551×
            project: a.project.clone(),
14651×
            scopes: a.scopes.clone(),
14751×
        })
14884×
    }
149
150
    /// The identity behind `key`, for checking its signatures.
15154×
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
15254×
        self.owner
15354×
            .iter()
154109×
            .find(|i| &i.hash() == key)
15554×
            .or_else(|| self.instance.as_ref().filter(|i| &i.hash() == key))
15654×
            .or_else(|| self.agents.get(key).map(|a| &a.identity))
15754×
    }
158
159
    /// Take one event into account, checking what it claims first.
160290×
    pub fn observe(&mut self, e: &Event) -> Result<(), String> {
161290×
        let p = e.json();
162290×
        match e.kind.as_str() {
163290×
            "identity.owner" => {
16475×
                if !self.owner.is_empty() {
1651×
                    return Err("an owner is already recorded".into());
16674×
                }
16774×
                let id = identity_of(&p)?;
16874×
                self_signed(e, &id)?;
16974×
                self.owner.push(id);
170
            }
171215×
            "identity.rotated" => {
17267×
                let new = identity_of(&p)?;
17367×
                let cur = self.owner().ok_or("no owner to succeed")?.clone();
17467×
                accept_successor(&cur, &new, &p)?;
17567×
                self_signed(e, &new)?;
17666×
                self.owner.push(new);
177
            }
178148×
            "identity.instance" => {
17976×
                let id = identity_of(&p)?;
18076×
                self_signed(e, &id)?;
18176×
                self.instance = Some(id);
182
            }
18372×
            "agent.added" => {
18467×
                let id = identity_of(&p)?;
18567×
                let key = id.hash();
18667×
                let owner = self.owner_signed(e)?;
18767×
                if !owner.delegates_to(&key, DELEGATION_SCOPE, e.hlc.wall_ms) {
1881×
                    return Err("added without the owner's delegation to its key".into());
18966×
                }
19066×
                let name = text(&p, "name")?;
19166×
                if self.by_name.get(&name).is_some_and(|k| *k != key) {
1920×
                    return Err(format!("agent {name} already exists with another key"));
19366×
                }
19466×
                self.by_name.insert(name.clone(), key);
19566×
                self.agents.insert(
19666×
                    key,
197
                    AgentRec {
19866×
                        name,
19966×
                        identity: id,
20066×
                        owner_name: owner.name.clone(),
20166×
                        uid: p.get("uid").and_then(Json::as_u64).map(|u| u as u32),
20266×
                        learn_uid: p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false),
20366×
                        project: text(&p, "project")?,
20466×
                        scopes: p
20566×
                            .get("scopes")
20666×
                            .and_then(Json::as_array)
207432×
                            .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())
20866×
                            .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
        }
235287×
        Ok(())
236290×
    }
237
238
    /// Check that `e` is signed by the owner's current identity; returns it.
23971×
    fn owner_signed(&self, e: &Event) -> Result<Identity, String> {
24071×
        let owner = self.owner().ok_or("no owner is recorded")?.clone();
24171×
        if e.auth.key != Some(owner.hash().0) {
2420×
            return Err("not signed by the owner's current identity".into());
24371×
        }
24471×
        check_proof(e, &owner)?;
24571×
        Ok(owner)
24671×
    }
247
248
    /// Check a signed event's proof against the principal its key was at
249
    /// the event's time.
25041×
    pub fn check_signed(&self, e: &Event) -> Result<(), String> {
25141×
        let key = oxy_core::hash::ObjectRef(e.auth.key.ok_or("signed, but names no key")?);
25241×
        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.
25539×
        if who.actor() != e.actor {
2562×
            return Err(format!("names {} as its actor but is signed by {}", e.actor, who.display()));
25737×
        }
25837×
        let identity = self.identity(&key).ok_or("an unknown key")?;
25937×
        check_proof(e, identity)
26041×
    }
261
}
262
263
impl KeyResolver for Principals {
264267×
    fn check(&mut self, e: &Event) -> Result<(), String> {
265267×
        match e.kind.as_str() {
266267×
            "identity.owner" | "identity.rotated" | "identity.instance" | "agent.added" | "agent.disabled" => {
26789×
                if e.auth.method != Method::Signature {
2682×
                    return Err(format!("{} must be signed", e.kind));
26987×
                }
27087×
                self.observe(e)
271
            }
272178×
            "agent.uid_bound" => self.observe(e),
273177×
            _ if matches!(e.auth.method, Method::Signature | Method::Passkey) => self.check_signed(e),
274136×
            _ => Ok(()),
275
        }
276267×
    }
277
}
278
279
/// Apply identity and agent events to the projection tables.
28042011×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
28142011×
    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(());
28942010×
    }
290
    // Who is who is only ever said by a signature; `verify` checks which.
29142010×
    if e.auth.method != Method::Signature {
29241604×
        return Ok(());
293406×
    }
294406×
    let p = e.json();
295406×
    let id = |p: &Json| identity_of(p).ok();
296406×
    match e.kind.as_str() {
297406×
        "identity.owner" | "identity.rotated" | "identity.instance" => {
29893×
            let Some(identity) = id(&p) else { return Ok(()) };
29993×
            let role = if e.kind == "identity.instance" { "instance" } else { "owner" };
30093×
            sqlx::query("UPDATE identities SET current = 0 WHERE role = ?").bind(role).execute(&mut *conn).await?;
30193×
            sqlx::query(
30293×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, ?, ?, ?, ?, 1, ?)",
303
            )
30493×
            .bind(identity.hash().to_hex())
30593×
            .bind(role)
30693×
            .bind(&identity.name)
30793×
            .bind(identity.encode())
30893×
            .bind(identity.previous.map(|k| k.to_hex()))
30993×
            .bind(e.seq as i64)
31093×
            .execute(&mut *conn)
31193×
            .await?;
312
        }
313313×
        "agent.added" => {
31433×
            let Some(identity) = id(&p) else { return Ok(()) };
31533×
            if p.get("name").and_then(Json::as_str).is_none_or(str::is_empty) {
3160×
                return Ok(());
31733×
            }
318198×
            let s = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or("").to_string();
31933×
            sqlx::query(
32033×
                "INSERT OR REPLACE INTO agents (name, key, owner, owner_name, kind, project, home, uid, learn_uid, scopes, created_ms, disabled_ms, seq) \
32133×
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
322
            )
32333×
            .bind(s("name"))
32433×
            .bind(identity.hash().to_hex())
32533×
            .bind(s("owner"))
32633×
            .bind(s("owner_name"))
32733×
            .bind(s("kind"))
32833×
            .bind(s("project"))
32933×
            .bind(s("home"))
33033×
            .bind(p.get("uid").and_then(Json::as_i64))
33133×
            .bind(p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false))
33233×
            .bind(p.get("scopes").map(|v| v.to_string()).unwrap_or_else(|| "[]".into()))
33333×
            .bind(e.at_ms as i64)
33433×
            .bind(e.seq as i64)
33533×
            .execute(&mut *conn)
33633×
            .await?;
33733×
            sqlx::query(
33833×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, 'agent', ?, ?, ?, 1, ?)",
339
            )
34033×
            .bind(identity.hash().to_hex())
34133×
            .bind(&identity.name)
34233×
            .bind(identity.encode())
34333×
            .bind(identity.previous.map(|k| k.to_hex()))
34433×
            .bind(e.seq as i64)
34533×
            .execute(&mut *conn)
34633×
            .await?;
347
        }
348280×
        "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
        }
355277×
        _ => {}
356
    }
357406×
    Ok(())
35842011×
}
359
360
/// The payload of an identity event for `identity`.
36190×
pub fn identity_payload(identity: &Identity) -> Json {
36290×
    serde_json::json!({ "key": identity.hash().to_hex(), "name": identity.name, "identity": hex::encode(identity.encode()) })
36390×
}
364
365410×
fn identity_of(p: &Json) -> Result<Identity, String> {
366410×
    let b = p.get("identity").and_then(Json::as_str).and_then(|h| hex::decode(h).ok()).ok_or("no identity in the event")?;
367410×
    Identity::decode(&b).map_err(|e| format!("malformed identity: {e}"))
368410×
}
369
370137×
fn text(p: &Json, k: &str) -> Result<String, String> {
371137×
    p.get(k).and_then(Json::as_str).map(String::from).ok_or_else(|| format!("no {k}"))
372137×
}
373
374217×
fn self_signed(e: &Event, id: &Identity) -> Result<(), String> {
375217×
    if e.auth.key != Some(id.hash().0) {
3761×
        return Err("not signed by the identity it records".into());
377216×
    }
378216×
    check_proof(e, id)
379217×
}
380
381
/// The event's proof verifies against `identity`, and a CLI proof covers
382
/// exactly the event's payload.
383324×
fn check_proof(e: &Event, identity: &Identity) -> Result<(), String> {
384324×
    let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
385324×
    if proof.key() != identity.hash().0 {
3860×
        return Err("the proof is by another key".into());
387324×
    }
388324×
    let body = (proof.method == "cli").then(|| e.payload.as_deref().unwrap_or(b""));
389324×
    proof.verify(identity, body)
390324×
}
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`).
39567×
fn accept_successor(cur: &Identity, new: &Identity, p: &Json) -> Result<(), String> {
39667×
    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());
39867×
    }
39967×
    let chain: Vec<Identity> = p
40067×
        .get("chain")
40167×
        .and_then(Json::as_array)
40267×
        .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())
40367×
        .unwrap_or_default();
40467×
    let mut at = new.clone();
40567×
    for _ in 0..=chain.len() {
40667×
        match at.previous {
40767×
            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())
41667×
}
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.
420131×
pub fn signed_event(pair: &crate::keys::KeyPair, actor: &str, kind: &str, payload: Json) -> crate::event::NewEvent {
421131×
    let body = crate::event::canonical_json(&payload);
422131×
    let proof = Proof::sign(pair, "cli", &body);
423131×
    crate::event::NewEvent::system(kind, payload)
424131×
        .by(actor, crate::event::Auth { key: Some(pair.key.0), method: Method::Signature, assurance: 2, proof: Some(proof.encode()) })
425131×
}