OXYGENHUB

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

343 of 373 lines run, 47 of 110 functions · run #33 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`.
40442×
    pub fn actor(&self) -> String {
41442×
        match self {
4274×
            Principal::Owner { .. } => "human".into(),
43360×
            Principal::Agent { name, .. } => format!("agent:{name}"),
448×
            Principal::Instance { .. } => "system".into(),
45
        }
46442×
    }
47
    /// How it is shown to people: `claude-oxygen · Andy McCall's agent`.
4840×
    pub fn display(&self) -> String {
4940×
        match self {
5028×
            Principal::Owner { name, .. } => name.clone(),
5112×
            Principal::Agent { name, owner_name, .. } => format!("{name} · {owner_name}'s agent"),
520×
            Principal::Instance { .. } => "Spectra".into(),
53
        }
5440×
    }
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.
81218×
    pub async fn load(ledger: &crate::ledger::Ledger) -> anyhow::Result<Principals> {
82218×
        let mut p = Principals::default();
83218×
        let mut from = 1;
84
        loop {
85436×
            let rows = ledger
86436×
                .events_of_kinds(
87436×
                    from,
88436×
                    &["identity.owner", "identity.rotated", "identity.instance", "agent.added", "agent.disabled", "agent.scoped"],
89436×
                    1000,
90436×
                )
91436×
                .await?;
92432×
            if rows.is_empty() {
93214×
                break;
94218×
            }
95825×
            for e in &rows {
96825×
                // Recorded facts were checked when written; `verify` checks them again.
97825×
                let _ = p.observe(e);
98825×
            }
99218×
            from = rows.last().map(|e| e.seq + 1).unwrap_or(from);
100
        }
101214×
        Ok(p)
102214×
    }
103
104
    /// The owner's current identity.
1051003×
    pub fn owner(&self) -> Option<&Identity> {
1061003×
        self.owner.last()
1071003×
    }
108
10932×
    pub fn instance(&self) -> Option<&Identity> {
11032×
        self.instance.as_ref()
11132×
    }
112
113
    /// The agent named `name`, whatever its state.
11432×
    pub fn agent_key(&self, name: &str) -> Option<KeyId> {
11532×
        self.by_name.get(name).copied()
11632×
    }
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.
121376×
    pub fn principal(&self, key: &KeyId, at_ms: u64) -> Result<Principal, String> {
122754×
        if let Some(owner) = self.owner.iter().rev().find(|i| &i.hash() == key) {
123150×
            return Ok(Principal::Owner { key: *key, name: owner.name.clone() });
124226×
        }
125226×
        if self.instance.as_ref().is_some_and(|i| &i.hash() == key) {
1268×
            return Ok(Principal::Instance { key: *key });
127218×
        }
128218×
        let a = self.agents.get(key).ok_or("an unknown key")?;
129215×
        if a.disabled {
1306×
            return Err(format!("agent {} is disabled", a.name));
131209×
        }
132209×
        let owner = self.owner().ok_or("no owner is recorded")?;
133209×
        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
            });
139208×
        }
140208×
        Ok(Principal::Agent {
141208×
            name: a.name.clone(),
142208×
            key: *key,
143208×
            owner_name: a.owner_name.clone(),
144208×
            uid: a.uid,
145208×
            learn_uid: a.learn_uid,
146208×
            project: a.project.clone(),
147208×
            scopes: a.scopes.clone(),
148208×
        })
149376×
    }
150
151
    /// The identity behind `key`, for checking its signatures.
152294×
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
153294×
        self.owner
154294×
            .iter()
155722×
            .find(|i| &i.hash() == key)
156294×
            .or_else(|| self.instance.as_ref().filter(|i| &i.hash() == key))
157294×
            .or_else(|| self.agents.get(key).map(|a| &a.identity))
158294×
    }
159
160
    /// Take one event into account, checking what it claims first.
