OXYGENHUB

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

343 of 373 lines run, 47 of 110 functions · run #32 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`.
40425×
    pub fn actor(&self) -> String {
41425×
        match self {
4271×
            Principal::Owner { .. } => "human".into(),
43346×
            Principal::Agent { name, .. } => format!("agent:{name}"),
448×
            Principal::Instance { .. } => "system".into(),
45
        }
46425×
    }
47
    /// How it is shown to people: `claude-oxygen · Andy McCall's agent`.
4837×
    pub fn display(&self) -> String {
4937×
        match self {
5025×
            Principal::Owner { name, .. } => name.clone(),
5112×
            Principal::Agent { name, owner_name, .. } => format!("{name} · {owner_name}'s agent"),
520×
            Principal::Instance { .. } => "Spectra".into(),
53
        }
5437×
    }
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.
81205×
    pub async fn load(ledger: &crate::ledger::Ledger) -> anyhow::Result<Principals> {
82205×
        let mut p = Principals::default();
83205×
        let mut from = 1;
84
        loop {
85410×
            let rows = ledger
86410×
                .events_of_kinds(
87410×
                    from,
88410×
                    &["identity.owner", "identity.rotated", "identity.instance", "agent.added", "agent.disabled", "agent.scoped"],
89410×
                    1000,
90410×
                )
91410×
                .await?;
92406×
            if rows.is_empty() {
93201×
                break;
94205×
            }
95767×
            for e in &rows {
96767×
                // Recorded facts were checked when written; `verify` checks them again.
97767×
                let _ = p.observe(e);
98767×
            }
99205×
            from = rows.last().map(|e| e.seq + 1).unwrap_or(from);
100
        }
101201×
        Ok(p)
102201×
    }
103
104
    /// The owner's current identity.
105958×
    pub fn owner(&self) -> Option<&Identity> {
106958×
        self.owner.last()
107958×
    }
108
10932×
    pub fn instance(&self) -> Option<&Identity> {
11032×
        self.instance.as_ref()
11132×
    }
112
113
    /// The agent named `name`, whatever its state.
11429×
    pub fn agent_key(&self, name: &str) -> Option<KeyId> {
11529×
        self.by_name.get(name).copied()
11629×
    }
117
118
    /// Who `key` is at `at_ms`, if anyone may act with it then: the owner
119
    /// (any of its identities' KeyIds), the instance, or an agent that is
120
    /// not disabled and that the owner's current identity delegates to.
121367×
    pub fn principal(&self, key: &KeyId, at_ms: u64) -> Result<Principal, String> {
122736×
        if let Some(owner) = self.owner.iter().rev().find(|i| &i.hash() == key) {
123144×
            return Ok(Principal::Owner { key: *key, name: owner.name.clone() });
124223×
        }
125223×
        if self.instance.as_ref().is_some_and(|i| &i.hash() == key) {
1268×
            return Ok(Principal::Instance { key: *key });
127215×
        }
128215×
        let a = self.agents.get(key).ok_or("an unknown key")?;
129212×
        if a.disabled {
1306×
            return Err(format!("agent {} is disabled", a.name));
131206×
        }
132206×
        let owner = self.owner().ok_or("no owner is recorded")?;
133206×
        if !owner.delegates_to(key, at_ms) {
1341×
            return Err(match owner.delegate(key) {
1351×
                Some(d) if d.expires.is_some_and(|x| at_ms > x) => format!("agent {}'s delegation from {} has expired", a.name, owner.name),
1360×
                Some(_) => format!("{}'s delegation to agent {} does not include `changes`", owner.name, a.name),
1370×
                None => format!("{}'s current identity does not delegate to agent {}", owner.name, a.name),
138
            });
139205×
        }
140205×
        Ok(Principal::Agent {
141205×
            name: a.name.clone(),
142205×
            key: *key,
143205×
            owner_name: a.owner_name.clone(),
144205×
            uid: a.uid,
145205×
            learn_uid: a.learn_uid,
146205×
            project: a.project.clone(),
147205×
            scopes: a.scopes.clone(),
148205×
        })
149367×
    }
