OXYGENHUB

Coverage / crates/oxy-core/src/repo/identity.rs 89.4%

412 of 461 lines run, 50 of 72 functions · run #296 on main · run missed

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
/// The outcome of replacing the configured identity (spec §14.2).
22
#[derive(Clone, Debug)]
23
pub struct Rotation {
24
    pub old: KeyId,
25
    pub new: KeyId,
26
    pub identity: Identity,
27
    /// The policy update that moved the old key's grants to the new key,
28
    /// when the repository has a policy naming the old key.
29
    pub policy: Option<PolicyUpdate>,
30
}
31
32
impl Repo {
33
    // ------------------------------------------------------------ identity
34
35
    /// Generate a composite key pair, store its identity object, keep the
36
    /// secret in the key directory, and record the author at `scope`.
3743×
    pub fn create_identity(
3843×
        &mut self,
3943×
        name: &str,
4043×
        email: &str,
4143×
        scope: IdentityScope,
4243×
    ) -> Result<(KeyId, Identity)> {
4343×
        self.create_identity_with(name, email, scope, None)
4443×
    }
45
46
    /// `create_identity` with an expiry (milliseconds since the epoch).
4745×
    pub fn create_identity_with(
4845×
        &mut self,
4945×
        name: &str,
5045×
        email: &str,
5145×
        scope: IdentityScope,
5245×
        expires: Option<u64>,
5345×
    ) -> Result<(KeyId, Identity)> {
5445×
        let sk = SecretKey::generate();
5545×
        let mut id = sk.identity(name, email, Hlc::now().wall_ms);
5645×
        id.expires = expires;
5745×
        let key = self.install_key(&id, &sk)?;
5845×
        self.set_author(&id, &key, scope)?;
5945×
        Ok((key, id))
6045×
    }
61
62
    /// Store an identity and keep its secret (and a copy of the identity)
63
    /// in the key directory.
6460×
    fn install_key(&self, id: &Identity, sk: &SecretKey) -> Result<KeyId> {
6560×
        let key = self.store.put_identity(id)?;
6660×
        fs::create_dir_all(&self.keys_dir)?;
6760×
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
6860×
        crate::durable::write_atomic_private(&path, &sk.encode(&key))?;
6960×
        write_atomic(
7060×
            &self.keys_dir.join(format!("{}.identity", key.to_hex())),
7160×
            &id.encode(),
720×
        )?;
7360×
        Ok(key)
7460×
    }
75
7661×
    fn set_author(&mut self, id: &Identity, key: &KeyId, scope: IdentityScope) -> Result<()> {
7761×
        match scope {
78
            IdentityScope::Repo => {
7934×
                self.config.set("author.name", &id.name)?;
8034×
                self.config.set("author.email", &id.email)?;
8134×
                self.config.set("author.key", &key.to_hex())?;
8234×
                self.save_config()?;
83
            }
84
            IdentityScope::User => {
8527×
                Config::set_user(&self.user_config, "author.name", &id.name)?;
8627×
                Config::set_user(&self.user_config, "author.email", &id.email)?;
8727×
                Config::set_user(&self.user_config, "author.key", &key.to_hex())?;
8827×
                self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
89
            }
90
        }
9161×
        Ok(())
9261×
    }
93
94
    /// The scope that holds the configured author key.
950×
    fn author_scope(&self) -> IdentityScope {
960×
        if self.config.repo_layer().contains_key("author.key") {
970×
            IdentityScope::Repo
98
        } else {
990×
            IdentityScope::User
100
        }
1010×
    }
102
103
    /// Record a successor key everywhere the old one was named: the
104
    /// repository layer when it pins the old key, and the user file when
105
    /// it names the old key, so every checkout that followed the old key
106
    /// follows the new one (oxygen#69). A key named nowhere falls back to
107
    /// the scope that resolved it.
10815×
    fn record_successor(&mut self, id: &Identity, old: &KeyId, new_key: &KeyId) -> Result<()> {
10930×
        let names = |v: Option<&String>| v.and_then(|k| KeyId::from_hex(k)) == Some(*old);
11015×
        let repo_pins = names(self.config.repo_layer().get("author.key"));
11115×
        let user_entries = super::config::read_config_file(&self.user_config).unwrap_or_default();
11215×
        let user_names = names(user_entries.get("author.key"));
11315×
        if !repo_pins && !user_names {
1140×
            return self.set_author(id, new_key, self.author_scope());
11515×
        }
11615×
        if user_names {
1175×
            self.set_author(id, new_key, IdentityScope::User)?;
11810×
        }
11915×
        if repo_pins {
12011×
            self.set_author(id, new_key, IdentityScope::Repo)?;
1214×
        }
12215×
        Ok(())
12315×
    }
124
125
    /// Replace the configured identity by `new` signed with `sk`: store it,
126
    /// record a `rotate` attestation signed by the old key, move the old
127
    /// key's policy grants to the new key, and switch the author config.
12815×
    fn replace_identity(
12915×
        &mut self,
13015×
        new: Identity,
13115×
        sk: SecretKey,
13215×
        command: &str,
13315×
    ) -> Result<Rotation> {
13415×
        let Some((old, old_sk)) = self.secret_key()? else {
1350×
            return fail("no secret key: run `oxy identity create` first");
136
        };
13715×
        if new.previous != Some(old) {
1380×
            return fail("the successor identity must name the current key as previous");
13915×
        }
14015×
        let new_key = self.install_key(&new, &sk)?;
14115×
        let attest = Attest {
14215×
            repo: self.id()?,
14315×
            hlc: Hlc::now(),
14415×
            body: AttestBody::Rotate { new: new_key },
145
        };
14615×
        let r = self.store.put_attest(&attest)?;
14715×
        self.store
14815×
            .put_signature(&r, &old_sk.sign(Domain::Attest, &old, &r))?;
14915×
        let policy = match self.current_policy()? {
1507×
            Some((_, sp)) if sp.policy.mentions(&old) => {
1517×
                let mut p = self.next_policy()?;
1527×
                p.substitute_key(&old, new.clone());
1537×
                Some(self.sign_policy_with(p, &[(old, &old_sk), (new_key, &sk)], command)?)
154
            }
1558×
            _ => None,
156
        };
15715×
        self.record_successor(&new, &old, &new_key)?;
15815×
        Ok(Rotation {
15915×
            old,
16015×
            new: new_key,
16115×
            identity: new,
16215×
            policy,
16315×
        })
16415×
    }
165
166
    /// Rotate to a fresh key pair; the new identity names the old one as
167
    /// `previous` and keeps its name, email, delegates, and expiry.
1682×
    pub fn rotate_identity(&mut self) -> Result<Rotation> {
1692×
        let Some((old, _)) = self.secret_key()? else {
1700×
            return fail("no secret key: run `oxy identity create` first");
171
        };
1722×
        let cur = self.identity(&old)?;
1732×
        let sk = SecretKey::generate();
1742×
        let mut id = sk.identity(&cur.name, &cur.email, Hlc::now().wall_ms);
1752×
        id.previous = Some(old);
1762×
        id.delegates = cur.delegates.clone();
1772×
        id.expires = cur.expires;
1782×
        self.replace_identity(id, sk, "oxy identity rotate")
1792×
    }
180
181
    /// Re-issue the identity with the same keys and a new expiry.
1821×
    pub fn renew_identity(&mut self, expires: Option<u64>) -> Result<Rotation> {
1831×
        let Some((old, sk)) = self.secret_key()? else {
1840×
            return fail("no secret key: run `oxy identity create` first");
185
        };
1861×
        let cur = self.identity(&old)?;
1871×
        let id = cur.successor(cur.delegates.clone(), expires, Hlc::now().wall_ms);
1881×
        self.replace_identity(id, sk, "oxy identity renew")
1891×
    }
190
191
    /// Let `delegate` act on this identity's behalf within `scope` until
192
    /// `expires` (spec §14.2). Delegates are part of the identity object,
193
    /// so this re-issues it with the same keys.
19411×
    pub fn delegate_add(
19511×
        &mut self,
19611×
        delegate: Identity,
19711×
        scope: Scope,
19811×
        expires: Option<u64>,
19911×
    ) -> Result<Rotation> {
20011×
        self.delegate_add_many(vec![delegate], scope, expires)
20111×
    }
202
203
    /// As [`Repo::delegate_add`], for several delegates in one rotation.
20412×
    pub fn delegate_add_many(
20512×
        &mut self,
20612×
        new_delegates: Vec<Identity>,
20712×
        scope: Scope,
20812×
        expires: Option<u64>,
20912×
    ) -> Result<Rotation> {
21012×
        let Some((old, sk)) = self.secret_key()? else {
2110×
            return fail("no secret key: run `oxy identity create` first");
212
        };
21312×
        if scope.is_empty() {
2140×
            return fail("a delegate needs at least one scope: changes, refs or seal");
21512×
        }
21612×
        if new_delegates.is_empty() {
2170×
            return fail("name at least one identity file");
21812×
        }
21912×
        let cur = self.identity(&old)?;
22012×
        let mut delegates = cur.delegates.clone();
22112×
        let mut added = Vec::new();
22213×
        for delegate in new_delegates {
22313×
            let dk = self.store.put_identity(&delegate)?;
22413×
            added.push(dk);
22513×
            if dk == old {
2260×
                return fail("an identity cannot delegate to itself");
22713×
            }
22813×
            if cur.delegate(&dk).is_some()
22911×
                || delegates
23011×
                    .iter()
23111×
                    .skip(cur.delegates.len())
23211×
                    .any(|d| d.key == dk)
233
            {
2342×
                return fail(format!(
235
                    "{} is already a delegate; remove it first to change its scope or expiry",
2362×
                    dk.short(12)
237
                ));
23811×
            }
23911×
            delegates.push(Delegate {
24011×
                key: dk,
24111×
                scope,
24211×
                expires,
24311×
            });
244
        }
24510×
        let id = cur.successor(delegates, cur.expires, Hlc::now().wall_ms);
24610×
        self.replace_identity(
24710×
            id,
24810×
            sk,
24910×
            &format!(
250
                "oxy identity delegate add {} --scope {scope}",
25110×
                added
25210×
                    .iter()
25311×
                    .map(|k| k.short(12))
25410×
                    .collect::<Vec<_>>()
25510×
                    .join(" ")
256
            ),
257
        )
25812×
    }
259
260
    /// Withdraw a delegation; re-issues the identity with the same keys.
2613×
    pub fn delegate_remove(&mut self, delegate: &KeyId) -> Result<Rotation> {
2623×
        let Some((old, sk)) = self.secret_key()? else {
2630×
            return fail("no secret key: run `oxy identity create` first");
264
        };
2653×
        let cur = self.identity(&old)?;
2663×
        if cur.delegate(delegate).is_none() {
2671×
            return fail(format!("{} is not a delegate", delegate.short(12)));
2682×
        }
2692×
        let delegates = cur
2702×
            .delegates
2712×
            .iter()
2722×
            .copied()
2732×
            .filter(|d| d.key != *delegate)
2742×
            .collect();
2752×
        let id = cur.successor(delegates, cur.expires, Hlc::now().wall_ms);
2762×
        self.replace_identity(
2772×
            id,
2782×
            sk,
2792×
            &format!("oxy identity delegate remove {}", delegate.short(12)),
280
        )
2813×
    }
282
283
    /// Revoke `key` (your own, one you delegated to, or any key when you
284
    /// hold a policy root): record a signed `revoke` attestation and a
285
    /// local marker, and drop the key from the policy where it has one.
286
    /// Revoking a delegate does not re-issue the identity; `delegate_remove`
287
    /// does that, and the CLI does both.
2885×
    pub fn revoke_identity(&self, key: &KeyId, reason: &str) -> Result<Option<PolicyUpdate>> {
2895×
        let Some((own, sk)) = self.secret_key()? else {
2900×
            return fail("no secret key: run `oxy identity create` first");
291
        };
2925×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
2935×
        let is_root = policy.as_ref().is_some_and(|p| p.roots.contains(&own));
2945×
        let is_delegate = self.identity(&own)?.delegate(key).is_some();
2955×
        if *key != own && !is_root && !is_delegate {
2961×
            return fail("only the key's holder, the identity that delegated to it, or a policy root can revoke it");
2974×
        }
2984×
        let attest = Attest {
2994×
            repo: self.id()?,
3004×
            hlc: Hlc::now(),
3014×
            body: AttestBody::Revoke {
3024×
                key: *key,
3034×
                reason: reason.into(),
3044×
            },
305
        };
3064×
        let r = self.store.put_attest(&attest)?;
3074×
        self.store
3084×
            .put_signature(&r, &sk.sign(Domain::Attest, &own, &r))?;
3094×
        let dir = self.oxy.join("revoked");
3104×
        fs::create_dir_all(&dir)?;
3114×
        write_atomic(&dir.join(key.to_hex()), r.to_hex().as_bytes())?;
3121×
        match policy {
3131×
            Some(p) if p.mentions(key) => Ok(Some(self.policy_revoke(key)?)),
3143×
            _ => Ok(None),
315
        }
3165×
    }
317
318
    /// Whether `key` is revoked by the policy or by a recorded revocation.
319226×
    pub fn is_revoked(&self, key: &KeyId) -> Result<bool> {
320226×
        if self.oxy.join("revoked").join(key.to_hex()).exists() {
3215×
            return Ok(true);
322221×
        }
323221×
        Ok(self
324221×
            .current_policy()?
325221×
            .is_some_and(|(_, sp)| sp.policy.is_revoked(key)))
326226×
    }
327
328
    /// The key this repository signs with: `author.signer` when set (an
329
    /// agent's own key, acting for the author), else `author.key`.
330668×
    pub fn signing_key(&self) -> Option<KeyId> {
331668×
        self.config.signer_key.or(self.config.author_key)
332668×
    }
333
334
    /// The secret key for `author.signer`, else `author.key`, if configured
335
    /// and present on disk. The identity object is kept beside the secret
336
    /// so a repository that has never seen it (a fresh clone) can store it
337
    /// when it first signs.
338594×
    pub fn secret_key(&self) -> Result<Option<(KeyId, SecretKey)>> {
339594×
        let Some(key) = self.signing_key() else {
340208×
            return Ok(None);
341
        };
342386×
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
343386×
        match fs::read(&path) {
344385×
            Ok(b) => {
345385×
                let (k, sk) = SecretKey::decode(&b)?;
346385×
                if k != key {
3470×
                    return fail(format!(
348
                        "{} holds a different key than its name",
3490×
                        path.display()
350
                    ));
351385×
                }
352385×
                if !self.store.has(&key) {
3531×
                    let id_path = self.keys_dir.join(format!("{}.identity", key.to_hex()));
3541×
                    if let Ok(bytes) = fs::read(&id_path) {
3551×
                        let id = Identity::decode(&bytes)?;
3561×
                        if id.hash() == key {
3571×
                            self.store.put_identity(&id)?;
3580×
                        }
3590×
                    }
360384×
                }
361385×
                Ok(Some((k, sk)))
362
            }
3631×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
3640×
            Err(e) => Err(e.into()),
365
        }
366594×
    }
367
368
    /// An identity: from this repository's store, or else from the key
369
    /// directory, where `oxy identity create` keeps the user's own (a new
370
    /// repository has not stored it yet). The file must hash to `key`.
371208×
    pub fn identity(&self, key: &KeyId) -> Result<Identity> {
372208×
        match self.store.get_identity(key) {
373204×
            Ok(id) => Ok(id),
3744×
            Err(e) => {
3754×
                let path = self.keys_dir.join(format!("{}.identity", key.to_hex()));
3764×
                match fs::read(&path) {
3772×
                    Ok(bytes) => {
3782×
                        let id = Identity::decode(&bytes)?;
3792×
                        if id.hash() != *key {
3801×
                            return fail(format!(
381
                                "{} does not hold identity {}",
3821×
                                path.display(),
3831×
                                key.short(12)
384
                            ));
3851×
                        }
3861×
                        Ok(id)
387
                    }
388
                    // The configured author's identity is neither in the
389
                    // repository nor in this home's keys: say why and what
390
                    // to do (oxygen#82), rather than "object … not found".
3912×
                    Err(_) if self.config.author_key == Some(*key) => fail(format!(
392
                        "this repository has no identity {} (author.key, set in {}): it is not in the repository, nor in {}.\n\
393
                         An agent home names its human's identity, and each delegation rotates that identity, so the key goes stale. \
394
                         Pin the identity this repository uses, as its owner sees it: `oxy identity show` in the owner's shell gives the key, \
395
                         then `oxy config author.key <KEY>` here; or ask the owner.",
3962×
                        key.short(12),
3972×
                        if self.config.is_repo_set("author.key") {
3981×
                            "this repository's config"
399
                        } else {
4001×
                            "the user config"
401
                        },
4022×
                        self.keys_dir.display()
403
                    )),
4040×
                    Err(_) => Err(e.into()),
405
                }
406
            }
407
        }
408208×
    }
409
410
    /// Sign a stored change with the configured secret key.
41143×
    pub fn sign_change(&self, hash: &ChangeHash) -> Result<Signature> {
41243×
        let Some((key, sk)) = self.secret_key()? else {
4130×
            return fail("no secret key: run `oxy identity create` first");
414
        };
41543×
        let sig = sk.sign(Domain::Change, &key, hash);
41643×
        self.store.put_signature(hash, &sig)?;
41743×
        Ok(sig)
41843×
    }
419
420
    /// Check the signatures on a change against the author-or-delegate rule.
42124×
    pub fn verify_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
42224×
        self.verify_change_known(hash, None)
42324×
    }
