OXYGENHUB
◆ v0.11.0 oxygen / crates / oxy-core / src / repo / identity.rs
34.4 KiB · Rust · last changed A stale author.key can no longer fork the identity (closes #163) 2 days ago source blame history raw
98286406 Andy McCall ↶ 1
//! Identities, signing, and signature verification (spec §14).
2
3
use super::*;
4
5
/// Outcome of verifying the signatures on a change (spec §14.3, §14.4).
6
#[derive(Clone, Debug, PartialEq, Eq)]
7
pub enum SignatureStatus {
8
    Unsigned,
28fc23d7 Andy McCall ↶ 9
    /// `revoked` marks a signature that verifies but whose key has since
10
    /// been revoked by policy or by a revocation this repository recorded.
75167672 Andy McCall 11
    Valid {
12
        key: KeyId,
13
        name: String,
14
        email: String,
15
        sealed: bool,
16
        revoked: bool,
17
    },
98286406 Andy McCall ↶ 18
    Invalid(String),
19
}
20
64dc5197 Andy McCall ↶ 21
/// Make a user identity with no repository (oxygen#144), so a first
22
/// identity comes before any repository: its secret and a copy of it go to
23
/// this home's keys, and the user file names it as the author, as `oxy
24
/// identity create` does inside one. A repository reads it from the keys
25
/// when it first signs with it. `name` and `email` default to the user
26
/// file's author, then to `$USER` and `OXY_AUTHOR_*`.
27
pub fn create_user_identity(
28
    name: Option<&str>,
29
    email: Option<&str>,
30
    expires: Option<u64>,
31
) -> Result<(KeyId, Identity)> {
32
    let user = default_user_config();
33
    let defaults = Config::load(Some(&user), Path::new(""))?;
34
    let name = name.map(str::to_string).unwrap_or(defaults.author_name);
35
    let email = email.map(str::to_string).unwrap_or(defaults.author_email);
36
    let sk = SecretKey::generate();
37
    let mut id = sk.identity(&name, &email, Hlc::now().wall_ms);
38
    id.expires = expires;
39
    let key = id.hash();
40
    let keys = default_keys_dir();
41
    fs::create_dir_all(&keys)?;
42
    crate::durable::write_atomic_private(
43
        &keys.join(format!("{}.secret", key.to_hex())),
44
        &sk.encode(&key),
45
    )?;
46
    write_atomic(
47
        &keys.join(format!("{}.identity", key.to_hex())),
48
        &id.encode(),
49
    )?;
50
    Config::set_user(&user, "author.name", &id.name)?;
51
    Config::set_user(&user, "author.email", &id.email)?;
52
    Config::set_user(&user, "author.key", &key.to_hex())?;
53
    Ok((key, id))
54
}
55
28fc23d7 Andy McCall ↶ 56
/// The outcome of replacing the configured identity (spec §14.2).
57
#[derive(Clone, Debug)]
58
pub struct Rotation {
59
    pub old: KeyId,
60
    pub new: KeyId,
61
    pub identity: Identity,
62
    /// The policy update that moved the old key's grants to the new key,
63
    /// when the repository has a policy naming the old key.
64
    pub policy: Option<PolicyUpdate>,
65
}
66
98286406 Andy McCall ↶ 67
impl Repo {
68
    // ------------------------------------------------------------ identity
69
70
    /// Generate a composite key pair, store its identity object, keep the
71
    /// secret in the key directory, and record the author at `scope`.
75167672 Andy McCall 72
    pub fn create_identity(
73
        &mut self,
74
        name: &str,
75
        email: &str,
76
        scope: IdentityScope,
77
    ) -> Result<(KeyId, Identity)> {
28fc23d7 Andy McCall ↶ 78
        self.create_identity_with(name, email, scope, None)
79
    }
80
81
    /// `create_identity` with an expiry (milliseconds since the epoch).
75167672 Andy McCall 82
    pub fn create_identity_with(
83
        &mut self,
84
        name: &str,
85
        email: &str,
86
        scope: IdentityScope,
87
        expires: Option<u64>,
88
    ) -> Result<(KeyId, Identity)> {
98286406 Andy McCall ↶ 89
        let sk = SecretKey::generate();
28fc23d7 Andy McCall ↶ 90
        let mut id = sk.identity(name, email, Hlc::now().wall_ms);
91
        id.expires = expires;
92
        let key = self.install_key(&id, &sk)?;
93
        self.set_author(&id, &key, scope)?;
94
        Ok((key, id))
95
    }
96
97
    /// Store an identity and keep its secret (and a copy of the identity)
98
    /// in the key directory.
99
    fn install_key(&self, id: &Identity, sk: &SecretKey) -> Result<KeyId> {
100
        let key = self.store.put_identity(id)?;
98286406 Andy McCall ↶ 101
        fs::create_dir_all(&self.keys_dir)?;
102
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
ff1f62fe Andy McCall ↶ 103
        crate::durable::write_atomic_private(&path, &sk.encode(&key))?;
75167672 Andy McCall 104
        write_atomic(
105
            &self.keys_dir.join(format!("{}.identity", key.to_hex())),
106
            &id.encode(),
107
        )?;
28fc23d7 Andy McCall ↶ 108
        Ok(key)
109
    }
110
111
    fn set_author(&mut self, id: &Identity, key: &KeyId, scope: IdentityScope) -> Result<()> {
98286406 Andy McCall ↶ 112
        match scope {
113
            IdentityScope::Repo => {
28fc23d7 Andy McCall ↶ 114
                self.config.set("author.name", &id.name)?;
115
                self.config.set("author.email", &id.email)?;
98286406 Andy McCall ↶ 116
                self.config.set("author.key", &key.to_hex())?;
117
                self.save_config()?;
118
            }
119
            IdentityScope::User => {
28fc23d7 Andy McCall ↶ 120
                Config::set_user(&self.user_config, "author.name", &id.name)?;
121
                Config::set_user(&self.user_config, "author.email", &id.email)?;
98286406 Andy McCall ↶ 122
                Config::set_user(&self.user_config, "author.key", &key.to_hex())?;
123
                self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
124
            }
125
        }
28fc23d7 Andy McCall ↶ 126
        Ok(())
127
    }
128
129
    /// The scope that holds the configured author key.
130
    fn author_scope(&self) -> IdentityScope {
75167672 Andy McCall 131
        if self.config.repo_layer().contains_key("author.key") {
132
            IdentityScope::Repo
133
        } else {
134
            IdentityScope::User
135
        }
28fc23d7 Andy McCall ↶ 136
    }
137
614f55e1 Andy McCall ↶ 138
    /// Record a successor key everywhere the old one was named: the
139
    /// repository layer when it pins the old key, and the user file when
140
    /// it names the old key, so every checkout that followed the old key
141
    /// follows the new one (oxygen#69). A key named nowhere falls back to
142
    /// the scope that resolved it.
143
    fn record_successor(&mut self, id: &Identity, old: &KeyId, new_key: &KeyId) -> Result<()> {
144
        let names = |v: Option<&String>| v.and_then(|k| KeyId::from_hex(k)) == Some(*old);
145
        let repo_pins = names(self.config.repo_layer().get("author.key"));
146
        let user_entries = super::config::read_config_file(&self.user_config).unwrap_or_default();
147
        let user_names = names(user_entries.get("author.key"));
148
        if !repo_pins && !user_names {
149
            return self.set_author(id, new_key, self.author_scope());
150
        }
151
        if user_names {
152
            self.set_author(id, new_key, IdentityScope::User)?;
153
        }
154
        if repo_pins {
155
            self.set_author(id, new_key, IdentityScope::Repo)?;
156
        }
157
        Ok(())
158
    }
159
28fc23d7 Andy McCall ↶ 160
    /// Replace the configured identity by `new` signed with `sk`: store it,
161
    /// record a `rotate` attestation signed by the old key, move the old
162
    /// key's policy grants to the new key, and switch the author config.
75167672 Andy McCall 163
    fn replace_identity(
164
        &mut self,
165
        new: Identity,
166
        sk: SecretKey,
167
        command: &str,
168
    ) -> Result<Rotation> {
28fc23d7 Andy McCall ↶ 169
        let Some((old, old_sk)) = self.secret_key()? else {
170
            return fail("no secret key: run `oxy identity create` first");
171
        };
172
        if new.previous != Some(old) {
173
            return fail("the successor identity must name the current key as previous");
174
        }
aded4110 Andy McCall ↶ 175
        // A key that already has a successor is not the identity's newest:
176
        // building another from it forks the identity into two branches
177
        // (oxygen#163), as a checkout whose stale `author.key` pin outlived
178
        // a rotation made elsewhere once did.
179
        if let Some(newer) = self.successors(&old)?.into_iter().next() {
180
            let newest = self.newest(&newer)?;
181
            let fix = if self.config.is_repo_set("author.key") {
182
                format!(
183
                    "This repository's config pins author.key to the older key: `oxy config author.key {}` here \
184
                     (or `oxy config --unset author.key` to follow the user config), then run it again.",
185
                    newest.to_hex()
186
                )
187
            } else {
188
                format!(
189
                    "The user config names the older key: `oxy config --user author.key {}`, then run it again.",
190
                    newest.to_hex()
191
                )
192
            };
193
            return fail(format!(
194
                "`{command}` would start from key {}, which is not your identity's newest ({} succeeds it, and {} is the newest). \
195
                 Another successor would fork the identity into two branches.\n{fix}",
196
                old.short(12),
197
                newer.short(12),
198
                newest.short(12),
199
            ));
200
        }
28fc23d7 Andy McCall ↶ 201
        let new_key = self.install_key(&new, &sk)?;
75167672 Andy McCall 202
        let attest = Attest {
203
            repo: self.id()?,
204
            hlc: Hlc::now(),
205
            body: AttestBody::Rotate { new: new_key },
206
        };
28fc23d7 Andy McCall ↶ 207
        let r = self.store.put_attest(&attest)?;
75167672 Andy McCall 208
        self.store
209
            .put_signature(&r, &old_sk.sign(Domain::Attest, &old, &r))?;
28fc23d7 Andy McCall ↶ 210
        let policy = match self.current_policy()? {
211
            Some((_, sp)) if sp.policy.mentions(&old) => {
212
                let mut p = self.next_policy()?;
213
                p.substitute_key(&old, new.clone());
214
                Some(self.sign_policy_with(p, &[(old, &old_sk), (new_key, &sk)], command)?)
215
            }
216
            _ => None,
217
        };
614f55e1 Andy McCall ↶ 218
        self.record_successor(&new, &old, &new_key)?;
75167672 Andy McCall 219
        Ok(Rotation {
220
            old,
221
            new: new_key,
222
            identity: new,
223
            policy,
224
        })
aded4110 Andy McCall ↶ 225
    }
226
227
    /// Keys in this home whose identity names `key` as `previous`: the
228
    /// successors already made from it. More than one means a fork.
229
    pub fn successors(&self, key: &KeyId) -> Result<Vec<KeyId>> {
230
        let mut found = Vec::new();
231
        let entries = match fs::read_dir(&self.keys_dir) {
232
            Ok(e) => e,
233
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(found),
234
            Err(e) => return Err(e.into()),
235
        };
236
        for entry in entries {
237
            let path = entry?.path();
238
            if path.extension().and_then(|e| e.to_str()) != Some("identity") {
239
                continue;
240
            }
241
            let Ok(bytes) = fs::read(&path) else { continue };
242
            let Ok(id) = Identity::decode(&bytes) else {
243
                continue;
244
            };
245
            if id.previous == Some(*key) {
246
                found.push(id.hash());
247
            }
248
        }
249
        found.sort();
250
        Ok(found)
251
    }
252
253
    /// The newest key of the line through `key` in this home: its
254
    /// successors followed to the end (the first, where there is a fork).
255
    pub fn newest(&self, key: &KeyId) -> Result<KeyId> {
256
        let mut cur = *key;
257
        for _ in 0..256 {
258
            match self.successors(&cur)?.into_iter().next() {
259
                Some(next) => cur = next,
260
                None => break,
261
            }
262
        }
263
        Ok(cur)
28fc23d7 Andy McCall ↶ 264
    }
265
266
    /// Rotate to a fresh key pair; the new identity names the old one as
267
    /// `previous` and keeps its name, email, delegates, and expiry.
268
    pub fn rotate_identity(&mut self) -> Result<Rotation> {
269
        let Some((old, _)) = self.secret_key()? else {
270
            return fail("no secret key: run `oxy identity create` first");
271
        };
272
        let cur = self.identity(&old)?;
273
        let sk = SecretKey::generate();
274
        let mut id = sk.identity(&cur.name, &cur.email, Hlc::now().wall_ms);
275
        id.previous = Some(old);
276
        id.delegates = cur.delegates.clone();
277
        id.expires = cur.expires;
278
        self.replace_identity(id, sk, "oxy identity rotate")
279
    }
280
281
    /// Re-issue the identity with the same keys and a new expiry.
282
    pub fn renew_identity(&mut self, expires: Option<u64>) -> Result<Rotation> {
283
        let Some((old, sk)) = self.secret_key()? else {
284
            return fail("no secret key: run `oxy identity create` first");
285
        };
286
        let cur = self.identity(&old)?;
287
        let id = cur.successor(cur.delegates.clone(), expires, Hlc::now().wall_ms);
288
        self.replace_identity(id, sk, "oxy identity renew")
289
    }
290
7ba155f2 Andy McCall ↶ 291
    /// Let `delegate` act on this identity's behalf within `scope` until
292
    /// `expires` (spec §14.2). Delegates are part of the identity object,
293
    /// so this re-issues it with the same keys.
294
    pub fn delegate_add(
295
        &mut self,
296
        delegate: Identity,
614f55e1 Andy McCall ↶ 297
        scope: Scope,
298
        expires: Option<u64>,
299
    ) -> Result<Rotation> {
300
        self.delegate_add_many(vec![delegate], scope, expires)
301
    }
302
303
    /// As [`Repo::delegate_add`], for several delegates in one rotation.
304
    pub fn delegate_add_many(
305
        &mut self,
306
        new_delegates: Vec<Identity>,
7ba155f2 Andy McCall ↶ 307
        scope: Scope,
308
        expires: Option<u64>,
309
    ) -> Result<Rotation> {
28fc23d7 Andy McCall ↶ 310
        let Some((old, sk)) = self.secret_key()? else {
311
            return fail("no secret key: run `oxy identity create` first");
312
        };
7ba155f2 Andy McCall ↶ 313
        if scope.is_empty() {
314
            return fail("a delegate needs at least one scope: changes, refs or seal");
315
        }
614f55e1 Andy McCall ↶ 316
        if new_delegates.is_empty() {
317
            return fail("name at least one identity file");
28fc23d7 Andy McCall ↶ 318
        }
319
        let cur = self.identity(&old)?;
614f55e1 Andy McCall ↶ 320
        let mut delegates = cur.delegates.clone();
321
        let mut added = Vec::new();
322
        for delegate in new_delegates {
323
            let dk = self.store.put_identity(&delegate)?;
324
            added.push(dk);
325
            if dk == old {
326
                return fail("an identity cannot delegate to itself");
327
            }
328
            if cur.delegate(&dk).is_some()
329
                || delegates
330
                    .iter()
331
                    .skip(cur.delegates.len())
332
                    .any(|d| d.key == dk)
333
            {
334
                return fail(format!(
335
                    "{} is already a delegate; remove it first to change its scope or expiry",
336
                    dk.short(12)
337
                ));
338
            }
339
            delegates.push(Delegate {
340
                key: dk,
341
                scope,
342
                expires,
343
            });
28fc23d7 Andy McCall ↶ 344
        }
345
        let id = cur.successor(delegates, cur.expires, Hlc::now().wall_ms);
75167672 Andy McCall 346
        self.replace_identity(
347
            id,
348
            sk,
614f55e1 Andy McCall ↶ 349
            &format!(
350
                "oxy identity delegate add {} --scope {scope}",
351
                added
352
                    .iter()
353
                    .map(|k| k.short(12))
354
                    .collect::<Vec<_>>()
355
                    .join(" ")
356
            ),
75167672 Andy McCall 357
        )
28fc23d7 Andy McCall ↶ 358
    }
359
360
    /// Withdraw a delegation; re-issues the identity with the same keys.
361
    pub fn delegate_remove(&mut self, delegate: &KeyId) -> Result<Rotation> {
362
        let Some((old, sk)) = self.secret_key()? else {
363
            return fail("no secret key: run `oxy identity create` first");
364
        };
365
        let cur = self.identity(&old)?;
7ba155f2 Andy McCall ↶ 366
        if cur.delegate(delegate).is_none() {
28fc23d7 Andy McCall ↶ 367
            return fail(format!("{} is not a delegate", delegate.short(12)));
368
        }
75167672 Andy McCall 369
        let delegates = cur
370
            .delegates
371
            .iter()
372
            .copied()
7ba155f2 Andy McCall ↶ 373
            .filter(|d| d.key != *delegate)
75167672 Andy McCall 374
            .collect();
28fc23d7 Andy McCall ↶ 375
        let id = cur.successor(delegates, cur.expires, Hlc::now().wall_ms);
75167672 Andy McCall 376
        self.replace_identity(
377
            id,
378
            sk,
379
            &format!("oxy identity delegate remove {}", delegate.short(12)),
380
        )
28fc23d7 Andy McCall ↶ 381
    }
382
7ba155f2 Andy McCall ↶ 383
    /// Revoke `key` (your own, one you delegated to, or any key when you
384
    /// hold a policy root): record a signed `revoke` attestation and a
385
    /// local marker, and drop the key from the policy where it has one.
386
    /// Revoking a delegate does not re-issue the identity; `delegate_remove`
387
    /// does that, and the CLI does both.
28fc23d7 Andy McCall ↶ 388
    pub fn revoke_identity(&self, key: &KeyId, reason: &str) -> Result<Option<PolicyUpdate>> {
389
        let Some((own, sk)) = self.secret_key()? else {
390
            return fail("no secret key: run `oxy identity create` first");
391
        };
392
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
393
        let is_root = policy.as_ref().is_some_and(|p| p.roots.contains(&own));
7ba155f2 Andy McCall ↶ 394
        let is_delegate = self.identity(&own)?.delegate(key).is_some();
395
        if *key != own && !is_root && !is_delegate {
396
            return fail("only the key's holder, the identity that delegated to it, or a policy root can revoke it");
28fc23d7 Andy McCall ↶ 397
        }
75167672 Andy McCall 398
        let attest = Attest {
399
            repo: self.id()?,
400
            hlc: Hlc::now(),
401
            body: AttestBody::Revoke {
402
                key: *key,
403
                reason: reason.into(),
404
            },
405
        };
28fc23d7 Andy McCall ↶ 406
        let r = self.store.put_attest(&attest)?;
75167672 Andy McCall 407
        self.store
408
            .put_signature(&r, &sk.sign(Domain::Attest, &own, &r))?;
28fc23d7 Andy McCall ↶ 409
        let dir = self.oxy.join("revoked");
410
        fs::create_dir_all(&dir)?;
411
        write_atomic(&dir.join(key.to_hex()), r.to_hex().as_bytes())?;
412
        match policy {
413
            Some(p) if p.mentions(key) => Ok(Some(self.policy_revoke(key)?)),
414
            _ => Ok(None),
415
        }
416
    }
417
418
    /// Whether `key` is revoked by the policy or by a recorded revocation.
419
    pub fn is_revoked(&self, key: &KeyId) -> Result<bool> {
420
        if self.oxy.join("revoked").join(key.to_hex()).exists() {
421
            return Ok(true);
422
        }
75167672 Andy McCall 423
        Ok(self
424
            .current_policy()?
425
            .is_some_and(|(_, sp)| sp.policy.is_revoked(key)))
98286406 Andy McCall ↶ 426
    }
427
ff1a64f8 Andy McCall ↶ 428
    /// The key this repository signs with: `author.signer` when set (an
429
    /// agent's own key, acting for the author), else `author.key`.
430
    pub fn signing_key(&self) -> Option<KeyId> {
c895bc52 Andy McCall ↶ 431
        if self.config.signer_keyless {
432
            // The key certified last, once this command has signed.
433
            return self.keyless_key.borrow().as_ref().map(|(k, _, _)| *k);
434
        }
ff1a64f8 Andy McCall ↶ 435
        self.config.signer_key.or(self.config.author_key)
436
    }
437
438
    /// The secret key for `author.signer`, else `author.key`, if configured
439
    /// and present on disk. The identity object is kept beside the secret
440
    /// so a repository that has never seen it (a fresh clone) can store it
441
    /// when it first signs.
98286406 Andy McCall ↶ 442
    pub fn secret_key(&self) -> Result<Option<(KeyId, SecretKey)>> {
c895bc52 Andy McCall ↶ 443
        if self.config.signer_keyless {
444
            return self.keyless_secret().map(Some);
445
        }
ff1a64f8 Andy McCall ↶ 446
        let Some(key) = self.signing_key() else {
75167672 Andy McCall 447
            return Ok(None);
448
        };
98286406 Andy McCall ↶ 449
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
450
        match fs::read(&path) {
451
            Ok(b) => {
452
                let (k, sk) = SecretKey::decode(&b)?;
453
                if k != key {
75167672 Andy McCall 454
                    return fail(format!(
455
                        "{} holds a different key than its name",
456
                        path.display()
457
                    ));
98286406 Andy McCall ↶ 458
                }
459
                if !self.store.has(&key) {
460
                    let id_path = self.keys_dir.join(format!("{}.identity", key.to_hex()));
461
                    if let Ok(bytes) = fs::read(&id_path) {
462
                        let id = Identity::decode(&bytes)?;
463
                        if id.hash() == key {
464
                            self.store.put_identity(&id)?;
465
                        }
466
                    }
467
                }
468
                Ok(Some((k, sk)))
469
            }
470
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
471
            Err(e) => Err(e.into()),
472
        }
473
    }
474
e3d071ce Andy McCall ↶ 475
    /// An identity: from this repository's store, or else from the key
476
    /// directory, where `oxy identity create` keeps the user's own (a new
477
    /// repository has not stored it yet). The file must hash to `key`.
98286406 Andy McCall ↶ 478
    pub fn identity(&self, key: &KeyId) -> Result<Identity> {
e3d071ce Andy McCall ↶ 479
        match self.store.get_identity(key) {
480
            Ok(id) => Ok(id),
481
            Err(e) => {
482
                let path = self.keys_dir.join(format!("{}.identity", key.to_hex()));
483
                match fs::read(&path) {
484
                    Ok(bytes) => {
485
                        let id = Identity::decode(&bytes)?;
486
                        if id.hash() != *key {
487
                            return fail(format!(
488
                                "{} does not hold identity {}",
489
                                path.display(),
490
                                key.short(12)
491
                            ));
492
                        }
493
                        Ok(id)
494
                    }
cbe8499a Andy McCall ↶ 495
                    // The configured author's identity is neither in the
496
                    // repository nor in this home's keys: say why and what
497
                    // to do (oxygen#82), rather than "object … not found".
498
                    Err(_) if self.config.author_key == Some(*key) => fail(format!(
499
                        "this repository has no identity {} (author.key, set in {}): it is not in the repository, nor in {}.\n\
500
                         An agent home names its human's identity, and each delegation rotates that identity, so the key goes stale. \
501
                         Pin the identity this repository uses, as its owner sees it: `oxy identity show` in the owner's shell gives the key, \
502
                         then `oxy config author.key <KEY>` here; or ask the owner.",
503
                        key.short(12),
504
                        if self.config.is_repo_set("author.key") {
505
                            "this repository's config"
506
                        } else {
507
                            "the user config"
508
                        },
509
                        self.keys_dir.display()
510
                    )),
e3d071ce Andy McCall ↶ 511
                    Err(_) => Err(e.into()),
512
                }
513
            }
514
        }
98286406 Andy McCall ↶ 515
    }
516
517
    /// Sign a stored change with the configured secret key.
518
    pub fn sign_change(&self, hash: &ChangeHash) -> Result<Signature> {
519
        let Some((key, sk)) = self.secret_key()? else {
520
            return fail("no secret key: run `oxy identity create` first");
521
        };
522
        let sig = sk.sign(Domain::Change, &key, hash);
523
        self.store.put_signature(hash, &sig)?;
524
        Ok(sig)
525
    }
526
527
    /// Check the signatures on a change against the author-or-delegate rule.
528
    pub fn verify_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
4cce912a Andy McCall ↶ 529
        self.verify_change_known(hash, None)
530
    }
531
532
    /// `verify_change`, with the change's metadata when the caller has it
533
    /// (a change object can be as large as the tree it adds). Signatures
534
    /// are looked up first: an unsigned change needs no metadata.
535
    fn verify_change_known(
536
        &self,
537
        hash: &ChangeHash,
538
        known: Option<&crate::state::ChangeMeta>,
539
    ) -> Result<SignatureStatus> {
98286406 Andy McCall ↶ 540
        let sigs = self.store.signatures(hash)?;
541
        if sigs.is_empty() {
542
            return Ok(SignatureStatus::Unsigned);
543
        }
4cce912a Andy McCall ↶ 544
        let read;
545
        let change = match known {
546
            Some(m) => m,
547
            None => {
548
                read = self.store.get_change_meta(hash)?;
549
                &read
550
            }
551
        };
98286406 Andy McCall ↶ 552
        let mut last_err = String::new();
553
        for sig in &sigs {
4cce912a Andy McCall ↶ 554
            match self.check_signer(change, sig, Domain::Change, hash) {
75167672 Andy McCall 555
                Ok(id) => {
556
                    return Ok(SignatureStatus::Valid {
557
                        key: sig.key,
68dcf21f Andy McCall ↶ 558
                        name: self.certified_subject(&sig.key).unwrap_or(id.name),
75167672 Andy McCall 559
                        email: id.email,
560
                        sealed: false,
561
                        revoked: self.is_revoked(&sig.key)?,
562
                    })
563
                }
98286406 Andy McCall ↶ 564
                Err(e) => last_err = e,
565
            }
566
        }
567
        Ok(SignatureStatus::Invalid(last_err))
568
    }
569
a2387d54 Andy McCall ↶ 570
    /// Whether `signer` is a short-lived key acting for `author` under a
571
    /// grant (spec §14.7): its certificate verifies with its issuer and
572
    /// carries a grant `author` signed, for the certificate's subject and
573
    /// issuer, giving `needed` at `at_ms` (the change's time, as for a
574
    /// delegation). Whether the certificate covered the time it signed is
575
    /// the policy's check, at a time the signer did not choose. `None`
576
    /// when it does; otherwise why not.
577
    fn granted(
578
        &self,
579
        author: &KeyId,
580
        signer: &KeyId,
581
        needed: Scope,
582
        at_ms: u64,
583
    ) -> std::result::Result<Option<String>, String> {
584
        let neither = || {
585
            Some(format!(
586
                "key {} is neither the author nor a delegate",
587
                signer.short(12)
588
            ))
589
        };
590
        let Ok(Some(c)) = self.store.certificate_of(signer) else {
591
            return Ok(neither());
592
        };
593
        let Ok(sc) = self.store.get_certificate(&c) else {
594
            return Ok(neither());
595
        };
596
        let Some(g) = &sc.cert.grant else {
597
            return Ok(neither());
598
        };
599
        let who = signer.short(12);
600
        let issuer = self
601
            .store
602
            .get_identity(&sc.cert.issuer)
603
            .map_err(|_| format!("key {who}'s certificate names an unknown issuer"))?;
604
        sc.verify(&issuer)
605
            .map_err(|e| format!("key {who}'s certificate: {e}"))?;
45a6f5ec Andy McCall ↶ 606
        // A grant by an earlier key of the author's identity counts while
607
        // it was made before that key was rotated away (oxygen#135).
608
        if g.grant.grantor != *author && !self.granted_before_rotation(author, &g.grant) {
a2387d54 Andy McCall ↶ 609
            return Ok(neither());
610
        }
611
        let grantor = self
45a6f5ec Andy McCall ↶ 612
            .identity(&g.grant.grantor)
a2387d54 Andy McCall ↶ 613
            .map_err(|_| format!("key {who}'s grant is by an unknown author"))?;
614
        g.verify(&grantor)
615
            .map_err(|e| format!("key {who}'s grant: {e}"))?;
616
        if g.grant.subject != sc.cert.subject || g.grant.issuer != sc.cert.issuer {
617
            return Err(format!(
618
                "key {who}'s grant is for {} from issuer {}, not its certificate's",
619
                g.grant.subject,
620
                g.grant.issuer.short(12)
621
            ));
622
        }
623
        if !sc.cert.scope.has(needed) || !g.grant.scope.has(needed) {
624
            return Err(format!("key {who} is not granted {needed}"));
625
        }
626
        if !g.grant.covers(needed, at_ms) {
627
            return Err(format!(
628
                "key {who}'s grant did not cover the time the change was made"
629
            ));
630
        }
631
        Ok(None)
45a6f5ec Andy McCall ↶ 632
    }
633
634
    /// Whether `grant` is by a key `author`'s identity was rotated from,
635
    /// made before that rotation (oxygen#135). An owner rotates with every
636
    /// delegation, and a repository may name the newest key as the author
637
    /// while the agent's grant is by an older one; the grant stays good, as
638
    /// a policy keeps a predecessor's signatures from before the rotation
639
    /// (spec §14.5), but a key rotated away grants nothing new.
640
    fn granted_before_rotation(&self, author: &KeyId, grant: &crate::cert::Grant) -> bool {
641
        let mut cur = self.identity(author).ok();
642
        for _ in 0..32 {
643
            let Some(id) = cur else {
644
                return false;
645
            };
646
            match id.previous {
647
                Some(prev) if prev == grant.grantor => return grant.not_before < id.created,
648
                Some(prev) => cur = self.identity(&prev).ok(),
649
                None => return false,
650
            }
651
        }
652
        false
a2387d54 Andy McCall ↶ 653
    }
654
68dcf21f Andy McCall ↶ 655
    /// The subject a short-lived key was certified for (spec §14.7), such
656
    /// as `agent:claude@andy`: what names it, since its identity is only
657
    /// a fresh key's.
658
    pub fn certified_subject(&self, key: &KeyId) -> Option<String> {
659
        let c = self.store.certificate_of(key).ok()??;
660
        Some(self.store.get_certificate(&c).ok()?.cert.subject)
661
    }
662
98286406 Andy McCall ↶ 663
    /// Verify `sig` over `target` and check the author-or-delegate rule for `change`.
75167672 Andy McCall 664
    fn check_signer(
665
        &self,
69816d68 Andy McCall ↶ 666
        change: &crate::state::ChangeMeta,
75167672 Andy McCall 667
        sig: &Signature,
668
        domain: Domain,
669
        target: &ObjectRef,
670
    ) -> std::result::Result<Identity, String> {
671
        let id = self
672
            .store
673
            .get_identity(&sig.key)
674
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
05e71ed6 Andy McCall ↶ 675
        // The author-or-delegate rule (spec §14.4). A change whose author is
676
        // the zero key names nobody (Git imports, history from before an
677
        // identity existed), so any key may adopt it with a seal; policy
7ba155f2 Andy McCall ↶ 678
        // then authorises that key for the reference as usual. A delegate
679
        // acts within its scope, signing changes or sealing them, and only
680
        // until its delegation expires (§14.2).
681
        if !change.author.is_zero() && sig.key != change.author {
682
            let needed = match domain {
683
                Domain::Change => Scope::CHANGES,
684
                _ => Scope::SEAL,
685
            };
686
            let delegation = self
75167672 Andy McCall 687
                .store
688
                .get_identity(&change.author)
7ba155f2 Andy McCall ↶ 689
                .ok()
690
                .and_then(|a| a.delegate(&sig.key).copied());
691
            match delegation {
a2387d54 Andy McCall ↶ 692
                // A certified key acting under the author's grant (§14.7).
7ba155f2 Andy McCall ↶ 693
                None => {
a2387d54 Andy McCall ↶ 694
                    if let Some(why) =
695
                        self.granted(&change.author, &sig.key, needed, change.hlc.wall_ms)?
696
                    {
697
                        return Err(why);
698
                    }
7ba155f2 Andy McCall ↶ 699
                }
700
                Some(d) if !d.scope.has(needed) => {
701
                    return Err(format!(
702
                        "key {} is a delegate for {} only and may not {}",
703
                        sig.key.short(12),
704
                        d.scope,
705
                        if needed == Scope::SEAL {
706
                            "seal"
707
                        } else {
708
                            "sign changes"
709
                        }
710
                    ))
711
                }
712
                Some(d) if !d.allows(needed, change.hlc.wall_ms) => {
713
                    return Err(format!(
714
                        "key {}'s delegation had expired when the change was made",
715
                        sig.key.short(12)
716
                    ))
717
                }
718
                Some(_) => {}
719
            }
98286406 Andy McCall ↶ 720
        }
28fc23d7 Andy McCall ↶ 721
        if id.is_expired_at(change.hlc.wall_ms) {
75167672 Andy McCall 722
            return Err(format!(
723
                "key {} had expired when the change was made",
724
                sig.key.short(12)
725
            ));
28fc23d7 Andy McCall ↶ 726
        }
98286406 Andy McCall ↶ 727
        verify_signature(&id, sig, domain, target).map_err(|e| e.to_string())?;
728
        Ok(id)
729
    }
730
731
    /// Like `verify_change`, but a change with no valid individual signature
732
    /// is also authenticated by a valid seal covering it (spec §14.4).
733
    pub fn authenticate_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
4cce912a Andy McCall ↶ 734
        self.authenticate_change_known(hash, None)
735
    }
