OXYGENHUB
◆ v0.1.0 spectra / crates / spectra-core / src / principals.rs
18.2 KiB · Rust · last changed Spectra stands alone: its own identities, signatures and CBOR; projects of any kind of work (#26, #27) 1 day ago source blame history raw
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`.
40
    pub fn actor(&self) -> String {
41
        match self {
42
            Principal::Owner { .. } => "human".into(),
43
            Principal::Agent { name, .. } => format!("agent:{name}"),
44
            Principal::Instance { .. } => "system".into(),
45
        }
46
    }
47
    /// How it is shown to people: `claude-oxygen · Andy McCall's agent`.
48
    pub fn display(&self) -> String {
49
        match self {
50
            Principal::Owner { name, .. } => name.clone(),
51
            Principal::Agent { name, owner_name, .. } => format!("{name} · {owner_name}'s agent"),
52
            Principal::Instance { .. } => "Spectra".into(),
53
        }
54
    }
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.
81
    pub async fn load(ledger: &crate::ledger::Ledger) -> anyhow::Result<Principals> {
82
        let mut p = Principals::default();
83
        let mut from = 1;
84
        loop {
85
            let rows = ledger
86
                .events_of_kinds(from, &["identity.owner", "identity.rotated", "identity.instance", "agent.added", "agent.disabled"], 1000)
87
                .await?;
88
            if rows.is_empty() {
89
                break;
90
            }
91
            for e in &rows {
92
                // Recorded facts were checked when written; `verify` checks them again.
93
                let _ = p.observe(e);
94
            }
95
            from = rows.last().map(|e| e.seq + 1).unwrap_or(from);
96
        }
97
        Ok(p)
98
    }
99
100
    /// The owner's current identity.
101
    pub fn owner(&self) -> Option<&Identity> {
102
        self.owner.last()
103
    }
104
105
    pub fn instance(&self) -> Option<&Identity> {
106
        self.instance.as_ref()
107
    }
108
109
    /// The agent named `name`, whatever its state.
110
    pub fn agent_key(&self, name: &str) -> Option<KeyId> {
111
        self.by_name.get(name).copied()
112
    }
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.
117
    pub fn principal(&self, key: &KeyId, at_ms: u64) -> Result<Principal, String> {
118
        if let Some(owner) = self.owner.iter().rev().find(|i| &i.hash() == key) {
119
            return Ok(Principal::Owner { key: *key, name: owner.name.clone() });
120
        }
121
        if self.instance.as_ref().is_some_and(|i| &i.hash() == key) {
122
            return Ok(Principal::Instance { key: *key });
123
        }
124
        let a = self.agents.get(key).ok_or("an unknown key")?;
125
        if a.disabled {
126
            return Err(format!("agent {} is disabled", a.name));
127
        }
128
        let owner = self.owner().ok_or("no owner is recorded")?;
129
        if !owner.delegates_to(key, at_ms) {
130
            return Err(match owner.delegate(key) {
131
                Some(d) if d.expires.is_some_and(|x| at_ms > x) => format!("agent {}'s delegation from {} has expired", a.name, owner.name),
132
                Some(_) => format!("{}'s delegation to agent {} does not include `changes`", owner.name, a.name),
133
                None => format!("{}'s current identity does not delegate to agent {}", owner.name, a.name),
134
            });
135
        }
136
        Ok(Principal::Agent {
137
            name: a.name.clone(),
138
            key: *key,
139
            owner_name: a.owner_name.clone(),
140
            uid: a.uid,
141
            learn_uid: a.learn_uid,
142
            project: a.project.clone(),
143
            scopes: a.scopes.clone(),
144
        })
145
    }
146
147
    /// The identity behind `key`, for checking its signatures.
148
    pub fn identity(&self, key: &KeyId) -> Option<&Identity> {
149
        self.owner
150
            .iter()
151
            .find(|i| &i.hash() == key)
152
            .or_else(|| self.instance.as_ref().filter(|i| &i.hash() == key))
153
            .or_else(|| self.agents.get(key).map(|a| &a.identity))
154
    }
155
156
    /// Take one event into account, checking what it claims first.
157
    pub fn observe(&mut self, e: &Event) -> Result<(), String> {
158
        let p = e.json();
159
        match e.kind.as_str() {
160
            "identity.owner" => {
161
                if !self.owner.is_empty() {
162
                    return Err("an owner is already recorded".into());
163
                }
164
                let id = identity_of(&p)?;
165
                self_signed(e, &id)?;
166
                self.owner.push(id);
167
            }
168
            "identity.rotated" => {
169
                let new = identity_of(&p)?;
170
                let cur = self.owner().ok_or("no owner to succeed")?.clone();
171
                accept_successor(&cur, &new, &p)?;
172
                self_signed(e, &new)?;
173
                self.owner.push(new);
174
            }
175
            "identity.instance" => {
176
                let id = identity_of(&p)?;
177
                self_signed(e, &id)?;
178
                self.instance = Some(id);
179
            }
180
            "agent.added" => {
181
                let id = identity_of(&p)?;
182
                let key = id.hash();
183
                let owner = self.owner_signed(e)?;
184
                if !owner.delegates_to(&key, e.hlc.wall_ms) {
185
                    return Err("added without the owner's delegation to its key".into());
186
                }
187
                let name = text(&p, "name")?;
188
                if self.by_name.get(&name).is_some_and(|k| *k != key) {
189
                    return Err(format!("agent {name} already exists with another key"));
190
                }
191
                self.by_name.insert(name.clone(), key);
192
                self.agents.insert(
193
                    key,
194
                    AgentRec {
195
                        name,
196
                        identity: id,
197
                        owner_name: owner.name.clone(),
198
                        uid: p.get("uid").and_then(Json::as_u64).map(|u| u as u32),
199
                        learn_uid: p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false),
200
                        project: text(&p, "project")?,
201
                        scopes: p
202
                            .get("scopes")
203
                            .and_then(Json::as_array)
204
                            .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())
205
                            .unwrap_or_default(),
206
                        disabled: false,
207
                    },
208
                );
209
            }
210
            "agent.uid_bound" => {
211
                // The daemon binds a learning agent to the uid of its first
212
                // signed connection; covered by the next checkpoint.
213
                let name = text(&p, "name")?;
214
                let uid = p.get("uid").and_then(Json::as_u64).ok_or("no uid")? as u32;
215
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
216
                if let Some(a) = self.agents.get_mut(&key) {
217
                    if a.uid.is_none() {
218
                        a.uid = Some(uid);
219
                    }
220
                }
221
            }
222
            "agent.disabled" => {
223
                self.owner_signed(e)?;
224
                let name = text(&p, "name")?;
225
                let key = *self.by_name.get(&name).ok_or("an unknown agent")?;
226
                if let Some(a) = self.agents.get_mut(&key) {
227
                    a.disabled = true;
228
                }
229
            }
230
            _ => {}
231
        }
