OXYGENHUB

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

260 of 288 lines run, 42 of 104 functions · run #5 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`.
437×
    pub fn actor(&self) -> String {
447×
        match self {
451×
            Principal::Owner { .. } => "human".into(),
466×
            Principal::Agent { name, .. } => format!("agent:{name}"),
470×
            Principal::Instance { .. } => "system".into(),
48
        }
497×
    }
50
    /// How it is shown to people: `claude-oxygen · Andy McCall's agent`.
514×
    pub fn display(&self) -> String {
524×
        match self {
530×
            Principal::Owner { name, .. } => name.clone(),
544×
            Principal::Agent { name, owner_name, .. } => format!("{name} · {owner_name}'s agent"),
550×
            Principal::Instance { .. } => "Spectra".into(),
56
        }
574×
    }
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.
8412×
    pub async fn load(ledger: &crate::ledger::Ledger) -> anyhow::Result<Principals> {
8512×
        let mut p = Principals::default();
8612×
        let mut from = 1;
87
        loop {
8824×
            let rows = ledger
8924×
                .events_of_kinds(from, &["identity.owner", "identity.rotated", "identity.instance", "agent.added", "agent.disabled"], 1000)
9024×
                .await?;
9124×
            if rows.is_empty() {
9212×
                break;
9312×
            }
9446×
            for e in &rows {
9546×
                // Recorded facts were checked when written; `verify` checks them again.
9646×
                let _ = p.observe(e);
9746×
            }
9812×
            from = rows.last().map(|e| e.seq + 1).unwrap_or(from);
99
        }
10012×
        Ok(p)
10112×
    }
102
103
    /// The owner's current identity.
10465×
    pub fn owner(&self) -> Option<&Identity> {
10565×
        self.owner.last()
10665×
    }
107
1080×
    pub fn instance(&self) -> Option<&Identity> {
1090×
        self.instance.as_ref()
1100×
    }
111
112
    /// The agent named `name`, whatever its state.
1133×
    pub fn agent_key(&self, name: &str) -> Option<KeyId> {
1143×
        self.by_name.get(name).copied()
1153×
    }
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.
12024×
    pub fn principal(&self, key: &KeyId, at_ms: u64) -> Result<Principal, String> {
12151×
        if let Some(owner) = self.owner.iter().rev().find(|i| &i.hash() == key) {
1221×
            return Ok(Principal::Owner { key: *key, name: owner.name.clone() });
12323×
        }
12423×
        if self.instance.as_ref().is_some_and(|i| &i.hash() == key) {
1250×
            return Ok(Principal::Instance { key: *key });
12623×
        }
12723×
        let a = self.agents.get(key).ok_or("an unknown key")?;
12821×
        if a.disabled {
1295×
            return Err(format!("agent {} is disabled", a.name));
13016×
        }
13116×
        let owner = self.owner().ok_or("no owner is recorded")?;
13216×
        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
            });
13815×
        }
13915×
        Ok(Principal::Agent {
14015×
            name: a.name.clone(),
14115×
            key: *key,
14215×
            owner_name: a.owner_name.clone(),
14315×
            uid: a.uid,
14415×
            learn_uid: a.learn_uid,
14515×
            project: a.project.clone(),
14615×
            scopes: a.scopes.clone(),
14715×
        })
14824×
    }
149
150
    /// The identity behind `key`, for checking its signatures.
1519×
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
1529×
        self.owner
1539×
            .iter()
15420×
            .find(|i| &i.hash() == key)
1559×
            .or_else(|| self.instance.as_ref().filter(|i| &i.hash() == key))
1569×
            .or_else(|| self.agents.get(key).map(|a| &a.identity))
1579×
    }
158
159
    /// Take one event into account, checking what it claims first.
16091×
    pub fn observe(&mut self, e: &Event) -> Result<(), String> {
16191×
        let p = e.json();
16291×
        match e.kind.as_str() {
16391×
            "identity.owner" => {
16423×
                if !self.owner.is_empty() {
1651×
                    return Err("an owner is already recorded".into());
16622×
                }
16722×
                let id = identity_of(&p)?;
16822×
                self_signed(e, &id)?;
16922×
                self.owner.push(id);
170
            }
17168×
            "identity.rotated" => {
17220×
                let new = identity_of(&p)?;
17320×
                let cur = self.owner().ok_or("no owner to succeed")?.clone();
17420×
                accept_successor(&cur, &new, &p)?;
17520×
                self_signed(e, &new)?;
17619×
                self.owner.push(new);
177
            }
17848×
            "identity.instance" => {
17924×
                let id = identity_of(&p)?;
18024×
                self_signed(e, &id)?;
18124×
                self.instance = Some(id);
182
            }
18324×
            "agent.added" => {
18420×
                let id = identity_of(&p)?;
18520×
                let key = id.hash();
18620×
                let owner = self.owner_signed(e)?;
18720×
                if !owner.delegates_to(&key, DELEGATION_SCOPE, e.hlc.wall_ms) {
1881×
                    return Err("added without the owner's delegation to its key".into());
18919×
                }
19019×
                let name = text(&p, "name")?;
19119×
                if self.by_name.get(&name).is_some_and(|k| *k != key) {
1920×
                    return Err(format!("agent {name} already exists with another key"));
19319×
                }
19419×
                self.by_name.insert(name.clone(), key);
19519×
                self.agents.insert(
19619×
                    key,
197
                    AgentRec {
19819×
                        name,
19919×
                        identity: id,
20019×
                        owner_name: owner.name.clone(),
20119×
                        uid: p.get("uid").and_then(Json::as_u64).map(|u| u as u32),
20219×
                        learn_uid: p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false),
20319×
                        project: text(&p, "project")?,
20419×
                        scopes: p
20519×
                            .get("scopes")
20619×
                            .and_then(Json::as_array)
20756×
                            .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())
20819×
                            .unwrap_or_default(),
209
                        disabled: false,
210
                    },
211
                );
212
            }
