OXYGENHUB

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

463 of 523 lines run, 56 of 86 functions · run #314 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`.
3752×
    pub fn create_identity(
3852×
        &mut self,
3952×
        name: &str,
4052×
        email: &str,
4152×
        scope: IdentityScope,
4252×
    ) -> Result<(KeyId, Identity)> {
4352×
        self.create_identity_with(name, email, scope, None)
4452×
    }
45
46
    /// `create_identity` with an expiry (milliseconds since the epoch).
4755×
    pub fn create_identity_with(
4855×
        &mut self,
4955×
        name: &str,
5055×
        email: &str,
5155×
        scope: IdentityScope,
5255×
        expires: Option<u64>,
5355×
    ) -> Result<(KeyId, Identity)> {
5455×
        let sk = SecretKey::generate();
5555×
        let mut id = sk.identity(name, email, Hlc::now().wall_ms);
5655×
        id.expires = expires;
5755×
        let key = self.install_key(&id, &sk)?;
5855×
        self.set_author(&id, &key, scope)?;
5955×
        Ok((key, id))
6055×
    }
61
62
    /// Store an identity and keep its secret (and a copy of the identity)
63
    /// in the key directory.
6471×
    fn install_key(&self, id: &Identity, sk: &SecretKey) -> Result<KeyId> {
6571×
        let key = self.store.put_identity(id)?;
6671×
        fs::create_dir_all(&self.keys_dir)?;
6771×
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
6871×
        crate::durable::write_atomic_private(&path, &sk.encode(&key))?;
6971×
        write_atomic(
7071×
            &self.keys_dir.join(format!("{}.identity", key.to_hex())),
7171×
            &id.encode(),
720×
        )?;
7371×
        Ok(key)
7471×
    }
75
7672×
    fn set_author(&mut self, id: &Identity, key: &KeyId, scope: IdentityScope) -> Result<()> {
7772×
        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 => {
8538×
                Config::set_user(&self.user_config, "author.name", &id.name)?;
8638×
                Config::set_user(&self.user_config, "author.email", &id.email)?;
8738×
                Config::set_user(&self.user_config, "author.key", &key.to_hex())?;
8838×
                self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
89
            }
90
        }
9172×
        Ok(())
