OXYGENHUB

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

474 of 534 lines run, 58 of 88 functions · run #326 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`.
3753×
    pub fn create_identity(
3853×
        &mut self,
3953×
        name: &str,
4053×
        email: &str,
4153×
        scope: IdentityScope,
4253×
    ) -> Result<(KeyId, Identity)> {
4353×
        self.create_identity_with(name, email, scope, None)
4453×
    }
45
46
    /// `create_identity` with an expiry (milliseconds since the epoch).
4756×
    pub fn create_identity_with(
4856×
        &mut self,
4956×
        name: &str,
5056×
        email: &str,
5156×
        scope: IdentityScope,
5256×
        expires: Option<u64>,
5356×
    ) -> Result<(KeyId, Identity)> {
5456×
        let sk = SecretKey::generate();
5556×
        let mut id = sk.identity(name, email, Hlc::now().wall_ms);
5656×
        id.expires = expires;
5756×
        let key = self.install_key(&id, &sk)?;
5856×
        self.set_author(&id, &key, scope)?;
5956×
        Ok((key, id))
6056×
    }
61
62
    /// Store an identity and keep its secret (and a copy of the identity)
63
    /// in the key directory.
6472×
    fn install_key(&self, id: &Identity, sk: &SecretKey) -> Result<KeyId> {
6572×
        let key = self.store.put_identity(id)?;
6672×
        fs::create_dir_all(&self.keys_dir)?;
6772×
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
6872×
        crate::durable::write_atomic_private(&path, &sk.encode(&key))?;
6972×
        write_atomic(
7072×
            &self.keys_dir.join(format!("{}.identity", key.to_hex())),
7172×
            &id.encode(),
720×
        )?;
7372×
        Ok(key)
7472×
    }
75
7673×
    fn set_author(&mut self, id: &Identity, key: &KeyId, scope: IdentityScope) -> Result<()> {
7773×
        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 => {
8539×
                Config::set_user(&self.user_config, "author.name", &id.name)?;
8639×
                Config::set_user(&self.user_config, "author.email", &id.email)?;
8739×
                Config::set_user(&self.user_config, "author.key", &key.to_hex())?;
8839×
                self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?;
89
            }
90
        }
9173×
        Ok(())