232
        Ok(())
233
    }
234
235
    /// Check that `e` is signed by the owner's current identity; returns it.
236
    fn owner_signed(&self, e: &Event) -> Result<Identity, String> {
237
        let owner = self.owner().ok_or("no owner is recorded")?.clone();
238
        if e.auth.key != Some(owner.hash().0) {
239
            return Err("not signed by the owner's current identity".into());
240
        }
241
        check_proof(e, &owner)?;
242
        Ok(owner)
243
    }
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.
248
    pub fn check_session(&self, e: &Event) -> Result<(), String> {
249
        let key = crate::identity::KeyId(e.auth.key.ok_or("a session event names no key")?);
250
        if !matches!(self.principal(&key, e.hlc.wall_ms)?, Principal::Owner { .. }) || e.actor != "human" {
251
            return Err("only the owner acts through a Radar session".into());
252
        }
253
        let identity = self.identity(&key).ok_or("an unknown key")?;
254
        let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
255
        if proof.key() != key.0 || proof.method != "POST /radar/link" {
256
            return Err("the session's proof is not the owner's sign-in request".into());
257
        }
258
        proof.verify(identity, None)
259
    }
260
261
    /// Check a signed event's proof against the principal its key was at
262
    /// the event's time.
263
    pub fn check_signed(&self, e: &Event) -> Result<(), String> {
264
        let key = crate::identity::KeyId(e.auth.key.ok_or("signed, but names no key")?);
265
        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.
268
        if who.actor() != e.actor {
269
            return Err(format!("names {} as its actor but is signed by {}", e.actor, who.display()));
270
        }
271
        let identity = self.identity(&key).ok_or("an unknown key")?;
272
        check_proof(e, identity)
273
    }
