OXYGENHUB

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

301 of 326 lines run, 42 of 100 functions · run #28 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::identity::Identity;
20
use crate::identity::KeyId;
21
use crate::ledger::KeyResolver;
22
use crate::proof::Proof;
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
/// Who caused something.
31
#[derive(Clone, Debug, PartialEq, Eq)]
32
pub enum Principal {
33
    Owner { key: KeyId, name: String },
34
    Agent { name: String, key: KeyId, owner_name: String, uid: Option<u32>, learn_uid: bool, project: String, scopes: Vec<String> },
35
    Instance { key: KeyId },
36
}
37
38
impl Principal {
39
    /// The `actor` events carry: `human`, `agent:NAME` or `system`.
40383×
    pub fn actor(&self) -> String {
41383×
        match self {
4267×
            Principal::Owner { .. } => "human".into(),
43308×
            Principal::Agent { name, .. } => format!("agent:{name}"),
448×
            Principal::Instance { .. } => "system".into(),
45
        }
46383×
    }
47
    /// How it is shown to people: `claude-oxygen · Andy McCall's agent`.
4834×
    pub fn display(&self) -> String {
4934×
        match self {
5024×
            Principal::Owner { name, .. } => name.clone(),
5110×
            Principal::Agent { name, owner_name, .. } => format!("{name} · {owner_name}'s agent"),
520×
            Principal::Instance { .. } => "Spectra".into(),
53
        }
5434×
    }
55
}
56
57
#[derive(Clone, Debug)]
58
struct AgentRec {
59
    name: String,
60
    identity: Identity,
61
    owner_name: String,
62
    uid: Option<u32>,
63
    learn_uid: bool,
64
    project: String,
65
    scopes: Vec<String>,
66
    disabled: bool,
67
}
68
69
/// The principals as of some point in the ledger.
70
#[derive(Clone, Debug, Default)]
71
pub struct Principals {
72
    /// The owner's identities, oldest first; the last is current.
73
    owner: Vec<Identity>,
74
    instance: Option<Identity>,
75
    agents: HashMap<KeyId, AgentRec>,
76
    by_name: HashMap<String, KeyId>,
77
}
78
79
impl Principals {
80
    /// Replay every identity and agent event of the ledger.
81176×
    pub async fn load(ledger: &crate::ledger::Ledger) -> anyhow::Result<Principals> {
82176×
        let mut p = Principals::default();
83176×
        let mut from = 1;
84
        loop {
85351×
            let rows = ledger
86351×
                .events_of_kinds(from, &["identity.owner", "identity.rotated", "identity.instance", "agent.added", "agent.disabled"], 1000)
87351×
                .await?;
88348×
            if rows.is_empty() {
89173×
                break;
90175×
            }
91657×
            for e in &rows {
92657×
                // Recorded facts were checked when written; `verify` checks them again.
93657×
                let _ = p.observe(e);
94657×
            }
95175×
            from = rows.last().map(|e| e.seq + 1).unwrap_or(from);
96
        }
97173×
        Ok(p)
98173×
    }
99
100
    /// The owner's current identity.
101835×
    pub fn owner(&self) -> Option<&Identity> {
102835×
        self.owner.last()
103835×
    }
104
10531×
    pub fn instance(&self) -> Option<&Identity> {
10631×
        self.instance.as_ref()
10731×
    }
108
109
    /// The agent named `name`, whatever its state.
11025×
    pub fn agent_key(&self, name: &str) -> Option<KeyId> {
11125×
        self.by_name.get(name).copied()
11225×
    }
113
114
    /// Who `key` is at `at_ms`, if anyone may act with it then: the owner
115
    /// (any of its identities' KeyIds), the instance, or an agent that is
116
    /// not disabled and that the owner's current identity delegates to.
117330×
    pub fn principal(&self, key: &KeyId, at_ms: u64) -> Result<Principal, String> {
118664×
        if let Some(owner) = self.owner.iter().rev().find(|i| &i.hash() == key) {
119131×
            return Ok(Principal::Owner { key: *key, name: owner.name.clone() });
120199×
        }
121199×
        if self.instance.as_ref().is_some_and(|i| &i.hash() == key) {
1228×
            return Ok(Principal::Instance { key: *key });
123191×
        }
124191×
        let a = self.agents.get(key).ok_or("an unknown key")?;
125188×
        if a.disabled {
1266×
            return Err(format!("agent {} is disabled", a.name));
127182×
        }
128182×
        let owner = self.owner().ok_or("no owner is recorded")?;
129182×
        if !owner.delegates_to(key, at_ms) {
1301×
            return Err(match owner.delegate(key) {
1311×
                Some(d) if d.expires.is_some_and(|x| at_ms > x) => format!("agent {}'s delegation from {} has expired", a.name, owner.name),
1320×
                Some(_) => format!("{}'s delegation to agent {} does not include `changes`", owner.name, a.name),
1330×
                None => format!("{}'s current identity does not delegate to agent {}", owner.name, a.name),
134
            });
135181×
        }
136181×
        Ok(Principal::Agent {
137181×
            name: a.name.clone(),
138181×
            key: *key,
139181×
            owner_name: a.owner_name.clone(),
140181×
            uid: a.uid,
141181×
            learn_uid: a.learn_uid,
142181×
            project: a.project.clone(),
143181×
            scopes: a.scopes.clone(),
144181×
        })
145330×
    }
146
147
    /// The identity behind `key`, for checking its signatures.
148258×
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
149258×
        self.owner
150258×
            .iter()
151640×
            .find(|i| &i.hash() == key)
152258×
            .or_else(|| self.instance.as_ref().filter(|i| &i.hash() == key))
153258×
            .or_else(|| self.agents.get(key).map(|a| &a.identity))
154258×
    }