736
737
    /// `authenticate_change`, with the change's metadata when the caller
738
    /// has it (from a log, say), so the change itself need not be read.
739
    pub fn authenticate_change_known(
740
        &self,
741
        hash: &ChangeHash,
742
        known: Option<&crate::state::ChangeMeta>,
743
    ) -> Result<SignatureStatus> {
744
        let direct = self.verify_change_known(hash, known)?;
98286406 Andy McCall ↶ 745
        if matches!(direct, SignatureStatus::Valid { .. }) {
746
            return Ok(direct);
747
        }
748
        let mut last_err = match &direct {
749
            SignatureStatus::Invalid(e) => e.clone(),
750
            _ => String::new(),
4cce912a Andy McCall ↶ 751
        };
752
        let seals = self.store.seals_for(hash)?;
753
        if seals.is_empty() {
754
            return Ok(match last_err.is_empty() {
755
                true => SignatureStatus::Unsigned,
756
                false => SignatureStatus::Invalid(last_err),
757
            });
758
        }
759
        let read;
760
        let change = match known {
761
            Some(m) => m,
762
            None => {
763
                read = self.store.get_change_meta(hash)?;
764
                &read
765
            }
98286406 Andy McCall ↶ 766
        };
4cce912a Andy McCall ↶ 767
        for seal_ref in seals {
98286406 Andy McCall ↶ 768
            let attest = self.store.get_attest(&seal_ref)?;
75167672 Andy McCall 769
            let AttestBody::Seal { hashes } = &attest.body else {
770
                continue;
771
            };
98286406 Andy McCall ↶ 772
            if !hashes.contains(hash) {
773
                continue;
774
            }
775
            for sig in self.store.signatures(&seal_ref)? {
4cce912a Andy McCall ↶ 776
                match self.check_signer(change, &sig, Domain::Attest, &seal_ref) {
75167672 Andy McCall 777
                    Ok(id) => {
778
                        return Ok(SignatureStatus::Valid {
779
                            key: sig.key,
68dcf21f Andy McCall ↶ 780
                            name: self.certified_subject(&sig.key).unwrap_or(id.name),
75167672 Andy McCall 781
                            email: id.email,
782
                            sealed: true,
783
                            revoked: self.is_revoked(&sig.key)?,
784
                        })
785
                    }
98286406 Andy McCall ↶ 786
                    Err(e) => last_err = e,
787
                }
788
            }
789
        }
75167672 Andy McCall 790
        if last_err.is_empty() {
791
            Ok(SignatureStatus::Unsigned)
792
        } else {
793
            Ok(SignatureStatus::Invalid(last_err))
794
        }
98286406 Andy McCall ↶ 795
    }
