OXYGENHUB

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

333 of 373 lines run, 46 of 110 functions · run #35 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`.
40416×
    pub fn actor(&self) -> String {
41416×
        match self {
4266×
            Principal::Owner { .. } => "human".into(),
43343×
            Principal::Agent { name, .. } => format!("agent:{name}"),
447×
            Principal::Instance { .. } => "system".into(),
45
        }
46416×
    }
47
    /// How it is shown to people: `claude-oxygen · Andy McCall's agent`.
4815×
    pub fn display(&self) -> String {
4915×
        match self {
503×
            Principal::Owner { name, .. } => name.clone(),
5112×
            Principal::Agent { name, owner_name, .. } => format!("{name} · {owner_name}'s agent"),
520×
            Principal::Instance { .. } => "Spectra".into(),
53
        }
5415×
    }
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.
81210×
    pub async fn load(ledger: &crate::ledger::Ledger) -> anyhow::Result<Principals> {
82210×
        let mut p = Principals::default();
83210×
        let mut from = 1;
84
        loop {
85419×
            let rows = ledger
86419×
                .events_of_kinds(
87419×
                    from,
88419×
                    &["identity.owner", "identity.rotated", "identity.instance", "agent.added", "agent.disabled", "agent.scoped"],
89419×
                    1000,
90419×
                )
91419×
                .await?;
92417×
            if rows.is_empty() {
93208×
                break;
94209×
            }
95806×
            for e in &rows {
96806×
                // Recorded facts were checked when written; `verify` checks them again.
97806×
                let _ = p.observe(e);
98806×
            }
99209×
            from = rows.last().map(|e| e.seq + 1).unwrap_or(from);
100
        }
101208×
        Ok(p)
102208×
    }
103
104
    /// The owner's current identity.
105977×
    pub fn owner(&self) -> Option<&Identity> {
106977×
        self.owner.last()
107977×
    }
108
10929×
    pub fn instance(&self) -> Option<&Identity> {
11029×
        self.instance.as_ref()
11129×
    }
112
113
    /// The agent named `name`, whatever its state.
11431×
    pub fn agent_key(&self, name: &str) -> Option<KeyId> {
11531×
        self.by_name.get(name).copied()
11631×
    }
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.
121332×
    pub fn principal(&self, key: &KeyId, at_ms: u64) -> Result<Principal, String> {
122702×
        if let Some(owner) = self.owner.iter().rev().find(|i| &i.hash() == key) {
123116×
            return Ok(Principal::Owner { key: *key, name: owner.name.clone() });
124216×
        }
125216×
        if self.instance.as_ref().is_some_and(|i| &i.hash() == key) {
1267×
            return Ok(Principal::Instance { key: *key });
127209×
        }
128209×
        let a = self.agents.get(key).ok_or("an unknown key")?;
129206×
        if a.disabled {
1306×
            return Err(format!("agent {} is disabled", a.name));
131200×
        }
132200×
        let owner = self.owner().ok_or("no owner is recorded")?;
133200×
        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
            });
139199×
        }
140199×
        Ok(Principal::Agent {
141199×
            name: a.name.clone(),
142199×
            key: *key,
143199×
            owner_name: a.owner_name.clone(),
144199×
            uid: a.uid,
145199×
            learn_uid: a.learn_uid,
146199×
            project: a.project.clone(),
147199×
            scopes: a.scopes.clone(),
148199×
        })
149332×
    }
150
151
    /// The identity behind `key`, for checking its signatures.
152272×
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
153272×
        self.owner
154272×
            .iter()
155682×
            .find(|i| &i.hash() == key)
156272×
            .or_else(|| self.instance.as_ref().filter(|i| &i.hash() == key))
157272×
            .or_else(|| self.agents.get(key).map(|a| &a.identity))
158272×
    }
159
160
    /// Take one event into account, checking what it claims first.
161965×
    pub fn observe(&mut self, e: &Event) -> Result<(), String> {
162965×
        let p = e.json();
163965×
        match e.kind.as_str() {
164965×
            "identity.owner" => {
165238×
                if !self.owner.is_empty() {
1661×
                    return Err("an owner is already recorded".into());
167237×
                }
168237×
                let id = identity_of(&p)?;
169237×
                self_signed(e, &id)?;
170237×
                self.owner.push(id);
171
            }
172727×
            "identity.rotated" => {
173251×
                let new = identity_of(&p)?;
174251×
                let cur = self.owner().ok_or("no owner to succeed")?.clone();
175251×
                accept_successor(&cur, &new, &p)?;
176251×
                self_signed(e, &new)?;
177250×
                self.owner.push(new);
178
            }
179476×
            "identity.instance" => {
180240×
                let id = identity_of(&p)?;
181240×
                self_signed(e, &id)?;
182240×
                self.instance = Some(id);
183
            }
184236×
            "agent.added" => {
185211×
                let id = identity_of(&p)?;
186211×
                let key = id.hash();
187211×
                let owner = self.owner_signed(e)?;
188211×
                if !owner.delegates_to(&key, e.hlc.wall_ms) {
1891×
                    return Err("added without the owner's delegation to its key".into());
190210×
                }
191210×
                let name = text(&p, "name")?;
192210×
                if self.by_name.get(&name).is_some_and(|k| *k != key) {
1930×
                    return Err(format!("agent {name} already exists with another key"));
194210×
                }
195210×
                self.by_name.insert(name.clone(), key);
196210×
                self.agents.insert(
197210×
                    key,
198
                    AgentRec {
199210×
                        name,
200210×
                        identity: id,
201210×
                        owner_name: owner.name.clone(),
202210×
                        uid: p.get("uid").and_then(Json::as_u64).map(|u| u as u32),
203210×
                        learn_uid: p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false),
204210×
                        project: text(&p, "project")?,
205210×
                        scopes: p
206210×
                            .get("scopes")
207210×
                            .and_then(Json::as_array)
2081584×
                            .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())
209210×
                            .unwrap_or_default(),
210
                        disabled: false,
211
                    },
212
                );
213
            }
