| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | | use anyhow::{bail, Context, Result}; |
| 11 | | use oxy_core::durable::{write_atomic, write_atomic_private}; |
| 12 | | use oxy_core::hash::KeyId; |
| 13 | | use oxy_core::identity::{Identity, SecretKey, Signature}; |
| 14 | | use std::fs; |
| 15 | | use std::path::{Path, PathBuf}; |
| 16 | |
|
| 17 | |
|
| 18 | | #[derive(Clone, Debug)] |
| 19 | | pub struct KeyPair { |
| 20 | | pub key: KeyId, |
| 21 | | pub identity: Identity, |
| 22 | | secret: SecretKey, |
| 23 | | } |
| 24 | |
|
| 25 | | impl KeyPair { |
| 26 | | |
| 27 | 100× | pub fn generate(name: &str, email: &str) -> KeyPair { |
| 28 | 100× | let secret = SecretKey::generate(); |
| 29 | 100× | let identity = secret.identity(name, email, crate::ids::now_ms()); |
| 30 | 100× | KeyPair { key: identity.hash(), identity, secret } |
| 31 | 100× | } |
| 32 | |
|
| 33 | | |
| 34 | | |
| 35 | | |
| 36 | | |
| 37 | 309× | pub fn sign(&self, message: &[u8]) -> Signature { |
| 38 | 309× | self.secret.sign_challenge(&self.key, message).expect("Spectra messages are longer than 16 bytes") |
| 39 | 309× | } |
| 40 | |
|
| 41 | | |
| 42 | | |
| 43 | 39× | pub fn create_home(home: &Path, name: &str, email: &str) -> Result<KeyPair> { |
| 44 | 39× | let pair = KeyPair::generate(name, email); |
| 45 | 39× | let keys = home.join("keys"); |
| 46 | 39× | fs::create_dir_all(&keys).with_context(|| format!("creating {}", keys.display()))?; |
| 47 | | #[cfg(unix)] |
| 48 | | { |
| 49 | | use std::os::unix::fs::PermissionsExt; |
| 50 | 39× | fs::set_permissions(home, fs::Permissions::from_mode(0o700))?; |
| 51 | | } |
| 52 | 39× | write_atomic_private(&keys.join(format!("{}.secret", pair.key.to_hex())), &pair.secret.encode(&pair.key))?; |
| 53 | 39× | write_atomic(&keys.join(format!("{}.identity", pair.key.to_hex())), &pair.identity.encode())?; |
| 54 | 39× | let config = home.join("config.toml"); |
| 55 | 39× | oxy_core::repo::Config::set_user(&config, "author.name", name)?; |
| 56 | 39× | oxy_core::repo::Config::set_user(&config, "author.email", email)?; |
| 57 | 39× | oxy_core::repo::Config::set_user(&config, "author.key", &pair.key.to_hex())?; |
| 58 | 39× | Ok(pair) |
| 59 | 39× | } |
| 60 | |
|
| 61 | | |
| 62 | | |
| 63 | 129× | pub fn load_home(home: &Path) -> Result<KeyPair> { |
| 64 | 129× | let keys = home.join("keys"); |
| 65 | 129× | let key = match author_key(home)? { |
| 66 | 128× | Some(k) => k, |
| 67 | | None => { |
| 68 | 1× | let secrets: Vec<PathBuf> = fs::read_dir(&keys) |
| 69 | 1× | .with_context(|| format!("reading {}", keys.display()))? |
| 70 | 0× | .filter_map(|e| e.ok().map(|e| e.path())) |
| 71 | 0× | .filter(|p| p.extension().is_some_and(|x| x == "secret")) |
| 72 | 0× | .collect(); |
| 73 | 0× | match secrets.as_slice() { |
| 74 | 0× | [one] => KeyId::from_hex(one.file_stem().and_then(|s| s.to_str()).unwrap_or("")) |
| 75 | 0× | .context("a secret key file is not named by its key")?, |
| 76 | 0× | [] => bail!("{} holds no secret key: an agent home is made by `spectra agent add`", home.display()), |
| 77 | 0× | _ => bail!("{} holds several keys and its config.toml names none (author.key)", home.display()), |
| 78 | | } |
| 79 | | } |
| 80 | | }; |
| 81 | 128× | KeyPair::load(&keys.join(format!("{}.secret", key.to_hex())), &keys.join(format!("{}.identity", key.to_hex()))) |
| 82 | 129× | } |
| 83 | |
|
| 84 | | |
| 85 | 178× | pub fn load(secret: &Path, identity: &Path) -> Result<KeyPair> { |
| 86 | 178× | let (key, secret_key) = SecretKey::decode(&fs::read(secret).with_context(|| format!("reading {}", secret.display()))?) |
| 87 | 178× | .map_err(|e| anyhow::anyhow!("{}: {e}", secret.display()))?; |
| 88 | 178× | let identity = Identity::decode(&fs::read(identity).with_context(|| format!("reading {}", identity.display()))?) |
| 89 | 178× | .map_err(|e| anyhow::anyhow!("{}: {e}", identity.display()))?; |
| 90 | 178× | if identity.hash() != key { |
| 91 | 0× | bail!("{} is not the identity of {}", identity.name, secret.display()); |
| 92 | 178× | } |
| 93 | 178× | if secret_key.identity(&identity.name, &identity.email, identity.created).ed25519_pk != identity.ed25519_pk { |
| 94 | 0× | bail!("the secret key in {} does not match its identity", secret.display()); |
| 95 | 178× | } |
| 96 | 178× | Ok(KeyPair { key, identity, secret: secret_key }) |
| 97 | 178× | } |
| 98 | |
|
| 99 | | |
| 100 | 85× | pub fn instance(data: &Path, name: &str) -> Result<KeyPair> { |
| 101 | 85× | let keys = data.join("keys"); |
| 102 | 85× | let (secret, identity) = (keys.join("instance.secret"), keys.join("instance.identity")); |
| 103 | 85× | if secret.exists() { |
| 104 | 48× | return KeyPair::load(&secret, &identity); |
| 105 | 37× | } |
| 106 | 37× | fs::create_dir_all(&keys)?; |
| 107 | 37× | let pair = KeyPair::generate(name, ""); |
| 108 | 37× | write_atomic_private(&secret, &pair.secret.encode(&pair.key))?; |
| 109 | 37× | write_atomic(&identity, &pair.identity.encode())?; |
| 110 | 37× | Ok(pair) |
| 111 | 85× | } |
| 112 | | } |
| 113 | |
|
| 114 | |
|
| 115 | |
|
| 116 | 16× | pub fn home_identity(home: &Path) -> Result<Identity> { |
| 117 | 16× | let key = author_key(home)?.with_context(|| format!("{} names no identity (author.key in config.toml)", home.display()))?; |
| 118 | 16× | let path = home.join("keys").join(format!("{}.identity", key.to_hex())); |
| 119 | 16× | Identity::decode(&fs::read(&path).with_context(|| format!("reading {}", path.display()))?) |
| 120 | 16× | .map_err(|e| anyhow::anyhow!("{}: {e}", path.display())) |
| 121 | 16× | } |
| 122 | |
|
| 123 | 145× | fn author_key(home: &Path) -> Result<Option<KeyId>> { |
| 124 | 145× | let config = home.join("config.toml"); |
| 125 | 145× | let Ok(text) = fs::read_to_string(&config) else { return Ok(None) }; |
| 126 | 144× | let table: toml::Table = text.parse().with_context(|| format!("reading {}", config.display()))?; |
| 127 | 144× | let found = table.get("author").and_then(|a| a.get("key")).or_else(|| table.get("author.key")).and_then(|v| v.as_str()); |
| 128 | 144× | Ok(match found { |
| 129 | 144× | Some(hex) => Some(KeyId::from_hex(hex).with_context(|| format!("{}: author.key is not a key", config.display()))?), |
| 130 | 0× | None => None, |
| 131 | | }) |
| 132 | 145× | } |
| 133 | |
|
| 134 | | #[cfg(test)] |
| 135 | | mod tests { |
| 136 | | use super::*; |
| 137 | |
|
| 138 | | #[test] |
| 139 | 1× | fn a_home_made_here_reads_back_and_signs_verifiably() { |
| 140 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 141 | 1× | let made = KeyPair::create_home(dir.path(), "claude-oxygen", "").unwrap(); |
| 142 | 1× | let read = KeyPair::load_home(dir.path()).unwrap(); |
| 143 | 1× | assert_eq!(made.key, read.key); |
| 144 | 1× | assert_eq!(home_identity(dir.path()).unwrap().hash(), made.key); |
| 145 | 1× | let msg = b"spectra1 test message of some length"; |
| 146 | 1× | let sig = read.sign(msg); |
| 147 | 1× | oxy_core::identity::verify_challenge(&made.identity, &sig, msg).unwrap(); |
| 148 | 1× | assert!(oxy_core::identity::verify_challenge(&made.identity, &sig, b"spectra1 another message entirely").is_err()); |
| 149 | 1× | } |
| 150 | |
|
| 151 | | #[test] |
| 152 | 1× | fn the_instance_key_is_made_once() { |
| 153 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 154 | 1× | let a = KeyPair::instance(dir.path(), "laptop").unwrap(); |
| 155 | 1× | let b = KeyPair::instance(dir.path(), "laptop").unwrap(); |
| 156 | 1× | assert_eq!(a.key, b.key); |
| 157 | 1× | } |
| 158 | | } |