796
797
    /// Store and sign an attestation with the configured key.
05e71ed6 Andy McCall ↶ 798
    /// Seal changes with the identity key (spec §14.4): a stored, indexed
799
    /// seal attestation over `hashes`, pushed with the next push. Returns
800
    /// the attestation's reference.
801
    pub fn seal(&self, hashes: &[ChangeHash]) -> Result<ObjectRef> {
802
        if hashes.is_empty() {
803
            return fail("nothing to seal");
804
        }
805
        if hashes.len() > crate::attest::MAX_SEAL_HASHES {
b0e64e81 Andy McCall ↶ 806
            return fail(format!(
807
                "a seal covers at most {} changes",
808
                crate::attest::MAX_SEAL_HASHES
809
            ));
05e71ed6 Andy McCall ↶ 810
        }
811
        for h in hashes {
812
            if !self.store.has(h) {
813
                return fail(format!("unknown change {}", h.short(12)));
814
            }
815
        }
816
        let mut sorted = hashes.to_vec();
817
        sorted.sort();
818
        sorted.dedup();
819
        let sa = self.sign_attest(&Attest::seal(self.id()?, sorted.clone()))?;
820
        let r = self.store.put_attest(&sa.attest)?;
821
        for sig in &sa.sigs {
822
            self.store.put_signature(&r, sig)?;
823
        }
824
        for h in &sorted {
825
            self.store.index_seal(h, &r)?;
826
        }
827
        Ok(r)
a2387d54 Andy McCall ↶ 828
    }