9272×
    }
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.
10816×
    fn record_successor(&mut self, id: &Identity, old: &KeyId, new_key: &KeyId) -> Result<()> {
10932×
        let names = |v: Option<&String>| v.and_then(|k| KeyId::from_hex(k)) == Some(*old);
11016×
        let repo_pins = names(self.config.repo_layer().get("author.key"));
11116×
        let user_entries = super::config::read_config_file(&self.user_config).unwrap_or_default();
11216×
        let user_names = names(user_entries.get("author.key"));
11316×
        if !repo_pins && !user_names {
1140×
            return self.set_author(id, new_key, self.author_scope());
11516×
        }
11616×
        if user_names {
1176×
            self.set_author(id, new_key, IdentityScope::User)?;
11810×
        }
11916×
        if repo_pins {
12011×
            self.set_author(id, new_key, IdentityScope::Repo)?;
1215×
        }
12216×
        Ok(())
12316×
    }
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.
12816×
    fn replace_identity(
12916×
        &mut self,
13016×
        new: Identity,
13116×
        sk: SecretKey,
13216×
        command: &str,
13316×
    ) -> Result<Rotation> {
13416×
        let Some((old, old_sk)) = self.secret_key()? else {
1350×
            return fail("no secret key: run `oxy identity create` first");
136
        };
13716×
        if new.previous != Some(old) {
1380×
            return fail("the successor identity must name the current key as previous");
13916×
        }
14016×
        let new_key = self.install_key(&new, &sk)?;
14116×
        let attest = Attest {
14216×
            repo: self.id()?,
14316×
            hlc: Hlc::now(),
14416×
            body: AttestBody::Rotate { new: new_key },
145
        };
14616×
        let r = self.store.put_attest(&attest)?;
14716×
        self.store
14816×
            .put_signature(&r, &old_sk.sign(Domain::Attest, &old, &r))?;
14916×
        let policy = match self.current_policy()? {
1508×
            Some((_, sp)) if sp.policy.mentions(&old) => {
1518×
                let mut p = self.next_policy()?;
1528×
                p.substitute_key(&old, new.clone());
1538×
                Some(self.sign_policy_with(p, &[(old, &old_sk), (new_key, &sk)], command)?)
154
            }
1558×
            _ => None,
156
        };
15716×
        self.record_successor(&new, &old, &new_key)?;
15816×
        Ok(Rotation {
15916×
            old,
16016×
            new: new_key,
16116×
            identity: new,
16216×
            policy,
16316×
        })
16416×
    }
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.
1683×
    pub fn rotate_identity(&mut self) -> Result<Rotation> {
1693×
        let Some((old, _)) = self.secret_key()? else {
1700×
            return fail("no secret key: run `oxy identity create` first");
171
        };
1723×
        let cur = self.identity(&old)?;
1733×
        let sk = SecretKey::generate();
1743×
        let mut id = sk.identity(&cur.name, &cur.email, Hlc::now().wall_ms);
1753×
        id.previous = Some(old);
1763×
        id.delegates = cur.delegates.clone();
1773×
        id.expires = cur.expires;
1783×
        self.replace_identity(id, sk, "oxy identity rotate")
1793×
    }
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.
319244×
    pub fn is_revoked(&self, key: &KeyId) -> Result<bool> {
320244×
        if self.oxy.join("revoked").join(key.to_hex()).exists() {
3215×
            return Ok(true);
322239×
        }
323239×
        Ok(self
324239×
            .current_policy()?
325239×
            .is_some_and(|(_, sp)| sp.policy.is_revoked(key)))
326244×
    }
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`.
330821×
    pub fn signing_key(&self) -> Option<KeyId> {
331821×
        self.config.signer_key.or(self.config.author_key)
332821×
    }
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.
338648×
    pub fn secret_key(&self) -> Result<Option<(KeyId, SecretKey)>> {
339648×
        let Some(key) = self.signing_key() else {
340206×
            return Ok(None);
341
        };
342442×
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
343442×
        match fs::read(&path) {
344441×
            Ok(b) => {
345441×
                let (k, sk) = SecretKey::decode(&b)?;
346441×
                if k != key {
3470×
                    return fail(format!(
348
                        "{} holds a different key than its name",
3490×
                        path.display()
350
                    ));
351441×
                }
352441×
                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×
                    }
360440×
                }
361441×
                Ok(Some((k, sk)))
362
            }
3631×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
3640×
            Err(e) => Err(e.into()),
365
        }
366648×
    }
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`.
371239×
    pub fn identity(&self, key: &KeyId) -> Result<Identity> {
372239×
        match self.store.get_identity(key) {
373235×
            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
        }
408239×
    }
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.
428415×
    fn verify_change_known(
429415×
        &self,
430415×
        hash: &ChangeHash,
431415×
        known: Option<&crate::state::ChangeMeta>,
432415×
    ) -> Result<SignatureStatus> {
433415×
        let sigs = self.store.signatures(hash)?;
434415×
        if sigs.is_empty() {
435328×
            return Ok(SignatureStatus::Unsigned);
43687×
        }
437
        let read;
43887×
        let change = match known {
43915×
            Some(m) => m,
440
            None => {
44172×
                read = self.store.get_change_meta(hash)?;
44272×
                &read
443
            }
444
        };
44587×
        let mut last_err = String::new();
44687×
        for sig in &sigs {
44787×
            match self.check_signer(change, sig, Domain::Change, hash) {
44881×
                Ok(id) => {
449
                    return Ok(SignatureStatus::Valid {
45081×
                        key: sig.key,
45181×
                        name: id.name,
45281×
                        email: id.email,
453
                        sealed: false,
45481×
                        revoked: self.is_revoked(&sig.key)?,
455
                    })
456
                }
4576×
                Err(e) => last_err = e,
458
            }
459
        }
4606×
        Ok(SignatureStatus::Invalid(last_err))
461415×
    }