150
151
    /// The identity behind `key`, for checking its signatures.
152288×
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
153288×
        self.owner
154288×
            .iter()
155704×
            .find(|i| &i.hash() == key)
156288×
            .or_else(|| self.instance.as_ref().filter(|i| &i.hash() == key))
157288×
            .or_else(|| self.agents.get(key).map(|a| &a.identity))
158288×
    }
159
160
    /// Take one event into account, checking what it claims first.
161939×
    pub fn observe(&mut self, e: &Event) -> Result<(), String> {
162939×
        let p = e.json();
163939×
        match e.kind.as_str() {
164939×
            "identity.owner" => {
165237×
                if !self.owner.is_empty() {
1661×
                    return Err("an owner is already recorded".into());
167236×
                }
168236×
                let id = identity_of(&p)?;
169236×
                self_signed(e, &id)?;
170236×
                self.owner.push(id);
171
            }
172702×
            "identity.rotated" => {
173242×
                let new = identity_of(&p)?;
174242×
                let cur = self.owner().ok_or("no owner to succeed")?.clone();
175242×
                accept_successor(&cur, &new, &p)?;
176242×
                self_signed(e, &new)?;
177241×
                self.owner.push(new);
178
            }
179460×
            "identity.instance" => {
180239×
                let id = identity_of(&p)?;
181239×
                self_signed(e, &id)?;
182239×
                self.instance = Some(id);
183
            }
184221×
            "agent.added" => {
185197×
                let id = identity_of(&p)?;
186197×
                let key = id.hash();
187197×
                let owner = self.owner_signed(e)?;
188197×
                if !owner.delegates_to(&key, e.hlc.wall_ms) {
1891×
                    return Err("added without the owner's delegation to its key".into());
190196×
                }
191196×
                let name = text(&p, "name")?;
192196×
                if self.by_name.get(&name).is_some_and(|k| *k != key) {
1930×
                    return Err(format!("agent {name} already exists with another key"));
194196×
                }
195196×
                self.by_name.insert(name.clone(), key);
196196×
                self.agents.insert(
197196×
                    key,
198
                    AgentRec {
199196×
                        name,
200196×
                        identity: id,
201196×
                        owner_name: owner.name.clone(),
202196×
                        uid: p.get("uid").and_then(Json::as_u64).map(|u| u as u32),
203196×
                        learn_uid: p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false),
204196×
                        project: text(&p, "project")?,
205196×
                        scopes: p
206196×
                            .get("scopes")
207196×
                            .and_then(Json::as_array)
2081472×
                            .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())
209196×
                            .unwrap_or_default(),
210
                        disabled: false,
211
                    },
212
                );
213
            }
21424×
            "agent.uid_bound" => {
215
                // The daemon binds a learning agent to the uid of its first
216
                // signed connection; covered by the next checkpoint.
2171×
                let name = text(&p, "name")?;
2181×
                let uid = p.get("uid").and_then(Json::as_u64).ok_or("no uid")? as u32;
2191×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
2201×
                if let Some(a) = self.agents.get_mut(&key) {
2211×
                    if a.uid.is_none() {
2221×
                        a.uid = Some(uid);
2231×
                    }
2240×
                }
225
            }
22623×
            "agent.disabled" => {
22711×
                self.owner_signed(e)?;
22811×
                let name = text(&p, "name")?;
22911×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
23011×
                if let Some(a) = self.agents.get_mut(&key) {
23111×
                    a.disabled = true;
23211×
                }
233
            }
234
            // The owner grants or takes back one scope (spec §8.4), such
235
            // as `channel:NAME` to post in another project's channel.
23612×
            "agent.scoped" => {
23712×
                self.owner_signed(e)?;
23812×
                let name = text(&p, "name")?;
23912×
                let scope = text(&p, "scope")?;
24012×
                if !grantable(&scope) {
2410×
                    return Err(format!("{scope} is not a scope an agent may be given"));
24212×
                }
24312×
                let grant = p.get("grant").and_then(Json::as_bool).unwrap_or(true);
24412×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
24512×
                if let Some(a) = self.agents.get_mut(&key) {
246100×
                    a.scopes.retain(|s| s != &scope);
24712×
                    if grant {
2488×
                        a.scopes.push(scope);
2498×
                    }
2500×
                }
251
            }