424
425
    /// `verify_change`, with the change's metadata when the caller has it
426
    /// (a change object can be as large as the tree it adds). Signatures
427
    /// are looked up first: an unsigned change needs no metadata.
428389×
    fn verify_change_known(
429389×
        &self,
430389×
        hash: &ChangeHash,
431389×
        known: Option<&crate::state::ChangeMeta>,
432389×
    ) -> Result<SignatureStatus> {
433389×
        let sigs = self.store.signatures(hash)?;
434389×
        if sigs.is_empty() {
435303×
            return Ok(SignatureStatus::Unsigned);
43686×
        }
437
        let read;
43886×
        let change = match known {
43915×
            Some(m) => m,
440
            None => {
44171×
                read = self.store.get_change_meta(hash)?;
44271×
                &read
443
            }
444
        };
44586×
        let mut last_err = String::new();
44686×
        for sig in &sigs {
44786×
            match self.check_signer(change, sig, Domain::Change, hash) {
44880×
                Ok(id) => {
449
                    return Ok(SignatureStatus::Valid {
45080×
                        key: sig.key,
45180×
                        name: id.name,
45280×
                        email: id.email,
453
                        sealed: false,
45480×
                        revoked: self.is_revoked(&sig.key)?,
455
                    })
456
                }
4576×
                Err(e) => last_err = e,
458
            }
459
        }
4606×
        Ok(SignatureStatus::Invalid(last_err))
461389×
    }