274
}
275
276
impl KeyResolver for Principals {
277
    fn check(&mut self, e: &Event) -> Result<(), String> {
278
        match e.kind.as_str() {
279
            "identity.owner" | "identity.rotated" | "identity.instance" | "agent.added" | "agent.disabled" => {
280
                if e.auth.method != Method::Signature {
281
                    return Err(format!("{} must be signed", e.kind));
282
                }
283
                self.observe(e)
284
            }
285
            "agent.uid_bound" => self.observe(e),
286
            _ if matches!(e.auth.method, Method::Signature | Method::Passkey) => self.check_signed(e),
287
            _ if e.auth.method == Method::Session => self.check_session(e),
288
            _ => Ok(()),
289
        }
290
    }
291
}
292
293
/// Apply identity and agent events to the projection tables.
294
pub async fn project(conn: &mut SqliteConnection, e: &Event) -> sqlx::Result<()> {
295
    if e.kind == "agent.uid_bound" {
296
        let p = e.json();
297
        sqlx::query("UPDATE agents SET uid = ? WHERE name = ? AND uid IS NULL")
298
            .bind(p.get("uid").and_then(Json::as_i64))
299
            .bind(p.get("name").and_then(Json::as_str))
300
            .execute(&mut *conn)
301
            .await?;
302
        return Ok(());
303
    }
304
    // Who is who is only ever said by a signature; `verify` checks which.
305
    if e.auth.method != Method::Signature {
306
        return Ok(());
307
    }
308
    let p = e.json();
309
    let id = |p: &Json| identity_of(p).ok();
310
    match e.kind.as_str() {
311
        "identity.owner" | "identity.rotated" | "identity.instance" => {
312
            let Some(identity) = id(&p) else { return Ok(()) };
313
            let role = if e.kind == "identity.instance" { "instance" } else { "owner" };
314
            sqlx::query("UPDATE identities SET current = 0 WHERE role = ?").bind(role).execute(&mut *conn).await?;
315
            sqlx::query(
316
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, ?, ?, ?, ?, 1, ?)",
317
            )
318
            .bind(identity.hash().to_hex())
319
            .bind(role)
320
            .bind(&identity.name)
321
            .bind(identity.encode())
322
            .bind(identity.previous.map(|k| k.to_hex()))
323
            .bind(e.seq as i64)
324
            .execute(&mut *conn)
325
            .await?;
326
        }
327
        "agent.added" => {
328
            let Some(identity) = id(&p) else { return Ok(()) };
329
            if p.get("name").and_then(Json::as_str).is_none_or(str::is_empty) {
330
                return Ok(());
331
            }
332
            let s = |k: &str| p.get(k).and_then(Json::as_str).unwrap_or("").to_string();
333
            sqlx::query(
334
                "INSERT OR REPLACE INTO agents (name, key, owner, owner_name, kind, project, home, uid, learn_uid, scopes, created_ms, disabled_ms, seq) \
335
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
336
            )
337
            .bind(s("name"))
338
            .bind(identity.hash().to_hex())
339
            .bind(s("owner"))
340
            .bind(s("owner_name"))
341
            .bind(s("kind"))
342
            .bind(s("project"))
343
            .bind(s("home"))
344
            .bind(p.get("uid").and_then(Json::as_i64))
345
            .bind(p.get("learn_uid").and_then(Json::as_bool).unwrap_or(false))
346
            .bind(p.get("scopes").map(|v| v.to_string()).unwrap_or_else(|| "[]".into()))
347
            .bind(e.at_ms as i64)
348
            .bind(e.seq as i64)
349
            .execute(&mut *conn)
350
            .await?;
351
            sqlx::query(
352
                "INSERT OR REPLACE INTO identities (key, role, name, identity, previous, current, seq) VALUES (?, 'agent', ?, ?, ?, 1, ?)",
353
            )
354
            .bind(identity.hash().to_hex())
355
            .bind(&identity.name)
356
            .bind(identity.encode())
357
            .bind(identity.previous.map(|k| k.to_hex()))
358
            .bind(e.seq as i64)
359
            .execute(&mut *conn)
360
            .await?;
361
        }
362
        "agent.disabled" => {
363
            sqlx::query("UPDATE agents SET disabled_ms = ? WHERE name = ?")
364
                .bind(e.at_ms as i64)
365
                .bind(p.get("name").and_then(Json::as_str))
366
                .execute(&mut *conn)
367
                .await?;
368
        }
369
        _ => {}
370
    }