2520×
            _ => {}
253
        }
254936×
        Ok(())
255939×
    }
256
257
    /// Check that `e` is signed by the owner's current identity; returns it.
258220×
    fn owner_signed(&self, e: &Event) -> Result<Identity, String> {
259220×
        let owner = self.owner().ok_or("no owner is recorded")?.clone();
260220×
        if e.auth.key != Some(owner.hash().0) {
2610×
            return Err("not signed by the owner's current identity".into());
262220×
        }
263220×
        check_proof(e, &owner)?;
264220×
        Ok(owner)
265220×
    }
266
267
    /// An event from a Radar session: its proof is the owner's signed
268
    /// request for the sign-in link, so it must verify against the owner,
269
    /// and only the owner acts this way.
2705×
    pub fn check_session(&self, e: &Event) -> Result<(), String> {
2715×
        let key = crate::identity::KeyId(e.auth.key.ok_or("a session event names no key")?);
2725×
        if !matches!(self.principal(&key, e.hlc.wall_ms)?, Principal::Owner { .. }) || e.actor != "human" {
2730×
            return Err("only the owner acts through a Radar session".into());
2745×
        }
2755×
        let identity = self.identity(&key).ok_or("an unknown key")?;
2765×
        let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
2775×
        if proof.key() != key.0 || proof.method != "POST /radar/link" {
2780×
            return Err("the session's proof is not the owner's sign-in request".into());
2795×
        }
2805×
        proof.verify(identity, None)
2815×
    }
282
283
    /// Check a signed event's proof against the principal its key was at
284
    /// the event's time.
285137×
    pub fn check_signed(&self, e: &Event) -> Result<(), String> {
286137×
        let key = crate::identity::KeyId(e.auth.key.ok_or("signed, but names no key")?);
287137×
        let who = self.principal(&key, e.hlc.wall_ms)?;
288
        // The actor an event names must be the principal that signed it:
289
        // an agent's key never makes an event in another's name.
290135×
        if who.actor() != e.actor {
2912×
            return Err(format!("names {} as its actor but is signed by {}", e.actor, who.display()));
292133×
        }
293133×
        let identity = self.identity(&key).ok_or("an unknown key")?;
294133×
        check_proof(e, identity)
295137×
    }
296
}
297
298
impl KeyResolver for Principals {
299515×
    fn check(&mut self, e: &Event) -> Result<(), String> {
300515×
        match e.kind.as_str() {
301515×
            "identity.owner" | "identity.rotated" | "identity.instance" | "agent.added" | "agent.disabled" | "agent.scoped" => {
302173×
                if e.auth.method != Method::Signature {
3032×
                    return Err(format!("{} must be signed", e.kind));
304171×
                }
305171×
                self.observe(e)
306
            }
307342×
            "agent.uid_bound" => self.observe(e),
308341×
            _ if matches!(e.auth.method, Method::Signature | Method::Passkey) => self.check_signed(e),
309204×
            _ if e.auth.method == Method::Session => self.check_session(e),
310199×
            _ => Ok(()),
311
        }
312515×
    }
313
}
314
315
/// Apply identity and agent events to the projection tables.
31642869×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
31742869×
    if e.kind == "agent.uid_bound" {
3181×
        let p = e.json();
3191×
        sqlx::query("UPDATE agents SET uid = ? WHERE name = ? AND uid IS NULL")
3201×
            .bind(p.get("uid").and_then(Json::as_i64))
3211×
            .bind(p.get("name").and_then(Json::as_str))
3221×
            .execute(&mut *conn)
3231×
            .await?;
3241×
        return Ok(());
32542868×
    }
326
    // Who is who is only ever said by a signature; `verify` checks which.
32742868×
    if e.auth.method != Method::Signature {
32842036×
        return Ok(());
329832×
    }
330832×
    let p = e.json();
331832×
    let id = |p: &Json| identity_of(p).ok();