462
463
    /// Whether `signer` is a short-lived key acting for `author` under a
464
    /// grant (spec §14.7): its certificate verifies with its issuer and
465
    /// carries a grant `author` signed, for the certificate's subject and
466
    /// issuer, giving `needed` at `at_ms` (the change's time, as for a
467
    /// delegation). Whether the certificate covered the time it signed is
468
    /// the policy's check, at a time the signer did not choose. `None`
469
    /// when it does; otherwise why not.
47012×
    fn granted(
47112×
        &self,
47212×
        author: &KeyId,
47312×
        signer: &KeyId,
47412×
        needed: Scope,
47512×
        at_ms: u64,
47612×
    ) -> std::result::Result<Option<String>, String> {
47712×
        let neither = || {
4786×
            Some(format!(
4796×
                "key {} is neither the author nor a delegate",
4806×
                signer.short(12)
4816×
            ))
4826×
        };
48312×
        let Ok(Some(c)) = self.store.certificate_of(signer) else {
4844×
            return Ok(neither());
485
        };
4868×
        let Ok(sc) = self.store.get_certificate(&c) else {
4870×
            return Ok(neither());
488
        };
4898×
        let Some(g) = &sc.cert.grant else {
4901×
            return Ok(neither());
491
        };
4927×
        let who = signer.short(12);
4937×
        let issuer = self
4947×
            .store
4957×
            .get_identity(&sc.cert.issuer)
4967×
            .map_err(|_| format!("key {who}'s certificate names an unknown issuer"))?;
4977×
        sc.verify(&issuer)
4987×
            .map_err(|e| format!("key {who}'s certificate: {e}"))?;
4997×
        if g.grant.grantor != *author {
5001×
            return Ok(neither());
5016×
        }
5026×
        let grantor = self
5036×
            .store
5046×
            .get_identity(author)
5056×
            .map_err(|_| format!("key {who}'s grant is by an unknown author"))?;
5066×
        g.verify(&grantor)
5076×
            .map_err(|e| format!("key {who}'s grant: {e}"))?;
5086×
        if g.grant.subject != sc.cert.subject || g.grant.issuer != sc.cert.issuer {
5090×
            return Err(format!(
5100×
                "key {who}'s grant is for {} from issuer {}, not its certificate's",
5110×
                g.grant.subject,
5120×
                g.grant.issuer.short(12)
5130×
            ));
5146×
        }
5156×
        if !sc.cert.scope.has(needed) || !g.grant.scope.has(needed) {
5160×
            return Err(format!("key {who} is not granted {needed}"));
5176×
        }
5186×
        if !g.grant.covers(needed, at_ms) {
5192×
            return Err(format!(
5202×
                "key {who}'s grant did not cover the time the change was made"
5212×
            ));
5224×
        }
5234×
        Ok(None)
52412×
    }
525
526
    /// Verify `sig` over `target` and check the author-or-delegate rule for `change`.
