| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | | use crate::durable::{write_atomic, write_atomic_private}; |
| 10 | | use crate::identity::{Delegate, Identity, KeyId, SecretKey, Signature}; |
| 11 | | use anyhow::{bail, Context, Result}; |
| 12 | | use std::fs; |
| 13 | | use std::path::{Path, PathBuf}; |
| 14 | |
|
| 15 | |
|
| 16 | 196× | pub fn default_home() -> PathBuf { |
| 17 | 196× | if let Some(h) = std::env::var_os("SPECTRA_HOME").filter(|h| !h.is_empty()) { |
| 18 | 196× | return PathBuf::from(h); |
| 19 | 0× | } |
| 20 | 0× | std::env::var_os("XDG_CONFIG_HOME") |
| 21 | 0× | .filter(|p| !p.is_empty()) |
| 22 | 0× | .map(PathBuf::from) |
| 23 | 0× | .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))) |
| 24 | 0× | .unwrap_or_else(|| PathBuf::from(".")) |
| 25 | 0× | .join("spectra") |
| 26 | 196× | } |
| 27 | |
|
| 28 | |
|
| 29 | | #[derive(Clone, Debug)] |
| 30 | | pub struct KeyPair { |
| 31 | | pub key: KeyId, |
| 32 | | pub identity: Identity, |
| 33 | | secret: SecretKey, |
| 34 | | } |
| 35 | |
|
| 36 | | impl KeyPair { |
| 37 | | |
| 38 | 134× | pub fn generate(name: &str, contact: &str) -> KeyPair { |
| 39 | 134× | let secret = SecretKey::generate(); |
| 40 | 134× | let identity = secret.identity(name, contact, crate::ids::now_ms()); |
| 41 | 134× | KeyPair { key: identity.hash(), identity, secret } |
| 42 | 134× | } |
| 43 | |
|
| 44 | | |
| 45 | 474× | pub fn sign(&self, message: &[u8]) -> Signature { |
| 46 | 474× | self.secret.sign(&self.key, message) |
| 47 | 474× | } |
| 48 | |
|
| 49 | | |
| 50 | 60× | pub fn create_home(home: &Path, name: &str, contact: &str) -> Result<KeyPair> { |
| 51 | 60× | if current_key(home)?.is_some() { |
| 52 | 2× | bail!("{} already holds an identity", home.display()); |
| 53 | 58× | } |
| 54 | 58× | let pair = KeyPair::generate(name, contact); |
| 55 | 58× | fs::create_dir_all(home).with_context(|| format!("creating {}", home.display()))?; |
| 56 | | #[cfg(unix)] |
| 57 | | { |
| 58 | | use std::os::unix::fs::PermissionsExt; |
| 59 | 58× | fs::set_permissions(home, fs::Permissions::from_mode(0o700))?; |
| 60 | | } |
| 61 | 58× | pair.write(home)?; |
| 62 | 58× | Ok(pair) |
| 63 | 60× | } |
| 64 | |
|
| 65 | | |
| 66 | 123× | fn write(&self, home: &Path) -> Result<()> { |
| 67 | 123× | let keys = home.join("keys"); |
| 68 | 123× | write_atomic_private(&keys.join(format!("{}.secret", self.key.to_hex())), &self.secret.encode(&self.key))?; |
| 69 | 123× | write_atomic(&keys.join(format!("{}.identity", self.key.to_hex())), &self.identity.encode())?; |
| 70 | 123× | write_atomic( |
| 71 | 123× | &home.join("identity.toml"), |
| 72 | 123× | format!( |
| 73 | 123× | "# The identity this home signs with (spec §8.0).\ncurrent = \"{}\"\nname = {}\n", |
| 74 | 123× | self.key.to_hex(), |
| 75 | 123× | toml_str(&self.identity.name) |
| 76 | 123× | ) |
| 77 | 123× | .as_bytes(), |
| 78 | 0× | )?; |
| 79 | 123× | Ok(()) |
| 80 | 123× | } |
| 81 | |
|
| 82 | | |
| 83 | | |
| 84 | 240× | pub fn load_home(home: &Path) -> Result<KeyPair> { |
| 85 | 240× | let keys = home.join("keys"); |
| 86 | 240× | let key = match current_key(home)? { |
| 87 | 239× | Some(k) => k, |
| 88 | | None => { |
| 89 | 1× | let secrets: Vec<PathBuf> = fs::read_dir(&keys) |
| 90 | 1× | .with_context(|| format!("{} holds no identity (spectra identity create)", home.display()))? |
| 91 | 0× | .filter_map(|e| e.ok().map(|e| e.path())) |
| 92 | 0× | .filter(|p| p.extension().is_some_and(|x| x == "secret")) |
| 93 | 0× | .collect(); |
| 94 | 0× | match secrets.as_slice() { |
| 95 | 0× | [one] => KeyId::from_hex(one.file_stem().and_then(|s| s.to_str()).unwrap_or("")) |
| 96 | 0× | .context("a secret key file is not named by its key")?, |
| 97 | 0× | [] => bail!("{} holds no identity (spectra identity create)", home.display()), |
| 98 | 0× | _ => bail!("{} holds several keys and its identity.toml names none", home.display()), |
| 99 | | } |
| 100 | | } |
| 101 | | }; |
| 102 | 239× | KeyPair::load_key(home, &key) |
| 103 | 240× | } |
| 104 | |
|
| 105 | | |
| 106 | 240× | pub fn load_key(home: &Path, key: &KeyId) -> Result<KeyPair> { |
| 107 | 240× | let keys = home.join("keys"); |
| 108 | 240× | KeyPair::load(&keys.join(format!("{}.secret", key.to_hex())), &keys.join(format!("{}.identity", key.to_hex()))) |
| 109 | 240× | } |
| 110 | |
|
| 111 | | |
| 112 | 359× | pub fn load(secret: &Path, identity: &Path) -> Result<KeyPair> { |
| 113 | 359× | let (key, secret_key) = SecretKey::decode(&fs::read(secret).with_context(|| format!("reading {}", secret.display()))?) |
| 114 | 358× | .map_err(|e| anyhow::anyhow!("{}: {e}", secret.display()))?; |
| 115 | 358× | let identity = Identity::decode(&fs::read(identity).with_context(|| format!("reading {}", identity.display()))?) |
| 116 | 358× | .map_err(|e| anyhow::anyhow!("{}: {e}", identity.display()))?; |
| 117 | 358× | if identity.hash() != key { |
| 118 | 0× | bail!("{} is not the identity of {}", identity.name, secret.display()); |
| 119 | 358× | } |
| 120 | 358× | if !secret_key.matches(&identity) { |
| 121 | 0× | bail!("the secret key in {} does not match its identity", secret.display()); |
| 122 | 358× | } |
| 123 | 358× | Ok(KeyPair { key, identity, secret: secret_key }) |
| 124 | 359× | } |
| 125 | |
|
| 126 | | |
| 127 | 138× | pub fn instance(data: &Path, name: &str) -> Result<KeyPair> { |
| 128 | 138× | let keys = data.join("keys"); |
| 129 | 138× | let (secret, identity) = (keys.join("instance.secret"), keys.join("instance.identity")); |
| 130 | 138× | if secret.exists() { |
| 131 | 89× | return KeyPair::load(&secret, &identity); |
| 132 | 49× | } |
| 133 | 49× | fs::create_dir_all(&keys)?; |
| 134 | 49× | let pair = KeyPair::generate(name, ""); |
| 135 | 49× | write_atomic_private(&secret, &pair.secret.encode(&pair.key))?; |
| 136 | 49× | write_atomic(&identity, &pair.identity.encode())?; |
| 137 | 49× | Ok(pair) |
| 138 | 138× | } |
| 139 | |
|
| 140 | | |
| 141 | | |
| 142 | 65× | pub fn succeed(&self, home: &Path, delegates: Vec<Delegate>) -> Result<KeyPair> { |
| 143 | 65× | let identity = self.identity.successor(delegates, self.identity.expires, crate::ids::now_ms()); |
| 144 | 65× | let next = KeyPair { key: identity.hash(), identity, secret: self.secret.clone() }; |
| 145 | 65× | next.write(home)?; |
| 146 | 65× | Ok(next) |
| 147 | 65× | } |
| 148 | | } |
| 149 | |
|
| 150 | |
|
| 151 | |
|
| 152 | 62× | pub fn delegate(home: &Path, key: KeyId, expires: Option<u64>) -> Result<KeyPair> { |
| 153 | 62× | let cur = KeyPair::load_home(home)?; |
| 154 | 62× | let mut d: Vec<Delegate> = cur.identity.delegates.iter().filter(|x| x.key != key).cloned().collect(); |
| 155 | 62× | d.push(Delegate { key, expires }); |
| 156 | 62× | cur.succeed(home, d) |
| 157 | 62× | } |
| 158 | |
|
| 159 | |
|
| 160 | 3× | pub fn undelegate(home: &Path, key: KeyId) -> Result<KeyPair> { |
| 161 | 3× | let cur = KeyPair::load_home(home)?; |
| 162 | 6× | let d = cur.identity.delegates.iter().filter(|x| x.key != key).cloned().collect(); |
| 163 | 3× | cur.succeed(home, d) |
| 164 | 3× | } |
| 165 | |
|
| 166 | |
|
| 167 | 25× | pub fn home_identity(home: &Path) -> Result<Identity> { |
| 168 | 25× | let key = current_key(home)?.with_context(|| format!("{} holds no identity (spectra identity create)", home.display()))?; |
| 169 | 25× | let path = home.join("keys").join(format!("{}.identity", key.to_hex())); |
| 170 | 25× | Identity::decode(&fs::read(&path).with_context(|| format!("reading {}", path.display()))?) |
| 171 | 25× | .map_err(|e| anyhow::anyhow!("{}: {e}", path.display())) |
| 172 | 25× | } |
| 173 | |
|
| 174 | |
|
| 175 | 0× | pub fn identity_in(home: &Path, key: &KeyId) -> Option<Identity> { |
| 176 | 0× | let path = home.join("keys").join(format!("{}.identity", key.to_hex())); |
| 177 | 0× | Identity::decode(&fs::read(path).ok()?).ok() |
| 178 | 0× | } |
| 179 | |
|
| 180 | 325× | fn current_key(home: &Path) -> Result<Option<KeyId>> { |
| 181 | 325× | let path = home.join("identity.toml"); |
| 182 | 325× | let Ok(text) = fs::read_to_string(&path) else { return Ok(None) }; |
| 183 | 266× | let table: toml::Table = text.parse().with_context(|| format!("reading {}", path.display()))?; |
| 184 | 266× | match table.get("current").and_then(|v| v.as_str()) { |
| 185 | 266× | Some(hex) => Ok(Some(KeyId::from_hex(hex).with_context(|| format!("{}: current is not a KeyId", path.display()))?)), |
| 186 | 0× | None => Ok(None), |
| 187 | | } |
| 188 | 325× | } |
| 189 | |
|
| 190 | 123× | fn toml_str(s: &str) -> String { |
| 191 | 123× | toml::Value::String(s.to_string()).to_string() |
| 192 | 123× | } |
| 193 | |
|
| 194 | | #[cfg(test)] |
| 195 | | mod tests { |
| 196 | | use super::*; |
| 197 | |
|
| 198 | | #[test] |
| 199 | 1× | fn a_home_made_here_reads_back_signs_and_delegates() { |
| 200 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 201 | 1× | let made = KeyPair::create_home(dir.path(), "Andy McCall", "").unwrap(); |
| 202 | 1× | let read = KeyPair::load_home(dir.path()).unwrap(); |
| 203 | 1× | assert_eq!(made.key, read.key); |
| 204 | 1× | assert_eq!(home_identity(dir.path()).unwrap().hash(), made.key); |
| 205 | 1× | let msg = b"spectra1 test message of some length"; |
| 206 | 1× | crate::identity::verify(&made.identity, &read.sign(msg), msg).unwrap(); |
| 207 | 1× | assert!(KeyPair::create_home(dir.path(), "again", "").is_err()); |
| 208 | |
|
| 209 | 1× | let agent = KeyPair::generate("claude", ""); |
| 210 | 1× | let next = delegate(dir.path(), agent.key, Some(u64::MAX)).unwrap(); |
| 211 | 1× | assert_eq!(next.identity.previous, Some(made.key)); |
| 212 | 1× | assert_eq!(KeyPair::load_home(dir.path()).unwrap().key, next.key, "the successor is current"); |
| 213 | 1× | assert!(next.identity.delegates_to(&agent.key, 1)); |
| 214 | 1× | assert!(KeyPair::load_key(dir.path(), &made.key).is_ok(), "the old identity is kept"); |
| 215 | 1× | let after = undelegate(dir.path(), agent.key).unwrap(); |
| 216 | 1× | assert!(!after.identity.delegates_to(&agent.key, 1)); |
| 217 | 1× | } |
| 218 | |
|
| 219 | | #[test] |
| 220 | 1× | fn the_instance_key_is_made_once() { |
| 221 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 222 | 1× | let a = KeyPair::instance(dir.path(), "laptop").unwrap(); |
| 223 | 1× | let b = KeyPair::instance(dir.path(), "laptop").unwrap(); |
| 224 | 1× | assert_eq!(a.key, b.key); |
| 225 | 1× | } |
| 226 | | } |