Skip to main content

docsrs_cli/config/
load.rs

1//! Config load/init, XDG paths, and TOML schema (`deny_unknown_fields`).
2
3use std::fs;
4use std::io::Write;
5use std::path::{Path, PathBuf};
6use std::time::Duration;
7
8use serde::{Deserialize, Serialize};
9
10use crate::domain::{AllowedOrigin, CrateName};
11use crate::error::{AppError, AppResult, ErrorKind};
12use crate::platform::{restrict_private_dir, restrict_private_file};
13
14use super::constants::*;
15use super::path_source::{PathSource, resolve_config_dir_with_source};
16use super::validate::{default_user_agent, validate_contact, validate_user_agent};
17
18/// Default `config.toml` body written by `config init` (commented template).
19///
20/// Values are documentation only until the user uncomments. Runtime still
21/// applies defaults when keys are absent. No secrets — product is public HTTP.
22///
23/// Version and contact URL come from [`APP_VERSION`] / [`DEFAULT_CONTACT_URL`]
24/// (`Cargo.toml`) so the template never pins a stale release string.
25pub fn default_config_toml() -> String {
26    format!(
27        r#"# docsrs-cli XDG configuration
28# Precedence: CLI flags > this file (XDG) > built-in defaults.
29# Path: …/docsrs-cli/config.toml (platform XDG / AppData / Library).
30# No .env file is required after cargo install. Product stores no API keys.
31#
32# Product knobs (timeout, UA, retries, budgets, origins, concurrency, cache TTL,
33# paths, lang) are read ONLY from CLI flags and this TOML — never from product
34# environment variables. Isolate storage with --config-dir / --cache-dir.
35#
36# Host diagnostics / proxy (not product knobs — OS env only):
37#   RUST_LOG, NO_COLOR, HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, NO_PROXY
38# HTTP client honors system proxy via reqwest feature `system-proxy`.
39#
40# timeout_secs = {DEFAULT_TIMEOUT_SECS}
41# connect_timeout_secs = {DEFAULT_CONNECT_TIMEOUT_SECS}
42# max_body_bytes = {DEFAULT_MAX_BODY_BYTES}
43# max_output_bytes = {DEFAULT_MAX_OUTPUT_BYTES}
44# max_redirects = {DEFAULT_MAX_REDIRECTS}
45# max_retries = {DEFAULT_MAX_RETRIES}
46# retry_base_ms = {DEFAULT_RETRY_BASE_MS}
47# retry_max_delay_ms = {DEFAULT_RETRY_MAX_DELAY_MS}
48# retry_max_elapsed_ms = 0   # 0 = derive from timeout_secs (ms); hard cap 300000
49# disable_retry = false
50# rate_limit_delay_ms = {DEFAULT_RATE_LIMIT_DELAY_MS}
51# max_concurrency = 0
52# user_agent = "{APP_NAME}/{APP_VERSION} (+{DEFAULT_CONTACT_URL})"
53# contact = "{DEFAULT_CONTACT_URL}"
54# lang = "en"
55# crates_io_origin = "{SCHEME_HTTPS}://{HOST_CRATES_IO}"
56# docs_rs_origin = "{SCHEME_HTTPS}://{HOST_DOCS_RS}"
57# allow_loopback = false   # true only for offline wiremock (CLI --allow-loopback also works)
58# cache_ttl_secs = {DEFAULT_CACHE_TTL_SECS}
59# max_cache_bytes = {DEFAULT_MAX_CACHE_BYTES}
60# no_cache = false
61"#
62    )
63}
64
65/// Runtime configuration resolved from defaults, XDG TOML, and CLI flags.
66#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct Config {
68    /// Wall-clock timeout in seconds for one operation.
69    pub timeout_secs: u64,
70    /// TCP connect timeout in seconds.
71    pub connect_timeout_secs: u64,
72    /// Maximum downloaded HTTP body size in bytes.
73    pub max_body_bytes: u64,
74    /// Maximum emitted stdout payload size in bytes.
75    pub max_output_bytes: u64,
76    /// Maximum HTTP redirects followed.
77    pub max_redirects: u32,
78    /// Maximum retries for transient HTTP errors.
79    pub max_retries: u32,
80    /// Base backoff delay in milliseconds between retries.
81    pub retry_base_ms: u64,
82    /// Ceiling for a single retry sleep in milliseconds.
83    pub retry_max_delay_ms: u64,
84    /// Total retry loop wall budget in milliseconds (`0` = derive from `timeout_secs`).
85    pub retry_max_elapsed_ms: u64,
86    /// Kill switch: when true, HTTP never retries (incident / debug).
87    pub disable_retry: bool,
88    /// Minimum delay between requests to the same host in milliseconds.
89    pub rate_limit_delay_ms: u64,
90    /// Max concurrent CPU (`spawn_blocking`) tasks; `0` = auto from CPUs/RAM.
91    ///
92    /// See [`crate::concurrency::resolve_max_concurrency`].
93    pub max_concurrency: u32,
94    /// HTTP User-Agent header value.
95    pub user_agent: String,
96    /// Optional contact URL or email embedded in the default User-Agent.
97    pub contact: Option<String>,
98    /// Preferred human-message locale (`en` or `pt-BR`).
99    pub lang: Option<String>,
100    /// Resolved XDG (or override) config directory.
101    pub config_dir: Option<PathBuf>,
102    /// XDG (or override) root for HTTP response cache between process runs.
103    pub cache_dir: Option<PathBuf>,
104    /// Disk cache TTL in seconds (default 24h).
105    pub cache_ttl_secs: u64,
106    /// Soft cap on disk cache size in bytes (`0` = unlimited).
107    pub max_cache_bytes: u64,
108    /// When true, skip disk cache read/write (`--no-cache`).
109    pub no_cache: bool,
110    /// Origin for crates.io API (default `https://crates.io`). Overridable for offline mocks.
111    pub crates_io_origin: AllowedOrigin,
112    /// Origin for docs.rs pages (default `https://docs.rs`). Overridable for offline mocks.
113    pub docs_rs_origin: AllowedOrigin,
114    /// When true, SSRF allowlist accepts loopback (`127.0.0.1` / `localhost`) for offline mocks.
115    ///
116    /// Set only via XDG `config.toml` (`allow_loopback = true`) or CLI `--allow-loopback`.
117    /// Never read from environment variables (ADR 0009).
118    pub allow_loopback: bool,
119    /// Layer that resolved [`Self::config_dir`].
120    pub config_path_source: PathSource,
121    /// Layer that resolved [`Self::cache_dir`].
122    pub cache_path_source: PathSource,
123    /// True when `config.toml` existed and was applied during load.
124    pub config_toml_loaded: bool,
125}
126
127impl Default for Config {
128    fn default() -> Self {
129        // Contact comes from TOML `contact` or CLI `--user-agent`, not process env.
130        let contact: Option<String> = None;
131        let ua = default_user_agent(contact.as_deref());
132        Self {
133            timeout_secs: DEFAULT_TIMEOUT_SECS,
134            connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT_SECS,
135            max_body_bytes: DEFAULT_MAX_BODY_BYTES,
136            max_output_bytes: DEFAULT_MAX_OUTPUT_BYTES,
137            max_redirects: DEFAULT_MAX_REDIRECTS,
138            max_retries: DEFAULT_MAX_RETRIES,
139            retry_base_ms: DEFAULT_RETRY_BASE_MS,
140            retry_max_delay_ms: DEFAULT_RETRY_MAX_DELAY_MS,
141            retry_max_elapsed_ms: DEFAULT_RETRY_MAX_ELAPSED_MS,
142            disable_retry: false,
143            rate_limit_delay_ms: DEFAULT_RATE_LIMIT_DELAY_MS,
144            max_concurrency: 0,
145            user_agent: ua,
146            contact,
147            lang: None,
148            config_dir: None,
149            cache_dir: None,
150            cache_ttl_secs: DEFAULT_CACHE_TTL_SECS,
151            max_cache_bytes: DEFAULT_MAX_CACHE_BYTES,
152            no_cache: false,
153            crates_io_origin: AllowedOrigin::crates_io_default(),
154            docs_rs_origin: AllowedOrigin::docs_rs_default(),
155            allow_loopback: false,
156            config_path_source: PathSource::Unresolved,
157            cache_path_source: PathSource::Unresolved,
158            config_toml_loaded: false,
159        }
160    }
161}
162
163/// Read `config.toml` with a hard size cap (poisoned-config / TOML bomb guard).
164///
165/// Uses `fs::read` + length check (not unbounded `read_to_string`). Metadata
166/// size is an early reject; the post-read length is authoritative (TOCTOU-safe).
167///
168/// # Errors
169///
170/// Returns [`ErrorKind::Config`] when the file is unreadable, over
171/// [`MAX_CONFIG_TOML_BYTES`], or not valid UTF-8.
172fn read_config_toml_capped(path: &Path) -> AppResult<String> {
173    if let Ok(meta) = fs::metadata(path)
174        && meta.len() > MAX_CONFIG_TOML_BYTES
175    {
176        return Err(AppError::new(
177            ErrorKind::Config,
178            format!(
179                "config.toml exceeds max size ({MAX_CONFIG_TOML_BYTES} bytes)"
180            ),
181        ));
182    }
183    let bytes = fs::read(path).map_err(|e| {
184        AppError::with_source(
185            ErrorKind::Config,
186            format!("failed to read {}", path.display()),
187            e,
188        )
189    })?;
190    if (bytes.len() as u64) > MAX_CONFIG_TOML_BYTES {
191        return Err(AppError::new(
192            ErrorKind::Config,
193            format!(
194                "config.toml exceeds max size ({MAX_CONFIG_TOML_BYTES} bytes)"
195            ),
196        ));
197    }
198    String::from_utf8(bytes).map_err(|e| {
199        AppError::with_source(
200            ErrorKind::Config,
201            "config.toml is not valid UTF-8",
202            e,
203        )
204    })
205}
206
207
208/// XDG `config.toml` keys only — unknown keys fail closed (typo ≠ silent ignore).
209#[derive(Debug, Default, Deserialize)]
210#[serde(deny_unknown_fields)]
211struct TomlConfig {
212    timeout_secs: Option<u64>,
213    connect_timeout_secs: Option<u64>,
214    max_body_bytes: Option<u64>,
215    max_output_bytes: Option<u64>,
216    max_redirects: Option<u32>,
217    max_retries: Option<u32>,
218    retry_base_ms: Option<u64>,
219    retry_max_delay_ms: Option<u64>,
220    retry_max_elapsed_ms: Option<u64>,
221    disable_retry: Option<bool>,
222    rate_limit_delay_ms: Option<u64>,
223    max_concurrency: Option<u32>,
224    user_agent: Option<String>,
225    contact: Option<String>,
226    lang: Option<String>,
227    crates_io_origin: Option<String>,
228    docs_rs_origin: Option<String>,
229    allow_loopback: Option<bool>,
230    cache_ttl_secs: Option<u64>,
231    max_cache_bytes: Option<u64>,
232    no_cache: Option<bool>,
233}
234
235impl Config {
236    /// Loads configuration with an optional config-directory override.
237    ///
238    /// # Errors
239    ///
240    /// Returns [`ErrorKind::Config`] when the TOML file is unreadable or invalid.
241    pub fn load(config_dir_override: Option<PathBuf>) -> AppResult<Self> {
242        Self::load_with_cache_dir(config_dir_override, None)
243    }
244
245    /// Load config with optional config-dir and cache-dir overrides (CLI / tests).
246    ///
247    /// # Errors
248    ///
249    /// Returns [`ErrorKind::Config`] when `config.toml` is unreadable or invalid TOML.
250    pub fn load_with_cache_dir(
251        config_dir_override: Option<PathBuf>,
252        cache_dir_override: Option<PathBuf>,
253    ) -> AppResult<Self> {
254        Self::load_with_options(config_dir_override, cache_dir_override, false)
255    }
256
257    /// Load config with optional path overrides and a CLI loopback seed.
258    ///
259    /// `allow_loopback` is applied **before** TOML origin parsing so
260    /// `--allow-loopback` works with mock origins in the same invocation
261    /// (ADR 0009 — never via env).
262    ///
263    /// # Errors
264    ///
265    /// Returns [`ErrorKind::Config`] when `config.toml` is unreadable or invalid TOML.
266    pub fn load_with_options(
267        config_dir_override: Option<PathBuf>,
268        cache_dir_override: Option<PathBuf>,
269        allow_loopback: bool,
270    ) -> AppResult<Self> {
271        let mut cfg = Self::default();
272        if allow_loopback {
273            cfg.allow_loopback = true;
274        }
275
276        let (config_dir, config_source) = resolve_config_dir_with_source(config_dir_override);
277        cfg.config_path_source = config_source;
278
279        let (cache_dir, cache_source) =
280            crate::cache::resolve_cache_dir_with_source(cache_dir_override);
281        cfg.cache_dir = cache_dir;
282        cfg.cache_path_source = cache_source;
283
284        // Borrow for TOML load, then move into `cfg` (no PathBuf clone).
285        if let Some(dir) = &config_dir {
286            let path = dir.join("config.toml");
287            if path.is_file() {
288                let text = read_config_toml_capped(&path)?;
289                let parsed: TomlConfig = toml::from_str(&text).map_err(|e| {
290                    AppError::with_source(ErrorKind::Config, "invalid config.toml", e)
291                })?;
292                cfg.apply_toml(parsed)?;
293                cfg.config_toml_loaded = true;
294            }
295        }
296        cfg.config_dir = config_dir;
297
298        cfg.apply_cache_path_defaults()?;
299        cfg.clamp_resource_limits();
300        cfg.validate_security()?;
301        Ok(cfg)
302    }
303
304    /// Re-validate origin fields after TOML/CLI mutation (fail-fast config).
305    ///
306    /// # Errors
307    ///
308    /// Returns [`ErrorKind::Config`] when either origin is not a valid allowlisted
309    /// HTTP(S) URL (SSRF gate at config boundary).
310    pub fn validate_origins(&mut self) -> AppResult<()> {
311        // Re-parse to re-assert allowlist proof after any TOML/CLI mutation path.
312        self.crates_io_origin =
313            AllowedOrigin::parse_with(self.crates_io_origin.as_str(), self.allow_loopback)?;
314        self.docs_rs_origin =
315            AllowedOrigin::parse_with(self.docs_rs_origin.as_str(), self.allow_loopback)?;
316        Ok(())
317    }
318
319    /// Validate security-sensitive config fields (origins + User-Agent + contact).
320    ///
321    /// # Errors
322    ///
323    /// Returns [`ErrorKind::Config`] on allowlist, contact, or User-Agent policy failures.
324    pub fn validate_security(&mut self) -> AppResult<()> {
325        self.validate_origins()?;
326        if let Some(c) = &self.contact {
327            validate_contact(c)?;
328        }
329        // Rebuild UA from contact when UA was not explicitly set from a prior
330        // explicit user_agent key path — contact may have been applied already
331        // in `apply_toml`; always re-check the effective header string.
332        validate_user_agent(&self.user_agent)?;
333        Ok(())
334    }
335
336    /// Absolute path to `config.toml` under the resolved config directory, if any.
337    pub fn config_file_path(&self) -> Option<PathBuf> {
338        self.config_dir.as_ref().map(|d| d.join("config.toml"))
339    }
340
341    /// Clamp resource budgets to hard safety ceilings (defense in depth).
342    ///
343    /// Call after every mutation path (TOML, CLI). Operator-facing surfaces
344    /// (**CLI flags** and **TOML** body/output keys) reject values above
345    /// [`HARD_MAX_BODY_BYTES`] / [`HARD_MAX_OUTPUT_BYTES`] before this runs
346    /// (GAP-X-005). This method remains a last-line cap for other knobs and
347    /// accidental internal elevations. Zero body/output is left as-is
348    /// (fail-closed for body reads).
349    pub fn clamp_resource_limits(&mut self) {
350        self.max_body_bytes = self.max_body_bytes.min(HARD_MAX_BODY_BYTES);
351        self.max_output_bytes = self.max_output_bytes.min(HARD_MAX_OUTPUT_BYTES);
352        self.max_retries = self.max_retries.min(crate::retry::HARD_MAX_RETRIES);
353        self.max_redirects = self.max_redirects.min(HARD_MAX_REDIRECTS);
354        // Zero timeouts are rejected at CLI boundary; clamp absurd ceilings here.
355        if self.timeout_secs > HARD_MAX_TIMEOUT_SECS {
356            self.timeout_secs = HARD_MAX_TIMEOUT_SECS;
357        }
358        if self.connect_timeout_secs > HARD_MAX_CONNECT_TIMEOUT_SECS {
359            self.connect_timeout_secs = HARD_MAX_CONNECT_TIMEOUT_SECS;
360        }
361        if self.connect_timeout_secs > self.timeout_secs && self.timeout_secs > 0 {
362            self.connect_timeout_secs = self.timeout_secs;
363        }
364        if self.rate_limit_delay_ms > HARD_MAX_RATE_LIMIT_DELAY_MS {
365            self.rate_limit_delay_ms = HARD_MAX_RATE_LIMIT_DELAY_MS;
366        }
367        if self.retry_base_ms == 0 {
368            self.retry_base_ms = DEFAULT_RETRY_BASE_MS;
369        } else if self.retry_base_ms < crate::retry::MIN_RETRY_BASE_MS {
370            // Rules: never configure initial backoff below 50ms.
371            self.retry_base_ms = crate::retry::MIN_RETRY_BASE_MS;
372        }
373        if self.retry_max_delay_ms == 0 {
374            self.retry_max_delay_ms = DEFAULT_RETRY_MAX_DELAY_MS;
375        }
376        self.retry_max_delay_ms = self
377            .retry_max_delay_ms
378            .min(crate::retry::HARD_MAX_DELAY_MS)
379            .max(self.retry_base_ms);
380        // `0` keeps "derive from timeout" semantics in RetryConfig::from_config.
381        if self.retry_max_elapsed_ms > 0 {
382            self.retry_max_elapsed_ms = self
383                .retry_max_elapsed_ms
384                .min(crate::retry::HARD_MAX_ELAPSED_MS)
385                .max(self.retry_max_delay_ms);
386        }
387        // Soft-cap oversized UA strings (full charset validation is `validate_user_agent`).
388        if self.user_agent.chars().count() > MAX_USER_AGENT_CHARS {
389            self.user_agent = self
390                .user_agent
391                .chars()
392                .take(MAX_USER_AGENT_CHARS)
393                .collect();
394        }
395    }
396
397    fn apply_toml(&mut self, t: TomlConfig) -> AppResult<()> {
398        if let Some(v) = t.timeout_secs {
399            self.timeout_secs = v;
400        }
401        if let Some(v) = t.connect_timeout_secs {
402            self.connect_timeout_secs = v;
403        }
404        if let Some(v) = t.max_body_bytes {
405            // Fail-closed for operator honesty (GAP-X-005): TOML cannot raise above HARD_MAX.
406            if v > HARD_MAX_BODY_BYTES {
407                return Err(AppError::new(
408                    ErrorKind::Config,
409                    format!("max_body_bytes exceeds hard maximum ({HARD_MAX_BODY_BYTES})"),
410                ));
411            }
412            self.max_body_bytes = v;
413        }
414        if let Some(v) = t.max_output_bytes {
415            if v > HARD_MAX_OUTPUT_BYTES {
416                return Err(AppError::new(
417                    ErrorKind::Config,
418                    format!("max_output_bytes exceeds hard maximum ({HARD_MAX_OUTPUT_BYTES})"),
419                ));
420            }
421            self.max_output_bytes = v;
422        }
423        if let Some(v) = t.max_redirects {
424            self.max_redirects = v;
425        }
426        if let Some(v) = t.max_retries {
427            self.max_retries = v;
428        }
429        if let Some(v) = t.retry_base_ms {
430            self.retry_base_ms = v;
431        }
432        if let Some(v) = t.retry_max_delay_ms {
433            self.retry_max_delay_ms = v;
434        }
435        if let Some(v) = t.retry_max_elapsed_ms {
436            self.retry_max_elapsed_ms = v;
437        }
438        if let Some(v) = t.disable_retry {
439            self.disable_retry = v;
440        }
441        if let Some(v) = t.rate_limit_delay_ms {
442            self.rate_limit_delay_ms = v;
443        }
444        if let Some(v) = t.max_concurrency {
445            self.max_concurrency = v;
446        }
447        if let Some(v) = t.contact {
448            self.contact = Some(v);
449        }
450        if let Some(v) = t.user_agent {
451            self.user_agent = v;
452        } else if let Some(c) = &self.contact {
453            self.user_agent = default_user_agent(Some(c));
454        }
455        if let Some(v) = t.lang {
456            self.lang = Some(v);
457        }
458        // Apply loopback gate before parsing origins so mock hosts validate.
459        if let Some(v) = t.allow_loopback {
460            self.allow_loopback = v;
461        }
462        if let Some(v) = t.crates_io_origin {
463            self.crates_io_origin = AllowedOrigin::parse_with(&v, self.allow_loopback)?;
464        }
465        if let Some(v) = t.docs_rs_origin {
466            self.docs_rs_origin = AllowedOrigin::parse_with(&v, self.allow_loopback)?;
467        }
468        if let Some(v) = t.cache_ttl_secs {
469            self.cache_ttl_secs = v;
470        }
471        if let Some(v) = t.max_cache_bytes {
472            self.max_cache_bytes = v;
473        }
474        if let Some(v) = t.no_cache {
475            self.no_cache = v;
476        }
477        Ok(())
478    }
479
480    /// Resolve cache path when still unset (XDG / test sandbox).
481    ///
482    /// Resolve cache path defaults from CLI override / XDG only (no product env).
483    fn apply_cache_path_defaults(&mut self) -> AppResult<()> {
484        if self.cache_dir.is_none() {
485            let (dir, source) = crate::cache::resolve_cache_dir_with_source(None);
486            self.cache_dir = dir;
487            self.cache_path_source = source;
488        }
489        Ok(())
490    }
491}
492
493/// Result of `config init`.
494#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
495pub struct ConfigInitResult {
496    /// Absolute path written (or already present when not forced).
497    pub path: String,
498    /// Directory that holds the file.
499    pub config_dir: String,
500    /// Layer that resolved the directory.
501    pub source: PathSource,
502    /// True when the file was created or overwritten in this call.
503    pub created: bool,
504    /// True when an existing file was replaced (`--force`).
505    pub overwritten: bool,
506}
507
508/// Create default `config.toml` under the resolved config directory.
509///
510/// # Errors
511///
512/// - [`ErrorKind::Config`] when the directory cannot be resolved or created,
513///   when the file already exists without `force`, or on I/O failure.
514pub fn init_config_toml(
515    config_dir_override: Option<PathBuf>,
516    force: bool,
517) -> AppResult<ConfigInitResult> {
518    let (dir, source) = resolve_config_dir_with_source(config_dir_override);
519    let dir = dir.ok_or_else(|| {
520        AppError::new(
521            ErrorKind::Config,
522            "config directory could not be resolved (set --config-dir or ensure XDG config home)",
523        )
524    })?;
525    fs::create_dir_all(&dir).map_err(|e| {
526        AppError::with_source(
527            ErrorKind::Config,
528            format!("failed to create config dir {}", dir.display()),
529            e,
530        )
531    })?;
532    restrict_private_dir(&dir);
533
534    let path = dir.join("config.toml");
535    let existed = path.is_file();
536    if existed && !force {
537        return Err(AppError::new(
538            ErrorKind::Config,
539            format!(
540                "config already exists: {} (pass --force to overwrite)",
541                path.display()
542            ),
543        ));
544    }
545
546    // Atomic-ish write: tempfile in same dir then rename.
547    let tmp = dir.join("config.toml.docsrs-cli.tmp");
548    let template = default_config_toml();
549    {
550        let mut f = fs::File::create(&tmp).map_err(|e| {
551            AppError::with_source(
552                ErrorKind::Config,
553                format!("failed to create {}", tmp.display()),
554                e,
555            )
556        })?;
557        f.write_all(template.as_bytes()).map_err(|e| {
558            AppError::with_source(
559                ErrorKind::Config,
560                format!("failed to write {}", tmp.display()),
561                e,
562            )
563        })?;
564        f.sync_all().map_err(|e| {
565            AppError::with_source(
566                ErrorKind::Config,
567                format!("failed to sync {}", tmp.display()),
568                e,
569            )
570        })?;
571    }
572    restrict_private_file(&tmp);
573    fs::rename(&tmp, &path).map_err(|e| {
574        let _ = fs::remove_file(&tmp);
575        AppError::with_source(
576            ErrorKind::Config,
577            format!("failed to install {}", path.display()),
578            e,
579        )
580    })?;
581    restrict_private_file(&path);
582
583    Ok(ConfigInitResult {
584        path: path.display().to_string(),
585        config_dir: dir.display().to_string(),
586        source,
587        created: true,
588        overwritten: existed,
589    })
590}
591
592/// Path inventory for `config path` (agent-readable).
593#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
594pub struct ConfigPathData {
595    /// Resolved config directory, if any.
596    pub config_dir: Option<String>,
597    /// Layer that resolved the config directory.
598    pub config_source: PathSource,
599    /// Absolute `config.toml` path (even if the file does not exist yet).
600    pub config_file: Option<String>,
601    /// Whether `config.toml` is present on disk.
602    pub config_file_exists: bool,
603    /// Whether load applied TOML keys (same as exists for normal runs).
604    pub config_toml_loaded: bool,
605    /// Resolved cache directory, if any.
606    pub cache_dir: Option<String>,
607    /// Layer that resolved the cache directory.
608    pub cache_source: PathSource,
609    /// Product does not use `.env` at runtime after install.
610    pub dotenv_runtime: bool,
611    /// Product stores no API keys; keyring/cloud secret layers are unused.
612    pub secrets_layers: &'static str,
613}
614
615/// Build path inventory from a loaded [`Config`].
616pub fn config_path_data(cfg: &Config) -> ConfigPathData {
617    let config_file = cfg.config_file_path();
618    let exists = config_file.as_ref().is_some_and(|p| p.is_file());
619    ConfigPathData {
620        config_dir: cfg.config_dir.as_ref().map(|p| p.display().to_string()),
621        config_source: cfg.config_path_source,
622        config_file: config_file.as_ref().map(|p| p.display().to_string()),
623        config_file_exists: exists,
624        config_toml_loaded: cfg.config_toml_loaded,
625        cache_dir: cfg.cache_dir.as_ref().map(|p| p.display().to_string()),
626        cache_source: cfg.cache_path_source,
627        dotenv_runtime: false,
628        secrets_layers: "none (public HTTP only; no API keys)",
629    }
630}
631
632/// Ensure `path` is under a directory (used by tests / path display).
633pub fn config_toml_under(dir: &Path) -> PathBuf {
634    dir.join("config.toml")
635}
636
637impl Config {
638    /// Wall-clock timeout duration (at least one second).
639    pub fn timeout(&self) -> Duration {
640        Duration::from_secs(self.timeout_secs.max(1))
641    }
642
643    /// TCP connect timeout duration (at least one second).
644    pub fn connect_timeout(&self) -> Duration {
645        Duration::from_secs(self.connect_timeout_secs.max(1))
646    }
647
648    /// Per-host rate-limit delay duration.
649    pub fn rate_limit_delay(&self) -> Duration {
650        Duration::from_millis(self.rate_limit_delay_ms)
651    }
652
653    /// TTL for disk cache entries.
654    pub fn cache_ttl(&self) -> Duration {
655        Duration::from_secs(self.cache_ttl_secs)
656    }
657
658    /// Whether disk cache should be used for HTTP GET bodies.
659    pub fn cache_enabled(&self) -> bool {
660        !self.no_cache && self.cache_dir.is_some()
661    }
662}
663
664/// Resolve docs origin for a crate: stdlib → doc.rust-lang.org, else configured docs.rs origin.
665pub fn docs_origin_for_crate(cfg: &Config, crate_name: &CrateName) -> AllowedOrigin {
666    if crate_name.is_stdlib() {
667        AllowedOrigin::stdlib_docs_default()
668    } else {
669        cfg.docs_rs_origin.clone()
670    }
671}
672