OXYGENHUB

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

301 of 326 lines run, 42 of 100 functions · run #18 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`.
43291×
    pub fn actor(&self) -> String {
44291×
        match self {
4539×
            Principal::Owner { .. } => "human".into(),
46250×
            Principal::Agent { name, .. } => format!("agent:{name}"),
472×
            Principal::Instance { .. } => "system".into(),
48
        }
49291×
    }
50
    /// How it is shown to people: `claude-oxygen · Andy McCall's agent`.
5121×
    pub fn display(&self) -> String {
5221×
        match self {
5311×
            Principal::Owner { name, .. } => name.clone(),
5410×
            Principal::Agent { name, owner_name, .. } => format!("{name} · {owner_name}'s agent"),
550×
            Principal::Instance { .. } => "Spectra".into(),
56
        }
5721×
    }
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.
84122×
    pub async fn load(ledger: &crate::ledger::Ledger) -> anyhow::Result<Principals> {
85122×
        let mut p = Principals::default();
86122×
        let mut from = 1;
87
        loop {
88243×
            let rows = ledger
89243×
                .events_of_kinds(from, &["identity.owner", "identity.rotated", "identity.instance", "agent.added", "agent.disabled"], 1000)
90243×
                .await?;
91240×
            if rows.is_empty() {
92119×
                break;
93121×
            }
94410×
            for e in &rows {
95410×
                // Recorded facts were checked when written; `verify` checks them again.
96410×
                let _ = p.observe(e);
97410×
            }
98121×
            from = rows.last().map(|e| e.seq + 1).unwrap_or(from);
99
        }
100119×
        Ok(p)
101119×
    }
102
103
    /// The owner's current identity.
104426×
    pub fn owner(&self) -> Option<&Identity> {
105426×
        self.owner.last()
106426×
    }
107
1084×
    pub fn instance(&self) -> Option<&Identity> {
1094×
        self.instance.as_ref()
1104×
    }
111
112
    /// The agent named `name`, whatever its state.
11322×
    pub fn agent_key(&self, name: &str) -> Option<KeyId> {
11422×
        self.by_name.get(name).copied()
11522×
    }
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.
120205×
    pub fn principal(&self, key: &KeyId, at_ms: u64) -> Result<Principal, String> {
121436×
        if let Some(owner) = self.owner.iter().rev().find(|i| &i.hash() == key) {
12254×
            return Ok(Principal::Owner { key: *key, name: owner.name.clone() });
123151×
        }
124151×
        if self.instance.as_ref().is_some_and(|i| &i.hash() == key) {
1252×
            return Ok(Principal::Instance { key: *key });
126149×
        }
127149×
        let a = self.agents.get(key).ok_or("an unknown key")?;
128146×
        if a.disabled {
1295×
            return Err(format!("agent {} is disabled", a.name));
130141×
        }
131141×
        let owner = self.owner().ok_or("no owner is recorded")?;
132141×
        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
            });
138140×
        }
139140×
        Ok(Principal::Agent {
140140×
            name: a.name.clone(),
141140×
            key: *key,
142140×
            owner_name: a.owner_name.clone(),
143140×
            uid: a.uid,
144140×
            learn_uid: a.learn_uid,
145140×
            project: a.project.clone(),
146140×
            scopes: a.scopes.clone(),
147140×
        })
148205×
    }
149
150
    /// The identity behind `key`, for checking its signatures.
151162×
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
152162×
        self.owner
153162×
            .iter()
154373×
            .find(|i| &i.hash() == key)
155162×
            .or_else(|| self.instance.as_ref().filter(|i| &i.hash() == key))
156162×
            .or_else(|| self.agents.get(key).map(|a| &a.identity))
157162×
    }
158
159
    /// Take one event into account, checking what it claims first.
