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//! ## Configuration precedence
8//!
9//! Call [`load_config`] to read config:
10//!
11//! 1. Variables already set in the process environment (highest priority), including `API_TOKEN` and
12//!    paths `ROMM_TOKEN_FILE` / `API_TOKEN_FILE` (file contents used as bearer token when `API_TOKEN` is unset).
13//! 2. User `config.json` (see [`user_config_json_path`]) — fills any field **not** already set from the environment.
14//!
15//! There is **no** automatic loading of a `.env` file; set variables in your shell or process manager,
16//! or rely on `config.json` written by `romm-cli init` / the TUI setup wizard.
17//!
18//! After env + JSON merge, secrets that are still placeholders (including [`KEYRING_SECRET_PLACEHOLDER`])
19//! are resolved via the OS keyring (`keyring` crate, service name `romm-cli`). On Windows the stored
20//! credential target is typically `API_TOKEN.romm-cli`, `API_PASSWORD.romm-cli`, or `API_KEY.romm-cli`.
21//! Missing entries are silent; other keyring errors are logged at warn (never with secret values).
22//! On save, a successful store is followed by read-back verification before writing the sentinel to JSON.
23//!
24//! ## `load_config` vs `config.json`
25//!
26//! [`load_config`] merges sources **per field**: process environment wins over values from
27//! `config.json` for `API_BASE_URL`, `ROMM_DOWNLOAD_DIR`, `API_USE_HTTPS`, and auth-related
28//! fields. The keyring is used only to replace placeholder or sentinel secret strings after that merge.
29
30use std::fs;
31use std::path::PathBuf;
32
33use anyhow::{anyhow, Context, Result};
34
35use serde::{Deserialize, Serialize};
36
37// ---------------------------------------------------------------------------
38// Types
39// ---------------------------------------------------------------------------
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
42pub enum AuthConfig {
43    Basic { username: String, password: String },
44    Bearer { token: String },
45    ApiKey { header: String, key: String },
46}
47
48#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct Config {
50    pub base_url: String,
51    pub download_dir: String,
52    pub use_https: bool,
53    pub auth: Option<AuthConfig>,
54}
55
56fn is_placeholder(value: &str) -> bool {
57    value.contains("your-") || value.contains("placeholder") || value.trim().is_empty()
58}
59
60/// Written to `config.json` when the real secret is stored in the OS keyring (`persist_user_config`).
61pub const KEYRING_SECRET_PLACEHOLDER: &str = "<stored-in-keyring>";
62
63/// True if `s` is the sentinel written to disk when the secret lives in the keyring.
64pub fn is_keyring_placeholder(s: &str) -> bool {
65    s == KEYRING_SECRET_PLACEHOLDER
66}
67
68/// RomM site URL: the same origin you use in the browser (scheme, host, optional port).
69///
70/// Trims whitespace and trailing `/`, and removes a trailing `/api` segment if present. HTTP
71/// calls use paths such as `/api/platforms`; they must not double up with `.../api/api/...`.
72pub fn normalize_romm_origin(url: &str) -> String {
73    let mut s = url.trim().trim_end_matches('/').to_string();
74    if s.ends_with("/api") {
75        s.truncate(s.len() - 4);
76    }
77    s.trim_end_matches('/').to_string()
78}
79
80// ---------------------------------------------------------------------------
81// Keyring helpers
82// ---------------------------------------------------------------------------
83
84const KEYRING_SERVICE: &str = "romm-cli";
85
86/// Store a secret in the OS keyring under the `romm-cli` service name.
87pub fn keyring_store(key: &str, value: &str) -> Result<()> {
88    let entry = keyring::Entry::new(KEYRING_SERVICE, key)
89        .map_err(|e| anyhow!("keyring entry error: {e}"))?;
90    entry
91        .set_password(value)
92        .map_err(|e| anyhow!("keyring set error: {e}"))
93}
94
95/// Map `get_password` result: [`keyring::Error::NoEntry`] is normal when no credential exists (no log).
96/// Other errors are logged (never logs secret bytes).
97fn keyring_get_password_result(key: &str, result: keyring::Result<String>) -> Option<String> {
98    match result {
99        Ok(s) => Some(s),
100        Err(keyring::Error::NoEntry) => None,
101        Err(e) => {
102            tracing::warn!("keyring get_password for key {key}: {e}");
103            None
104        }
105    }
106}
107
108/// Retrieve a secret from the OS keyring, returning `None` if not found or on error (after logging unexpected errors).
109pub(crate) fn keyring_get(key: &str) -> Option<String> {
110    let entry = match keyring::Entry::new(KEYRING_SERVICE, key) {
111        Ok(e) => e,
112        Err(e) => {
113            tracing::warn!("keyring Entry::new for key {key}: {e}");
114            return None;
115        }
116    };
117    keyring_get_password_result(key, entry.get_password())
118}
119
120/// After a successful `set_password`, confirm read-back matches `expected`. If not, caller should keep plaintext in JSON.
121fn keyring_verify_read_back_matches(key: &str, expected: &str) -> bool {
122    let entry = match keyring::Entry::new(KEYRING_SERVICE, key) {
123        Ok(e) => e,
124        Err(e) => {
125            tracing::warn!(
126                "keyring verify: Entry::new for key {key} after successful store: {e}; writing plaintext to config.json"
127            );
128            return false;
129        }
130    };
131    match entry.get_password() {
132        Ok(read) if read == expected => true,
133        Ok(_) => {
134            tracing::warn!(
135                "keyring verify: read-back for key {key} did not match; writing plaintext to config.json"
136            );
137            false
138        }
139        Err(e) => {
140            tracing::warn!(
141                "keyring verify: get_password for key {key} after successful store: {e}; writing plaintext to config.json"
142            );
143            false
144        }
145    }
146}
147
148// ---------------------------------------------------------------------------
149// Paths
150// ---------------------------------------------------------------------------
151
152/// Directory for user-level config (`romm-cli` under the OS config dir).
153pub fn user_config_dir() -> Option<PathBuf> {
154    if let Ok(dir) = std::env::var("ROMM_TEST_CONFIG_DIR") {
155        return Some(PathBuf::from(dir));
156    }
157    dirs::config_dir().map(|d| d.join("romm-cli"))
158}
159
160/// Path to the user-level `config.json` file (`.../romm-cli/config.json`).
161pub fn user_config_json_path() -> Option<PathBuf> {
162    user_config_dir().map(|d| d.join("config.json"))
163}
164
165/// Reads `config.json` from disk only (no env merge, no keyring resolution).
166/// Used by the TUI setup wizard to detect `<stored-in-keyring>` placeholders.
167pub fn read_user_config_json_from_disk() -> Option<Config> {
168    let path = user_config_json_path()?;
169    let content = std::fs::read_to_string(path).ok()?;
170    serde_json::from_str(&content).ok()
171}
172
173/// Auth to pass to [`persist_user_config`] when saving non-auth fields (e.g. TUI Settings).
174///
175/// Prefer the in-memory [`Config::auth`]. If it is `None` (e.g. [`load_config`] could not read the
176/// token from the keyring), reuse `auth` from [`read_user_config_json_from_disk`] so we do not
177/// overwrite `config.json` with `"auth": null` while the file still held a bearer sentinel.
178pub fn auth_for_persist_merge(in_memory: Option<AuthConfig>) -> Option<AuthConfig> {
179    in_memory.or_else(|| read_user_config_json_from_disk().and_then(|c| c.auth))
180}
181
182/// Where the OpenAPI spec is cached (`.../romm-cli/openapi.json`).
183///
184/// Override with `ROMM_OPENAPI_PATH` (absolute or relative path).
185pub fn openapi_cache_path() -> Result<PathBuf> {
186    if let Ok(p) = std::env::var("ROMM_OPENAPI_PATH") {
187        return Ok(PathBuf::from(p));
188    }
189    let dir = user_config_dir().ok_or_else(|| {
190        anyhow!("Could not resolve config directory. Set ROMM_OPENAPI_PATH to store openapi.json.")
191    })?;
192    Ok(dir.join("openapi.json"))
193}
194
195// ---------------------------------------------------------------------------
196// Loading
197// ---------------------------------------------------------------------------
198
199fn env_nonempty(key: &str) -> Option<String> {
200    std::env::var(key).ok().filter(|s| !s.trim().is_empty())
201}
202
203/// Max bytes read from bearer token files (`ROMM_TOKEN_FILE` / `API_TOKEN_FILE`).
204const MAX_TOKEN_FILE_BYTES: usize = 64 * 1024;
205
206/// Bearer token: `API_TOKEN` env, else UTF-8 file at `ROMM_TOKEN_FILE` or `API_TOKEN_FILE` path.
207fn token_from_env_or_file() -> Result<Option<String>> {
208    if let Some(t) = env_nonempty("API_TOKEN") {
209        return Ok(Some(t));
210    }
211    let path = env_nonempty("ROMM_TOKEN_FILE").or_else(|| env_nonempty("API_TOKEN_FILE"));
212    let Some(path) = path else {
213        return Ok(None);
214    };
215    let path = path.trim();
216    let bytes = fs::read(path).with_context(|| format!("read bearer token file {path}"))?;
217    if bytes.len() > MAX_TOKEN_FILE_BYTES {
218        return Err(anyhow!(
219            "bearer token file exceeds max size of {} bytes",
220            MAX_TOKEN_FILE_BYTES
221        ));
222    }
223    let s = String::from_utf8(bytes)
224        .map_err(|e| anyhow!("bearer token file must be valid UTF-8: {e}"))?;
225    let t = s.trim();
226    if t.is_empty() {
227        return Err(anyhow!(
228            "bearer token file is empty after trimming whitespace"
229        ));
230    }
231    Ok(Some(t.to_string()))
232}
233
234/// Returns true when [`load_config`] has no resolved [`AuthConfig::Bearer`] (etc.) but `config.json`
235/// on disk still contains [`KEYRING_SECRET_PLACEHOLDER`] (OS keyring could not supply the secret).
236pub fn disk_has_unresolved_keyring_sentinel(config: &Config) -> bool {
237    if config.auth.is_some() {
238        return false;
239    }
240    let Some(disk) = read_user_config_json_from_disk() else {
241        return false;
242    };
243    match &disk.auth {
244        Some(AuthConfig::Bearer { token }) => is_keyring_placeholder(token),
245        Some(AuthConfig::Basic { password, .. }) => is_keyring_placeholder(password),
246        Some(AuthConfig::ApiKey { key, .. }) => is_keyring_placeholder(key),
247        None => false,
248    }
249}
250
251/// Loads merged config from env, optional `config.json`, and the OS keyring.
252///
253/// Bearer token resolution order: `API_TOKEN`, then UTF-8 file at `ROMM_TOKEN_FILE` or `API_TOKEN_FILE`
254/// (max 64 KiB, trimmed), then JSON. If a token file path is set but the file is missing, empty, or
255/// too large, returns an error.
256pub fn load_config() -> Result<Config> {
257    // 1. Load from JSON first (if it exists)
258    let mut json_config = None;
259    if let Some(path) = user_config_json_path() {
260        if path.is_file() {
261            if let Ok(content) = std::fs::read_to_string(&path) {
262                if let Ok(config) = serde_json::from_str::<Config>(&content) {
263                    json_config = Some(config);
264                }
265            }
266        }
267    }
268
269    // 2. Resolve base_url
270    let base_raw = env_nonempty("API_BASE_URL")
271        .or_else(|| json_config.as_ref().map(|c| c.base_url.clone()))
272        .ok_or_else(|| {
273            anyhow!(
274                "API_BASE_URL is not set. Set it in the environment, a config.json file, or run: romm-cli init"
275            )
276        })?;
277    let mut base_url = normalize_romm_origin(&base_raw);
278
279    // 3. Resolve download_dir
280    let download_dir = env_nonempty("ROMM_DOWNLOAD_DIR")
281        .or_else(|| json_config.as_ref().map(|c| c.download_dir.clone()))
282        .unwrap_or_else(|| {
283            dirs::download_dir()
284                .unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join("Downloads"))
285                .join("romm-cli")
286                .display()
287                .to_string()
288        });
289
290    // 4. Resolve use_https
291    let use_https = if let Ok(s) = std::env::var("API_USE_HTTPS") {
292        s.to_lowercase() == "true"
293    } else if let Some(c) = &json_config {
294        c.use_https
295    } else {
296        true
297    };
298
299    if use_https && base_url.starts_with("http://") {
300        base_url = base_url.replace("http://", "https://");
301    }
302
303    // 5. Resolve Auth
304    let mut username = env_nonempty("API_USERNAME");
305    let mut password = env_nonempty("API_PASSWORD");
306    let mut token = token_from_env_or_file()?;
307    let mut api_key = env_nonempty("API_KEY");
308    let mut api_key_header = env_nonempty("API_KEY_HEADER");
309
310    if let Some(c) = &json_config {
311        if let Some(auth) = &c.auth {
312            match auth {
313                AuthConfig::Basic {
314                    username: u,
315                    password: p,
316                } => {
317                    if username.is_none() {
318                        username = Some(u.clone());
319                    }
320                    if password.is_none() {
321                        password = Some(p.clone());
322                    }
323                }
324                AuthConfig::Bearer { token: t } => {
325                    if token.is_none() {
326                        token = Some(t.clone());
327                    }
328                }
329                AuthConfig::ApiKey { header: h, key: k } => {
330                    if api_key_header.is_none() {
331                        api_key_header = Some(h.clone());
332                    }
333                    if api_key.is_none() {
334                        api_key = Some(k.clone());
335                    }
336                }
337            }
338        }
339    }
340
341    // Resolve placeholders from keyring (including disk sentinel `<stored-in-keyring>`).
342    if let Some(p) = &password {
343        if is_placeholder(p) || is_keyring_placeholder(p) {
344            if let Some(k) = keyring_get("API_PASSWORD") {
345                password = Some(k);
346            }
347        }
348    } else {
349        password = keyring_get("API_PASSWORD");
350    }
351
352    if let Some(t) = &token {
353        if is_placeholder(t) || is_keyring_placeholder(t) {
354            if let Some(k) = keyring_get("API_TOKEN") {
355                token = Some(k);
356            }
357        }
358    } else {
359        token = keyring_get("API_TOKEN");
360    }
361
362    if let Some(k) = &api_key {
363        if is_placeholder(k) || is_keyring_placeholder(k) {
364            if let Some(kr) = keyring_get("API_KEY") {
365                api_key = Some(kr);
366            }
367        }
368    } else {
369        api_key = keyring_get("API_KEY");
370    }
371
372    if let Some(ref p) = password {
373        if is_keyring_placeholder(p) {
374            tracing::warn!(
375                "Could not read API_PASSWORD from the OS keyring; value is still <stored-in-keyring>. \
376                 On Windows, look for a Generic credential with target API_PASSWORD.romm-cli."
377            );
378        }
379    }
380    if let Some(ref t) = token {
381        if is_keyring_placeholder(t) {
382            tracing::warn!(
383                "Could not read API_TOKEN from the OS keyring; value is still <stored-in-keyring>. \
384                 On Windows, look for a Generic credential with target API_TOKEN.romm-cli."
385            );
386        }
387    }
388    if let Some(ref k) = api_key {
389        if is_keyring_placeholder(k) {
390            tracing::warn!(
391                "Could not read API_KEY from the OS keyring; value is still <stored-in-keyring>. \
392                 On Windows, look for a Generic credential with target API_KEY.romm-cli."
393            );
394        }
395    }
396
397    let auth = if let (Some(user), Some(pass)) = (username, password) {
398        if !is_placeholder(&pass) && !is_keyring_placeholder(&pass) {
399            Some(AuthConfig::Basic {
400                username: user,
401                password: pass,
402            })
403        } else {
404            None
405        }
406    } else if let (Some(key), Some(header)) = (api_key, api_key_header) {
407        if !is_placeholder(&key) && !is_keyring_placeholder(&key) {
408            Some(AuthConfig::ApiKey { header, key })
409        } else {
410            None
411        }
412    } else if let Some(tok) = token {
413        if !is_placeholder(&tok) && !is_keyring_placeholder(&tok) {
414            Some(AuthConfig::Bearer { token: tok })
415        } else {
416            None
417        }
418    } else {
419        None
420    };
421
422    Ok(Config {
423        base_url,
424        download_dir,
425        use_https,
426        auth,
427    })
428}
429
430/// Write user-level `romm-cli/config.json` and store secrets in the OS keyring when possible
431/// (same layout as interactive `romm-cli init`).
432///
433/// If a secret field is already [`KEYRING_SECRET_PLACEHOLDER`], it is written to JSON as-is and
434/// the keyring is not updated (avoids overwriting the vault with the literal sentinel string).
435///
436/// After a successful [`keyring_store`], the secret is read back from the keyring; only if it
437/// matches the stored value is JSON updated to the sentinel (otherwise plaintext is kept and a
438/// warning is logged).
439pub fn persist_user_config(
440    base_url: &str,
441    download_dir: &str,
442    use_https: bool,
443    auth: Option<AuthConfig>,
444) -> Result<()> {
445    let Some(path) = user_config_json_path() else {
446        return Err(anyhow!(
447            "Could not determine config directory (no HOME / APPDATA?)."
448        ));
449    };
450    let dir = path
451        .parent()
452        .ok_or_else(|| anyhow!("invalid config path"))?;
453    std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
454
455    let mut config_to_save = Config {
456        base_url: base_url.to_string(),
457        download_dir: download_dir.to_string(),
458        use_https,
459        auth: auth.clone(),
460    };
461
462    match &mut config_to_save.auth {
463        None => {}
464        Some(AuthConfig::Basic { password, .. }) => {
465            if is_keyring_placeholder(password) {
466                tracing::debug!(
467                    "skip keyring store for API_PASSWORD: value is keyring sentinel; leaving disk sentinel unchanged"
468                );
469            } else if let Err(e) = keyring_store("API_PASSWORD", password) {
470                tracing::warn!("keyring store API_PASSWORD: {e}; writing plaintext to config.json");
471            } else if keyring_verify_read_back_matches("API_PASSWORD", password.as_str()) {
472                *password = KEYRING_SECRET_PLACEHOLDER.to_string();
473            }
474        }
475        Some(AuthConfig::Bearer { token }) => {
476            if is_keyring_placeholder(token) {
477                tracing::debug!(
478                    "skip keyring store for API_TOKEN: value is keyring sentinel; leaving disk sentinel unchanged"
479                );
480            } else if let Err(e) = keyring_store("API_TOKEN", token) {
481                tracing::warn!("keyring store API_TOKEN: {e}; writing plaintext to config.json");
482            } else if keyring_verify_read_back_matches("API_TOKEN", token.as_str()) {
483                *token = KEYRING_SECRET_PLACEHOLDER.to_string();
484            }
485        }
486        Some(AuthConfig::ApiKey { key, .. }) => {
487            if is_keyring_placeholder(key) {
488                tracing::debug!(
489                    "skip keyring store for API_KEY: value is keyring sentinel; leaving disk sentinel unchanged"
490                );
491            } else if let Err(e) = keyring_store("API_KEY", key) {
492                tracing::warn!("keyring store API_KEY: {e}; writing plaintext to config.json");
493            } else if keyring_verify_read_back_matches("API_KEY", key.as_str()) {
494                *key = KEYRING_SECRET_PLACEHOLDER.to_string();
495            }
496        }
497    }
498
499    let content = serde_json::to_string_pretty(&config_to_save)?;
500    {
501        use std::io::Write;
502        let mut f =
503            std::fs::File::create(&path).with_context(|| format!("write {}", path.display()))?;
504        f.write_all(content.as_bytes())?;
505    }
506
507    #[cfg(unix)]
508    {
509        use std::os::unix::fs::PermissionsExt;
510        let mut perms = std::fs::metadata(&path)?.permissions();
511        perms.set_mode(0o600);
512        std::fs::set_permissions(&path, perms)?;
513    }
514
515    Ok(())
516}
517
518#[cfg(test)]
519mod tests {
520    use super::*;
521    use std::sync::{Mutex, MutexGuard, OnceLock};
522
523    #[test]
524    fn keyring_get_password_result_ok() {
525        assert_eq!(
526            super::keyring_get_password_result("API_TOKEN", Ok("secret".into())),
527            Some("secret".into())
528        );
529    }
530
531    #[test]
532    fn keyring_get_password_result_no_entry_is_none() {
533        assert_eq!(
534            super::keyring_get_password_result("API_TOKEN", Err(keyring::Error::NoEntry)),
535            None
536        );
537    }
538
539    fn env_lock() -> &'static Mutex<()> {
540        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
541        LOCK.get_or_init(|| Mutex::new(()))
542    }
543
544    struct TestEnv {
545        _guard: MutexGuard<'static, ()>,
546        config_dir: PathBuf,
547    }
548
549    impl TestEnv {
550        fn new() -> Self {
551            let guard = env_lock().lock().expect("env lock");
552            clear_auth_env();
553
554            let ts = std::time::SystemTime::now()
555                .duration_since(std::time::UNIX_EPOCH)
556                .unwrap()
557                .as_nanos();
558            let config_dir = std::env::temp_dir().join(format!("romm-config-test-{ts}"));
559            std::fs::create_dir_all(&config_dir).unwrap();
560            std::env::set_var("ROMM_TEST_CONFIG_DIR", &config_dir);
561
562            Self {
563                _guard: guard,
564                config_dir,
565            }
566        }
567    }
568
569    impl Drop for TestEnv {
570        fn drop(&mut self) {
571            clear_auth_env();
572            std::env::remove_var("ROMM_TEST_CONFIG_DIR");
573            let _ = std::fs::remove_dir_all(&self.config_dir);
574        }
575    }
576
577    fn clear_auth_env() {
578        for key in [
579            "API_BASE_URL",
580            "API_USERNAME",
581            "API_PASSWORD",
582            "API_TOKEN",
583            "ROMM_TOKEN_FILE",
584            "API_TOKEN_FILE",
585            "API_KEY",
586            "API_KEY_HEADER",
587            "API_USE_HTTPS",
588            "ROMM_TEST_CONFIG_DIR",
589        ] {
590            std::env::remove_var(key);
591        }
592    }
593
594    #[test]
595    fn prefers_basic_auth_over_other_modes() {
596        let _env = TestEnv::new();
597        std::env::set_var("API_BASE_URL", "http://example.test");
598        std::env::set_var("API_USERNAME", "user");
599        std::env::set_var("API_PASSWORD", "pass");
600        std::env::set_var("API_TOKEN", "token");
601        std::env::set_var("API_KEY", "apikey");
602        std::env::set_var("API_KEY_HEADER", "X-Api-Key");
603
604        let cfg = load_config().expect("config should load");
605        match cfg.auth {
606            Some(AuthConfig::Basic { username, password }) => {
607                assert_eq!(username, "user");
608                assert_eq!(password, "pass");
609            }
610            _ => panic!("expected basic auth"),
611        }
612    }
613
614    #[test]
615    fn uses_api_key_header_when_token_missing() {
616        let _env = TestEnv::new();
617        std::env::set_var("API_BASE_URL", "http://example.test");
618        std::env::set_var("API_KEY", "real-key");
619        std::env::set_var("API_KEY_HEADER", "X-Api-Key");
620
621        let cfg = load_config().expect("config should load");
622        match cfg.auth {
623            Some(AuthConfig::ApiKey { header, key }) => {
624                assert_eq!(header, "X-Api-Key");
625                assert_eq!(key, "real-key");
626            }
627            _ => panic!("expected api key auth"),
628        }
629    }
630
631    #[test]
632    fn normalizes_api_base_url_and_enforces_https_by_default() {
633        let _env = TestEnv::new();
634        std::env::set_var("API_BASE_URL", "http://romm.example/api/");
635        let cfg = load_config().expect("config");
636        // Upgraded to https by default
637        assert_eq!(cfg.base_url, "https://romm.example");
638    }
639
640    #[test]
641    fn does_not_enforce_https_if_toggle_is_false() {
642        let _env = TestEnv::new();
643        std::env::set_var("API_BASE_URL", "http://romm.example/api/");
644        std::env::set_var("API_USE_HTTPS", "false");
645        let cfg = load_config().expect("config");
646        assert_eq!(cfg.base_url, "http://romm.example");
647    }
648
649    #[test]
650    fn normalize_romm_origin_trims_and_strips_api_suffix() {
651        assert_eq!(
652            normalize_romm_origin("http://localhost:8080/api/"),
653            "http://localhost:8080"
654        );
655        assert_eq!(
656            normalize_romm_origin("https://x.example"),
657            "https://x.example"
658        );
659    }
660
661    #[test]
662    fn empty_api_username_does_not_enable_basic() {
663        let _env = TestEnv::new();
664        std::env::set_var("API_BASE_URL", "http://example.test");
665        std::env::set_var("API_USERNAME", "");
666        std::env::set_var("API_PASSWORD", "secret");
667
668        let cfg = load_config().expect("config should load");
669        assert!(
670            cfg.auth.is_none(),
671            "empty API_USERNAME should not pair with password for Basic"
672        );
673    }
674
675    #[test]
676    fn ignores_placeholder_bearer_token() {
677        let _env = TestEnv::new();
678        std::env::set_var("API_BASE_URL", "http://example.test");
679        std::env::set_var("API_TOKEN", "your-bearer-token-here");
680
681        let cfg = load_config().expect("config should load");
682        assert!(cfg.auth.is_none(), "placeholder token should be ignored");
683    }
684
685    #[test]
686    fn loads_from_user_json_file() {
687        let env = TestEnv::new();
688        let config_json = r#"{
689            "base_url": "http://from-json-file.test",
690            "download_dir": "/tmp/downloads",
691            "use_https": false,
692            "auth": null
693        }"#;
694
695        std::fs::write(env.config_dir.join("config.json"), config_json).unwrap();
696
697        let cfg = load_config().expect("load from user config.json");
698        assert_eq!(cfg.base_url, "http://from-json-file.test");
699        assert_eq!(cfg.download_dir, "/tmp/downloads");
700        assert!(!cfg.use_https);
701    }
702
703    #[test]
704    fn auth_for_persist_merge_prefers_in_memory() {
705        let env = TestEnv::new();
706        let on_disk = r#"{
707            "base_url": "http://disk.test",
708            "download_dir": "/tmp",
709            "use_https": false,
710            "auth": { "Bearer": { "token": "from-disk" } }
711        }"#;
712        std::fs::write(env.config_dir.join("config.json"), on_disk).unwrap();
713
714        let mem = Some(AuthConfig::Bearer {
715            token: "from-memory".into(),
716        });
717        let merged = auth_for_persist_merge(mem.clone());
718        assert_eq!(format!("{:?}", merged), format!("{:?}", mem));
719    }
720
721    #[test]
722    fn auth_for_persist_merge_falls_back_to_disk_when_memory_empty() {
723        let env = TestEnv::new();
724        let on_disk = r#"{
725            "base_url": "http://disk.test",
726            "download_dir": "/tmp",
727            "use_https": false,
728            "auth": { "Bearer": { "token": "<stored-in-keyring>" } }
729        }"#;
730        std::fs::write(env.config_dir.join("config.json"), on_disk).unwrap();
731
732        let merged = auth_for_persist_merge(None);
733        match merged {
734            Some(AuthConfig::Bearer { token }) => {
735                assert_eq!(token, KEYRING_SECRET_PLACEHOLDER);
736            }
737            _ => panic!("expected bearer auth from disk"),
738        }
739    }
740
741    #[test]
742    fn bearer_keyring_sentinel_without_keyring_entry_yields_no_auth() {
743        let env = TestEnv::new();
744        std::env::set_var("API_BASE_URL", "http://example.test");
745        let config_json = r#"{
746            "base_url": "http://example.test",
747            "download_dir": "/tmp",
748            "use_https": false,
749            "auth": { "Bearer": { "token": "<stored-in-keyring>" } }
750        }"#;
751        std::fs::write(env.config_dir.join("config.json"), config_json).unwrap();
752
753        let cfg = load_config().expect("load");
754        assert!(
755            cfg.auth.is_none(),
756            "unresolved keyring sentinel must not become Bearer auth in Config"
757        );
758        assert!(disk_has_unresolved_keyring_sentinel(&cfg));
759    }
760
761    #[test]
762    fn bearer_token_from_romm_token_file() {
763        let env = TestEnv::new();
764        let token_path = env.config_dir.join("secret.token");
765        std::fs::write(&token_path, "  tok-from-file\n").unwrap();
766        std::env::set_var("API_BASE_URL", "http://example.test");
767        std::env::set_var("ROMM_TOKEN_FILE", token_path.to_str().unwrap());
768
769        let cfg = load_config().expect("load");
770        match cfg.auth {
771            Some(AuthConfig::Bearer { token }) => assert_eq!(token, "tok-from-file"),
772            _ => panic!("expected bearer from token file"),
773        }
774    }
775
776    #[test]
777    fn api_token_env_wins_over_token_file() {
778        let env = TestEnv::new();
779        let token_path = env.config_dir.join("secret.token");
780        std::fs::write(&token_path, "from-file").unwrap();
781        std::env::set_var("API_BASE_URL", "http://example.test");
782        std::env::set_var("ROMM_TOKEN_FILE", token_path.to_str().unwrap());
783        std::env::set_var("API_TOKEN", "from-env");
784
785        let cfg = load_config().expect("load");
786        match cfg.auth {
787            Some(AuthConfig::Bearer { token }) => assert_eq!(token, "from-env"),
788            _ => panic!("expected env API_TOKEN to win"),
789        }
790    }
791
792    #[test]
793    fn romm_token_file_overrides_json_bearer() {
794        let env = TestEnv::new();
795        let token_path = env.config_dir.join("secret.token");
796        std::fs::write(&token_path, "from-file").unwrap();
797        std::env::set_var("API_BASE_URL", "http://example.test");
798        std::env::set_var("ROMM_TOKEN_FILE", token_path.to_str().unwrap());
799        let config_json = r#"{
800            "base_url": "http://example.test",
801            "download_dir": "/tmp",
802            "use_https": false,
803            "auth": { "Bearer": { "token": "from-json" } }
804        }"#;
805        std::fs::write(env.config_dir.join("config.json"), config_json).unwrap();
806
807        let cfg = load_config().expect("load");
808        match cfg.auth {
809            Some(AuthConfig::Bearer { token }) => assert_eq!(token, "from-file"),
810            _ => panic!("expected token file to override json"),
811        }
812    }
813
814    #[test]
815    fn romm_token_file_missing_errors() {
816        let env = TestEnv::new();
817        let missing = env.config_dir.join("this-token-file-does-not-exist");
818        std::env::set_var("API_BASE_URL", "http://example.test");
819        std::env::set_var("ROMM_TOKEN_FILE", missing.to_str().unwrap());
820
821        let err = load_config().expect_err("missing token file should error");
822        let msg = format!("{err:#}");
823        assert!(
824            msg.contains("read bearer token file"),
825            "unexpected error: {msg}"
826        );
827    }
828
829    #[test]
830    fn romm_token_file_empty_errors() {
831        let env = TestEnv::new();
832        let token_path = env.config_dir.join("empty.token");
833        std::fs::write(&token_path, "   \n\t  ").unwrap();
834        std::env::set_var("API_BASE_URL", "http://example.test");
835        std::env::set_var("ROMM_TOKEN_FILE", token_path.to_str().unwrap());
836
837        let err = load_config().expect_err("empty token file should error");
838        assert!(
839            format!("{err:#}").contains("empty"),
840            "unexpected error: {err:#}"
841        );
842    }
843
844    #[test]
845    fn romm_token_file_too_large_errors() {
846        let env = TestEnv::new();
847        let token_path = env.config_dir.join("huge.token");
848        std::fs::write(&token_path, vec![b'a'; MAX_TOKEN_FILE_BYTES + 1]).unwrap();
849        std::env::set_var("API_BASE_URL", "http://example.test");
850        std::env::set_var("ROMM_TOKEN_FILE", token_path.to_str().unwrap());
851
852        let err = load_config().expect_err("oversized token file should error");
853        assert!(
854            format!("{err:#}").contains("max size"),
855            "unexpected error: {err:#}"
856        );
857    }
858
859    /// When auth is merged from disk as [`KEYRING_SECRET_PLACEHOLDER`], persist must not call
860    /// `keyring_store` with that literal (would overwrite the real vault entry). JSON should still
861    /// contain the sentinel and updated non-auth fields.
862    #[test]
863    fn persist_user_config_preserves_sentinel_secrets_in_json() {
864        let env = TestEnv::new();
865        let path = env.config_dir.join("config.json");
866
867        persist_user_config(
868            "https://updated.example",
869            "/var/romm-dl",
870            true,
871            Some(AuthConfig::Bearer {
872                token: KEYRING_SECRET_PLACEHOLDER.to_string(),
873            }),
874        )
875        .expect("persist bearer sentinel");
876
877        let cfg: Config = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
878        assert_eq!(cfg.base_url, "https://updated.example");
879        assert_eq!(cfg.download_dir, "/var/romm-dl");
880        assert!(cfg.use_https);
881        match cfg.auth {
882            Some(AuthConfig::Bearer { token }) => {
883                assert_eq!(token, KEYRING_SECRET_PLACEHOLDER);
884            }
885            _ => panic!("expected bearer sentinel preserved in config.json"),
886        }
887
888        persist_user_config(
889            "https://apikey.example",
890            "/dl",
891            false,
892            Some(AuthConfig::ApiKey {
893                header: "X-Api-Key".into(),
894                key: KEYRING_SECRET_PLACEHOLDER.to_string(),
895            }),
896        )
897        .expect("persist api key sentinel");
898
899        let cfg: Config = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
900        assert_eq!(cfg.base_url, "https://apikey.example");
901        match cfg.auth {
902            Some(AuthConfig::ApiKey { header, key }) => {
903                assert_eq!(header, "X-Api-Key");
904                assert_eq!(key, KEYRING_SECRET_PLACEHOLDER);
905            }
906            _ => panic!("expected api key sentinel preserved"),
907        }
908
909        persist_user_config(
910            "https://basic.example",
911            "/dl",
912            true,
913            Some(AuthConfig::Basic {
914                username: "alice".into(),
915                password: KEYRING_SECRET_PLACEHOLDER.to_string(),
916            }),
917        )
918        .expect("persist basic password sentinel");
919
920        let cfg: Config = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
921        assert_eq!(cfg.base_url, "https://basic.example");
922        match cfg.auth {
923            Some(AuthConfig::Basic { username, password }) => {
924                assert_eq!(username, "alice");
925                assert_eq!(password, KEYRING_SECRET_PLACEHOLDER);
926            }
927            _ => panic!("expected basic password sentinel preserved"),
928        }
929    }
930}