21425×
            "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
            }
22624×
            "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.
23613×
            "agent.scoped" => {
23713×
                self.owner_signed(e)?;
23813×
                let name = text(&p, "name")?;
23913×
                let scope = text(&p, "scope")?;
24013×
                if !grantable(&scope) {
2410×
                    return Err(format!("{scope} is not a scope an agent may be given"));
24213×
                }
24313×
                let grant = p.get("grant").and_then(Json::as_bool).unwrap_or(true);
24413×
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
24513×
                if let Some(a) = self.agents.get_mut(&key) {
246108×
                    a.scopes.retain(|s| s != &scope);
24713×
                    if grant {
2489×
                        a.scopes.push(scope);
2499×
                    }
2500×
                }
251
            }
2520×
            _ => {}
253
        }
254962×
        Ok(())
255965×
    }
256
257
    /// Check that `e` is signed by the owner's current identity; returns it.
258235×
    fn owner_signed(&self, e: &Event) -> Result<Identity, String> {
259235×
        let owner = self.owner().ok_or("no owner is recorded")?.clone();
260235×
        if e.auth.key != Some(owner.hash().0) {
2610×
            return Err("not signed by the owner's current identity".into());
262235×
        }
263235×
        check_proof(e, &owner)?;
264235×
        Ok(owner)
265235×
    }
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.
2700×
    pub fn check_session(&self, e: &Event) -> Result<(), String> {
2710×
        let key = crate::identity::KeyId(e.auth.key.ok_or("a session event names no key")?);
2720×
        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());
2740×
        }
2750×
        let identity = self.identity(&key).ok_or("an unknown key")?;
2760×
        let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
2770×
        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());
2790×
        }
2800×
        proof.verify(identity, None)
2810×
    }
282
283
    /// Check a signed event's proof against the principal its key was at
284
    /// the event's time.
285126×
    pub fn check_signed(&self, e: &Event) -> Result<(), String> {
286126×
        let key = crate::identity::KeyId(e.auth.key.ok_or("signed, but names no key")?);
287126×
        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.
290124×
        if who.actor() != e.actor {
2912×
            return Err(format!("names {} as its actor but is signed by {}", e.actor, who.display()));
292122×
        }
293122×
        let identity = self.identity(&key).ok_or("an unknown key")?;
294122×
        check_proof(e, identity)
295126×
    }
296
}
297
298
impl KeyResolver for Principals {
299472×
    fn check(&mut self, e: &Event) -> Result<(), String> {
300472×
        match e.kind.as_str() {
301472×
            "identity.owner" | "identity.rotated" | "identity.instance" | "agent.added" | "agent.disabled" | "agent.scoped" => {
302160×
                if e.auth.method != Method::Signature {
3032×
                    return Err(format!("{} must be signed", e.kind));
304158×
                }
305158×
                self.observe(e)
306
            }
307312×
            "agent.uid_bound" => self.observe(e),
308311×
            _ if matches!(e.auth.method, Method::Signature | Method::Passkey) => self.check_signed(e),
309185×
            _ if e.auth.method == Method::Session => self.check_session(e),
310185×
            _ => Ok(()),
311
        }
312472×
    }
313
}
314
315
/// Apply identity and agent events to the projection tables.
31642870×
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
31742870×
    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(());
32542869×
    }
326
    // Who is who is only ever said by a signature; `verify` checks which.
32742869×
    if e.auth.method != Method::Signature {
32842033×
        return Ok(());
329836×
    }
330836×
    let p = e.json();
331836×
    let id = |p: &Json| identity_of(p).ok();
332836×
    match e.kind.as_str() {
333836×
        "identity.owner" | "identity.rotated" | "identity.instance" => {
334179×
            let Some(identity) = id(&p) else { return Ok(()) };
335179×
            let role = if e.kind == "identity.instance" { "instance" } else { "owner" };
336179×
            sqlx::query("UPDATE identities SET current = 0 WHERE role = ?").bind(role).execute(&mut *conn).await?;
337179×
            sqlx::query(
338179×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, ?, ?, ?, ?, 1, ?)",
339
            )
340179×
            .bind(identity.hash().to_hex())
341179×
            .bind(role)
342179×
            .bind(&identity.name)
343179×
            .bind(identity.encode())
344179×
            .bind(identity.previous.map(|k| k.to_hex()))
345179×
            .bind(e.seq as i64)
346179×
            .execute(&mut *conn)
347179×
            .await?;
348
        }