462
463
    /// Verify `sig` over `target` and check the author-or-delegate rule for `change`.
464224×
    fn check_signer(
465224×
        &self,
466224×
        change: &crate::state::ChangeMeta,
467224×
        sig: &Signature,
468224×
        domain: Domain,
469224×
        target: &ObjectRef,
470224×
    ) -> std::result::Result<Identity, String> {
471224×
        let id = self
472224×
            .store
473224×
            .get_identity(&sig.key)
474224×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
475
        // The author-or-delegate rule (spec §14.4). A change whose author is
476
        // the zero key names nobody (Git imports, history from before an
477
        // identity existed), so any key may adopt it with a seal; policy
478
        // then authorises that key for the reference as usual. A delegate
479
        // acts within its scope, signing changes or sealing them, and only
480
        // until its delegation expires (§14.2).
481224×
        if !change.author.is_zero() && sig.key != change.author {
48223×
            let needed = match domain {
48321×
                Domain::Change => Scope::CHANGES,
4842×
                _ => Scope::SEAL,
485
            };
48623×
            let delegation = self
48723×
                .store
48823×
                .get_identity(&change.author)
48923×
                .ok()
49023×
                .and_then(|a| a.delegate(&sig.key).copied());
49118×
            match delegation {
492
                None => {
4934×
                    return Err(format!(
4944×
                        "key {} is neither the author nor a delegate",
4954×
                        sig.key.short(12)
4964×
                    ))
497
                }
49819×
                Some(d) if !d.scope.has(needed) => {
4991×
                    return Err(format!(
500
                        "key {} is a delegate for {} only and may not {}",
5011×
                        sig.key.short(12),
502
                        d.scope,
5031×
                        if needed == Scope::SEAL {
5041×
                            "seal"
505
                        } else {
5060×
                            "sign changes"
507
                        }
508
                    ))
509
                }
51018×
                Some(d) if !d.allows(needed, change.hlc.wall_ms) => {
5111×
                    return Err(format!(
5121×
                        "key {}'s delegation had expired when the change was made",
5131×
                        sig.key.short(12)
5141×
                    ))
515
                }
51617×
                Some(_) => {}
517
            }
518201×
        }
519218×
        if id.is_expired_at(change.hlc.wall_ms) {
5201×
            return Err(format!(
5211×
                "key {} had expired when the change was made",
5221×
                sig.key.short(12)
5231×
            ));
524217×
        }
525217×
        verify_signature(&id, sig, domain, target).map_err(|e| e.to_string())?;
526216×
        Ok(id)
527224×
    }