371
    Ok(())
372
}
373
374
/// The payload of an identity event for `identity`.
375
pub fn identity_payload(identity: &Identity) -> Json {
376
    serde_json::json!({ "key": identity.hash().to_hex(), "name": identity.name, "identity": hex::encode(identity.encode()) })
377
}
378
379
fn identity_of(p: &Json) -> Result<Identity, String> {
380
    let b = p.get("identity").and_then(Json::as_str).and_then(|h| hex::decode(h).ok()).ok_or("no identity in the event")?;
381
    Identity::decode(&b).map_err(|e| format!("malformed identity: {e}"))
382
}
383
384
fn text(p: &Json, k: &str) -> Result<String, String> {
385
    p.get(k).and_then(Json::as_str).map(String::from).ok_or_else(|| format!("no {k}"))
386
}
387
388
fn self_signed(e: &Event, id: &Identity) -> Result<(), String> {
389
    if e.auth.key != Some(id.hash().0) {
390
        return Err("not signed by the identity it records".into());
391
    }
392
    check_proof(e, id)
393
}
394
395
/// The event's proof verifies against `identity`, and a CLI proof covers
396
/// exactly the event's payload.
397
fn check_proof(e: &Event, identity: &Identity) -> Result<(), String> {
398
    let proof = Proof::decode(e.auth.proof.as_deref().ok_or("no proof")?)?;
399
    if proof.key() != identity.hash().0 {
400
        return Err("the proof is by another key".into());
401
    }
402
    let body = (proof.method == "cli").then(|| e.payload.as_deref().unwrap_or(b""));
403
    proof.verify(identity, body)
404
}
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`).
409
fn accept_successor(cur: &Identity, new: &Identity, p: &Json) -> Result<(), String> {
410
    if new.ed25519_pk != cur.ed25519_pk || new.mldsa65_pk != cur.mldsa65_pk {
411
        return Err("a successor with a fresh key pair needs `oxy identity rotate`'s attestation, not accepted in 0.1".into());
412
    }
413
    let chain: Vec<Identity> = p
414
        .get("chain")
415
        .and_then(Json::as_array)
416
        .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())
417
        .unwrap_or_default();
418
    let mut at = new.clone();
419
    for _ in 0..=chain.len() {
420
        match at.previous {
421
            Some(prev) if prev == cur.hash() => return Ok(()),
422
            Some(prev) => match chain.iter().find(|i| i.hash() == prev) {
423
                Some(i) if i.ed25519_pk == cur.ed25519_pk => at = i.clone(),
424
                _ => break,
425
            },
426
            None => break,
427
        }
428
    }
429
    Err("does not succeed the recorded owner".into())
430
}
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.
434
pub fn signed_event(pair: &crate::keys::KeyPair, actor: &str, kind: &str, payload: Json) -> crate::event::NewEvent {
435
    let body = crate::event::canonical_json(&payload);
436
    let proof = Proof::sign(pair, "cli", &body);
437
    crate::event::NewEvent::system(kind, payload)
438
        .by(actor, crate::event::Auth { key: Some(pair.key.0), method: Method::Signature, assurance: 2, proof: Some(proof.encode()) })
439
}