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