528
529
    /// Like `verify_change`, but a change with no valid individual signature
530
    /// is also authenticated by a valid seal covering it (spec §14.4).
531290×
    pub fn authenticate_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
532290×
        self.authenticate_change_known(hash, None)
533290×
    }
534
535
    /// `authenticate_change`, with the change's metadata when the caller
536
    /// has it (from a log, say), so the change itself need not be read.
537365×
    pub fn authenticate_change_known(
538365×
        &self,
539365×
        hash: &ChangeHash,
540365×
        known: Option<&crate::state::ChangeMeta>,
541365×
    ) -> Result<SignatureStatus> {
542365×
        let direct = self.verify_change_known(hash, known)?;
543365×
        if matches!(direct, SignatureStatus::Valid { .. }) {
54465×
            return Ok(direct);
545300×
        }
546300×
        let mut last_err = match &direct {
5472×
            SignatureStatus::Invalid(e) => e.clone(),
548298×
            _ => String::new(),
549
        };
550300×
        let seals = self.store.seals_for(hash)?;
551300×
        if seals.is_empty() {
552162×
            return Ok(match last_err.is_empty() {
553160×
                true => SignatureStatus::Unsigned,
5542×
                false => SignatureStatus::Invalid(last_err),
555
            });
556138×
        }
557
        let read;
558138×
        let change = match known {
5590×
            Some(m) => m,
560
            None => {
561138×
                read = self.store.get_change_meta(hash)?;
562138×
                &read
563
            }
564
        };
565138×
        for seal_ref in seals {
566138×
            let attest = self.store.get_attest(&seal_ref)?;
567138×
            let AttestBody::Seal { hashes } = &attest.body else {
5680×
                continue;
569
            };
570138×
            if !hashes.contains(hash) {
5710×
                continue;
572138×
            }
573138×
            for sig in self.store.signatures(&seal_ref)? {
574138×
                match self.check_signer(change, &sig, Domain::Attest, &seal_ref) {
575136×
                    Ok(id) => {
576
                        return Ok(SignatureStatus::Valid {
577136×
                            key: sig.key,
578136×
                            name: id.name,
579136×
                            email: id.email,
580
                            sealed: true,
581136×
                            revoked: self.is_revoked(&sig.key)?,
582
                        })
583
                    }
5842×
                    Err(e) => last_err = e,
585
                }
586
            }
587
        }
5882×
        if last_err.is_empty() {
5890×
            Ok(SignatureStatus::Unsigned)
590
        } else {
5912×
            Ok(SignatureStatus::Invalid(last_err))
592
        }
593365×
    }