155
156
    /// Take one event into account, checking what it claims first.
157821×
    pub fn observe(&mut self, e: &Event) -> Result<(), String> {
158821×
        let p = e.json();
159821×
        match e.kind.as_str() {
160821×
            "identity.owner" => {
161206×
                if !self.owner.is_empty() {
1621×
                    return Err("an owner is already recorded".into());
163205×
                }
164205×
                let id = identity_of(&p)?;
165205×
                self_signed(e, &id)?;
166205×
                self.owner.push(id);
167
            }
168615×
            "identity.rotated" => {
169220×
                let new = identity_of(&p)?;
170220×
                let cur = self.owner().ok_or("no owner to succeed")?.clone();
171220×
                accept_successor(&cur, &new, &p)?;
172220×
                self_signed(e, &new)?;
173219×
                self.owner.push(new);
174
            }
175395×
            "identity.instance" => {
176208×
                let id = identity_of(&p)?;
177208×
                self_signed(e, &id)?;
178208×
                self.instance = Some(id);
179
            }
180187×
            "agent.added" => {
181175×
                let id = identity_of(&p)?;
182175×
                let key = id.hash();
183175×
                let owner = self.owner_signed(e)?;
184175×
                if !owner.delegates_to(&key, e.hlc.wall_ms) {
1851×
                    return Err("added without the owner's delegation to its key".into());
186174×
                }
187174×
                let name = text(&p, "name")?;
188174×
                if self.by_name.get(&name).is_some_and(|k| *k != key) {
1890×
                    return Err(format!("agent {name} already exists with another key"));
190174×
                }
191174×
                self.by_name.insert(name.clone(), key);
192174×
                self.agents.insert(
193174×
                    key,
194
                    AgentRec {
195174×
                        name,
196174×
                        identity: id,
197174×
                        owner_name: owner.name.clone(),
198174×
                        uid: p.get("uid").and_then(Json::as_u64).map(|u| u as u32),
199174×
                        learn_uid: p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false),
200174×
                        project: text(&p, "project")?,
201174×
                        scopes: p
202174×
                            .get("scopes")
203174×
                            .and_then(Json::as_array)
2041296×
                            .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())
205174×
                            .unwrap_or_default(),
206
                        disabled: false,
207
                    },
208
                );
209
            }
21012×
            "agent.uid_bound" => {
211
                // The daemon binds a learning agent to the uid of its first
212
                // signed connection; covered by the next checkpoint.
2131×
                let name = text(&p, "name")?;
2141×
                let uid = p.get("uid").and_then(Json::as_u64).ok_or("no uid")? as u32;
2151×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
2161×
                if let Some(a) = self.agents.get_mut(&key) {
2171×
                    if a.uid.is_none() {
2181×
                        a.uid = Some(uid);
2191×
                    }
2200×
                }
221
            }
22211×
            "agent.disabled" => {
22311×
                self.owner_signed(e)?;
22411×
                let name = text(&p, "name")?;
22511×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
22611×
                if let Some(a) = self.agents.get_mut(&key) {
22711×
                    a.disabled = true;
22811×
                }
229
            }
2300×
            _ => {}
231
        }
232818×
        Ok(())
233821×
    }
234
235
    /// Check that `e` is signed by the owner's current identity; returns it.
236186×
    fn owner_signed(&self, e: &Event) -> Result<Identity, String> {
237186×
        let owner = self.owner().ok_or("no owner is recorded")?.clone();
238186×
        if e.auth.key != Some(owner.hash().0) {
2390×
            return Err("not signed by the owner's current identity".into());
240186×
        }
241186×
        check_proof(e, &owner)?;
242186×
        Ok(owner)
243186×
    }
244
245
    /// An event from a Radar session: its proof is the owner's signed
246
    /// request for the sign-in link, so it must verify against the owner,
247
    /// and only the owner acts this way.
