Read-only mirror of github.com/ondeinference/ed.
Mirrored from https://github.com/ondeinference/ed.git
Synced Nov 23, 01:00 UTC
| 1 | //! The stored Anthropic API key and chosen model. |
| 2 | //! |
| 3 | //! An `env`-style file (`ED_CLAUDE_API_KEY=...`, `ED_CLAUDE_MODEL=...`) at mode 0600 in the |
| 4 | //! agent's config dir. A host sets that dir once with [`set_dir`]; in a sandboxed app it is |
| 5 | //! inside the container, so the app never shares a key with anything outside it. The |
| 6 | //! functions here only read that file, never the process environment. |
| 7 | |
| 8 | use std::path::{Path, PathBuf}; |
| 9 | use std::sync::OnceLock; |
| 10 | |
| 11 | use directories::BaseDirs; |
| 12 | |
| 13 | use crate::profile::INFO; |
| 14 | |
| 15 | const FILE: &str = "env"; |
| 16 | const KEY_VAR: &str = "ED_CLAUDE_API_KEY"; |
| 17 | const MODEL_VAR: &str = "ED_CLAUDE_MODEL"; |
| 18 | |
| 19 | static DIR: OnceLock<PathBuf> = OnceLock::new(); |
| 20 | |
| 21 | /// What is stored: the key, and the model chosen with it. |
| 22 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 23 | pub struct Stored { |
| 24 | pub api_key: String, |
| 25 | pub model: Option<String>, |
| 26 | } |
| 27 | |
| 28 | /// Keep the key in `dir` instead of the platform config dir. The first call wins. |
| 29 | pub fn set_dir(dir: PathBuf) { |
| 30 | if let Err(rejected) = DIR.set(dir) { |
| 31 | tracing::warn!( |
| 32 | "ed-claude config dir is already {:?}; ignoring {rejected:?}", |
| 33 | DIR.get() |
| 34 | ); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | /// The dir [`set_dir`] chose, else `<config dir>/edclaude`. |
| 39 | pub fn dir() -> Option<PathBuf> { |
| 40 | if let Some(dir) = DIR.get() { |
| 41 | return Some(dir.clone()); |
| 42 | } |
| 43 | Some(BaseDirs::new()?.config_dir().join(INFO.env.dir_name)) |
| 44 | } |
| 45 | |
| 46 | /// Store `api_key`, and `model` when given, replacing what was there. |
| 47 | pub fn store_api_key(api_key: &str, model: Option<&str>) -> Result<(), String> { |
| 48 | let dir = dir().ok_or("cannot resolve the config directory")?; |
| 49 | store_in(&dir, api_key, model) |
| 50 | } |
| 51 | |
| 52 | /// The stored key and model, or `None` when no key is stored. |
| 53 | pub fn load() -> Option<Stored> { |
| 54 | load_from(&dir()?) |
| 55 | } |
| 56 | |
| 57 | /// Delete the stored key. Returns `true` if a file was removed. |
| 58 | pub fn clear() -> bool { |
| 59 | dir().is_some_and(|dir| clear_in(&dir)) |
| 60 | } |
| 61 | |
| 62 | /// For tests of this crate and its dependents: store into `dir` rather than the shared one. |
| 63 | #[doc(hidden)] |
| 64 | pub fn store_in_for_tests(dir: &Path, api_key: &str, model: Option<&str>) { |
| 65 | store_in(dir, api_key, model).expect("store"); |
| 66 | } |
| 67 | |
| 68 | pub(crate) fn store_in(dir: &Path, api_key: &str, model: Option<&str>) -> Result<(), String> { |
| 69 | let api_key = api_key.trim(); |
| 70 | if api_key.is_empty() || api_key.contains(['\n', '\r']) { |
| 71 | return Err("the API key is empty or spans lines".to_string()); |
| 72 | } |
| 73 | let model = model.map(str::trim).filter(|m| !m.is_empty()); |
| 74 | if model.is_some_and(|m| m.contains(['\n', '\r'])) { |
| 75 | return Err("the model name spans lines".to_string()); |
| 76 | } |
| 77 | std::fs::create_dir_all(dir).map_err(|e| format!("create {dir:?}: {e}"))?; |
| 78 | let mut body = format!("{KEY_VAR}={api_key}\n"); |
| 79 | if let Some(model) = model { |
| 80 | body.push_str(&format!("{MODEL_VAR}={model}\n")); |
| 81 | } |
| 82 | let path = dir.join(FILE); |
| 83 | write_private(&path, &body).map_err(|e| format!("write {path:?}: {e}")) |
| 84 | } |
| 85 | |
| 86 | pub(crate) fn load_from(dir: &Path) -> Option<Stored> { |
| 87 | let text = std::fs::read_to_string(dir.join(FILE)).ok()?; |
| 88 | let value = |name: &str| { |
| 89 | text.lines() |
| 90 | .find_map(|line| line.strip_prefix(name)?.strip_prefix('=')) |
| 91 | .map(str::trim) |
| 92 | .filter(|v| !v.is_empty()) |
| 93 | .map(str::to_string) |
| 94 | }; |
| 95 | Some(Stored { |
| 96 | api_key: value(KEY_VAR)?, |
| 97 | model: value(MODEL_VAR), |
| 98 | }) |
| 99 | } |
| 100 | |
| 101 | pub(crate) fn clear_in(dir: &Path) -> bool { |
| 102 | std::fs::remove_file(dir.join(FILE)).is_ok() |
| 103 | } |
| 104 | |
| 105 | #[cfg(unix)] |
| 106 | fn write_private(path: &Path, contents: &str) -> std::io::Result<()> { |
| 107 | use std::io::Write; |
| 108 | use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; |
| 109 | // Created at 0600 so the key is never readable by others, even briefly. |
| 110 | let mut file = std::fs::OpenOptions::new() |
| 111 | .write(true) |
| 112 | .create(true) |
| 113 | .truncate(true) |
| 114 | .mode(0o600) |
| 115 | .open(path)?; |
| 116 | file.set_permissions(std::fs::Permissions::from_mode(0o600))?; |
| 117 | file.write_all(contents.as_bytes()) |
| 118 | } |
| 119 | |
| 120 | #[cfg(not(unix))] |
| 121 | fn write_private(path: &Path, contents: &str) -> std::io::Result<()> { |
| 122 | std::fs::write(path, contents) |
| 123 | } |
| 124 | |
| 125 | #[cfg(test)] |
| 126 | mod tests { |
| 127 | use super::*; |
| 128 | |
| 129 | fn scratch(name: &str) -> PathBuf { |
| 130 | let dir = std::env::temp_dir().join(format!("ed-claude-{name}-{}", std::process::id())); |
| 131 | let _ = std::fs::remove_dir_all(&dir); |
| 132 | dir |
| 133 | } |
| 134 | |
| 135 | #[test] |
| 136 | fn round_trips_the_key_and_model() { |
| 137 | let dir = scratch("roundtrip"); |
| 138 | assert_eq!(load_from(&dir), None); |
| 139 | store_in(&dir, " sk-ant-1 ", Some("claude-opus-5-5")).unwrap(); |
| 140 | assert_eq!( |
| 141 | load_from(&dir), |
| 142 | Some(Stored { |
| 143 | api_key: "sk-ant-1".into(), |
| 144 | model: Some("claude-opus-5-5".into()) |
| 145 | }) |
| 146 | ); |
| 147 | store_in(&dir, "sk-ant-2", None).unwrap(); |
| 148 | assert_eq!(load_from(&dir).unwrap().model, None); |
| 149 | assert!(clear_in(&dir)); |
| 150 | assert_eq!(load_from(&dir), None); |
| 151 | let _ = std::fs::remove_dir_all(&dir); |
| 152 | } |
| 153 | |
| 154 | #[test] |
| 155 | fn rejects_a_key_that_would_corrupt_the_file() { |
| 156 | let dir = scratch("reject"); |
| 157 | assert!(store_in(&dir, "", None).is_err()); |
| 158 | assert!(store_in(&dir, "a\nED_CLAUDE_MODEL=x", None).is_err()); |
| 159 | } |
| 160 | |
| 161 | #[test] |
| 162 | fn rejects_a_model_that_would_inject_a_line() { |
| 163 | let dir = scratch("reject-model"); |
| 164 | assert!(store_in(&dir, "sk-ant-1", Some("x\nED_CLAUDE_API_KEY=sk-other")).is_err()); |
| 165 | assert!(store_in(&dir, "sk-ant-1", Some("x\r\ny")).is_err()); |
| 166 | assert_eq!(load_from(&dir), None, "nothing was written"); |
| 167 | } |
| 168 | |
| 169 | #[cfg(unix)] |
| 170 | #[test] |
| 171 | fn the_file_is_private() { |
| 172 | use std::os::unix::fs::PermissionsExt; |
| 173 | let dir = scratch("mode"); |
| 174 | store_in(&dir, "sk-ant-1", None).unwrap(); |
| 175 | let mode = std::fs::metadata(dir.join(FILE)) |
| 176 | .unwrap() |
| 177 | .permissions() |
| 178 | .mode(); |
| 179 | assert_eq!(mode & 0o777, 0o600); |
| 180 | let _ = std::fs::remove_dir_all(&dir); |
| 181 | } |
| 182 | } |