332832×
    match e.kind.as_str() {
333832×
        "identity.owner" | "identity.rotated" | "identity.instance" => {
334180×
            let Some(identity) = id(&p) else { return Ok(()) };
335180×
            let role = if e.kind == "identity.instance" { "instance" } else { "owner" };
336180×
            sqlx::query("UPDATE identities SET current = 0 WHERE role = ?").bind(role).execute(&mut *conn).await?;
337180×
            sqlx::query(
338180×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, ?, ?, ?, ?, 1, ?)",
339
            )
340180×
            .bind(identity.hash().to_hex())
341180×
            .bind(role)
342180×
            .bind(&identity.name)
343180×
            .bind(identity.encode())
344180×
            .bind(identity.previous.map(|k| k.to_hex()))
345180×
            .bind(e.seq as i64)
346180×
            .execute(&mut *conn)
347180×
            .await?;
348
        }
349652×
        "agent.added" => {
35061×
            let Some(identity) = id(&p) else { return Ok(()) };
35161×
            if p.get("name").and_then(Json::as_str).is_none_or(str::is_empty) {
3520×
                return Ok(());
35361×
            }
354366×
            let s = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or("").to_string();
35561×
            sqlx::query(
35661×
                "INSERT OR REPLACE INTO agents (name, key, owner, owner_name, kind, project, home, uid, learn_uid, scopes, created_ms, disabled_ms, seq) \
35761×
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
358
            )
35961×
            .bind(s("name"))
36061×
            .bind(identity.hash().to_hex())
36161×
            .bind(s("owner"))
36261×
            .bind(s("owner_name"))
36361×
            .bind(s("kind"))
36461×
            .bind(s("project"))
36561×
            .bind(s("home"))
36661×
            .bind(p.get("uid").and_then(Json::as_i64))
36761×
            .bind(p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false))
36861×
            .bind(p.get("scopes").map(|v| v.to_string()).unwrap_or_else(|| "[]".into()))
36961×
            .bind(e.at_ms as i64)
37061×
            .bind(e.seq as i64)
37161×
            .execute(&mut *conn)
37261×
            .await?;
37361×
            sqlx::query(
37461×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, 'agent', ?, ?, ?, 1, ?)",
375
            )
37661×
            .bind(identity.hash().to_hex())
37761×
            .bind(&identity.name)
37861×
            .bind(identity.encode())
37961×
            .bind(identity.previous.map(|k| k.to_hex()))
38061×
            .bind(e.seq as i64)
38161×
            .execute(&mut *conn)
38261×
            .await?;
383
        }
384591×
        "agent.disabled" => {
3854×
            sqlx::query("UPDATE agents SET disabled_ms = ? WHERE name = ?")
3864×
                .bind(e.at_ms as i64)
3874×
                .bind(p.get("name").and_then(Json::as_str))
3884×
                .execute(&mut *conn)
3894×
                .await?;
390
        }
391587×
        "agent.scoped" if e.actor == "human" => {
3926×
            let (Some(name), Some(scope)) = (p.get("name").and_then(Json::as_str), p.get("scope").and_then(Json::as_str)) else {
3930×
                return Ok(());
394
            };
3956×
            if !grantable(scope) {
3960×
                return Ok(());
3976×
            }
3986×
            let grant = p.get("grant").and_then(Json::as_bool).unwrap_or(true);
3996×
            let current: Option<String> =
4006×
                sqlx::query_scalar("SELECT scopes FROM agents WHERE name = ?").bind(name).fetch_optional(&mut *conn).await?;
4016×
            let mut scopes: Vec<String> = current.and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
40251×
            scopes.retain(|s| s != scope);
4036×
            if grant {
4043×
                scopes.push(scope.to_string());
4053×
            }
4066×
            sqlx::query("UPDATE agents SET scopes = ? WHERE name = ?")
4076×
                .bind(serde_json::to_string(&scopes).unwrap_or_default())
4086×
                .bind(name)
4096×
                .execute(&mut *conn)
4106×
                .await?;
411
        }
412581×
        _ => {}
413
    }