2485×
    pub fn check_session(&self, e: &Event) -> Result<(), String> {
2495×
        let key = crate::identity::KeyId(e.auth.key.ok_or("a session event names no key")?);
2505×
        if !matches!(self.principal(&key, e.hlc.wall_ms)?, Principal::Owner { .. }) || e.actor != "human" {
2510×
            return Err("only the owner acts through a Radar session".into());
2525×
        }
2535×
        let identity = self.identity(&key).ok_or("an unknown key")?;
2545×
        let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
2555×
        if proof.key() != key.0 || proof.method != "POST /radar/link" {
2560×
            return Err("the session's proof is not the owner's sign-in request".into());
2575×
        }
2585×
        proof.verify(identity, None)
2595×
    }
260
261
    /// Check a signed event's proof against the principal its key was at
262
    /// the event's time.
263128×
    pub fn check_signed(&self, e: &Event) -> Result<(), String> {
264128×
        let key = crate::identity::KeyId(e.auth.key.ok_or("signed, but names no key")?);
265128×
        let who = self.principal(&key, e.hlc.wall_ms)?;
266
        // The actor an event names must be the principal that signed it:
267
        // an agent's key never makes an event in another's name.
268126×
        if who.actor() != e.actor {
2692×
            return Err(format!("names {} as its actor but is signed by {}", e.actor, who.display()));
270124×
        }
271124×
        let identity = self.identity(&key).ok_or("an unknown key")?;
272124×
        check_proof(e, identity)
273128×
    }
274
}
275
276
impl KeyResolver for Principals {
277492×
    fn check(&mut self, e: &Event) -> Result<(), String> {
278492×
        match e.kind.as_str() {
279492×
            "identity.owner" | "identity.rotated" | "identity.instance" | "agent.added" | "agent.disabled" => {
280165×
                if e.auth.method != Method::Signature {
2812×
                    return Err(format!("{} must be signed", e.kind));
282163×
                }
283163×
                self.observe(e)
284
            }
285327×
            "agent.uid_bound" => self.observe(e),
286326×
            _ if matches!(e.auth.method, Method::Signature | Method::Passkey) => self.check_signed(e),
287198×
            _ if e.auth.method == Method::Session => self.check_session(e),
288193×
            _ => Ok(()),
289
        }
290492×
    }
291
}
292
293
/// Apply identity and agent events to the projection tables.
29442737×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
29542737×
    if e.kind == "agent.uid_bound" {
2961×
        let p = e.json();
2971×
        sqlx::query("UPDATE agents SET uid = ? WHERE name = ? AND uid IS NULL")
2981×
            .bind(p.get("uid").and_then(Json::as_i64))
2991×
            .bind(p.get("name").and_then(Json::as_str))
3001×
            .execute(&mut *conn)
3011×
            .await?;
3021×
        return Ok(());
30342736×
    }
304
    // Who is who is only ever said by a signature; `verify` checks which.
30542736×
    if e.auth.method != Method::Signature {
30642003×
        return Ok(());
307733×
    }
308733×
    let p = e.json();
309733×
    let id = |p: &Json| identity_of(p).ok();
310733×
    match e.kind.as_str() {
311733×
        "identity.owner" | "identity.rotated" | "identity.instance" => {
312162×
            let Some(identity) = id(&p) else { return Ok(()) };
313162×
            let role = if e.kind == "identity.instance" { "instance" } else { "owner" };
314162×
            sqlx::query("UPDATE identities SET current = 0 WHERE role = ?").bind(role).execute(&mut *conn).await?;
315162×
            sqlx::query(
316162×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, ?, ?, ?, ?, 1, ?)",
317
            )
318162×
            .bind(identity.hash().to_hex())
319162×
            .bind(role)
320162×
            .bind(&identity.name)
321162×
            .bind(identity.encode())
322162×
            .bind(identity.previous.map(|k| k.to_hex()))
323162×
            .bind(e.seq as i64)
324162×
            .execute(&mut *conn)
325162×
            .await?;
326
        }
327571×
        "agent.added" => {
32855×
            let Some(identity) = id(&p) else { return Ok(()) };
32955×
            if p.get("name").and_then(Json::as_str).is_none_or(str::is_empty) {
3300×
                return Ok(());
33155×
            }
332330×
            let s = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or("").to_string();
33355×
            sqlx::query(
33455×
                "INSERT OR REPLACE INTO agents (name, key, owner, owner_name, kind, project, home, uid, learn_uid, scopes, created_ms, disabled_ms, seq) \
33555×
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
336
            )
33755×
            .bind(s("name"))
33855×
            .bind(identity.hash().to_hex())
33955×
            .bind(s("owner"))
34055×
            .bind(s("owner_name"))
34155×
            .bind(s("kind"))
34255×
            .bind(s("project"))
34355×
            .bind(s("home"))
34455×
            .bind(p.get("uid").and_then(Json::as_i64))
34555×
            .bind(p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false))
