Skip to main content

romm_cli/
config.rs

1//! Configuration and authentication for the ROMM client.
2//!
3//! This module is deliberately independent of any particular frontend:
4//! both the TUI and the command-line subcommands share the same `Config`
5//! and `AuthConfig` types.
6//!
7//! ## Environment file precedence
8//!
9//! Call [`load_layered_env`] before reading config:
10//!
11//! 1. Variables already set in the process environment (highest priority).
12//! 2. Project `.env` in the current working directory (via `dotenvy`).
13//! 3. User config: `{config_dir}/romm-cli/.env` — fills keys not already set (so a repo `.env` wins over user defaults).
14//! 4. OS keyring — secrets stored by `romm-cli init` (lowest priority fallback).
15
16use std::path::PathBuf;
17
18use anyhow::{anyhow, Context, Result};
19
20// ---------------------------------------------------------------------------
21// Types
22// ---------------------------------------------------------------------------
23
24#[derive(Debug, Clone)]
25pub enum AuthConfig {
26    Basic { username: String, password: String },
27    Bearer { token: String },
28    ApiKey { header: String, key: String },
29}
30
31#[derive(Debug, Clone)]
32pub struct Config {
33    pub base_url: String,
34    pub download_dir: String,
35    pub use_https: bool,
36    pub auth: Option<AuthConfig>,
37}
38
39fn is_placeholder(value: &str) -> bool {
40    value.contains("your-") || value.contains("placeholder") || value.trim().is_empty()
41}
42
43/// RomM site URL: the same origin you use in the browser (scheme, host, optional port).
44///
45/// Trims whitespace and trailing `/`, and removes a trailing `/api` segment if present. HTTP
46/// calls use paths such as `/api/platforms`; they must not double up with `.../api/api/...`.
47pub fn normalize_romm_origin(url: &str) -> String {
48    let mut s = url.trim().trim_end_matches('/').to_string();
49    if s.ends_with("/api") {
50        s.truncate(s.len() - 4);
51    }
52    s.trim_end_matches('/').to_string()
53}
54
55// ---------------------------------------------------------------------------
56// Keyring helpers
57// ---------------------------------------------------------------------------
58
59const KEYRING_SERVICE: &str = "romm-cli";
60
61/// Store a secret in the OS keyring under the `romm-cli` service name.
62pub fn keyring_store(key: &str, value: &str) -> Result<()> {
63    let entry = keyring::Entry::new(KEYRING_SERVICE, key)
64        .map_err(|e| anyhow!("keyring entry error: {e}"))?;
65    entry
66        .set_password(value)
67        .map_err(|e| anyhow!("keyring set error: {e}"))
68}
69
70/// Retrieve a secret from the OS keyring, returning `None` if not found.
71fn keyring_get(key: &str) -> Option<String> {
72    let entry = keyring::Entry::new(KEYRING_SERVICE, key).ok()?;
73    entry.get_password().ok()
74}
75
76// ---------------------------------------------------------------------------
77// Paths
78// ---------------------------------------------------------------------------
79
80/// Directory for user-level config (`romm-cli` under the OS config dir).
81pub fn user_config_dir() -> Option<PathBuf> {
82    if let Ok(dir) = std::env::var("ROMM_TEST_CONFIG_DIR") {
83        return Some(PathBuf::from(dir));
84    }
85    dirs::config_dir().map(|d| d.join("romm-cli"))
86}
87
88/// Path to the user-level `.env` file (`.../romm-cli/.env`).
89pub fn user_config_env_path() -> Option<PathBuf> {
90    user_config_dir().map(|d| d.join(".env"))
91}
92
93/// Where the OpenAPI spec is cached (`.../romm-cli/openapi.json`).
94///
95/// Override with `ROMM_OPENAPI_PATH` (absolute or relative path).
96pub fn openapi_cache_path() -> Result<PathBuf> {
97    if let Ok(p) = std::env::var("ROMM_OPENAPI_PATH") {
98        return Ok(PathBuf::from(p));
99    }
100    let dir = user_config_dir().ok_or_else(|| {
101        anyhow!("Could not resolve config directory. Set ROMM_OPENAPI_PATH to store openapi.json.")
102    })?;
103    Ok(dir.join("openapi.json"))
104}
105
106// ---------------------------------------------------------------------------
107// Loading
108// ---------------------------------------------------------------------------
109
110/// Load env vars from `./.env` in cwd, then from the user config file.
111/// Later files only set variables not already set (env or earlier file), so a project `.env` overrides the same keys in the user file.
112pub fn load_layered_env() {
113    let _ = dotenvy::dotenv();
114    if let Some(path) = user_config_env_path() {
115        if path.is_file() {
116            let _ = dotenvy::from_path(path);
117        }
118    }
119}
120
121/// Read an env var, falling back to the OS keyring if unset or empty.
122///
123/// A line like `API_PASSWORD=` in a project `.env` sets the variable to the empty string; we treat
124/// that as "not set" so the keyring (e.g. after `romm-cli init` / TUI setup) is still used.
125fn env_or_keyring(key: &str) -> Option<String> {
126    match std::env::var(key) {
127        Ok(s) if !s.trim().is_empty() => Some(s),
128        Ok(_) => keyring_get(key),
129        Err(_) => keyring_get(key),
130    }
131}
132
133fn env_nonempty(key: &str) -> Option<String> {
134    std::env::var(key).ok().filter(|s| !s.trim().is_empty())
135}
136
137pub fn load_config() -> Result<Config> {
138    let base_raw = std::env::var("API_BASE_URL").map_err(|_| {
139        anyhow!(
140            "API_BASE_URL is not set. Set it in the environment, a .env file, or run: romm-cli init"
141        )
142    })?;
143    let mut base_url = normalize_romm_origin(&base_raw);
144
145    let download_dir = env_nonempty("ROMM_DOWNLOAD_DIR").unwrap_or_else(|| {
146        dirs::download_dir()
147            .unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join("Downloads"))
148            .join("romm-cli")
149            .display()
150            .to_string()
151    });
152
153    let use_https = std::env::var("API_USE_HTTPS")
154        .map(|s| s.to_lowercase() == "true")
155        .unwrap_or(true);
156
157    if use_https && base_url.starts_with("http://") {
158        base_url = base_url.replace("http://", "https://");
159    }
160
161    let username = env_nonempty("API_USERNAME");
162    let password = env_or_keyring("API_PASSWORD");
163    let token = env_or_keyring("API_TOKEN").or_else(|| env_or_keyring("API_KEY"));
164    let api_key = env_or_keyring("API_KEY");
165    let api_key_header = env_nonempty("API_KEY_HEADER");
166
167    let auth = if let (Some(user), Some(pass)) = (username, password) {
168        // Priority 1: Basic auth
169        Some(AuthConfig::Basic {
170            username: user,
171            password: pass,
172        })
173    } else if let (Some(key), Some(header)) = (api_key, api_key_header) {
174        // Priority 2: API key in custom header (when both set, prefer over bearer)
175        if !is_placeholder(&key) {
176            Some(AuthConfig::ApiKey { header, key })
177        } else {
178            None
179        }
180    } else if let Some(tok) = token {
181        // Priority 3: Bearer token (skip placeholders)
182        if !is_placeholder(&tok) {
183            Some(AuthConfig::Bearer { token: tok })
184        } else {
185            None
186        }
187    } else {
188        None
189    };
190
191    Ok(Config {
192        base_url,
193        download_dir,
194        use_https,
195        auth,
196    })
197}
198
199/// Escape a value for use in a `.env` file line (same rules as `romm-cli init`).
200pub(crate) fn escape_env_value(s: &str) -> String {
201    let needs_quote = s.is_empty()
202        || s.chars()
203            .any(|c| c.is_whitespace() || c == '#' || c == '"' || c == '\'');
204    if needs_quote {
205        let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
206        format!("\"{}\"", escaped)
207    } else {
208        s.to_string()
209    }
210}
211
212/// Write user-level `romm-cli/.env` and store secrets in the OS keyring when possible
213/// (same layout as interactive `romm-cli init`).
214pub fn persist_user_config(
215    base_url: &str,
216    download_dir: &str,
217    use_https: bool,
218    auth: Option<AuthConfig>,
219) -> Result<()> {
220    let Some(path) = user_config_env_path() else {
221        return Err(anyhow!(
222            "Could not determine config directory (no HOME / APPDATA?)."
223        ));
224    };
225    let dir = path
226        .parent()
227        .ok_or_else(|| anyhow!("invalid config path"))?;
228    std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
229
230    let mut lines: Vec<String> = vec![
231        "# romm-cli user configuration".to_string(),
232        "# Secrets are stored in the OS keyring when available.".to_string(),
233        "# Applied after project .env: only fills variables not already set.".to_string(),
234        String::new(),
235        format!("API_BASE_URL={}", escape_env_value(base_url)),
236        format!("ROMM_DOWNLOAD_DIR={}", escape_env_value(download_dir)),
237        format!("API_USE_HTTPS={}", if use_https { "true" } else { "false" }),
238        String::new(),
239    ];
240
241    match &auth {
242        None => {
243            lines.push("# No auth variables set.".to_string());
244        }
245        Some(AuthConfig::Basic { username, password }) => {
246            lines.push("# Basic auth (password stored in OS keyring)".to_string());
247            lines.push(format!("API_USERNAME={}", escape_env_value(username)));
248            if let Err(e) = keyring_store("API_PASSWORD", password) {
249                tracing::warn!("keyring store API_PASSWORD: {e}; writing plaintext to .env");
250                lines.push(format!("API_PASSWORD={}", escape_env_value(password)));
251            }
252        }
253        Some(AuthConfig::Bearer { token }) => {
254            lines.push("# Bearer token (stored in OS keyring)".to_string());
255            if let Err(e) = keyring_store("API_TOKEN", token) {
256                tracing::warn!("keyring store API_TOKEN: {e}; writing plaintext to .env");
257                lines.push(format!("API_TOKEN={}", escape_env_value(token)));
258            }
259        }
260        Some(AuthConfig::ApiKey { header, key }) => {
261            lines.push("# Custom header API key (key stored in OS keyring)".to_string());
262            lines.push(format!("API_KEY_HEADER={}", escape_env_value(header)));
263            if let Err(e) = keyring_store("API_KEY", key) {
264                tracing::warn!("keyring store API_KEY: {e}; writing plaintext to .env");
265                lines.push(format!("API_KEY={}", escape_env_value(key)));
266            }
267        }
268    }
269
270    let content = lines.join("\n") + "\n";
271    {
272        use std::io::Write;
273        let mut f =
274            std::fs::File::create(&path).with_context(|| format!("write {}", path.display()))?;
275        f.write_all(content.as_bytes())?;
276    }
277
278    #[cfg(unix)]
279    {
280        use std::os::unix::fs::PermissionsExt;
281        let mut perms = std::fs::metadata(&path)?.permissions();
282        perms.set_mode(0o600);
283        std::fs::set_permissions(&path, perms)?;
284    }
285
286    Ok(())
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292    use std::sync::{Mutex, OnceLock};
293
294    fn env_lock() -> &'static Mutex<()> {
295        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
296        LOCK.get_or_init(|| Mutex::new(()))
297    }
298
299    fn clear_auth_env() {
300        for key in [
301            "API_BASE_URL",
302            "API_USERNAME",
303            "API_PASSWORD",
304            "API_TOKEN",
305            "API_KEY",
306            "API_KEY_HEADER",
307            "API_USE_HTTPS",
308        ] {
309            std::env::remove_var(key);
310        }
311    }
312
313    #[test]
314    fn prefers_basic_auth_over_other_modes() {
315        let _guard = env_lock().lock().expect("env lock");
316        clear_auth_env();
317        std::env::set_var("API_BASE_URL", "http://example.test");
318        std::env::set_var("API_USERNAME", "user");
319        std::env::set_var("API_PASSWORD", "pass");
320        std::env::set_var("API_TOKEN", "token");
321        std::env::set_var("API_KEY", "apikey");
322        std::env::set_var("API_KEY_HEADER", "X-Api-Key");
323
324        let cfg = load_config().expect("config should load");
325        match cfg.auth {
326            Some(AuthConfig::Basic { username, password }) => {
327                assert_eq!(username, "user");
328                assert_eq!(password, "pass");
329            }
330            _ => panic!("expected basic auth"),
331        }
332    }
333
334    #[test]
335    fn uses_api_key_header_when_token_missing() {
336        let _guard = env_lock().lock().expect("env lock");
337        clear_auth_env();
338        std::env::set_var("API_BASE_URL", "http://example.test");
339        std::env::set_var("API_KEY", "real-key");
340        std::env::set_var("API_KEY_HEADER", "X-Api-Key");
341
342        let cfg = load_config().expect("config should load");
343        match cfg.auth {
344            Some(AuthConfig::ApiKey { header, key }) => {
345                assert_eq!(header, "X-Api-Key");
346                assert_eq!(key, "real-key");
347            }
348            _ => panic!("expected api key auth"),
349        }
350    }
351
352    #[test]
353    fn normalizes_api_base_url_and_enforces_https_by_default() {
354        let _guard = env_lock().lock().expect("env lock");
355        clear_auth_env();
356        std::env::set_var("API_BASE_URL", "http://romm.example/api/");
357        let cfg = load_config().expect("config");
358        // Upgraded to https by default
359        assert_eq!(cfg.base_url, "https://romm.example");
360    }
361
362    #[test]
363    fn does_not_enforce_https_if_toggle_is_false() {
364        let _guard = env_lock().lock().expect("env lock");
365        clear_auth_env();
366        std::env::set_var("API_BASE_URL", "http://romm.example/api/");
367        std::env::set_var("API_USE_HTTPS", "false");
368        let cfg = load_config().expect("config");
369        assert_eq!(cfg.base_url, "http://romm.example");
370    }
371
372    #[test]
373    fn normalize_romm_origin_trims_and_strips_api_suffix() {
374        assert_eq!(
375            normalize_romm_origin("http://localhost:8080/api/"),
376            "http://localhost:8080"
377        );
378        assert_eq!(
379            normalize_romm_origin("https://x.example"),
380            "https://x.example"
381        );
382    }
383
384    #[test]
385    fn empty_api_username_does_not_enable_basic() {
386        let _guard = env_lock().lock().expect("env lock");
387        clear_auth_env();
388        std::env::set_var("API_BASE_URL", "http://example.test");
389        std::env::set_var("API_USERNAME", "");
390        std::env::set_var("API_PASSWORD", "secret");
391
392        let cfg = load_config().expect("config should load");
393        assert!(
394            cfg.auth.is_none(),
395            "empty API_USERNAME should not pair with password for Basic"
396        );
397    }
398
399    #[test]
400    fn ignores_placeholder_bearer_token() {
401        let _guard = env_lock().lock().expect("env lock");
402        clear_auth_env();
403        std::env::set_var("API_BASE_URL", "http://example.test");
404        std::env::set_var("API_TOKEN", "your-bearer-token-here");
405
406        let cfg = load_config().expect("config should load");
407        assert!(cfg.auth.is_none(), "placeholder token should be ignored");
408    }
409
410    #[test]
411    fn layered_env_applies_user_file_for_unset_keys() {
412        let _guard = env_lock().lock().expect("env lock");
413        clear_auth_env();
414        std::env::remove_var("API_BASE_URL");
415
416        let ts = std::time::SystemTime::now()
417            .duration_since(std::time::UNIX_EPOCH)
418            .unwrap()
419            .as_nanos();
420        let base = std::env::temp_dir().join(format!("romm-layered-{ts}"));
421        std::fs::create_dir_all(&base).unwrap();
422        let work = base.join("work");
423        std::fs::create_dir_all(&work).unwrap();
424        std::fs::write(
425            base.join(".env"),
426            "API_BASE_URL=http://from-user-file.test\n",
427        )
428        .unwrap();
429
430        std::env::set_var("ROMM_TEST_CONFIG_DIR", base.as_os_str());
431        let old_cwd = std::env::current_dir().unwrap();
432        std::env::set_current_dir(&work).unwrap();
433
434        load_layered_env();
435        // Force use_https=false so the http assertion works
436        std::env::set_var("API_USE_HTTPS", "false");
437        let cfg = load_config().expect("load from user .env");
438        assert_eq!(cfg.base_url, "http://from-user-file.test");
439
440        std::env::set_current_dir(old_cwd).unwrap();
441        std::env::remove_var("ROMM_TEST_CONFIG_DIR");
442        std::env::remove_var("API_BASE_URL");
443        let _ = std::fs::remove_dir_all(&base);
444    }
445}