160524×
    pub fn observe(&mut self, e: &Event) -> Result<(), String> {
161524×
        let p = e.json();
162524×
        match e.kind.as_str() {
163524×
            "identity.owner" => {
164147×
                if !self.owner.is_empty() {
1651×
                    return Err("an owner is already recorded".into());
166146×
                }
167146×
                let id = identity_of(&p)?;
168146×
                self_signed(e, &id)?;
169146×
                self.owner.push(id);
170
            }
171377×
            "identity.rotated" => {
172112×
                let new = identity_of(&p)?;
173112×
                let cur = self.owner().ok_or("no owner to succeed")?.clone();
174112×
                accept_successor(&cur, &new, &p)?;
175112×
                self_signed(e, &new)?;
176111×
                self.owner.push(new);
177
            }
178265×
            "identity.instance" => {
179148×
                let id = identity_of(&p)?;
180148×
                self_signed(e, &id)?;
181148×
                self.instance = Some(id);
182
            }
183117×
            "agent.added" => {
184112×
                let id = identity_of(&p)?;
185112×
                let key = id.hash();
186112×
                let owner = self.owner_signed(e)?;
187112×
                if !owner.delegates_to(&key, DELEGATION_SCOPE, e.hlc.wall_ms) {
1881×
                    return Err("added without the owner's delegation to its key".into());
189111×
                }
190111×
                let name = text(&p, "name")?;
191111×
                if self.by_name.get(&name).is_some_and(|k| *k != key) {
1920×
                    return Err(format!("agent {name} already exists with another key"));
193111×
                }
194111×
                self.by_name.insert(name.clone(), key);
195111×
                self.agents.insert(
196111×
                    key,
197
                    AgentRec {
198111×
                        name,
199111×
                        identity: id,
200111×
                        owner_name: owner.name.clone(),
201111×
                        uid: p.get("uid").and_then(Json::as_u64).map(|u| u as u32),
202111×
                        learn_uid: p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false),
203111×
                        project: text(&p, "project")?,
204111×
                        scopes: p
205111×
                            .get("scopes")
206111×
                            .and_then(Json::as_array)
207792×
                            .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())
208111×
                            .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
        }
235521×
        Ok(())
236524×
    }
237
238
    /// Check that `e` is signed by the owner's current identity; returns it.
239116×
    fn owner_signed(&self, e: &Event) -> Result<Identity, String> {
240116×
        let owner = self.owner().ok_or("no owner is recorded")?.clone();
241116×
        if e.auth.key != Some(owner.hash().0) {
2420×
            return Err("not signed by the owner's current identity".into());
243116×
        }
244116×
        check_proof(e, &owner)?;
245116×
        Ok(owner)
246116×
    }
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.
2512×
    pub fn check_session(&self, e: &Event) -> Result<(), String> {
2522×
        let key = oxy_core::hash::ObjectRef(e.auth.key.ok_or("a session event names no key")?);
2532×
        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());
2552×
        }
2562×
        let identity = self.identity(&key).ok_or("an unknown key")?;
2572×
        let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
2582×
        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());
2602×
        }
2612×
        proof.verify(identity, None)
2622×
    }
263
264
    /// Check a signed event's proof against the principal its key was at
265
    /// the event's time.
26684×
    pub fn check_signed(&self, e: &Event) -> Result<(), String> {
26784×
        let key = oxy_core::hash::ObjectRef(e.auth.key.ok_or("signed, but names no key")?);
26884×
        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.
27182×
        if who.actor() != e.actor {
2722×
            return Err(format!("names {} as its actor but is signed by {}", e.actor, who.display()));
27380×
        }
27480×
        let identity = self.identity(&key).ok_or("an unknown key")?;
27580×
        check_proof(e, identity)
27684×
    }
277
}
278
279
impl KeyResolver for Principals {
280370×
    fn check(&mut self, e: &Event) -> Result<(), String> {
281370×
        match e.kind.as_str() {
282370×
            "identity.owner" | "identity.rotated" | "identity.instance" | "agent.added" | "agent.disabled" => {
283115×
                if e.auth.method != Method::Signature {
2842×
                    return Err(format!("{} must be signed", e.kind));
285113×
                }
286113×
                self.observe(e)
287
            }
288255×
            "agent.uid_bound" => self.observe(e),
289254×
            _ if matches!(e.auth.method, Method::Signature | Method::Passkey) => self.check_signed(e),
290170×
            _ if e.auth.method == Method::Session => self.check_session(e),
291168×
            _ => Ok(()),
292
        }
293370×
    }
294
}
295
296
/// Apply identity and agent events to the projection tables.
29742541×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
29842541×
    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(());
30642540×
    }
307
    // Who is who is only ever said by a signature; `verify` checks which.
30842540×
    if e.auth.method != Method::Signature {
30941967×
        return Ok(());
310573×
    }
311573×
    let p = e.json();
312573×
    let id = |p: &Json| identity_of(p).ok();
313573×
    match e.kind.as_str() {
314573×
        "identity.owner" | "identity.rotated" | "identity.instance" => {
315131×
            let Some(identity) = id(&p) else { return Ok(()) };
316131×
            let role = if e.kind == "identity.instance" { "instance" } else { "owner" };
317131×
            sqlx::query("UPDATE identities SET current = 0 WHERE role = ?").bind(role).execute(&mut *conn).await?;
318131×
            sqlx::query(
319131×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, ?, ?, ?, ?, 1, ?)",
320
            )
321131×
            .bind(identity.hash().to_hex())
322131×
            .bind(role)
323131×
            .bind(&identity.name)
324131×
            .bind(identity.encode())
325131×
            .bind(identity.previous.map(|k| k.to_hex()))
326131×
            .bind(e.seq as i64)
327131×
            .execute(&mut *conn)
328131×
            .await?;
329
        }
