//! Signing with short-lived keys (spec ยง14.7, oxygenhub#241): with //! `author.signer = keyless`, oxy asks the hub to certify a fresh key //! whenever it must sign, with the agent's grant token as the credential, //! and keeps the key in memory for its certificate's minutes. Nothing that //! signs is ever written to disk: the home holds only the grant token, //! which its owner revokes on the hub. The certificate carries the owner's //! grant, so what the key signs counts in the owner's name. use super::*; use crate::cert::{certify_challenge, SignedCertificate}; use crate::credentials::{hub_of, Credentials}; use crate::protocol::{http_get, http_json, RemoteOptions}; /// A certified key is used until this long before its certificate ends, /// so a push started near the end does not outlive it. const MARGIN_MS: u64 = 2 * 60 * 1000; impl Repo { /// The hub that certifies keys: `keyless.hub`, else the default /// remote's. fn keyless_hub(&self) -> Result { let url = match &self.config.keyless_hub { Some(h) => h.clone(), None => self .config .remotes .get(&self.default_remote()) .cloned() .ok_or_else(|| { RepoError::Msg( "author.signer is keyless, but neither keyless.hub nor a default remote names the hub that certifies keys" .into(), ) })?, }; hub_of(&url).ok_or_else(|| RepoError::Msg(format!("{url} is not a hub URL"))) } /// The key to sign with now: the one certified last while it has more /// than a couple of minutes left, else a fresh one the hub certifies. pub(crate) fn keyless_secret(&self) -> Result<(KeyId, SecretKey)> { let now = Hlc::now().wall_ms; if let Some((k, sk, until)) = self.keyless_key.borrow().as_ref() { if now + MARGIN_MS < *until { return Ok((*k, sk.clone())); } } let hub = self.keyless_hub()?; let home = self .user_config .parent() .map(Path::to_path_buf) .unwrap_or_else(default_home); let creds = Credentials::at(home.clone()); let token = creds.grant(&hub).map_err(RepoError::Msg)?.ok_or_else(|| { RepoError::Msg(format!( "author.signer is keyless, but there is no agent grant for {hub}: its owner makes one with `oh agent grant NAME`, and `oxy auth grant TOKEN` keeps it" )) })?; let options = RemoteOptions { token: Some(token.clone()), ca: creds.get(&hub).map_err(RepoError::Msg)?.and_then(|e| e.ca), ..RemoteOptions::default() }; let sk = SecretKey::generate(); let id = sk.identity(&self.config.author_name, &self.config.author_email, now); let key = id.hash(); let proof = sk .sign_challenge(&key, &certify_challenge(&token)) .map_err(|e| RepoError::Msg(e.to_string()))?; let body = serde_json::json!({ "identity": crate::dsse::base64(&id.encode()), "proof": crate::dsse::base64(&crate::cbor::encode(&proof.to_value())), "scope": "changes,refs,seal", }); let (code, answer) = http_json( "POST", &format!("{hub}/api/v1/keyless/certify"), Some(&body.to_string()), &options, )?; let reply: serde_json::Value = serde_json::from_str(&answer).unwrap_or_default(); if !(200..300).contains(&code) { let why = reply["error"].as_str().unwrap_or(answer.trim()); return fail(format!( "{hub} would not certify a key (HTTP {code}): {why}" )); } let cert = reply["certificate"] .as_str() .and_then(crate::dsse::base64_decode) .ok_or_else(|| RepoError::Msg(format!("{hub} answered with no certificate")))?; let cert = SignedCertificate::decode(&cert) .map_err(|e| RepoError::Msg(format!("{hub}'s certificate: {e}")))?; if cert.cert.key_id() != key { return fail(format!( "{hub} certified another key than the one it was asked for" )); } // The issuer's identity, so this repository (and whoever it pushes // to) can check the certificate: the hub's own, as it publishes it. let issuer = match self.store.get_identity(&cert.cert.issuer) { Ok(i) => i, Err(_) => { let bytes = http_get( &format!("{hub}/.well-known/oxyhub-key"), &RemoteOptions { token: None, ..options.clone() }, )?; let i = Identity::decode(&bytes)?; if i.hash() != cert.cert.issuer { return fail(format!( "{hub}'s published key is not the one that signed its certificate" )); } i } }; cert.verify(&issuer) .map_err(|e| RepoError::Msg(format!("{hub}'s certificate: {e}")))?; // The grant's author, so the grant can be checked here and wherever // this pushes (oxygen#134): from the hub's answer, else this home's // copy of it. Without it, a repository that never saw the owner's // current identity reads the change as signed by an unknown author. if let Some(g) = &cert.cert.grant { let grantor = g.grant.grantor; if self.store.get_identity(&grantor).is_err() { let sent = reply["grantor_identity"] .as_str() .and_then(crate::dsse::base64_decode) .and_then(|b| Identity::decode(&b).ok()); let kept = || { std::fs::read( home.join("keys") .join(format!("{}.identity", grantor.to_hex())), ) .ok() .and_then(|b| Identity::decode(&b).ok()) }; match sent.filter(|i| i.hash() == grantor).or_else(|| kept().filter(|i| i.hash() == grantor)) { Some(i) => { self.store.put_identity(&i)?; } None => { return fail(format!( "the grant is signed by {}, whose identity neither {hub} nor this home has: export it there (oxy identity export) into this home's keys/", grantor.short(12) )) } } } } if let (Some(owner), Some(g)) = (&self.config.author_for, &cert.cert.grant) { self.follow_author(owner, &cert.cert.subject, g.grant.grantor, &reply, &home)?; } self.store.put_identity(&issuer)?; self.store.put_identity(&id)?; self.store.put_certificate(&cert)?; *self.keyless_key.borrow_mut() = Some((key, sk.clone(), cert.cert.expires)); Ok((key, sk)) } } impl Repo { /// `author.for` (oxygen#82): keep the identity the hub names as the /// grant's owner's newest (`author_chain`, newest first, each the /// successor of the next, the last the grant's key's), store the chain /// here so the grant checks against it, and note its key in the home, /// so this and the home's next commands author as it. fn follow_author( &self, owner: &str, subject: &str, grantor: KeyId, reply: &serde_json::Value, home: &Path, ) -> Result<()> { let granted_by = subject.rsplit_once('@').map(|(_, o)| o).unwrap_or(subject); if !granted_by.eq_ignore_ascii_case(owner) { return fail(format!( "author.for is {owner}, but this home's grant is from {granted_by}: set author.for to the account that granted it" )); } let chain: Vec = reply["author_chain"] .as_array() .map(|a| { a.iter() .filter_map(|v| v.as_str().and_then(crate::dsse::base64_decode)) .filter_map(|b| Identity::decode(&b).ok()) .collect() }) .unwrap_or_default(); let linked = chain.windows(2).all(|w| w[0].previous == Some(w[1].hash())) && chain.last().is_none_or(|l| l.previous == Some(grantor)); if !linked { return fail( "the hub's author chain does not lead back to the grant's key".to_string(), ); } let keys = home.join("keys"); std::fs::create_dir_all(&keys)?; for id in &chain { self.store.put_identity(id)?; let path = keys.join(format!("{}.identity", id.hash().to_hex())); if !path.exists() { crate::durable::write_atomic(&path, &id.encode())?; } } let newest = chain.first().map(Identity::hash).unwrap_or(grantor); crate::durable::write_atomic( &keys.join(super::config::AUTHOR_FOR_FILE), format!("{}\n", newest.to_hex()).as_bytes(), )?; Ok(()) } } /// The key a home names as its author (`author.key` in its /// `config.toml`), with its secret from the home's `keys/`: what signs /// outside any repository, such as a grant to an agent (`oh agent grant`). /// `None` when the home names no key or does not hold its secret. pub fn home_key(home: &Path) -> Result> { let config = read_config_file(&home.join("config.toml"))?; let Some(hex) = config.get("author.key").filter(|v| !v.is_empty()) else { return Ok(None); }; let key = KeyId::from_hex(hex) .ok_or_else(|| RepoError::Msg("author.key must be a 64-character hex KeyId".into()))?; let keys = home.join("keys"); let secret = match fs::read(keys.join(format!("{hex}.secret"))) { Ok(b) => b, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(e) => return Err(e.into()), }; let (k, sk) = SecretKey::decode(&secret)?; let id = Identity::decode(&fs::read(keys.join(format!("{hex}.identity")))?)?; if k != key || id.hash() != key { return fail(format!( "{} holds another key than author.key", keys.display() )); } Ok(Some((id, sk))) } #[cfg(test)] mod tests { use super::*; #[test] fn a_home_s_key_signs_outside_any_repository() { static HOME: std::sync::OnceLock = std::sync::OnceLock::new(); HOME.get_or_init(|| { let d = tempfile::tempdir().unwrap(); std::env::set_var("OXY_HOME", d.path()); d }); let dir = tempfile::tempdir().unwrap(); let home = dir.path().join("home"); assert!(home_key(&home).unwrap().is_none(), "no config, no key"); let mut r = Repo::init(&dir.path().join("work")) .unwrap() .with_home(home.clone()); let (key, id) = r .create_identity("Andy", "andy@example.org", IdentityScope::User) .unwrap(); let (got, sk) = home_key(&home).unwrap().expect("the home's author key"); assert_eq!(got, id); let sig = sk.sign(Domain::Grant, &key, &ObjectRef([1; 32])); assert!(verify_signature(&id, &sig, Domain::Grant, &ObjectRef([1; 32])).is_ok()); // An agent whose signer is keyless signs nothing until it asks. r.set_user_config("author.signer", "keyless").unwrap(); assert!(r.config.signer_keyless && r.config.signer_key.is_none()); assert_eq!(r.signing_key(), None); let err = r.secret_key().unwrap_err().to_string(); assert!(err.contains("keyless.hub nor a default remote"), "{err}"); } }