//! Identities, signing, and signature verification (spec §14). use super::*; /// Outcome of verifying the signatures on a change (spec §14.3, §14.4). #[derive(Clone, Debug, PartialEq, Eq)] pub enum SignatureStatus { Unsigned, /// `revoked` marks a signature that verifies but whose key has since /// been revoked by policy or by a revocation this repository recorded. Valid { key: KeyId, name: String, email: String, sealed: bool, revoked: bool, }, Invalid(String), } /// The outcome of replacing the configured identity (spec §14.2). #[derive(Clone, Debug)] pub struct Rotation { pub old: KeyId, pub new: KeyId, pub identity: Identity, /// The policy update that moved the old key's grants to the new key, /// when the repository has a policy naming the old key. pub policy: Option, } impl Repo { // ------------------------------------------------------------ identity /// Generate a composite key pair, store its identity object, keep the /// secret in the key directory, and record the author at `scope`. pub fn create_identity( &mut self, name: &str, email: &str, scope: IdentityScope, ) -> Result<(KeyId, Identity)> { self.create_identity_with(name, email, scope, None) } /// `create_identity` with an expiry (milliseconds since the epoch). pub fn create_identity_with( &mut self, name: &str, email: &str, scope: IdentityScope, expires: Option, ) -> Result<(KeyId, Identity)> { let sk = SecretKey::generate(); let mut id = sk.identity(name, email, Hlc::now().wall_ms); id.expires = expires; let key = self.install_key(&id, &sk)?; self.set_author(&id, &key, scope)?; Ok((key, id)) } /// Store an identity and keep its secret (and a copy of the identity) /// in the key directory. fn install_key(&self, id: &Identity, sk: &SecretKey) -> Result { let key = self.store.put_identity(id)?; fs::create_dir_all(&self.keys_dir)?; let path = self.keys_dir.join(format!("{}.secret", key.to_hex())); crate::durable::write_atomic_private(&path, &sk.encode(&key))?; write_atomic( &self.keys_dir.join(format!("{}.identity", key.to_hex())), &id.encode(), )?; Ok(key) } fn set_author(&mut self, id: &Identity, key: &KeyId, scope: IdentityScope) -> Result<()> { match scope { IdentityScope::Repo => { self.config.set("author.name", &id.name)?; self.config.set("author.email", &id.email)?; self.config.set("author.key", &key.to_hex())?; self.save_config()?; } IdentityScope::User => { Config::set_user(&self.user_config, "author.name", &id.name)?; Config::set_user(&self.user_config, "author.email", &id.email)?; Config::set_user(&self.user_config, "author.key", &key.to_hex())?; self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?; } } Ok(()) } /// The scope that holds the configured author key. fn author_scope(&self) -> IdentityScope { if self.config.repo_layer().contains_key("author.key") { IdentityScope::Repo } else { IdentityScope::User } } /// Record a successor key everywhere the old one was named: the /// repository layer when it pins the old key, and the user file when /// it names the old key, so every checkout that followed the old key /// follows the new one (oxygen#69). A key named nowhere falls back to /// the scope that resolved it. fn record_successor(&mut self, id: &Identity, old: &KeyId, new_key: &KeyId) -> Result<()> { let names = |v: Option<&String>| v.and_then(|k| KeyId::from_hex(k)) == Some(*old); let repo_pins = names(self.config.repo_layer().get("author.key")); let user_entries = super::config::read_config_file(&self.user_config).unwrap_or_default(); let user_names = names(user_entries.get("author.key")); if !repo_pins && !user_names { return self.set_author(id, new_key, self.author_scope()); } if user_names { self.set_author(id, new_key, IdentityScope::User)?; } if repo_pins { self.set_author(id, new_key, IdentityScope::Repo)?; } Ok(()) } /// Replace the configured identity by `new` signed with `sk`: store it, /// record a `rotate` attestation signed by the old key, move the old /// key's policy grants to the new key, and switch the author config. fn replace_identity( &mut self, new: Identity, sk: SecretKey, command: &str, ) -> Result { let Some((old, old_sk)) = self.secret_key()? else { return fail("no secret key: run `oxy identity create` first"); }; if new.previous != Some(old) { return fail("the successor identity must name the current key as previous"); } let new_key = self.install_key(&new, &sk)?; let attest = Attest { repo: self.id()?, hlc: Hlc::now(), body: AttestBody::Rotate { new: new_key }, }; let r = self.store.put_attest(&attest)?; self.store .put_signature(&r, &old_sk.sign(Domain::Attest, &old, &r))?; let policy = match self.current_policy()? { Some((_, sp)) if sp.policy.mentions(&old) => { let mut p = self.next_policy()?; p.substitute_key(&old, new.clone()); Some(self.sign_policy_with(p, &[(old, &old_sk), (new_key, &sk)], command)?) } _ => None, }; self.record_successor(&new, &old, &new_key)?; Ok(Rotation { old, new: new_key, identity: new, policy, }) } /// Rotate to a fresh key pair; the new identity names the old one as /// `previous` and keeps its name, email, delegates, and expiry. pub fn rotate_identity(&mut self) -> Result { let Some((old, _)) = self.secret_key()? else { return fail("no secret key: run `oxy identity create` first"); }; let cur = self.identity(&old)?; let sk = SecretKey::generate(); let mut id = sk.identity(&cur.name, &cur.email, Hlc::now().wall_ms); id.previous = Some(old); id.delegates = cur.delegates.clone(); id.expires = cur.expires; self.replace_identity(id, sk, "oxy identity rotate") } /// Re-issue the identity with the same keys and a new expiry. pub fn renew_identity(&mut self, expires: Option) -> Result { let Some((old, sk)) = self.secret_key()? else { return fail("no secret key: run `oxy identity create` first"); }; let cur = self.identity(&old)?; let id = cur.successor(cur.delegates.clone(), expires, Hlc::now().wall_ms); self.replace_identity(id, sk, "oxy identity renew") } /// Let `delegate` act on this identity's behalf within `scope` until /// `expires` (spec §14.2). Delegates are part of the identity object, /// so this re-issues it with the same keys. pub fn delegate_add( &mut self, delegate: Identity, scope: Scope, expires: Option, ) -> Result { self.delegate_add_many(vec![delegate], scope, expires) } /// As [`Repo::delegate_add`], for several delegates in one rotation. pub fn delegate_add_many( &mut self, new_delegates: Vec, scope: Scope, expires: Option, ) -> Result { let Some((old, sk)) = self.secret_key()? else { return fail("no secret key: run `oxy identity create` first"); }; if scope.is_empty() { return fail("a delegate needs at least one scope: changes, refs or seal"); } if new_delegates.is_empty() { return fail("name at least one identity file"); } let cur = self.identity(&old)?; let mut delegates = cur.delegates.clone(); let mut added = Vec::new(); for delegate in new_delegates { let dk = self.store.put_identity(&delegate)?; added.push(dk); if dk == old { return fail("an identity cannot delegate to itself"); } if cur.delegate(&dk).is_some() || delegates .iter() .skip(cur.delegates.len()) .any(|d| d.key == dk) { return fail(format!( "{} is already a delegate; remove it first to change its scope or expiry", dk.short(12) )); } delegates.push(Delegate { key: dk, scope, expires, }); } let id = cur.successor(delegates, cur.expires, Hlc::now().wall_ms); self.replace_identity( id, sk, &format!( "oxy identity delegate add {} --scope {scope}", added .iter() .map(|k| k.short(12)) .collect::>() .join(" ") ), ) } /// Withdraw a delegation; re-issues the identity with the same keys. pub fn delegate_remove(&mut self, delegate: &KeyId) -> Result { let Some((old, sk)) = self.secret_key()? else { return fail("no secret key: run `oxy identity create` first"); }; let cur = self.identity(&old)?; if cur.delegate(delegate).is_none() { return fail(format!("{} is not a delegate", delegate.short(12))); } let delegates = cur .delegates .iter() .copied() .filter(|d| d.key != *delegate) .collect(); let id = cur.successor(delegates, cur.expires, Hlc::now().wall_ms); self.replace_identity( id, sk, &format!("oxy identity delegate remove {}", delegate.short(12)), ) } /// Revoke `key` (your own, one you delegated to, or any key when you /// hold a policy root): record a signed `revoke` attestation and a /// local marker, and drop the key from the policy where it has one. /// Revoking a delegate does not re-issue the identity; `delegate_remove` /// does that, and the CLI does both. pub fn revoke_identity(&self, key: &KeyId, reason: &str) -> Result> { let Some((own, sk)) = self.secret_key()? else { return fail("no secret key: run `oxy identity create` first"); }; let policy = self.current_policy()?.map(|(_, sp)| sp.policy); let is_root = policy.as_ref().is_some_and(|p| p.roots.contains(&own)); let is_delegate = self.identity(&own)?.delegate(key).is_some(); if *key != own && !is_root && !is_delegate { return fail("only the key's holder, the identity that delegated to it, or a policy root can revoke it"); } let attest = Attest { repo: self.id()?, hlc: Hlc::now(), body: AttestBody::Revoke { key: *key, reason: reason.into(), }, }; let r = self.store.put_attest(&attest)?; self.store .put_signature(&r, &sk.sign(Domain::Attest, &own, &r))?; let dir = self.oxy.join("revoked"); fs::create_dir_all(&dir)?; write_atomic(&dir.join(key.to_hex()), r.to_hex().as_bytes())?; match policy { Some(p) if p.mentions(key) => Ok(Some(self.policy_revoke(key)?)), _ => Ok(None), } } /// Whether `key` is revoked by the policy or by a recorded revocation. pub fn is_revoked(&self, key: &KeyId) -> Result { if self.oxy.join("revoked").join(key.to_hex()).exists() { return Ok(true); } Ok(self .current_policy()? .is_some_and(|(_, sp)| sp.policy.is_revoked(key))) } /// The key this repository signs with: `author.signer` when set (an /// agent's own key, acting for the author), else `author.key`. pub fn signing_key(&self) -> Option { if self.config.signer_keyless { // The key certified last, once this command has signed. return self.keyless_key.borrow().as_ref().map(|(k, _, _)| *k); } self.config.signer_key.or(self.config.author_key) } /// The secret key for `author.signer`, else `author.key`, if configured /// and present on disk. The identity object is kept beside the secret /// so a repository that has never seen it (a fresh clone) can store it /// when it first signs. pub fn secret_key(&self) -> Result> { if self.config.signer_keyless { return self.keyless_secret().map(Some); } let Some(key) = self.signing_key() else { return Ok(None); }; let path = self.keys_dir.join(format!("{}.secret", key.to_hex())); match fs::read(&path) { Ok(b) => { let (k, sk) = SecretKey::decode(&b)?; if k != key { return fail(format!( "{} holds a different key than its name", path.display() )); } if !self.store.has(&key) { let id_path = self.keys_dir.join(format!("{}.identity", key.to_hex())); if let Ok(bytes) = fs::read(&id_path) { let id = Identity::decode(&bytes)?; if id.hash() == key { self.store.put_identity(&id)?; } } } Ok(Some((k, sk))) } Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(e) => Err(e.into()), } } /// An identity: from this repository's store, or else from the key /// directory, where `oxy identity create` keeps the user's own (a new /// repository has not stored it yet). The file must hash to `key`. pub fn identity(&self, key: &KeyId) -> Result { match self.store.get_identity(key) { Ok(id) => Ok(id), Err(e) => { let path = self.keys_dir.join(format!("{}.identity", key.to_hex())); match fs::read(&path) { Ok(bytes) => { let id = Identity::decode(&bytes)?; if id.hash() != *key { return fail(format!( "{} does not hold identity {}", path.display(), key.short(12) )); } Ok(id) } // The configured author's identity is neither in the // repository nor in this home's keys: say why and what // to do (oxygen#82), rather than "object … not found". Err(_) if self.config.author_key == Some(*key) => fail(format!( "this repository has no identity {} (author.key, set in {}): it is not in the repository, nor in {}.\n\ An agent home names its human's identity, and each delegation rotates that identity, so the key goes stale. \ Pin the identity this repository uses, as its owner sees it: `oxy identity show` in the owner's shell gives the key, \ then `oxy config author.key ` here; or ask the owner.", key.short(12), if self.config.is_repo_set("author.key") { "this repository's config" } else { "the user config" }, self.keys_dir.display() )), Err(_) => Err(e.into()), } } } } /// Sign a stored change with the configured secret key. pub fn sign_change(&self, hash: &ChangeHash) -> Result { let Some((key, sk)) = self.secret_key()? else { return fail("no secret key: run `oxy identity create` first"); }; let sig = sk.sign(Domain::Change, &key, hash); self.store.put_signature(hash, &sig)?; Ok(sig) } /// Check the signatures on a change against the author-or-delegate rule. pub fn verify_change(&self, hash: &ChangeHash) -> Result { self.verify_change_known(hash, None) } /// `verify_change`, with the change's metadata when the caller has it /// (a change object can be as large as the tree it adds). Signatures /// are looked up first: an unsigned change needs no metadata. fn verify_change_known( &self, hash: &ChangeHash, known: Option<&crate::state::ChangeMeta>, ) -> Result { let sigs = self.store.signatures(hash)?; if sigs.is_empty() { return Ok(SignatureStatus::Unsigned); } let read; let change = match known { Some(m) => m, None => { read = self.store.get_change_meta(hash)?; &read } }; let mut last_err = String::new(); for sig in &sigs { match self.check_signer(change, sig, Domain::Change, hash) { Ok(id) => { return Ok(SignatureStatus::Valid { key: sig.key, name: self.certified_subject(&sig.key).unwrap_or(id.name), email: id.email, sealed: false, revoked: self.is_revoked(&sig.key)?, }) } Err(e) => last_err = e, } } Ok(SignatureStatus::Invalid(last_err)) } /// Whether `signer` is a short-lived key acting for `author` under a /// grant (spec §14.7): its certificate verifies with its issuer and /// carries a grant `author` signed, for the certificate's subject and /// issuer, giving `needed` at `at_ms` (the change's time, as for a /// delegation). Whether the certificate covered the time it signed is /// the policy's check, at a time the signer did not choose. `None` /// when it does; otherwise why not. fn granted( &self, author: &KeyId, signer: &KeyId, needed: Scope, at_ms: u64, ) -> std::result::Result, String> { let neither = || { Some(format!( "key {} is neither the author nor a delegate", signer.short(12) )) }; let Ok(Some(c)) = self.store.certificate_of(signer) else { return Ok(neither()); }; let Ok(sc) = self.store.get_certificate(&c) else { return Ok(neither()); }; let Some(g) = &sc.cert.grant else { return Ok(neither()); }; let who = signer.short(12); let issuer = self .store .get_identity(&sc.cert.issuer) .map_err(|_| format!("key {who}'s certificate names an unknown issuer"))?; sc.verify(&issuer) .map_err(|e| format!("key {who}'s certificate: {e}"))?; if g.grant.grantor != *author { return Ok(neither()); } let grantor = self .store .get_identity(author) .map_err(|_| format!("key {who}'s grant is by an unknown author"))?; g.verify(&grantor) .map_err(|e| format!("key {who}'s grant: {e}"))?; if g.grant.subject != sc.cert.subject || g.grant.issuer != sc.cert.issuer { return Err(format!( "key {who}'s grant is for {} from issuer {}, not its certificate's", g.grant.subject, g.grant.issuer.short(12) )); } if !sc.cert.scope.has(needed) || !g.grant.scope.has(needed) { return Err(format!("key {who} is not granted {needed}")); } if !g.grant.covers(needed, at_ms) { return Err(format!( "key {who}'s grant did not cover the time the change was made" )); } Ok(None) } /// The subject a short-lived key was certified for (spec §14.7), such /// as `agent:claude@andy`: what names it, since its identity is only /// a fresh key's. pub fn certified_subject(&self, key: &KeyId) -> Option { let c = self.store.certificate_of(key).ok()??; Some(self.store.get_certificate(&c).ok()?.cert.subject) } /// Verify `sig` over `target` and check the author-or-delegate rule for `change`. fn check_signer( &self, change: &crate::state::ChangeMeta, sig: &Signature, domain: Domain, target: &ObjectRef, ) -> std::result::Result { let id = self .store .get_identity(&sig.key) .map_err(|_| format!("unknown key {}", sig.key.short(12)))?; // The author-or-delegate rule (spec §14.4). A change whose author is // the zero key names nobody (Git imports, history from before an // identity existed), so any key may adopt it with a seal; policy // then authorises that key for the reference as usual. A delegate // acts within its scope, signing changes or sealing them, and only // until its delegation expires (§14.2). if !change.author.is_zero() && sig.key != change.author { let needed = match domain { Domain::Change => Scope::CHANGES, _ => Scope::SEAL, }; let delegation = self .store .get_identity(&change.author) .ok() .and_then(|a| a.delegate(&sig.key).copied()); match delegation { // A certified key acting under the author's grant (§14.7). None => { if let Some(why) = self.granted(&change.author, &sig.key, needed, change.hlc.wall_ms)? { return Err(why); } } Some(d) if !d.scope.has(needed) => { return Err(format!( "key {} is a delegate for {} only and may not {}", sig.key.short(12), d.scope, if needed == Scope::SEAL { "seal" } else { "sign changes" } )) } Some(d) if !d.allows(needed, change.hlc.wall_ms) => { return Err(format!( "key {}'s delegation had expired when the change was made", sig.key.short(12) )) } Some(_) => {} } } if id.is_expired_at(change.hlc.wall_ms) { return Err(format!( "key {} had expired when the change was made", sig.key.short(12) )); } verify_signature(&id, sig, domain, target).map_err(|e| e.to_string())?; Ok(id) } /// Like `verify_change`, but a change with no valid individual signature /// is also authenticated by a valid seal covering it (spec §14.4). pub fn authenticate_change(&self, hash: &ChangeHash) -> Result { self.authenticate_change_known(hash, None) } /// `authenticate_change`, with the change's metadata when the caller /// has it (from a log, say), so the change itself need not be read. pub fn authenticate_change_known( &self, hash: &ChangeHash, known: Option<&crate::state::ChangeMeta>, ) -> Result { let direct = self.verify_change_known(hash, known)?; if matches!(direct, SignatureStatus::Valid { .. }) { return Ok(direct); } let mut last_err = match &direct { SignatureStatus::Invalid(e) => e.clone(), _ => String::new(), }; let seals = self.store.seals_for(hash)?; if seals.is_empty() { return Ok(match last_err.is_empty() { true => SignatureStatus::Unsigned, false => SignatureStatus::Invalid(last_err), }); } let read; let change = match known { Some(m) => m, None => { read = self.store.get_change_meta(hash)?; &read } }; for seal_ref in seals { let attest = self.store.get_attest(&seal_ref)?; let AttestBody::Seal { hashes } = &attest.body else { continue; }; if !hashes.contains(hash) { continue; } for sig in self.store.signatures(&seal_ref)? { match self.check_signer(change, &sig, Domain::Attest, &seal_ref) { Ok(id) => { return Ok(SignatureStatus::Valid { key: sig.key, name: self.certified_subject(&sig.key).unwrap_or(id.name), email: id.email, sealed: true, revoked: self.is_revoked(&sig.key)?, }) } Err(e) => last_err = e, } } } if last_err.is_empty() { Ok(SignatureStatus::Unsigned) } else { Ok(SignatureStatus::Invalid(last_err)) } } /// Store and sign an attestation with the configured key. /// Seal changes with the identity key (spec §14.4): a stored, indexed /// seal attestation over `hashes`, pushed with the next push. Returns /// the attestation's reference. pub fn seal(&self, hashes: &[ChangeHash]) -> Result { if hashes.is_empty() { return fail("nothing to seal"); } if hashes.len() > crate::attest::MAX_SEAL_HASHES { return fail(format!( "a seal covers at most {} changes", crate::attest::MAX_SEAL_HASHES )); } for h in hashes { if !self.store.has(h) { return fail(format!("unknown change {}", h.short(12))); } } let mut sorted = hashes.to_vec(); sorted.sort(); sorted.dedup(); let sa = self.sign_attest(&Attest::seal(self.id()?, sorted.clone()))?; let r = self.store.put_attest(&sa.attest)?; for sig in &sa.sigs { self.store.put_signature(&r, sig)?; } for h in &sorted { self.store.index_seal(h, &r)?; } Ok(r) } /// Whether `signer` seals changes by `author`: its own, anonymous ones /// (§14.4), and, when it signs for the configured author (a delegate, /// or a short-lived key under the author's grant, §14.7), the /// author's. A receiver still checks it may. pub(crate) fn seals_for_author(&self, author: &KeyId, signer: &KeyId) -> bool { author == signer || author.is_zero() || ((self.config.signer_key.is_some() || self.config.signer_keyless) && self.config.author_key == Some(*author)) } /// The changes of the current bookmark this identity can authenticate /// but has not: its own unsigned ones, anonymous ones, and the /// author's when it signs for them. pub fn sealable(&self) -> Result> { let Some((key, _)) = self.secret_key()? else { return fail("no identity: run oxy identity create"); }; let heads = self.bookmark_heads()?; let state = self.load_state_history(&heads)?; let mut out = Vec::new(); for (h, meta) in state.changes() { if self.seals_for_author(&meta.author, &key) && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) { out.push(*h); } } out.sort(); Ok(out) } pub(crate) fn sign_attest(&self, attest: &Attest) -> Result { let Some((key, sk)) = self.secret_key()? else { return fail("no secret key: run `oxy identity create` first"); }; let r = self.store.put_attest(attest)?; let sig = sk.sign(Domain::Attest, &key, &r); self.store.put_signature(&r, &sig)?; if let AttestBody::Seal { hashes } = &attest.body { for h in hashes { self.store.index_seal(h, &r)?; } } Ok(SignedAttest { attest: attest.clone(), sigs: vec![sig], }) } }