9273×
    }
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`.
330826×
    pub fn signing_key(&self) -> Option<KeyId> {
331826×
        if self.config.signer_keyless {
332
            // The key certified last, once this command has signed.
3331×
            return self.keyless_key.borrow().as_ref().map(|(k, _, _)| *k);
334825×
        }
335825×
        self.config.signer_key.or(self.config.author_key)
336826×
    }
337
338
    /// The secret key for `author.signer`, else `author.key`, if configured
339
    /// and present on disk. The identity object is kept beside the secret
340
    /// so a repository that has never seen it (a fresh clone) can store it
341
    /// when it first signs.
342653×
    pub fn secret_key(&self) -> Result<Option<(KeyId, SecretKey)>> {
343653×
        if self.config.signer_keyless {
3441×
            return self.keyless_secret().map(Some);
345652×
        }
346652×
        let Some(key) = self.signing_key() else {
347210×
            return Ok(None);
348
        };
349442×
        let path = self.keys_dir.join(format!("{}.secret", key.to_hex()));
350442×
        match fs::read(&path) {
351441×
            Ok(b) => {
352441×
                let (k, sk) = SecretKey::decode(&b)?;
353441×
                if k != key {
3540×
                    return fail(format!(
355
                        "{} holds a different key than its name",
3560×
                        path.display()
357
                    ));
358441×
                }
359441×
                if !self.store.has(&key) {
3601×
                    let id_path = self.keys_dir.join(format!("{}.identity", key.to_hex()));
3611×
                    if let Ok(bytes) = fs::read(&id_path) {
3621×
                        let id = Identity::decode(&bytes)?;
3631×
                        if id.hash() == key {
3641×
                            self.store.put_identity(&id)?;
3650×
                        }
3660×
                    }
367440×
                }
368441×
                Ok(Some((k, sk)))
369
            }
3701×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
3710×
            Err(e) => Err(e.into()),
372
        }
373653×
    }
374
375
    /// An identity: from this repository's store, or else from the key
376
    /// directory, where `oxy identity create` keeps the user's own (a new
377
    /// repository has not stored it yet). The file must hash to `key`.
378239×
    pub fn identity(&self, key: &KeyId) -> Result<Identity> {
379239×
        match self.store.get_identity(key) {
380235×
            Ok(id) => Ok(id),
3814×
            Err(e) => {
3824×
                let path = self.keys_dir.join(format!("{}.identity", key.to_hex()));
3834×
                match fs::read(&path) {
3842×
                    Ok(bytes) => {
3852×
                        let id = Identity::decode(&bytes)?;
3862×
                        if id.hash() != *key {
3871×
                            return fail(format!(
388
                                "{} does not hold identity {}",
3891×
                                path.display(),
3901×
                                key.short(12)
391
                            ));
3921×
                        }
3931×
                        Ok(id)
394
                    }
395
                    // The configured author's identity is neither in the
396
                    // repository nor in this home's keys: say why and what
397
                    // to do (oxygen#82), rather than "object … not found".
3982×
                    Err(_) if self.config.author_key == Some(*key) => fail(format!(
399
                        "this repository has no identity {} (author.key, set in {}): it is not in the repository, nor in {}.\n\
400
                         An agent home names its human's identity, and each delegation rotates that identity, so the key goes stale. \
401
                         Pin the identity this repository uses, as its owner sees it: `oxy identity show` in the owner's shell gives the key, \
402
                         then `oxy config author.key <KEY>` here; or ask the owner.",
4032×
                        key.short(12),
4042×
                        if self.config.is_repo_set("author.key") {
4051×
                            "this repository's config"
406
                        } else {
4071×
                            "the user config"
408
                        },
4092×
                        self.keys_dir.display()
410
                    )),
4110×
                    Err(_) => Err(e.into()),
412
                }
413
            }
414
        }
415239×
    }
416
417
    /// Sign a stored change with the configured secret key.
41843×
    pub fn sign_change(&self, hash: &ChangeHash) -> Result<Signature> {
41943×
        let Some((key, sk)) = self.secret_key()? else {
4200×
            return fail("no secret key: run `oxy identity create` first");
421
        };
42243×
        let sig = sk.sign(Domain::Change, &key, hash);
42343×
        self.store.put_signature(hash, &sig)?;
42443×
        Ok(sig)
42543×
    }
426
427
    /// Check the signatures on a change against the author-or-delegate rule.
42824×
    pub fn verify_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
42924×
        self.verify_change_known(hash, None)
43024×
    }
431
432
    /// `verify_change`, with the change's metadata when the caller has it
433
    /// (a change object can be as large as the tree it adds). Signatures
434
    /// are looked up first: an unsigned change needs no metadata.
435415×
    fn verify_change_known(
436415×
        &self,
437415×
        hash: &ChangeHash,
438415×
        known: Option<&crate::state::ChangeMeta>,
439415×
    ) -> Result<SignatureStatus> {
440415×
        let sigs = self.store.signatures(hash)?;
441415×
        if sigs.is_empty() {
442328×
            return Ok(SignatureStatus::Unsigned);
44387×
        }
444
        let read;
44587×
        let change = match known {
44615×
            Some(m) => m,
447
            None => {
44872×
                read = self.store.get_change_meta(hash)?;
44972×
                &read
450
            }
451
        };
45287×
        let mut last_err = String::new();
45387×
        for sig in &sigs {
45487×
            match self.check_signer(change, sig, Domain::Change, hash) {
45581×
                Ok(id) => {
456
                    return Ok(SignatureStatus::Valid {
45781×
                        key: sig.key,
45881×
                        name: self.certified_subject(&sig.key).unwrap_or(id.name),
45981×
                        email: id.email,
460
                        sealed: false,
46181×
                        revoked: self.is_revoked(&sig.key)?,
462
                    })
463
                }
4646×
                Err(e) => last_err = e,
465
            }
466
        }
4676×
        Ok(SignatureStatus::Invalid(last_err))
468415×
    }
469
470
    /// Whether `signer` is a short-lived key acting for `author` under a
471
    /// grant (spec §14.7): its certificate verifies with its issuer and
472
    /// carries a grant `author` signed, for the certificate's subject and
473
    /// issuer, giving `needed` at `at_ms` (the change's time, as for a
474
    /// delegation). Whether the certificate covered the time it signed is
475
    /// the policy's check, at a time the signer did not choose. `None`
476
    /// when it does; otherwise why not.
47712×
    fn granted(
47812×
        &self,
47912×
        author: &KeyId,
48012×
        signer: &KeyId,
48112×
        needed: Scope,
48212×
        at_ms: u64,
48312×
    ) -> std::result::Result<Option<String>, String> {
48412×
        let neither = || {
4856×
            Some(format!(
4866×
                "key {} is neither the author nor a delegate",
4876×
                signer.short(12)
4886×
            ))
4896×
        };
49012×
        let Ok(Some(c)) = self.store.certificate_of(signer) else {
4914×
            return Ok(neither());
492
        };
4938×
        let Ok(sc) = self.store.get_certificate(&c) else {
4940×
            return Ok(neither());
495
        };
4968×
        let Some(g) = &sc.cert.grant else {
4971×
            return Ok(neither());
498
        };
4997×
        let who = signer.short(12);
5007×
        let issuer = self
5017×
            .store
5027×
            .get_identity(&sc.cert.issuer)
5037×
            .map_err(|_| format!("key {who}'s certificate names an unknown issuer"))?;
5047×
        sc.verify(&issuer)
5057×
            .map_err(|e| format!("key {who}'s certificate: {e}"))?;
5067×
        if g.grant.grantor != *author {
5071×
            return Ok(neither());
5086×
        }
5096×
        let grantor = self
5106×
            .store
5116×
            .get_identity(author)
5126×
            .map_err(|_| format!("key {who}'s grant is by an unknown author"))?;
5136×
        g.verify(&grantor)
5146×
            .map_err(|e| format!("key {who}'s grant: {e}"))?;
5156×
        if g.grant.subject != sc.cert.subject || g.grant.issuer != sc.cert.issuer {
5160×
            return Err(format!(
5170×
                "key {who}'s grant is for {} from issuer {}, not its certificate's",
5180×
                g.grant.subject,
5190×
                g.grant.issuer.short(12)
5200×
            ));
5216×
        }
5226×
        if !sc.cert.scope.has(needed) || !g.grant.scope.has(needed) {
5230×
            return Err(format!("key {who} is not granted {needed}"));
5246×
        }
5256×
        if !g.grant.covers(needed, at_ms) {
5262×
            return Err(format!(
5272×
                "key {who}'s grant did not cover the time the change was made"
5282×
            ));
5294×
        }
5304×
        Ok(None)
53112×
    }
532
533
    /// The subject a short-lived key was certified for (spec §14.7), such
534
    /// as `agent:claude@andy`: what names it, since its identity is only
535
    /// a fresh key's.
536229×
    pub fn certified_subject(&self, key: &KeyId) -> Option<String> {
537229×
        let c = self.store.certificate_of(key).ok()??;
5388×
        Some(self.store.get_certificate(&c).ok()?.cert.subject)
539229×
    }
540
541
    /// Verify `sig` over `target` and check the author-or-delegate rule for `change`.
542241×
    fn check_signer(
543241×
        &self,
544241×
        change: &crate::state::ChangeMeta,
545241×
        sig: &Signature,
546241×
        domain: Domain,
547241×
        target: &ObjectRef,
548241×
    ) -> std::result::Result<Identity, String> {
549241×
        let id = self
550241×
            .store
551241×
            .get_identity(&sig.key)
552241×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
553
        // The author-or-delegate rule (spec §14.4). A change whose author is
554
        // the zero key names nobody (Git imports, history from before an
555
        // identity existed), so any key may adopt it with a seal; policy
556
        // then authorises that key for the reference as usual. A delegate
557
        // acts within its scope, signing changes or sealing them, and only
558
        // until its delegation expires (§14.2).
559241×
        if !change.author.is_zero() && sig.key != change.author {
56032×
            let needed = match domain {
56122×
                Domain::Change => Scope::CHANGES,
56210×
                _ => Scope::SEAL,
563
            };
56432×
            let delegation = self
56532×
                .store
56632×
                .get_identity(&change.author)
56732×
                .ok()
56832×
                .and_then(|a| a.delegate(&sig.key).copied());
56919×
            match delegation {
570
                // A certified key acting under the author's grant (§14.7).
571
                None => {
5726×
                    if let Some(why) =
57312×
                        self.granted(&change.author, &sig.key, needed, change.hlc.wall_ms)?
574
                    {
5756×
                        return Err(why);
5764×
                    }
577
                }
57820×
                Some(d) if !d.scope.has(needed) => {
5791×
                    return Err(format!(
580
                        "key {} is a delegate for {} only and may not {}",
5811×
                        sig.key.short(12),
582
                        d.scope,
5831×
                        if needed == Scope::SEAL {
5841×
                            "seal"
585
                        } else {
5860×
                            "sign changes"
587
                        }
588
                    ))
589
                }
59019×
                Some(d) if !d.allows(needed, change.hlc.wall_ms) => {
5911×
                    return Err(format!(
5921×
                        "key {}'s delegation had expired when the change was made",
5931×
                        sig.key.short(12)
5941×
                    ))
595
                }
59618×
                Some(_) => {}
597
            }
598209×
        }
599231×
        if id.is_expired_at(change.hlc.wall_ms) {
6001×
            return Err(format!(
6011×
                "key {} had expired when the change was made",
6021×
                sig.key.short(12)
6031×
            ));
604230×
        }
605230×
        verify_signature(&id, sig, domain, target).map_err(|e| e.to_string())?;
606229×
        Ok(id)
607241×
    }
608
609
    /// Like `verify_change`, but a change with no valid individual signature
610
    /// is also authenticated by a valid seal covering it (spec §14.4).
611316×
    pub fn authenticate_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> {
612316×
        self.authenticate_change_known(hash, None)
613316×
    }
614
615
    /// `authenticate_change`, with the change's metadata when the caller
616
    /// has it (from a log, say), so the change itself need not be read.
617391×
    pub fn authenticate_change_known(
618391×
        &self,
619391×
        hash: &ChangeHash,
620391×
        known: Option<&crate::state::ChangeMeta>,
621391×
    ) -> Result<SignatureStatus> {
622391×
        let direct = self.verify_change_known(hash, known)?;
623391×
        if matches!(direct, SignatureStatus::Valid { .. }) {
62466×
            return Ok(direct);
625325×
        }
626325×
        let mut last_err = match &direct {
6272×
            SignatureStatus::Invalid(e) => e.clone(),
628323×
            _ => String::new(),
629
        };
630325×
        let seals = self.store.seals_for(hash)?;
631325×
        if seals.is_empty() {
632171×
            return Ok(match last_err.is_empty() {
633169×
                true => SignatureStatus::Unsigned,
6342×
                false => SignatureStatus::Invalid(last_err),
635
            });
636154×
        }
637
        let read;
638154×
        let change = match known {
6390×
            Some(m) => m,
640
            None => {
641154×
                read = self.store.get_change_meta(hash)?;
642154×
                &read
643
            }
644
        };
645154×
        for seal_ref in seals {
646154×
            let attest = self.store.get_attest(&seal_ref)?;
647154×
            let AttestBody::Seal { hashes } = &attest.body else {
6480×
                continue;
649
            };
650154×
            if !hashes.contains(hash) {
6510×
                continue;
652154×
            }
653154×
            for sig in self.store.signatures(&seal_ref)? {
654154×
                match self.check_signer(change, &sig, Domain::Attest, &seal_ref) {
655148×
                    Ok(id) => {
656
                        return Ok(SignatureStatus::Valid {
657148×
                            key: sig.key,
658148×
                            name: self.certified_subject(&sig.key).unwrap_or(id.name),
659148×
                            email: id.email,
660
                            sealed: true,
661148×
                            revoked: self.is_revoked(&sig.key)?,
662
                        })
663
                    }
6646×
                    Err(e) => last_err = e,
665
                }
666
            }
667
        }
6686×
        if last_err.is_empty() {
6690×
            Ok(SignatureStatus::Unsigned)
670
        } else {
6716×
            Ok(SignatureStatus::Invalid(last_err))
672
        }
673391×
    }
674
675
    /// Store and sign an attestation with the configured key.
676
    /// Seal changes with the identity key (spec §14.4): a stored, indexed
677
    /// seal attestation over `hashes`, pushed with the next push. Returns
678
    /// the attestation's reference.
6791×
    pub fn seal(&self, hashes: &[ChangeHash]) -> Result<ObjectRef> {
6801×
        if hashes.is_empty() {
6810×
            return fail("nothing to seal");
6821×
        }
6831×
        if hashes.len() > crate::attest::MAX_SEAL_HASHES {
6840×
            return fail(format!(
685
                "a seal covers at most {} changes",
686
                crate::attest::MAX_SEAL_HASHES
687
            ));
6881×
        }
6891×
        for h in hashes {
6901×
            if !self.store.has(h) {
6910×
                return fail(format!("unknown change {}", h.short(12)));
6921×
            }
693
        }
6941×
        let mut sorted = hashes.to_vec();
6951×
        sorted.sort();
6961×
        sorted.dedup();
6971×
        let sa = self.sign_attest(&Attest::seal(self.id()?, sorted.clone()))?;
6981×
        let r = self.store.put_attest(&sa.attest)?;
6991×
        for sig in &sa.sigs {
7001×
            self.store.put_signature(&r, sig)?;
701
        }
7021×
        for h in &sorted {
7031×
            self.store.index_seal(h, &r)?;
704
        }
7051×
        Ok(r)
7061×
    }
707
708
    /// Whether `signer` seals changes by `author`: its own, anonymous ones
709
    /// (§14.4), and, when it signs for the configured author (a delegate,
710
    /// or a short-lived key under the author's grant, §14.7), the
711
    /// author's. A receiver still checks it may.
71279×
    pub(crate) fn seals_for_author(&self, author: &KeyId, signer: &KeyId) -> bool {
71379×
        author == signer
7149×
            || author.is_zero()
7158×
            || ((self.config.signer_key.is_some() || self.config.signer_keyless)
7166×
                && self.config.author_key == Some(*author))
71779×
    }
718
719
    /// The changes of the current bookmark this identity can authenticate
720
    /// but has not: its own unsigned ones, anonymous ones, and the
721
    /// author's when it signs for them.
7220×
    pub fn sealable(&self) -> Result<Vec<ChangeHash>> {
7230×
        let Some((key, _)) = self.secret_key()? else {
7240×
            return fail("no identity: run oxy identity create");
725
        };
7260×
        let heads = self.bookmark_heads()?;
7270×
        let state = self.load_state_history(&heads)?;
7280×
        let mut out = Vec::new();
7290×
        for (h, meta) in state.changes() {
7300×
            if self.seals_for_author(&meta.author, &key)
7310×
                && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
7320×
            {
7330×
                out.push(*h);
7340×
            }
735
        }
7360×
        out.sort();
7370×
        Ok(out)
7380×
    }
739
740142×
    pub(crate) fn sign_attest(&self, attest: &Attest) -> Result<SignedAttest> {
741142×
        let Some((key, sk)) = self.secret_key()? else {
7420×
            return fail("no secret key: run `oxy identity create` first");
743
        };
744142×
        let r = self.store.put_attest(attest)?;
745140×
        let sig = sk.sign(Domain::Attest, &key, &r);
746140×
        self.store.put_signature(&r, &sig)?;
747140×
        if let AttestBody::Seal { hashes } = &attest.body {
74847×
            for h in hashes {
74947×
                self.store.index_seal(h, &r)?;
750
            }
75196×
        }
752140×
        Ok(SignedAttest {
753140×
            attest: attest.clone(),
754140×
            sigs: vec![sig],
755140×
        })
756142×
    }
757
}