Coverage / crates/oxy-core/src/repo/identity.rs 88.8%
474 of 534 lines run, 58 of 88 functions · run #357 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`. | |
| 37 | 59× | pub fn create_identity( |
| 38 | 59× | &mut self, |
| 39 | 59× | name: &str, |
| 40 | 59× | email: &str, |
| 41 | 59× | scope: IdentityScope, |
| 42 | 59× | ) -> Result<(KeyId, Identity)> { |
| 43 | 59× | self.create_identity_with(name, email, scope, None) |
| 44 | 59× | } |
| 45 | | |
| 46 | /// `create_identity` with an expiry (milliseconds since the epoch). | |
| 47 | 62× | pub fn create_identity_with( |
| 48 | 62× | &mut self, |
| 49 | 62× | name: &str, |
| 50 | 62× | email: &str, |
| 51 | 62× | scope: IdentityScope, |
| 52 | 62× | expires: Option<u64>, |
| 53 | 62× | ) -> Result<(KeyId, Identity)> { |
| 54 | 62× | let sk = SecretKey::generate(); |
| 55 | 62× | let mut id = sk.identity(name, email, Hlc::now().wall_ms); |
| 56 | 62× | id.expires = expires; |
| 57 | 62× | let key = self.install_key(&id, &sk)?; |
| 58 | 62× | self.set_author(&id, &key, scope)?; |
| 59 | 62× | Ok((key, id)) |
| 60 | 62× | } |
| 61 | | |
| 62 | /// Store an identity and keep its secret (and a copy of the identity) | |
| 63 | /// in the key directory. | |
| 64 | 79× | fn install_key(&self, id: &Identity, sk: &SecretKey) -> Result<KeyId> { |
| 65 | 79× | let key = self.store.put_identity(id)?; |
| 66 | 79× | fs::create_dir_all(&self.keys_dir)?; |
| 67 | 79× | let path = self.keys_dir.join(format!("{}.secret", key.to_hex())); |
| 68 | 79× | crate::durable::write_atomic_private(&path, &sk.encode(&key))?; |
| 69 | 79× | write_atomic( |
| 70 | 79× | &self.keys_dir.join(format!("{}.identity", key.to_hex())), |
| 71 | 79× | &id.encode(), |
| 72 | 0× | )?; |
| 73 | 79× | Ok(key) |
| 74 | 79× | } |
| 75 | | |
| 76 | 80× | fn set_author(&mut self, id: &Identity, key: &KeyId, scope: IdentityScope) -> Result<()> { |
| 77 | 80× | match scope { |
| 78 | IdentityScope::Repo => { | |
| 79 | 37× | self.config.set("author.name", &id.name)?; |
| 80 | 37× | self.config.set("author.email", &id.email)?; |
| 81 | 37× | self.config.set("author.key", &key.to_hex())?; |
| 82 | 37× | self.save_config()?; |
| 83 | } | |
| 84 | IdentityScope::User => { | |
| 85 | 43× | Config::set_user(&self.user_config, "author.name", &id.name)?; |
| 86 | 43× | Config::set_user(&self.user_config, "author.email", &id.email)?; |
| 87 | 43× | Config::set_user(&self.user_config, "author.key", &key.to_hex())?; |
| 88 | 43× | self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?; |
| 89 | } | |
| 90 | } | |
| 91 | 80× | Ok(()) |
| 92 | 80× | } |
| 93 | | |
| 94 | /// The scope that holds the configured author key. | |
| 95 | 0× | fn author_scope(&self) -> IdentityScope { |
| 96 | 0× | if self.config.repo_layer().contains_key("author.key") { |
| 97 | 0× | IdentityScope::Repo |
| 98 | } else { | |
| 99 | 0× | IdentityScope::User |
| 100 | } | |
| 101 | 0× | } |
| 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. | |
| 108 | 17× | fn record_successor(&mut self, id: &Identity, old: &KeyId, new_key: &KeyId) -> Result<()> { |
| 109 | 34× | let names = |v: Option<&String>| v.and_then(|k| KeyId::from_hex(k)) == Some(*old); |
| 110 | 17× | let repo_pins = names(self.config.repo_layer().get("author.key")); |
| 111 | 17× | let user_entries = super::config::read_config_file(&self.user_config).unwrap_or_default(); |
| 112 | 17× | let user_names = names(user_entries.get("author.key")); |
| 113 | 17× | if !repo_pins && !user_names { |
| 114 | 0× | return self.set_author(id, new_key, self.author_scope()); |
| 115 | 17× | } |
| 116 | 17× | if user_names { |
| 117 | 6× | self.set_author(id, new_key, IdentityScope::User)?; |
| 118 | 11× | } |
| 119 | 17× | if repo_pins { |
| 120 | 12× | self.set_author(id, new_key, IdentityScope::Repo)?; |
| 121 | 5× | } |
| 122 | 17× | Ok(()) |
| 123 | 17× | } |
| 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. | |
| 128 | 17× | fn replace_identity( |
| 129 | 17× | &mut self, |
| 130 | 17× | new: Identity, |
| 131 | 17× | sk: SecretKey, |
| 132 | 17× | command: &str, |
| 133 | 17× | ) -> Result<Rotation> { |
| 134 | 17× | let Some((old, old_sk)) = self.secret_key()? else { |
| 135 | 0× | return fail("no secret key: run `oxy identity create` first"); |
| 136 | }; | |
| 137 | 17× | if new.previous != Some(old) { |
| 138 | 0× | return fail("the successor identity must name the current key as previous"); |
| 139 | 17× | } |
| 140 | 17× | let new_key = self.install_key(&new, &sk)?; |
| 141 | 17× | let attest = Attest { |
| 142 | 17× | repo: self.id()?, |
| 143 | 17× | hlc: Hlc::now(), |
| 144 | 17× | body: AttestBody::Rotate { new: new_key }, |
| 145 | }; | |
| 146 | 17× | let r = self.store.put_attest(&attest)?; |
| 147 | 17× | self.store |
| 148 | 17× | .put_signature(&r, &old_sk.sign(Domain::Attest, &old, &r))?; |
| 149 | 17× | let policy = match self.current_policy()? { |
| 150 | 9× | Some((_, sp)) if sp.policy.mentions(&old) => { |
| 151 | 9× | let mut p = self.next_policy()?; |
| 152 | 9× | p.substitute_key(&old, new.clone()); |
| 153 | 9× | Some(self.sign_policy_with(p, &[(old, &old_sk), (new_key, &sk)], command)?) |
| 154 | } | |
| 155 | 8× | _ => None, |
| 156 | }; | |
| 157 | 17× | self.record_successor(&new, &old, &new_key)?; |
| 158 | 17× | Ok(Rotation { |
| 159 | 17× | old, |
| 160 | 17× | new: new_key, |
| 161 | 17× | identity: new, |
| 162 | 17× | policy, |
| 163 | 17× | }) |
| 164 | 17× | } |
| 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. | |
| 168 | 3× | pub fn rotate_identity(&mut self) -> Result<Rotation> { |
| 169 | 3× | let Some((old, _)) = self.secret_key()? else { |
| 170 | 0× | return fail("no secret key: run `oxy identity create` first"); |
| 171 | }; | |
| 172 | 3× | let cur = self.identity(&old)?; |
| 173 | 3× | let sk = SecretKey::generate(); |
| 174 | 3× | let mut id = sk.identity(&cur.name, &cur.email, Hlc::now().wall_ms); |
| 175 | 3× | id.previous = Some(old); |
| 176 | 3× | id.delegates = cur.delegates.clone(); |
| 177 | 3× | id.expires = cur.expires; |
| 178 | 3× | self.replace_identity(id, sk, "oxy identity rotate") |
| 179 | 3× | } |
| 180 | | |
| 181 | /// Re-issue the identity with the same keys and a new expiry. | |
| 182 | 1× | pub fn renew_identity(&mut self, expires: Option<u64>) -> Result<Rotation> { |
| 183 | 1× | let Some((old, sk)) = self.secret_key()? else { |
| 184 | 0× | return fail("no secret key: run `oxy identity create` first"); |
| 185 | }; | |
| 186 | 1× | let cur = self.identity(&old)?; |
| 187 | 1× | let id = cur.successor(cur.delegates.clone(), expires, Hlc::now().wall_ms); |
| 188 | 1× | self.replace_identity(id, sk, "oxy identity renew") |
| 189 | 1× | } |
| 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. | |
| 194 | 12× | pub fn delegate_add( |
| 195 | 12× | &mut self, |
| 196 | 12× | delegate: Identity, |
| 197 | 12× | scope: Scope, |
| 198 | 12× | expires: Option<u64>, |
| 199 | 12× | ) -> Result<Rotation> { |
| 200 | 12× | self.delegate_add_many(vec![delegate], scope, expires) |
| 201 | 12× | } |
| 202 | | |
| 203 | /// As [`Repo::delegate_add`], for several delegates in one rotation. | |
| 204 | 13× | pub fn delegate_add_many( |
| 205 | 13× | &mut self, |
| 206 | 13× | new_delegates: Vec<Identity>, |
| 207 | 13× | scope: Scope, |
| 208 | 13× | expires: Option<u64>, |
| 209 | 13× | ) -> Result<Rotation> { |
| 210 | 13× | let Some((old, sk)) = self.secret_key()? else { |
| 211 | 0× | return fail("no secret key: run `oxy identity create` first"); |
| 212 | }; | |
| 213 | 13× | if scope.is_empty() { |
| 214 | 0× | return fail("a delegate needs at least one scope: changes, refs or seal"); |
| 215 | 13× | } |
| 216 | 13× | if new_delegates.is_empty() { |
| 217 | 0× | return fail("name at least one identity file"); |
| 218 | 13× | } |
| 219 | 13× | let cur = self.identity(&old)?; |
| 220 | 13× | let mut delegates = cur.delegates.clone(); |
| 221 | 13× | let mut added = Vec::new(); |
| 222 | 14× | for delegate in new_delegates { |
| 223 | 14× | let dk = self.store.put_identity(&delegate)?; |
| 224 | 14× | added.push(dk); |
| 225 | 14× | if dk == old { |
| 226 | 0× | return fail("an identity cannot delegate to itself"); |
| 227 | 14× | } |
| 228 | 14× | if cur.delegate(&dk).is_some() |
| 229 | 12× | || delegates |
| 230 | 12× | .iter() |
| 231 | 12× | .skip(cur.delegates.len()) |
| 232 | 12× | .any(|d| d.key == dk) |
| 233 | { | |
| 234 | 2× | return fail(format!( |
| 235 | "{} is already a delegate; remove it first to change its scope or expiry", | |
| 236 | 2× | dk.short(12) |
| 237 | )); | |
| 238 | 12× | } |
| 239 | 12× | delegates.push(Delegate { |
| 240 | 12× | key: dk, |
| 241 | 12× | scope, |
| 242 | 12× | expires, |
| 243 | 12× | }); |
| 244 | } | |
| 245 | 11× | let id = cur.successor(delegates, cur.expires, Hlc::now().wall_ms); |
| 246 | 11× | self.replace_identity( |
| 247 | 11× | id, |
| 248 | 11× | sk, |
| 249 | 11× | &format!( |
| 250 | "oxy identity delegate add {} --scope {scope}", | |
| 251 | 11× | added |
| 252 | 11× | .iter() |
| 253 | 12× | .map(|k| k.short(12)) |
| 254 | 11× | .collect::<Vec<_>>() |
| 255 | 11× | .join(" ") |
| 256 | ), | |
| 257 | ) | |
| 258 | 13× | } |
| 259 | | |
| 260 | /// Withdraw a delegation; re-issues the identity with the same keys. | |
| 261 | 3× | pub fn delegate_remove(&mut self, delegate: &KeyId) -> Result<Rotation> { |
| 262 | 3× | let Some((old, sk)) = self.secret_key()? else { |
| 263 | 0× | return fail("no secret key: run `oxy identity create` first"); |
| 264 | }; | |
| 265 | 3× | let cur = self.identity(&old)?; |
| 266 | 3× | if cur.delegate(delegate).is_none() { |
| 267 | 1× | return fail(format!("{} is not a delegate", delegate.short(12))); |
| 268 | 2× | } |
| 269 | 2× | let delegates = cur |
| 270 | 2× | .delegates |
| 271 | 2× | .iter() |
| 272 | 2× | .copied() |
| 273 | 2× | .filter(|d| d.key != *delegate) |
| 274 | 2× | .collect(); |
| 275 | 2× | let id = cur.successor(delegates, cur.expires, Hlc::now().wall_ms); |
| 276 | 2× | self.replace_identity( |
| 277 | 2× | id, |
| 278 | 2× | sk, |
| 279 | 2× | &format!("oxy identity delegate remove {}", delegate.short(12)), |
| 280 | ) | |
| 281 | 3× | } |
| 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. | |
| 288 | 5× | pub fn revoke_identity(&self, key: &KeyId, reason: &str) -> Result<Option<PolicyUpdate>> { |
| 289 | 5× | let Some((own, sk)) = self.secret_key()? else { |
| 290 | 0× | return fail("no secret key: run `oxy identity create` first"); |
| 291 | }; | |
| 292 | 5× | let policy = self.current_policy()?.map(|(_, sp)| sp.policy); |
| 293 | 5× | let is_root = policy.as_ref().is_some_and(|p| p.roots.contains(&own)); |
| 294 | 5× | let is_delegate = self.identity(&own)?.delegate(key).is_some(); |
| 295 | 5× | if *key != own && !is_root && !is_delegate { |
| 296 | 1× | return fail("only the key's holder, the identity that delegated to it, or a policy root can revoke it"); |
| 297 | 4× | } |
| 298 | 4× | let attest = Attest { |
| 299 | 4× | repo: self.id()?, |
| 300 | 4× | hlc: Hlc::now(), |
| 301 | 4× | body: AttestBody::Revoke { |
| 302 | 4× | key: *key, |
| 303 | 4× | reason: reason.into(), |
| 304 | 4× | }, |
| 305 | }; | |
| 306 | 4× | let r = self.store.put_attest(&attest)?; |
| 307 | 4× | self.store |
| 308 | 4× | .put_signature(&r, &sk.sign(Domain::Attest, &own, &r))?; |
| 309 | 4× | let dir = self.oxy.join("revoked"); |
| 310 | 4× | fs::create_dir_all(&dir)?; |
| 311 | 4× | write_atomic(&dir.join(key.to_hex()), r.to_hex().as_bytes())?; |
| 312 | 1× | match policy { |
| 313 | 1× | Some(p) if p.mentions(key) => Ok(Some(self.policy_revoke(key)?)), |
| 314 | 3× | _ => Ok(None), |
| 315 | } | |
| 316 | 5× | } |
| 317 | | |
| 318 | /// Whether `key` is revoked by the policy or by a recorded revocation. | |
| 319 | 259× | pub fn is_revoked(&self, key: &KeyId) -> Result<bool> { |
| 320 | 259× | if self.oxy.join("revoked").join(key.to_hex()).exists() { |
| 321 | 5× | return Ok(true); |
| 322 | 254× | } |
| 323 | 254× | Ok(self |
| 324 | 254× | .current_policy()? |
| 325 | 254× | .is_some_and(|(_, sp)| sp.policy.is_revoked(key))) |
| 326 | 259× | } |
| 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`. | |
| 330 | 887× | pub fn signing_key(&self) -> Option<KeyId> { |
| 331 | 887× | if self.config.signer_keyless { |
| 332 | // The key certified last, once this command has signed. | |
| 333 | 1× | return self.keyless_key.borrow().as_ref().map(|(k, _, _)| *k); |
| 334 | 886× | } |
| 335 | 886× | self.config.signer_key.or(self.config.author_key) |
| 336 | 887× | } |
| 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. | |
| 342 | 694× | pub fn secret_key(&self) -> Result<Option<(KeyId, SecretKey)>> { |
| 343 | 694× | if self.config.signer_keyless { |
| 344 | 1× | return self.keyless_secret().map(Some); |
| 345 | 693× | } |
| 346 | 693× | let Some(key) = self.signing_key() else { |
| 347 | 208× | return Ok(None); |
| 348 | }; | |
| 349 | 485× | let path = self.keys_dir.join(format!("{}.secret", key.to_hex())); |
| 350 | 485× | match fs::read(&path) { |
| 351 | 484× | Ok(b) => { |
| 352 | 484× | let (k, sk) = SecretKey::decode(&b)?; |
| 353 | 484× | if k != key { |
| 354 | 0× | return fail(format!( |
| 355 | "{} holds a different key than its name", | |
| 356 | 0× | path.display() |
| 357 | )); | |
| 358 | 484× | } |
| 359 | 484× | if !self.store.has(&key) { |
| 360 | 1× | let id_path = self.keys_dir.join(format!("{}.identity", key.to_hex())); |
| 361 | 1× | if let Ok(bytes) = fs::read(&id_path) { |
| 362 | 1× | let id = Identity::decode(&bytes)?; |
| 363 | 1× | if id.hash() == key { |
| 364 | 1× | self.store.put_identity(&id)?; |
| 365 | 0× | } |
| 366 | 0× | } |
| 367 | 483× | } |
| 368 | 484× | Ok(Some((k, sk))) |
| 369 | } | |
| 370 | 1× | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), |
| 371 | 0× | Err(e) => Err(e.into()), |
| 372 | } | |
| 373 | 694× | } |
| 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`. | |
| 378 | 266× | pub fn identity(&self, key: &KeyId) -> Result<Identity> { |
| 379 | 266× | match self.store.get_identity(key) { |
| 380 | 262× | Ok(id) => Ok(id), |
| 381 | 4× | Err(e) => { |
| 382 | 4× | let path = self.keys_dir.join(format!("{}.identity", key.to_hex())); |
| 383 | 4× | match fs::read(&path) { |
| 384 | 2× | Ok(bytes) => { |
| 385 | 2× | let id = Identity::decode(&bytes)?; |
| 386 | 2× | if id.hash() != *key { |
| 387 | 1× | return fail(format!( |
| 388 | "{} does not hold identity {}", | |
| 389 | 1× | path.display(), |
| 390 | 1× | key.short(12) |
| 391 | )); | |
| 392 | 1× | } |
| 393 | 1× | 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". | |
| 398 | 2× | 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.", | |
| 403 | 2× | key.short(12), |
| 404 | 2× | if self.config.is_repo_set("author.key") { |
| 405 | 1× | "this repository's config" |
| 406 | } else { | |
| 407 | 1× | "the user config" |
| 408 | }, | |
| 409 | 2× | self.keys_dir.display() |
| 410 | )), | |
| 411 | 0× | Err(_) => Err(e.into()), |
| 412 | } | |
| 413 | } | |
| 414 | } | |
| 415 | 266× | } |
| 416 | | |
| 417 | /// Sign a stored change with the configured secret key. | |
| 418 | 45× | pub fn sign_change(&self, hash: &ChangeHash) -> Result<Signature> { |
| 419 | 45× | let Some((key, sk)) = self.secret_key()? else { |
| 420 | 0× | return fail("no secret key: run `oxy identity create` first"); |
| 421 | }; | |
| 422 | 45× | let sig = sk.sign(Domain::Change, &key, hash); |
| 423 | 45× | self.store.put_signature(hash, &sig)?; |
| 424 | 45× | Ok(sig) |
| 425 | 45× | } |
| 426 | | |
| 427 | /// Check the signatures on a change against the author-or-delegate rule. | |
| 428 | 24× | pub fn verify_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> { |
| 429 | 24× | self.verify_change_known(hash, None) |
| 430 | 24× | } |
| 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. | |
| 435 | 431× | fn verify_change_known( |
| 436 | 431× | &self, |
| 437 | 431× | hash: &ChangeHash, |
| 438 | 431× | known: Option<&crate::state::ChangeMeta>, |
| 439 | 431× | ) -> Result<SignatureStatus> { |
| 440 | 431× | let sigs = self.store.signatures(hash)?; |
| 441 | 431× | if sigs.is_empty() { |
| 442 | 333× | return Ok(SignatureStatus::Unsigned); |
| 443 | 98× | } |
| 444 | let read; | |
| 445 | 98× | let change = match known { |
| 446 | 16× | Some(m) => m, |
| 447 | None => { | |
| 448 | 82× | read = self.store.get_change_meta(hash)?; |
| 449 | 82× | &read |
| 450 | } | |
| 451 | }; | |
| 452 | 98× | let mut last_err = String::new(); |
| 453 | 98× | for sig in &sigs { |
| 454 | 98× | match self.check_signer(change, sig, Domain::Change, hash) { |
| 455 | 92× | Ok(id) => { |
| 456 | return Ok(SignatureStatus::Valid { | |
| 457 | 92× | key: sig.key, |
| 458 | 92× | name: self.certified_subject(&sig.key).unwrap_or(id.name), |
| 459 | 92× | email: id.email, |
| 460 | sealed: false, | |
| 461 | 92× | revoked: self.is_revoked(&sig.key)?, |
| 462 | }) | |
| 463 | } | |
| 464 | 6× | Err(e) => last_err = e, |
| 465 | } | |
| 466 | } | |
| 467 | 6× | Ok(SignatureStatus::Invalid(last_err)) |
| 468 | 431× | } |
| 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. | |
| 477 | 12× | fn granted( |
| 478 | 12× | &self, |
| 479 | 12× | author: &KeyId, |
| 480 | 12× | signer: &KeyId, |
| 481 | 12× | needed: Scope, |
| 482 | 12× | at_ms: u64, |
| 483 | 12× | ) -> std::result::Result<Option<String>, String> { |
| 484 | 12× | let neither = || { |
| 485 | 6× | Some(format!( |
| 486 | 6× | "key {} is neither the author nor a delegate", |
| 487 | 6× | signer.short(12) |
| 488 | 6× | )) |
| 489 | 6× | }; |
| 490 | 12× | let Ok(Some(c)) = self.store.certificate_of(signer) else { |
| 491 | 4× | return Ok(neither()); |
| 492 | }; | |
| 493 | 8× | let Ok(sc) = self.store.get_certificate(&c) else { |
| 494 | 0× | return Ok(neither()); |
| 495 | }; | |
| 496 | 8× | let Some(g) = &sc.cert.grant else { |
| 497 | 1× | return Ok(neither()); |
| 498 | }; | |
| 499 | 7× | let who = signer.short(12); |
| 500 | 7× | let issuer = self |
| 501 | 7× | .store |
| 502 | 7× | .get_identity(&sc.cert.issuer) |
| 503 | 7× | .map_err(|_| format!("key {who}'s certificate names an unknown issuer"))?; |
| 504 | 7× | sc.verify(&issuer) |
| 505 | 7× | .map_err(|e| format!("key {who}'s certificate: {e}"))?; |
| 506 | 7× | if g.grant.grantor != *author { |
| 507 | 1× | return Ok(neither()); |
| 508 | 6× | } |
| 509 | 6× | let grantor = self |
| 510 | 6× | .store |
| 511 | 6× | .get_identity(author) |
| 512 | 6× | .map_err(|_| format!("key {who}'s grant is by an unknown author"))?; |
| 513 | 6× | g.verify(&grantor) |
| 514 | 6× | .map_err(|e| format!("key {who}'s grant: {e}"))?; |
| 515 | 6× | if g.grant.subject != sc.cert.subject || g.grant.issuer != sc.cert.issuer { |
| 516 | 0× | return Err(format!( |
| 517 | 0× | "key {who}'s grant is for {} from issuer {}, not its certificate's", |
| 518 | 0× | g.grant.subject, |
| 519 | 0× | g.grant.issuer.short(12) |
| 520 | 0× | )); |
| 521 | 6× | } |
| 522 | 6× | if !sc.cert.scope.has(needed) || !g.grant.scope.has(needed) { |
| 523 | 0× | return Err(format!("key {who} is not granted {needed}")); |
| 524 | 6× | } |
| 525 | 6× | if !g.grant.covers(needed, at_ms) { |
| 526 | 2× | return Err(format!( |
| 527 | 2× | "key {who}'s grant did not cover the time the change was made" |
| 528 | 2× | )); |
| 529 | 4× | } |
| 530 | 4× | Ok(None) |
| 531 | 12× | } |
| 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. | |
| 536 | 244× | pub fn certified_subject(&self, key: &KeyId) -> Option<String> { |
| 537 | 244× | let c = self.store.certificate_of(key).ok()??; |
| 538 | 8× | Some(self.store.get_certificate(&c).ok()?.cert.subject) |
| 539 | 244× | } |
| 540 | | |
| 541 | /// Verify `sig` over `target` and check the author-or-delegate rule for `change`. | |
| 542 | 256× | fn check_signer( |
| 543 | 256× | &self, |
| 544 | 256× | change: &crate::state::ChangeMeta, |
| 545 | 256× | sig: &Signature, |
| 546 | 256× | domain: Domain, |
| 547 | 256× | target: &ObjectRef, |
| 548 | 256× | ) -> std::result::Result<Identity, String> { |
| 549 | 256× | let id = self |
| 550 | 256× | .store |
| 551 | 256× | .get_identity(&sig.key) |
| 552 | 256× | .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). | |
| 559 | 256× | if !change.author.is_zero() && sig.key != change.author { |
| 560 | 32× | let needed = match domain { |
| 561 | 22× | Domain::Change => Scope::CHANGES, |
| 562 | 10× | _ => Scope::SEAL, |
| 563 | }; | |
| 564 | 32× | let delegation = self |
| 565 | 32× | .store |
| 566 | 32× | .get_identity(&change.author) |
| 567 | 32× | .ok() |
| 568 | 32× | .and_then(|a| a.delegate(&sig.key).copied()); |
| 569 | 19× | match delegation { |
| 570 | // A certified key acting under the author's grant (§14.7). | |
| 571 | None => { | |
| 572 | 6× | if let Some(why) = |
| 573 | 12× | self.granted(&change.author, &sig.key, needed, change.hlc.wall_ms)? |
| 574 | { | |
| 575 | 6× | return Err(why); |
| 576 | 4× | } |
| 577 | } | |
| 578 | 20× | Some(d) if !d.scope.has(needed) => { |
| 579 | 1× | return Err(format!( |
| 580 | "key {} is a delegate for {} only and may not {}", | |
| 581 | 1× | sig.key.short(12), |
| 582 | d.scope, | |
| 583 | 1× | if needed == Scope::SEAL { |
| 584 | 1× | "seal" |
| 585 | } else { | |
| 586 | 0× | "sign changes" |
| 587 | } | |
| 588 | )) | |
| 589 | } | |
| 590 | 19× | Some(d) if !d.allows(needed, change.hlc.wall_ms) => { |
| 591 | 1× | return Err(format!( |
| 592 | 1× | "key {}'s delegation had expired when the change was made", |
| 593 | 1× | sig.key.short(12) |
| 594 | 1× | )) |
| 595 | } | |
| 596 | 18× | Some(_) => {} |
| 597 | } | |
| 598 | 224× | } |
| 599 | 246× | if id.is_expired_at(change.hlc.wall_ms) { |
| 600 | 1× | return Err(format!( |
| 601 | 1× | "key {} had expired when the change was made", |
| 602 | 1× | sig.key.short(12) |
| 603 | 1× | )); |
| 604 | 245× | } |
| 605 | 245× | verify_signature(&id, sig, domain, target).map_err(|e| e.to_string())?; |
| 606 | 244× | Ok(id) |
| 607 | 256× | } |
| 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). | |
| 611 | 331× | pub fn authenticate_change(&self, hash: &ChangeHash) -> Result<SignatureStatus> { |
| 612 | 331× | self.authenticate_change_known(hash, None) |
| 613 | 331× | } |
| 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. | |
| 617 | 407× | pub fn authenticate_change_known( |
| 618 | 407× | &self, |
| 619 | 407× | hash: &ChangeHash, |
| 620 | 407× | known: Option<&crate::state::ChangeMeta>, |
| 621 | 407× | ) -> Result<SignatureStatus> { |
| 622 | 407× | let direct = self.verify_change_known(hash, known)?; |
| 623 | 407× | if matches!(direct, SignatureStatus::Valid { .. }) { |
| 624 | 77× | return Ok(direct); |
| 625 | 330× | } |
| 626 | 330× | let mut last_err = match &direct { |
| 627 | 2× | SignatureStatus::Invalid(e) => e.clone(), |
| 628 | 328× | _ => String::new(), |
| 629 | }; | |
| 630 | 330× | let seals = self.store.seals_for(hash)?; |
| 631 | 330× | if seals.is_empty() { |
| 632 | 172× | return Ok(match last_err.is_empty() { |
| 633 | 170× | true => SignatureStatus::Unsigned, |
| 634 | 2× | false => SignatureStatus::Invalid(last_err), |
| 635 | }); | |
| 636 | 158× | } |
| 637 | let read; | |
| 638 | 158× | let change = match known { |
| 639 | 0× | Some(m) => m, |
| 640 | None => { | |
| 641 | 158× | read = self.store.get_change_meta(hash)?; |
| 642 | 158× | &read |
| 643 | } | |
| 644 | }; | |
| 645 | 158× | for seal_ref in seals { |
| 646 | 158× | let attest = self.store.get_attest(&seal_ref)?; |
| 647 | 158× | let AttestBody::Seal { hashes } = &attest.body else { |
| 648 | 0× | continue; |
| 649 | }; | |
| 650 | 158× | if !hashes.contains(hash) { |
| 651 | 0× | continue; |
| 652 | 158× | } |
| 653 | 158× | for sig in self.store.signatures(&seal_ref)? { |
| 654 | 158× | match self.check_signer(change, &sig, Domain::Attest, &seal_ref) { |
| 655 | 152× | Ok(id) => { |
| 656 | return Ok(SignatureStatus::Valid { | |
| 657 | 152× | key: sig.key, |
| 658 | 152× | name: self.certified_subject(&sig.key).unwrap_or(id.name), |
| 659 | 152× | email: id.email, |
| 660 | sealed: true, | |
| 661 | 152× | revoked: self.is_revoked(&sig.key)?, |
| 662 | }) | |
| 663 | } | |
| 664 | 6× | Err(e) => last_err = e, |
| 665 | } | |
| 666 | } | |
| 667 | } | |
| 668 | 6× | if last_err.is_empty() { |
| 669 | 0× | Ok(SignatureStatus::Unsigned) |
| 670 | } else { | |
| 671 | 6× | Ok(SignatureStatus::Invalid(last_err)) |
| 672 | } | |
| 673 | 407× | } |
| 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. | |
| 679 | 1× | pub fn seal(&self, hashes: &[ChangeHash]) -> Result<ObjectRef> { |
| 680 | 1× | if hashes.is_empty() { |
| 681 | 0× | return fail("nothing to seal"); |
| 682 | 1× | } |
| 683 | 1× | if hashes.len() > crate::attest::MAX_SEAL_HASHES { |
| 684 | 0× | return fail(format!( |
| 685 | "a seal covers at most {} changes", | |
| 686 | crate::attest::MAX_SEAL_HASHES | |
| 687 | )); | |
| 688 | 1× | } |
| 689 | 1× | for h in hashes { |
| 690 | 1× | if !self.store.has(h) { |
| 691 | 0× | return fail(format!("unknown change {}", h.short(12))); |
| 692 | 1× | } |
| 693 | } | |
| 694 | 1× | let mut sorted = hashes.to_vec(); |
| 695 | 1× | sorted.sort(); |
| 696 | 1× | sorted.dedup(); |
| 697 | 1× | let sa = self.sign_attest(&Attest::seal(self.id()?, sorted.clone()))?; |
| 698 | 1× | let r = self.store.put_attest(&sa.attest)?; |
| 699 | 1× | for sig in &sa.sigs { |
| 700 | 1× | self.store.put_signature(&r, sig)?; |
| 701 | } | |
| 702 | 1× | for h in &sorted { |
| 703 | 1× | self.store.index_seal(h, &r)?; |
| 704 | } | |
| 705 | 1× | Ok(r) |
| 706 | 1× | } |
| 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. | |
| 712 | 87× | pub(crate) fn seals_for_author(&self, author: &KeyId, signer: &KeyId) -> bool { |
| 713 | 87× | author == signer |
| 714 | 11× | || author.is_zero() |
| 715 | 10× | || ((self.config.signer_key.is_some() || self.config.signer_keyless) |
| 716 | 7× | && self.config.author_key == Some(*author)) |
| 717 | 87× | } |
| 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. | |
| 722 | 0× | pub fn sealable(&self) -> Result<Vec<ChangeHash>> { |
| 723 | 0× | let Some((key, _)) = self.secret_key()? else { |
| 724 | 0× | return fail("no identity: run oxy identity create"); |
| 725 | }; | |
| 726 | 0× | let heads = self.bookmark_heads()?; |
| 727 | 0× | let state = self.load_state_history(&heads)?; |
| 728 | 0× | let mut out = Vec::new(); |
| 729 | 0× | for (h, meta) in state.changes() { |
| 730 | 0× | if self.seals_for_author(&meta.author, &key) |
| 731 | 0× | && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) |
| 732 | 0× | { |
| 733 | 0× | out.push(*h); |
| 734 | 0× | } |
| 735 | } | |
| 736 | 0× | out.sort(); |
| 737 | 0× | Ok(out) |
| 738 | 0× | } |
| 739 | | |
| 740 | 153× | pub(crate) fn sign_attest(&self, attest: &Attest) -> Result<SignedAttest> { |
| 741 | 153× | let Some((key, sk)) = self.secret_key()? else { |
| 742 | 0× | return fail("no secret key: run `oxy identity create` first"); |
| 743 | }; | |
| 744 | 153× | let r = self.store.put_attest(attest)?; |
| 745 | 151× | let sig = sk.sign(Domain::Attest, &key, &r); |
| 746 | 151× | self.store.put_signature(&r, &sig)?; |
| 747 | 151× | if let AttestBody::Seal { hashes } = &attest.body { |
| 748 | 48× | for h in hashes { |
| 749 | 48× | self.store.index_seal(h, &r)?; |
| 750 | } | |
| 751 | 106× | } |
| 752 | 151× | Ok(SignedAttest { |
| 753 | 151× | attest: attest.clone(), |
| 754 | 151× | sigs: vec![sig], |
| 755 | 151× | }) |
| 756 | 153× | } |
| 757 | } |