2134×
            "agent.disabled" => {
2144×
                self.owner_signed(e)?;
2154×
                let name = text(&p, "name")?;
2164×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
2174×
                if let Some(a) = self.agents.get_mut(&key) {
2184×
                    a.disabled = true;
2194×
                }
220
            }
2210×
            _ => {}
222
        }
22388×
        Ok(())
22491×
    }
225
226
    /// Check that `e` is signed by the owner's current identity; returns it.
22724×
    fn owner_signed(&self, e: &Event) -> Result<Identity, String> {
22824×
        let owner = self.owner().ok_or("no owner is recorded")?.clone();
22924×
        if e.auth.key != Some(owner.hash().0) {
2300×
            return Err("not signed by the owner's current identity".into());
23124×
        }
23224×
        check_proof(e, &owner)?;
23324×
        Ok(owner)
23424×
    }
235
236
    /// Check a signed event's proof against the principal its key was at
237
    /// the event's time.
2387×
    pub fn check_signed(&self, e: &Event) -> Result<(), String> {
2397×
        let key = oxy_core::hash::ObjectRef(e.auth.key.ok_or("signed, but names no key")?);
2407×
        let who = self.principal(&key, e.hlc.wall_ms)?;
241
        // The actor an event names must be the principal that signed it:
242
        // an agent's key never makes an event in another's name.
2435×
        if who.actor() != e.actor {
2442×
            return Err(format!("names {} as its actor but is signed by {}", e.actor, who.display()));
2453×
        }
2463×
        let identity = self.identity(&key).ok_or("an unknown key")?;
2473×
        check_proof(e, identity)
2487×
    }
249
}
250
251
impl KeyResolver for Principals {
252132×
    fn check(&mut self, e: &Event) -> Result<(), String> {
253132×
        match e.kind.as_str() {
254132×
            "identity.owner" | "identity.rotated" | "identity.instance" | "agent.added" | "agent.disabled" => {
25545×
                if e.auth.method != Method::Signature {
2560×
                    return Err(format!("{} must be signed", e.kind));
25745×
                }
25845×
                self.observe(e)
259
            }
26087×
            _ if matches!(e.auth.method, Method::Signature | Method::Passkey) => self.check_signed(e),
26180×
            _ => Ok(()),
262
        }
263132×
    }
264
}
265
266
/// Apply identity and agent events to the projection tables.
26741741×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
26841741×
    let p = e.json();
26941741×
    let id = |p: &Json| identity_of(p).ok();
27041741×
    match e.kind.as_str() {
27141741×
        "identity.owner" | "identity.rotated" | "identity.instance" => {
27252×
            let Some(identity) = id(&p) else { return Ok(()) };
27352×
            let role = if e.kind == "identity.instance" { "instance" } else { "owner" };
27452×
            sqlx::query("UPDATE identities SET current = 0 WHERE role = ?").bind(role).execute(&mut *conn).await?;
27552×
            sqlx::query(
27652×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, ?, ?, ?, ?, 1, ?)",
277
            )
27852×
            .bind(identity.hash().to_hex())
27952×
            .bind(role)
28052×
            .bind(&identity.name)
28152×
            .bind(identity.encode())
28252×
            .bind(identity.previous.map(|k| k.to_hex()))
28352×
            .bind(e.seq as i64)
28452×
            .execute(&mut *conn)
28552×
            .await?;
286
        }
28741689×
        "agent.added" => {
28813×
            let Some(identity) = id(&p) else { return Ok(()) };
28978×
            let s = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or("").to_string();
29013×
            sqlx::query(
29113×
                "INSERT OR REPLACE INTO agents (name, key, owner, owner_name, kind, project, home, uid, learn_uid, scopes, created_ms, disabled_ms, seq) \
29213×
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
293
            )
29413×
            .bind(s("name"))
29513×
            .bind(identity.hash().to_hex())
29613×
            .bind(s("owner"))
29713×
            .bind(s("owner_name"))
29813×
            .bind(s("kind"))
29913×
            .bind(s("project"))
30013×
            .bind(s("home"))
30113×
            .bind(p.get("uid").and_then(Json::as_i64))
30213×
            .bind(p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false))