527241×
    fn check_signer(
528241×
        &self,
529241×
        change: &crate::state::ChangeMeta,
530241×
        sig: &Signature,
531241×
        domain: Domain,
532241×
        target: &ObjectRef,
533241×
    ) -> std::result::Result<Identity, String> {
534241×
        let id = self
535241×
            .store
536241×
            .get_identity(&sig.key)
537241×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
538
        // The author-or-delegate rule (spec §14.4). A change whose author is
539
        // the zero key names nobody (Git imports, history from before an
540
        // identity existed), so any key may adopt it with a seal; policy
541
        // then authorises that key for the reference as usual. A delegate
542
        // acts within its scope, signing changes or sealing them, and only
543
        // until its delegation expires (§14.2).
544241×
        if !change.author.is_zero() && sig.key != change.author {
54532×
            let needed = match domain {
54622×
                Domain::Change => Scope::CHANGES,
54710×
                _ => Scope::SEAL,
548
            };
54932×
            let delegation = self
55032×
                .store
55132×
                .get_identity(&change.author)
55232×
                .ok()
55332×
                .and_then(|a| a.delegate(&sig.key).copied());
55419×
            match delegation {
555
                // A certified key acting under the author's grant (§14.7).
556
                None => {
5576×
                    if let Some(why) =
55812×
                        self.granted(&change.author, &sig.key, needed, change.hlc.wall_ms)?
559
                    {
5606×
                        return Err(why);
5614×
                    }
562
                }
56320×
                Some(d) if !d.scope.has(needed) => {
5641×
                    return Err(format!(
565
                        "key {} is a delegate for {} only and may not {}",
5661×
                        sig.key.short(12),
567
                        d.scope,
5681×
                        if needed == Scope::SEAL {
5691×
                            "seal"
570
                        } else {
5710×
                            "sign changes"
572
                        }
573
                    ))
574
                }
57519×
                Some(d) if !d.allows(needed, change.hlc.wall_ms) => {
5761×
                    return Err(format!(
5771×
                        "key {}'s delegation had expired when the change was made",
5781×
                        sig.key.short(12)
5791×
                    ))
580
                }
58118×
                Some(_) => {}
582
            }
583209×
        }
584231×
        if id.is_expired_at(change.hlc.wall_ms) {
5851×
            return Err(format!(
5861×
                "key {} had expired when the change was made",
5871×
                sig.key.short(12)
5881×
            ));
589230×
        }
590230×
        verify_signature(&id, sig, domain, target).map_err(|e| e.to_string())?;
591229×
        Ok(id)
592241×
    }
593
594
    /// Like `verify_change`, but a change with no valid individual signature
595
    /// is also authenticated by a valid seal covering it (spec §14.4).
596316×
    pub fn authenticate_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
597316×
        self.authenticate_change_known(hash, None)
598316×
    }
599
600
    /// `authenticate_change`, with the change's metadata when the caller
601
    /// has it (from a log, say), so the change itself need not be read.
602391×
    pub fn authenticate_change_known(
603391×
        &self,
604391×
        hash: &ChangeHash,
605391×
        known: Option<&crate::state::ChangeMeta>,
606391×
    ) -> Result<SignatureStatus> {
607391×
        let direct = self.verify_change_known(hash, known)?;
608391×
        if matches!(direct, SignatureStatus::Valid { .. }) {
60966×
            return Ok(direct);
610325×
        }
611325×
        let mut last_err = match &direct {
6122×
            SignatureStatus::Invalid(e) => e.clone(),
613323×
            _ => String::new(),
614
        };
615325×
        let seals = self.store.seals_for(hash)?;
616325×
        if seals.is_empty() {
617171×
            return Ok(match last_err.is_empty() {
618169×
                true => SignatureStatus::Unsigned,
6192×
                false => SignatureStatus::Invalid(last_err),
620
            });
621154×
        }
622
        let read;
623154×
        let change = match known {
6240×
            Some(m) => m,
625
            None => {
626154×
                read = self.store.get_change_meta(hash)?;
627154×
                &read
628
            }
629
        };
630154×
        for seal_ref in seals {
631154×
            let attest = self.store.get_attest(&seal_ref)?;
632154×
            let AttestBody::Seal { hashes } = &attest.body else {
6330×
                continue;
634
            };
635154×
            if !hashes.contains(hash) {
6360×
                continue;
637154×
            }
638154×
            for sig in self.store.signatures(&seal_ref)? {
639154×
                match self.check_signer(change, &sig, Domain::Attest, &seal_ref) {
640148×
                    Ok(id) => {
641
                        return Ok(SignatureStatus::Valid {
642148×
                            key: sig.key,
643148×
                            name: id.name,
644148×
                            email: id.email,
645
                            sealed: true,
646148×
                            revoked: self.is_revoked(&sig.key)?,
647
                        })
648
                    }
6496×
                    Err(e) => last_err = e,
650
                }
651
            }
652
        }
6536×
        if last_err.is_empty() {
6540×
            Ok(SignatureStatus::Unsigned)
655
        } else {
6566×
            Ok(SignatureStatus::Invalid(last_err))
657
        }
658391×
    }