34655×
            .bind(p.get("scopes").map(|v| v.to_string()).unwrap_or_else(|| "[]".into()))
34755×
            .bind(e.at_ms as i64)
34855×
            .bind(e.seq as i64)
34955×
            .execute(&mut *conn)
35055×
            .await?;
35155×
            sqlx::query(
35255×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, 'agent', ?, ?, ?, 1, ?)",
353
            )
35455×
            .bind(identity.hash().to_hex())
35555×
            .bind(&identity.name)
35655×
            .bind(identity.encode())
35755×
            .bind(identity.previous.map(|k| k.to_hex()))
35855×
            .bind(e.seq as i64)
35955×
            .execute(&mut *conn)
36055×
            .await?;
361
        }
362516×
        "agent.disabled" => {
3634×
            sqlx::query("UPDATE agents SET disabled_ms = ? WHERE name = ?")
3644×
                .bind(e.at_ms as i64)
3654×
                .bind(p.get("name").and_then(Json::as_str))
3664×
                .execute(&mut *conn)
3674×
                .await?;
368
        }
369512×
        _ => {}
370
    }
371733×
    Ok(())
37242737×
}
373
374
/// The payload of an identity event for `identity`.
375199×
pub fn identity_payload(identity: &Identity) -> Json {
376199×
    serde_json::json!({ "key": identity.hash().to_hex(), "name": identity.name, "identity": hex::encode(identity.encode()) })
377199×
}
378
3791025×
fn identity_of(p: &Json) -> Result<Identity, String> {
3801025×
    let b = p.get("identity").and_then(Json::as_str).and_then(|h| hex::decode(h).ok()).ok_or("no identity in the event")?;
3811025×
    Identity::decode(&b).map_err(|e| format!("malformed identity: {e}"))
3821025×
}
383
384360×
fn text(p: &Json, k: &str) -> Result<String, String> {
385360×
    p.get(k).and_then(Json::as_str).map(String::from).ok_or_else(|| format!("no {k}"))
386360×
}
387
388633×
fn self_signed(e: &Event, id: &Identity) -> Result<(), String> {
389633×
    if e.auth.key != Some(id.hash().0) {
3901×
        return Err("not signed by the identity it records".into());
391632×
    }
392632×
    check_proof(e, id)
393633×
}
394
395
/// The event's proof verifies against `identity`, and a CLI proof covers
396
/// exactly the event's payload.
397942×
fn check_proof(e: &Event, identity: &Identity) -> Result<(), String> {
398942×
    let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
399942×
    if proof.key() != identity.hash().0 {
4000×
        return Err("the proof is by another key".into());
401942×
    }
402942×
    let body = (proof.method == "cli").then(|| e.payload.as_deref().unwrap_or(b""));
403942×
    proof.verify(identity, body)
404942×
}
405
406
/// A successor of the owner must keep the key pair and chain back to the
407
/// current identity through `previous` (the intermediate identities, if
408
/// any, are carried in the event as `chain`).
409220×
fn accept_successor(cur: &Identity, new: &Identity, p: &Json) -> Result<(), String> {
410220×
    if new.ed25519_pk != cur.ed25519_pk || new.mldsa65_pk != cur.mldsa65_pk {
4110×
        return Err("a successor with a fresh key pair needs `oxy identity rotate`'s attestation, not accepted in 0.1".into());
412220×
    }
413220×
    let chain: Vec<Identity> = p
414220×
        .get("chain")
415220×
        .and_then(Json::as_array)
416220×
        .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())
417220×
        .unwrap_or_default();
418220×
    let mut at = new.clone();
419220×
    for _ in 0..=chain.len() {
420220×
        match at.previous {
421220×
            Some(prev) if prev == cur.hash() => return Ok(()),
4220×
            Some(prev) => match chain.iter().find(|i| i.hash() == prev) {
4230×
                Some(i) if i.ed25519_pk == cur.ed25519_pk => at = i.clone(),
4240×
                _ => break,
425
            },
4260×
            None => break,
427
        }
428
    }
4290×
    Err("does not succeed the recorded owner".into())
430220×
}
431
432
/// An event signed by `pair` from the command line: its proof covers the
433
/// canonical payload, so the event's content is bound to the signature.
434239×
pub fn signed_event(pair: &crate::keys::KeyPair, actor: &str, kind: &str, payload: Json) -> crate::event::NewEvent {
435239×
    let body = crate::event::canonical_json(&payload);
436239×
    let proof = Proof::sign(pair, "cli", &body);
437239×
    crate::event::NewEvent::system(kind, payload)
438239×
        .by(actor, crate::event::Auth { key: Some(pair.key.0), method: Method::Signature, assurance: 2, proof: Some(proof.encode()) })
439239×
}