30313×
            .bind(p.get("scopes").map(|v| v.to_string()).unwrap_or_else(|| "[]".into()))
30413×
            .bind(e.at_ms as i64)
30513×
            .bind(e.seq as i64)
30613×
            .execute(&mut *conn)
30713×
            .await?;
30813×
            sqlx::query(
30913×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, 'agent', ?, ?, ?, 1, ?)",
310
            )
31113×
            .bind(identity.hash().to_hex())
31213×
            .bind(&identity.name)
31313×
            .bind(identity.encode())
31413×
            .bind(identity.previous.map(|k| k.to_hex()))
31513×
            .bind(e.seq as i64)
31613×
            .execute(&mut *conn)
31713×
            .await?;
318
        }
31941676×
        "agent.disabled" => {
3203×
            sqlx::query("UPDATE agents SET disabled_ms = ? WHERE name = ?")
3213×
                .bind(e.at_ms as i64)
3223×
                .bind(p.get("name").and_then(Json::as_str))
3233×
                .execute(&mut *conn)
3243×
                .await?;
325
        }
32641673×
        _ => {}
327
    }
32841741×
    Ok(())
32941741×
}
330
331
/// The payload of an identity event for `identity`.
33242×
pub fn identity_payload(identity: &Identity) -> Json {
33342×
    serde_json::json!({ "key": identity.hash().to_hex(), "name": identity.name, "identity": hex::encode(identity.encode()) })
33442×
}
335
336151×
fn identity_of(p: &Json) -> Result<Identity, String> {
337151×
    let b = p.get("identity").and_then(Json::as_str).and_then(|h| hex::decode(h).ok()).ok_or("no identity in the event")?;
338151×
    Identity::decode(&b).map_err(|e| format!("malformed identity: {e}"))
339151×
}
340
34142×
fn text(p: &Json, k: &str) -> Result<String, String> {
34242×
    p.get(k).and_then(Json::as_str).map(String::from).ok_or_else(|| format!("no {k}"))
34342×
}
344
34566×
fn self_signed(e: &Event, id: &Identity) -> Result<(), String> {
34666×
    if e.auth.key != Some(id.hash().0) {
3471×
        return Err("not signed by the identity it records".into());
34865×
    }
34965×
    check_proof(e, id)
35066×
}
351
352
/// The event's proof verifies against `identity`, and a CLI proof covers
353
/// exactly the event's payload.
35492×
fn check_proof(e: &Event, identity: &Identity) -> Result<(), String> {
35592×
    let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
35692×
    if proof.key() != identity.hash().0 {
3570×
        return Err("the proof is by another key".into());
35892×
    }
35992×
    let body = (proof.method == "cli").then(|| e.payload.as_deref().unwrap_or(b""));
36092×
    proof.verify(identity, body)
36192×
}
362
363
/// A successor of the owner must keep the key pair and chain back to the
364
/// current identity through `previous` (the intermediate identities, if
365
/// any, are carried in the event as `chain`).
36620×
fn accept_successor(cur: &Identity, new: &Identity, p: &Json) -> Result<(), String> {
36720×
    if new.ed25519_pk != cur.ed25519_pk || new.mldsa65_pk != cur.mldsa65_pk {
3680×
        return Err("a successor with a fresh key pair needs `oxy identity rotate`'s attestation, not accepted in 0.1".into());
36920×
    }
37020×
    let chain: Vec<Identity> = p
37120×
        .get("chain")
37220×
        .and_then(Json::as_array)
37320×
        .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())
37420×
        .unwrap_or_default();
37520×
    let mut at = new.clone();
37620×
    for _ in 0..=chain.len() {
37720×
        match at.previous {
37820×
            Some(prev) if prev == cur.hash() => return Ok(()),
3790×
            Some(prev) => match chain.iter().find(|i| i.hash() == prev) {
3800×
                Some(i) if i.ed25519_pk == cur.ed25519_pk => at = i.clone(),
3810×
                _ => break,
382
            },
3830×
            None => break,
384
        }
385
    }
3860×
    Err("does not succeed the recorded owner".into())
38720×
}
388
389
/// An event signed by `pair` from the command line: its proof covers the
390
/// canonical payload, so the event's content is bound to the signature.
39151×
pub fn signed_event(pair: &crate::keys::KeyPair, actor: &str, kind: &str, payload: Json) -> crate::event::NewEvent {
39251×
    let body = crate::event::canonical_json(&payload);
39351×
    let proof = Proof::sign(pair, "cli", &body);
39451×
    crate::event::NewEvent::system(kind, payload)
39551×
        .by(actor, crate::event::Auth { key: Some(pair.key.0), method: Method::Signature, assurance: 2, proof: Some(proof.encode()) })
39651×
}