594
595
    /// Store and sign an attestation with the configured key.
596
    /// Seal changes with the identity key (spec §14.4): a stored, indexed
597
    /// seal attestation over `hashes`, pushed with the next push. Returns
598
    /// the attestation's reference.
5991×
    pub fn seal(&self, hashes: &[ChangeHash]) -> Result<ObjectRef> {
6001×
        if hashes.is_empty() {
6010×
            return fail("nothing to seal");
6021×
        }
6031×
        if hashes.len() > crate::attest::MAX_SEAL_HASHES {
6040×
            return fail(format!(
605
                "a seal covers at most {} changes",
606
                crate::attest::MAX_SEAL_HASHES
607
            ));
6081×
        }
6091×
        for h in hashes {
6101×
            if !self.store.has(h) {
6110×
                return fail(format!("unknown change {}", h.short(12)));
6121×
            }
613
        }
6141×
        let mut sorted = hashes.to_vec();
6151×
        sorted.sort();
6161×
        sorted.dedup();
6171×
        let sa = self.sign_attest(&Attest::seal(self.id()?, sorted.clone()))?;
6181×
        let r = self.store.put_attest(&sa.attest)?;
6191×
        for sig in &sa.sigs {
6201×
            self.store.put_signature(&r, sig)?;
621
        }
6221×
        for h in &sorted {
6231×
            self.store.index_seal(h, &r)?;
624
        }
6251×
        Ok(r)
6261×
    }