349657×
        "agent.added" => {
35063×
            let Some(identity) = id(&p) else { return Ok(()) };
35163×
            if p.get("name").and_then(Json::as_str).is_none_or(str::is_empty) {
3520×
                return Ok(());
35363×
            }
354378×
            let s = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or("").to_string();
35563×
            sqlx::query(
35663×
                "INSERT OR REPLACE INTO agents (name, key, owner, owner_name, kind, project, home, uid, learn_uid, scopes, created_ms, disabled_ms, seq) \
35763×
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
358
            )
35963×
            .bind(s("name"))
36063×
            .bind(identity.hash().to_hex())
36163×
            .bind(s("owner"))
36263×
            .bind(s("owner_name"))
36363×
            .bind(s("kind"))
36463×
            .bind(s("project"))
36563×
            .bind(s("home"))
36663×
            .bind(p.get("uid").and_then(Json::as_i64))
36763×
            .bind(p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false))
36863×
            .bind(p.get("scopes").map(|v| v.to_string()).unwrap_or_else(|| "[]".into()))
36963×
            .bind(e.at_ms as i64)
37063×
            .bind(e.seq as i64)
37163×
            .execute(&mut *conn)
37263×
            .await?;
37363×
            sqlx::query(
37463×
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, 'agent', ?, ?, ?, 1, ?)",
375
            )
37663×
            .bind(identity.hash().to_hex())
37763×
            .bind(&identity.name)
37863×
            .bind(identity.encode())
37963×
            .bind(identity.previous.map(|k| k.to_hex()))
38063×
            .bind(e.seq as i64)
38163×
            .execute(&mut *conn)
38263×
            .await?;
383
        }
384594×
        "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
        }
391590×
        "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
        }
412584×
        _ => {}
413
    }
414836×
    Ok(())
41542870×
}
416
417
/// A scope the owner may give an agent (spec §8.4): never the owner's own
418
/// authority, only reach.
41922×
pub fn grantable(scope: &str) -> bool {
42022×
    match scope.strip_prefix("channel:") {
421253×
        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
    }
42422×
}
425
426
/// The payload of an identity event for `identity`.
427214×
pub fn identity_payload(identity: &Identity) -> Json {
428214×
    serde_json::json!({ "key": identity.hash().to_hex(), "name": identity.name, "identity": hex::encode(identity.encode()) })
429214×
}
430
4311181×
fn identity_of(p: &Json) -> Result<Identity, String> {
4321181×
    let b = p.get("identity").and_then(Json::as_str).and_then(|h| hex::decode(h).ok()).ok_or("no identity in the event")?;
4331181×
    Identity::decode(&b).map_err(|e| format!("malformed identity: {e}"))
4341181×
}
435
436458×
fn text(p: &Json, k: &str) -> Result<String, String> {
437458×
    p.get(k).and_then(Json::as_str).map(String::from).ok_or_else(|| format!("no {k}"))
438458×
}
439
440728×
fn self_signed(e: &Event, id: &Identity) -> Result<(), String> {
441728×
    if e.auth.key != Some(id.hash().0) {
4421×
        return Err("not signed by the identity it records".into());
443727×
    }
444727×
    check_proof(e, id)
445728×
}
446
447
/// The event's proof verifies against `identity`, and a CLI proof covers
448
/// exactly the event's payload.
4491084×
fn check_proof(e: &Event, identity: &Identity) -> Result<(), String> {
4501084×
    let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
4511084×
    if proof.key() != identity.hash().0 {
4520×
        return Err("the proof is by another key".into());
4531084×
    }
4541084×
    let body = (proof.method == "cli").then(|| e.payload.as_deref().unwrap_or(b""));
4551084×
    proof.verify(identity, body)
4561084×
}
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`).
461251×
fn accept_successor(cur: &Identity, new: &Identity, p: &Json) -> Result<(), String> {
462251×
    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());
464251×
    }
465251×
    let chain: Vec<Identity> = p
466251×
        .get("chain")
467251×
        .and_then(Json::as_array)
468251×
        .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())
469251×
        .unwrap_or_default();
470251×
    let mut at = new.clone();
471251×
    for _ in 0..=chain.len() {
472251×
        match at.previous {
473251×
            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())
482251×
}
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.
486266×
pub fn signed_event(pair: &crate::keys::KeyPair, actor: &str, kind: &str, payload: Json) -> crate::event::NewEvent {
487266×
    let body = crate::event::canonical_json(&payload);
488266×
    let proof = Proof::sign(pair, "cli", &body);
489266×
    crate::event::NewEvent::system(kind, payload)
490266×
        .by(actor, crate::event::Auth { key: Some(pair.key.0), method: Method::Signature, assurance: 2, proof: Some(proof.encode()) })
491266×
}