659
660
    /// Store and sign an attestation with the configured key.
661
    /// Seal changes with the identity key (spec §14.4): a stored, indexed
662
    /// seal attestation over `hashes`, pushed with the next push. Returns
663
    /// the attestation's reference.
6641×
    pub fn seal(&self, hashes: &[ChangeHash]) -> Result<ObjectRef> {
6651×
        if hashes.is_empty() {
6660×
            return fail("nothing to seal");
6671×
        }
6681×
        if hashes.len() > crate::attest::MAX_SEAL_HASHES {
6690×
            return fail(format!(
670
                "a seal covers at most {} changes",
671
                crate::attest::MAX_SEAL_HASHES
672
            ));
6731×
        }
6741×
        for h in hashes {
6751×
            if !self.store.has(h) {
6760×
                return fail(format!("unknown change {}", h.short(12)));
6771×
            }
678
        }
6791×
        let mut sorted = hashes.to_vec();
6801×
        sorted.sort();
6811×
        sorted.dedup();
6821×
        let sa = self.sign_attest(&Attest::seal(self.id()?, sorted.clone()))?;
6831×
        let r = self.store.put_attest(&sa.attest)?;
6841×
        for sig in &sa.sigs {
6851×
            self.store.put_signature(&r, sig)?;
686
        }
6871×
        for h in &sorted {
6881×
            self.store.index_seal(h, &r)?;
689
        }
6901×
        Ok(r)
6911×
    }
692
693
    /// Whether `signer` seals changes by `author`: its own, anonymous ones
694
    /// (§14.4), and, when it signs for the configured author (a delegate,
695
    /// or a short-lived key under the author's grant, §14.7), the
696
    /// author's. A receiver still checks it may.
69779×
    pub(crate) fn seals_for_author(&self, author: &KeyId, signer: &KeyId) -> bool {
69879×
        author == signer
6999×
            || author.is_zero()
7008×
            || (self.config.signer_key.is_some() && self.config.author_key == Some(*author))
70179×
    }
702
703
    /// The changes of the current bookmark this identity can authenticate
704
    /// but has not: its own unsigned ones, anonymous ones, and the
705
    /// author's when it signs for them.
7060×
    pub fn sealable(&self) -> Result<Vec<ChangeHash>> {
7070×
        let Some((key, _)) = self.secret_key()? else {
7080×
            return fail("no identity: run oxy identity create");
709
        };
7100×
        let heads = self.bookmark_heads()?;
7110×
        let state = self.load_state_history(&heads)?;
7120×
        let mut out = Vec::new();
7130×
        for (h, meta) in state.changes() {
7140×
            if self.seals_for_author(&meta.author, &key)
7150×
                && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
7160×
            {
7170×
                out.push(*h);
7180×
            }
719
        }
7200×
        out.sort();
7210×
        Ok(out)
7220×
    }
723
724142×
    pub(crate) fn sign_attest(&self, attest: &Attest) -> Result<SignedAttest> {
725142×
        let Some((key, sk)) = self.secret_key()? else {
7260×
            return fail("no secret key: run `oxy identity create` first");
727
        };
728142×
        let r = self.store.put_attest(attest)?;
729140×
        let sig = sk.sign(Domain::Attest, &key, &r);
730140×
        self.store.put_signature(&r, &sig)?;
731140×
        if let AttestBody::Seal { hashes } = &attest.body {
73247×
            for h in hashes {
73347×
                self.store.index_seal(h, &r)?;
734
            }
73596×
        }
736140×
        Ok(SignedAttest {
737140×
            attest: attest.clone(),
738140×
            sigs: vec![sig],
739140×
        })
740142×
    }
741
}