414832×
    Ok(())
41542869×
}
416
417
/// A scope the owner may give an agent (spec §8.4): never the owner's own
418
/// authority, only reach.
41921×
pub fn grantable(scope: &str) -> bool {
42021×
    match scope.strip_prefix("channel:") {
421241×
        Some(ch) => !ch.is_empty() && ch.len() <= 64 && ch.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'),
4220×
        None => matches!(scope, "projects:all" | "schedule:any" | "webhooks:read"),
423
    }
42421×
}
425
426
/// The payload of an identity event for `identity`.
427216×
pub fn identity_payload(identity: &Identity) -> Json {
428216×
    serde_json::json!({ "key": identity.hash().to_hex(), "name": identity.name, "identity": hex::encode(identity.encode()) })
429216×
}
430
4311155×
fn identity_of(p: &Json) -> Result<Identity, String> {
4321155×
    let b = p.get("identity").and_then(Json::as_str).and_then(|h| hex::decode(h).ok()).ok_or("no identity in the event")?;
4331155×
    Identity::decode(&b).map_err(|e| format!("malformed identity: {e}"))
4341155×
}
435
436428×
fn text(p: &Json, k: &str) -> Result<String, String> {
437428×
    p.get(k).and_then(Json::as_str).map(String::from).ok_or_else(|| format!("no {k}"))
438428×
}
439
440717×
fn self_signed(e: &Event, id: &Identity) -> Result<(), String> {
441717×
    if e.auth.key != Some(id.hash().0) {
4421×
        return Err("not signed by the identity it records".into());
443716×
    }
444716×
    check_proof(e, id)
445717×
}
446
447
/// The event's proof verifies against `identity`, and a CLI proof covers
448
/// exactly the event's payload.
4491069×
fn check_proof(e: &Event, identity: &Identity) -> Result<(), String> {
4501069×
    let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
4511069×
    if proof.key() != identity.hash().0 {
4520×
        return Err("the proof is by another key".into());
4531069×
    }
4541069×
    let body = (proof.method == "cli").then(|| e.payload.as_deref().unwrap_or(b""));
4551069×
    proof.verify(identity, body)
4561069×
}
457
458
/// A successor of the owner must keep the key pair and chain back to the
459
/// current identity through `previous` (the intermediate identities, if
460
/// any, are carried in the event as `chain`).
461242×
fn accept_successor(cur: &Identity, new: &Identity, p: &Json) -> Result<(), String> {
462242×
    if new.ed25519_pk != cur.ed25519_pk || new.mldsa65_pk != cur.mldsa65_pk {
4630×
        return Err("a successor with a fresh key pair needs `oxy identity rotate`'s attestation, not accepted in 0.1".into());
464242×
    }
465242×
    let chain: Vec<Identity> = p
466242×
        .get("chain")
467242×
        .and_then(Json::as_array)
468242×
        .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())
469242×
        .unwrap_or_default();
470242×
    let mut at = new.clone();
471242×
    for _ in 0..=chain.len() {
472242×
        match at.previous {
473242×
            Some(prev) if prev == cur.hash() => return Ok(()),
4740×
            Some(prev) => match chain.iter().find(|i| i.hash() == prev) {
4750×
                Some(i) if i.ed25519_pk == cur.ed25519_pk => at = i.clone(),
4760×
                _ => break,
477
            },
4780×
            None => break,
479
        }
480
    }
4810×
    Err("does not succeed the recorded owner".into())
482242×
}
483
484
/// An event signed by `pair` from the command line: its proof covers the
485
/// canonical payload, so the event's content is bound to the signature.
486264×
pub fn signed_event(pair: &crate::keys::KeyPair, actor: &str, kind: &str, payload: Json) -> crate::event::NewEvent {
487264×
    let body = crate::event::canonical_json(&payload);
488264×
    let proof = Proof::sign(pair, "cli", &body);
489264×
    crate::event::NewEvent::system(kind, payload)
490264×
        .by(actor, crate::event::Auth { key: Some(pair.key.0), method: Method::Signature, assurance: 2, proof: Some(proof.encode()) })
491264×
}