829
830
    /// Whether `signer` seals changes by `author`: its own, anonymous ones
831
    /// (§14.4), and, when it signs for the configured author (a delegate,
832
    /// or a short-lived key under the author's grant, §14.7), the
833
    /// author's. A receiver still checks it may.
834
    pub(crate) fn seals_for_author(&self, author: &KeyId, signer: &KeyId) -> bool {
835
        author == signer
836
            || author.is_zero()
c895bc52 Andy McCall ↶ 837
            || ((self.config.signer_key.is_some() || self.config.signer_keyless)
838
                && self.config.author_key == Some(*author))
05e71ed6 Andy McCall ↶ 839
    }
840
841
    /// The changes of the current bookmark this identity can authenticate
a2387d54 Andy McCall ↶ 842
    /// but has not: its own unsigned ones, anonymous ones, and the
843
    /// author's when it signs for them.
05e71ed6 Andy McCall ↶ 844
    pub fn sealable(&self) -> Result<Vec<ChangeHash>> {
b0e64e81 Andy McCall ↶ 845
        let Some((key, _)) = self.secret_key()? else {
846
            return fail("no identity: run oxy identity create");
847
        };
05e71ed6 Andy McCall ↶ 848
        let heads = self.bookmark_heads()?;
57eaac91 Andy McCall ↶ 849
        let state = self.load_state_history(&heads)?;
05e71ed6 Andy McCall ↶ 850
        let mut out = Vec::new();
851
        for (h, meta) in state.changes() {
a2387d54 Andy McCall ↶ 852
            if self.seals_for_author(&meta.author, &key)
b0e64e81 Andy McCall ↶ 853
                && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
854
            {
05e71ed6 Andy McCall ↶ 855
                out.push(*h);
856
            }
857
        }
858
        out.sort();
859
        Ok(out)
860
    }
861
98286406 Andy McCall ↶ 862
    pub(crate) fn sign_attest(&self, attest: &Attest) -> Result<SignedAttest> {
863
        let Some((key, sk)) = self.secret_key()? else {
864
            return fail("no secret key: run `oxy identity create` first");
865
        };
866
        let r = self.store.put_attest(attest)?;
867
        let sig = sk.sign(Domain::Attest, &key, &r);
868
        self.store.put_signature(&r, &sig)?;
869
        if let AttestBody::Seal { hashes } = &attest.body {
870
            for h in hashes {
871
                self.store.index_seal(h, &r)?;
872
            }
873
        }
75167672 Andy McCall 874
        Ok(SignedAttest {
875
            attest: attest.clone(),
876
            sigs: vec![sig],
877
        })
98286406 Andy McCall ↶ 878
    }
879
}