627
628
    /// The changes of the current bookmark this identity can authenticate
629
    /// but has not: its own unsigned ones and anonymous ones.
6300×
    pub fn sealable(&self) -> Result<Vec<ChangeHash>> {
6310×
        let Some((key, _)) = self.secret_key()? else {
6320×
            return fail("no identity: run oxy identity create");
633
        };
6340×
        let heads = self.bookmark_heads()?;
6350×
        let state = self.load_state_history(&heads)?;
6360×
        let mut out = Vec::new();
6370×
        for (h, meta) in state.changes() {
6380×
            if (meta.author == key || meta.author.is_zero())
6390×
                && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
6400×
            {
6410×
                out.push(*h);
6420×
            }
643
        }
6440×
        out.sort();
6450×
        Ok(out)
6460×
    }
647
648121×
    pub(crate) fn sign_attest(&self, attest: &Attest) -> Result<SignedAttest> {
649121×
        let Some((key, sk)) = self.secret_key()? else {
6500×
            return fail("no secret key: run `oxy identity create` first");
651
        };
652121×
        let r = self.store.put_attest(attest)?;
653119×
        let sig = sk.sign(Domain::Attest, &key, &r);
654119×
        self.store.put_signature(&r, &sig)?;
655119×
        if let AttestBody::Seal { hashes } = &attest.body {
65638×
            for h in hashes {
65738×
                self.store.index_seal(h, &r)?;
658
            }
65984×
        }
660119×
        Ok(SignedAttest {
661119×
            attest: attest.clone(),
662119×
            sigs: vec![sig],
663119×
        })
664121×
    }
665
}