161997×
    pub fn observe(&mut self, e: &Event) -> Result<(), String> {
162997×
        let p = e.json();
163997×
        match e.kind.as_str() {
164997×
            "identity.owner" => {
165250×
                if !self.owner.is_empty() {
1661×
                    return Err("an owner is already recorded".into());
167249×
                }
168249×
                let id = identity_of(&p)?;
169249×
                self_signed(e, &id)?;
170249×
                self.owner.push(id);
171
            }
172747×
            "identity.rotated" => {
173258×
                let new = identity_of(&p)?;
174258×
                let cur = self.owner().ok_or("no owner to succeed")?.clone();
175258×
                accept_successor(&cur, &new, &p)?;
176258×
                self_signed(e, &new)?;
177257×
                self.owner.push(new);
178
            }
179489×
            "identity.instance" => {
180252×
                let id = identity_of(&p)?;
181252×
                self_signed(e, &id)?;
182252×
                self.instance = Some(id);
183
            }
184237×
            "agent.added" => {
185213×
                let id = identity_of(&p)?;
186213×
                let key = id.hash();
187213×
                let owner = self.owner_signed(e)?;
188213×
                if !owner.delegates_to(&key, e.hlc.wall_ms) {
1891×
                    return Err("added without the owner's delegation to its key".into());
190212×
                }
191212×
                let name = text(&p, "name")?;
192212×
                if self.by_name.get(&name).is_some_and(|k| *k != key) {
1930×
                    return Err(format!("agent {name} already exists with another key"));
194212×
                }
195212×
                self.by_name.insert(name.clone(), key);
196212×
                self.agents.insert(
197212×
                    key,
198
                    AgentRec {
199212×
                        name,
200212×
                        identity: id,
201212×
                        owner_name: owner.name.clone(),
202212×
                        uid: p.get("uid").and_then(Json::as_u64).map(|u| u as u32),
203212×
                        learn_uid: p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false),
204212×
                        project: text(&p, "project")?,
205212×
                        scopes: p
206212×
                            .get("scopes")
207212×
                            .and_then(Json::as_array)
2081600×
                            .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())
209212×
                            .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
        }
254994×
        Ok(())
255997×
    }
256
257
    /// Check that `e` is signed by the owner's current identity; returns it.
258236×
    fn owner_signed(&self, e: &Event) -> Result<Identity, String> {
259236×
        let owner = self.owner().ok_or("no owner is recorded")?.clone();
260236×
        if e.auth.key != Some(owner.hash().0) {
2610×
            return Err("not signed by the owner's current identity".into());
262236×
        }
263236×
        check_proof(e, &owner)?;
264236×
        Ok(owner)
265236×
    }
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.
2707×
    pub fn check_session(&self, e: &Event) -> Result<(), String> {
2717×
        let key = crate::identity::KeyId(e.auth.key.ok_or("a session event names no key")?);
2727×
        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());
2747×
        }
2757×
        let identity = self.identity(&key).ok_or("an unknown key")?;
2767×
        let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
2777×
        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());
2797×
        }
2807×
        proof.verify(identity, None)
2817×
    }
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 {
299517×
    fn check(&mut self, e: &Event) -> Result<(), String> {
300517×
        match e.kind.as_str() {
301517×
            "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
            }
307344×
            "agent.uid_bound" => self.observe(e),
308343×
            _ if matches!(e.auth.method, Method::Signature | Method::Passkey) => self.check_signed(e),
309206×
            _ if e.auth.method == Method::Session => self.check_session(e),
310199×
            _ => Ok(()),
311
        }
312517×
    }
313
}
314
315
/// Apply identity and agent events to the projection tables.
31642903×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
31742903×
    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(());
32542902×
    }
326
    // Who is who is only ever said by a signature; `verify` checks which.
32742902×
    if e.auth.method != Method::Signature {
32842046×
        return Ok(());
329856×
    }
330856×
    let p = e.json();
331856×
    let id = |p: &Json| identity_of(p).ok();
332856×
    match e.kind.as_str() {
333856×
        "identity.owner" | "identity.rotated" | "identity.instance" => {
334185×
            let Some(identity) = id(&p) else { return Ok(()) };
335185×
            let role = if e.kind == "identity.instance" { "instance" } else { "owner" };
336185×
            sqlx::query("UPDATE identities SET current = 0 WHERE role = ?").bind(role).execute(&mut *conn).await?;
337185×
            sqlx::query(
338185×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, ?, ?, ?, ?, 1, ?)",
339
            )
340185×
            .bind(identity.hash().to_hex())
341185×
            .bind(role)
342185×
            .bind(&identity.name)
343185×
            .bind(identity.encode())
344185×
            .bind(identity.previous.map(|k| k.to_hex()))
345185×
            .bind(e.seq as i64)
346185×
            .execute(&mut *conn)
347185×
            .await?;
348
        }