330442×
        "agent.added" => {
33147×
            let Some(identity) = id(&p) else { return Ok(()) };
33247×
            if p.get("name").and_then(Json::as_str).is_none_or(str::is_empty) {
3330×
                return Ok(());
33447×
            }
335282×
            let s = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or("").to_string();
33647×
            sqlx::query(
33747×
                "INSERT OR REPLACE INTO agents (name, key, owner, owner_name, kind, project, home, uid, learn_uid, scopes, created_ms, disabled_ms, seq) \
33847×
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
339
            )
34047×
            .bind(s("name"))
34147×
            .bind(identity.hash().to_hex())
34247×
            .bind(s("owner"))
34347×
            .bind(s("owner_name"))
34447×
            .bind(s("kind"))
34547×
            .bind(s("project"))
34647×
            .bind(s("home"))
34747×
            .bind(p.get("uid").and_then(Json::as_i64))
34847×
            .bind(p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false))
34947×
            .bind(p.get("scopes").map(|v| v.to_string()).unwrap_or_else(|| "[]".into()))
35047×
            .bind(e.at_ms as i64)
35147×
            .bind(e.seq as i64)
35247×
            .execute(&mut *conn)
35347×
            .await?;
35447×
            sqlx::query(
35547×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, 'agent', ?, ?, ?, 1, ?)",
356
            )
35747×
            .bind(identity.hash().to_hex())
35847×
            .bind(&identity.name)
35947×
            .bind(identity.encode())
36047×
            .bind(identity.previous.map(|k| k.to_hex()))
36147×
            .bind(e.seq as i64)
36247×
            .execute(&mut *conn)
36347×
            .await?;
364
        }
365395×
        "agent.disabled" => {
3663×
            sqlx::query("UPDATE agents SET disabled_ms = ? WHERE name = ?")
3673×
                .bind(e.at_ms as i64)
3683×
                .bind(p.get("name").and_then(Json::as_str))
3693×
                .execute(&mut *conn)
3703×
                .await?;
371
        }
372392×
        _ => {}
373
    }
374573×
    Ok(())
37542541×
}
376
377
/// The payload of an identity event for `identity`.
378145×
pub fn identity_payload(identity: &Identity) -> Json {
379145×
    serde_json::json!({ "key": identity.hash().to_hex(), "name": identity.name, "identity": hex::encode(identity.encode()) })
380145×
}
381
382696×
fn identity_of(p: &Json) -> Result<Identity, String> {
383696×
    let b = p.get("identity").and_then(Json::as_str).and_then(|h| hex::decode(h).ok()).ok_or("no identity in the event")?;
384696×
    Identity::decode(&b).map_err(|e| format!("malformed identity: {e}"))
385696×
}
386
387227×
fn text(p: &Json, k: &str) -> Result<String, String> {
388227×
    p.get(k).and_then(Json::as_str).map(String::from).ok_or_else(|| format!("no {k}"))
389227×
}
390
391406×
fn self_signed(e: &Event, id: &Identity) -> Result<(), String> {
392406×
    if e.auth.key != Some(id.hash().0) {
3931×
        return Err("not signed by the identity it records".into());
394405×
    }
395405×
    check_proof(e, id)
396406×
}
397
398
/// The event's proof verifies against `identity`, and a CLI proof covers
399
/// exactly the event's payload.
400601×
fn check_proof(e: &Event, identity: &Identity) -> Result<(), String> {
401601×
    let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
402601×
    if proof.key() != identity.hash().0 {
4030×
        return Err("the proof is by another key".into());
404601×
    }
405601×
    let body = (proof.method == "cli").then(|| e.payload.as_deref().unwrap_or(b""));
406601×
    proof.verify(identity, body)
407601×
}
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`).
412112×
fn accept_successor(cur: &Identity, new: &Identity, p: &Json) -> Result<(), String> {
413112×
    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());
415112×
    }
416112×
    let chain: Vec<Identity> = p
417112×
        .get("chain")
418112×
        .and_then(Json::as_array)
419112×
        .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())
420112×
        .unwrap_or_default();
421112×
    let mut at = new.clone();
422112×
    for _ in 0..=chain.len() {
423112×
        match at.previous {
424112×
            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())
433112×
}
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.
437198×
pub fn signed_event(pair: &crate::keys::KeyPair, actor: &str, kind: &str, payload: Json) -> crate::event::NewEvent {
438198×
    let body = crate::event::canonical_json(&payload);
439198×
    let proof = Proof::sign(pair, "cli", &body);
440198×
    crate::event::NewEvent::system(kind, payload)
441198×
        .by(actor, crate::event::Auth { key: Some(pair.key.0), method: Method::Signature, assurance: 2, proof: Some(proof.encode()) })
442198×
}