349671×
        "agent.added" => {
35064×
            let Some(identity) = id(&p) else { return Ok(()) };
35164×
            if p.get("name").and_then(Json::as_str).is_none_or(str::is_empty) {
3520×
                return Ok(());
35364×
            }
354384×
            let s = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or("").to_string();
35564×
            sqlx::query(
35664×
                "INSERT OR REPLACE INTO agents (name, key, owner, owner_name, kind, project, home, uid, learn_uid, scopes, created_ms, disabled_ms, seq) \
35764×
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
358
            )
35964×
            .bind(s("name"))
36064×
            .bind(identity.hash().to_hex())
36164×
            .bind(s("owner"))
36264×
            .bind(s("owner_name"))
36364×
            .bind(s("kind"))
36464×
            .bind(s("project"))
36564×
            .bind(s("home"))
36664×
            .bind(p.get("uid").and_then(Json::as_i64))
36764×
            .bind(p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false))
36864×
            .bind(p.get("scopes").map(|v| v.to_string()).unwrap_or_else(|| "[]".into()))
36964×
            .bind(e.at_ms as i64)
37064×
            .bind(e.seq as i64)
37164×
            .execute(&mut *conn)
37264×
            .await?;
37364×
            sqlx::query(
37464×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, 'agent', ?, ?, ?, 1, ?)",
375
            )
37664×
            .bind(identity.hash().to_hex())
37764×
            .bind(&identity.name)
37864×
            .bind(identity.encode())
37964×
            .bind(identity.previous.map(|k| k.to_hex()))
38064×
            .bind(e.seq as i64)
38164×
            .execute(&mut *conn)
38264×
            .await?;
383
        }
384607×
        "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
        }
391603×
        "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
        }
412597×
        _ => {}
413
    }
414856×
    Ok(())
41542903×
}
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`.
427224×
pub fn identity_payload(identity: &Identity) -> Json {
428224×
    serde_json::json!({ "key": identity.hash().to_hex(), "name": identity.name, "identity": hex::encode(identity.encode()) })
429224×
}
430
4311221×
fn identity_of(p: &Json) -> Result<Identity, String> {
4321221×
    let b = p.get("identity").and_then(Json::as_str).and_then(|h| hex::decode(h).ok()).ok_or("no identity in the event")?;
4331221×
    Identity::decode(&b).map_err(|e| format!("malformed identity: {e}"))
4341221×
}
435
436460×
fn text(p: &Json, k: &str) -> Result<String, String> {
437460×
    p.get(k).and_then(Json::as_str).map(String::from).ok_or_else(|| format!("no {k}"))
438460×
}
439
440759×
fn self_signed(e: &Event, id: &Identity) -> Result<(), String> {
441759×
    if e.auth.key != Some(id.hash().0) {
4421×
        return Err("not signed by the identity it records".into());
443758×
    }
444758×
    check_proof(e, id)
445759×
}
446
447
/// The event's proof verifies against `identity`, and a CLI proof covers
448
/// exactly the event's payload.
4491127×
fn check_proof(e: &Event, identity: &Identity) -> Result<(), String> {
4501127×
    let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
4511127×
    if proof.key() != identity.hash().0 {
4520×
        return Err("the proof is by another key".into());
4531127×
    }
4541127×
    let body = (proof.method == "cli").then(|| e.payload.as_deref().unwrap_or(b""));
4551127×
    proof.verify(identity, body)
4561127×
}
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`).
461258×
fn accept_successor(cur: &Identity, new: &Identity, p: &Json) -> Result<(), String> {
462258×
    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());
464258×
    }
465258×
    let chain: Vec<Identity> = p
466258×
        .get("chain")
467258×
        .and_then(Json::as_array)
468258×
        .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())
469258×
        .unwrap_or_default();
470258×
    let mut at = new.clone();
471258×
    for _ in 0..=chain.len() {
472258×
        match at.previous {
473258×
            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())
482258×
}
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.
486275×
pub fn signed_event(pair: &crate::keys::KeyPair, actor: &str, kind: &str, payload: Json) -> crate::event::NewEvent {
487275×
    let body = crate::event::canonical_json(&payload);
488275×
    let proof = Proof::sign(pair, "cli", &body);
489275×
    crate::event::NewEvent::system(kind, payload)
490275×
        .by(actor, crate::event::Auth { key: Some(pair.key.0), method: Method::Signature, assurance: 2, proof: Some(proof.encode()) })
491275×
}