Skip to main content

docsrs_cli/
config.rs

1//! Configuration: defaults, XDG TOML, env allowlist, CLI override.
2
3use std::fs;
4use std::io::Write;
5use std::path::{Path, PathBuf};
6use std::time::Duration;
7
8use directories::ProjectDirs;
9use serde::{Deserialize, Serialize};
10
11use crate::error::{AppError, AppResult, ErrorKind};
12use crate::platform::{restrict_private_dir, restrict_private_file};
13
14/// Default wall-clock timeout (seconds) for one operation.
15pub const DEFAULT_TIMEOUT_SECS: u64 = 30;
16/// Default TCP connect timeout (seconds).
17pub const DEFAULT_CONNECT_TIMEOUT_SECS: u64 = 10;
18/// Default maximum downloaded response body size (bytes).
19pub const DEFAULT_MAX_BODY_BYTES: u64 = 10_485_760;
20/// Hard ceiling for HTTP body size (CLI / TOML / env cannot raise above this).
21///
22/// Equal to [`DEFAULT_MAX_BODY_BYTES`] so operators may only lower the cap.
23/// Prevents multi-GiB allocations from untrusted Content-Length or config.
24pub const HARD_MAX_BODY_BYTES: u64 = DEFAULT_MAX_BODY_BYTES;
25/// Default maximum emitted stdout payload size (bytes).
26pub const DEFAULT_MAX_OUTPUT_BYTES: u64 = 2_097_152;
27/// Hard ceiling for emitted stdout payload size (CLI / TOML / env cannot raise above).
28pub const HARD_MAX_OUTPUT_BYTES: u64 = DEFAULT_MAX_OUTPUT_BYTES;
29/// Default maximum HTTP redirects followed.
30pub const DEFAULT_MAX_REDIRECTS: u32 = 5;
31/// Default maximum retries for transient HTTP errors.
32pub const DEFAULT_MAX_RETRIES: u32 = crate::retry::DEFAULT_MAX_RETRIES;
33/// Base backoff delay (milliseconds) for retries.
34pub const DEFAULT_RETRY_BASE_MS: u64 = crate::retry::DEFAULT_RETRY_BASE_MS;
35/// Default ceiling for a single retry sleep (milliseconds).
36pub const DEFAULT_RETRY_MAX_DELAY_MS: u64 = crate::retry::DEFAULT_RETRY_MAX_DELAY_MS;
37/// Default minimum delay between requests to the same host (milliseconds).
38pub const DEFAULT_RATE_LIMIT_DELAY_MS: u64 = 1000;
39/// Default `per_page` for crates.io search.
40pub const DEFAULT_PER_PAGE: u32 = 10;
41/// Default hit limit for search-in-crate.
42pub const DEFAULT_SEARCH_LIMIT: u32 = 100;
43/// Maximum `per_page` accepted for crates.io search.
44pub const MAX_PER_PAGE: u32 = 100;
45/// Maximum hit limit for search-in-crate.
46pub const MAX_SEARCH_IN_CRATE_LIMIT: u32 = 1000;
47/// Maximum query string length.
48pub const MAX_QUERY_CHARS: usize = 256;
49/// Maximum crate name length.
50pub const MAX_CRATE_NAME_CHARS: usize = 64;
51/// Maximum rustdoc item path length.
52pub const MAX_ITEM_PATH_CHARS: usize = 512;
53/// Maximum version string length.
54pub const MAX_VERSION_CHARS: usize = 64;
55/// Maximum User-Agent length.
56pub const MAX_USER_AGENT_CHARS: usize = 256;
57/// Default HTTP disk cache TTL (seconds).
58pub const DEFAULT_CACHE_TTL_SECS: u64 = crate::cache::DEFAULT_CACHE_TTL_SECS;
59/// Default HTTP disk cache budget in bytes (256 MiB). `0` = unlimited.
60pub const DEFAULT_MAX_CACHE_BYTES: u64 = crate::cache::DEFAULT_MAX_CACHE_BYTES;
61/// Product binary / crate name.
62pub const APP_NAME: &str = "docsrs-cli";
63/// Package version from Cargo.
64pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
65/// Minimum supported Rust version.
66pub const MSRV: &str = "1.88.0";
67/// JSON envelope `schema_version` constant.
68pub const SCHEMA_VERSION: u32 = 1;
69
70/// crates.io host allowlist entry.
71pub const HOST_CRATES_IO: &str = "crates.io";
72/// docs.rs host allowlist entry.
73pub const HOST_DOCS_RS: &str = "docs.rs";
74/// static.docs.rs host allowlist entry (redirects).
75pub const HOST_STATIC_DOCS_RS: &str = "static.docs.rs";
76/// Official stdlib rustdoc host (`std` / `core` / `alloc`).
77pub const HOST_DOC_RUST_LANG_ORG: &str = "doc.rust-lang.org";
78
79/// Which layer won when resolving a storage path (XDG hierarchy diagnostics).
80///
81/// Product has no API keys; layers for OS keyring / cloud secret managers are
82/// out of scope. Precedence for paths: CLI/env dir override → `DOCSRS_CLI_HOME`
83/// sandbox → `ProjectDirs` XDG/AppData/Library.
84#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(rename_all = "kebab-case")]
86pub enum PathSource {
87    /// `--config-dir` / `--cache-dir` or clap env aliases for those flags.
88    CliOrEnv,
89    /// `{DOCSRS_CLI_HOME}/config` or `{DOCSRS_CLI_HOME}/cache`.
90    HomeSandbox,
91    /// `directories::ProjectDirs` platform defaults.
92    Xdg,
93    /// No path could be resolved.
94    #[default]
95    Unresolved,
96}
97
98impl PathSource {
99    /// Stable machine token for doctor / config path JSON.
100    pub const fn as_str(self) -> &'static str {
101        match self {
102            Self::CliOrEnv => "cli-or-env",
103            Self::HomeSandbox => "home-sandbox",
104            Self::Xdg => "xdg",
105            Self::Unresolved => "unresolved",
106        }
107    }
108}
109
110/// Default `config.toml` body written by `config init` (commented template).
111///
112/// Values are documentation only until the user uncomments. Runtime still
113/// applies defaults when keys are absent. No secrets — product is public HTTP.
114pub const DEFAULT_CONFIG_TOML: &str = r#"# docsrs-cli XDG configuration
115# Precedence: CLI flags > environment allowlist > this file > built-in defaults.
116# Path: $XDG_CONFIG_HOME/docsrs-cli/config.toml (or platform equivalent).
117# No .env file is required after cargo install. Product stores no API keys.
118#
119# timeout_secs = 30
120# connect_timeout_secs = 10
121# max_body_bytes = 10485760
122# max_output_bytes = 2097152
123# max_redirects = 5
124# max_retries = 3
125# retry_base_ms = 200
126# retry_max_delay_ms = 30000
127# disable_retry = false
128# rate_limit_delay_ms = 1000
129# max_concurrency = 0
130# user_agent = "docsrs-cli/0.1.0 (+https://github.com/docsrs-cli/docsrs-cli)"
131# contact = "you@example.com"
132# lang = "en"
133# crates_io_origin = "https://crates.io"
134# docs_rs_origin = "https://docs.rs"
135# cache_ttl_secs = 86400
136# max_cache_bytes = 268435456
137# no_cache = false
138"#;
139
140/// Runtime configuration resolved from defaults, XDG TOML, env, and CLI.
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct Config {
143    /// Wall-clock timeout in seconds for one operation.
144    pub timeout_secs: u64,
145    /// TCP connect timeout in seconds.
146    pub connect_timeout_secs: u64,
147    /// Maximum downloaded HTTP body size in bytes.
148    pub max_body_bytes: u64,
149    /// Maximum emitted stdout payload size in bytes.
150    pub max_output_bytes: u64,
151    /// Maximum HTTP redirects followed.
152    pub max_redirects: u32,
153    /// Maximum retries for transient HTTP errors.
154    pub max_retries: u32,
155    /// Base backoff delay in milliseconds between retries.
156    pub retry_base_ms: u64,
157    /// Ceiling for a single retry sleep in milliseconds.
158    pub retry_max_delay_ms: u64,
159    /// Kill switch: when true, HTTP never retries (incident / debug).
160    pub disable_retry: bool,
161    /// Minimum delay between requests to the same host in milliseconds.
162    pub rate_limit_delay_ms: u64,
163    /// Max concurrent CPU (`spawn_blocking`) tasks; `0` = auto from CPUs/RAM.
164    ///
165    /// See [`crate::concurrency::resolve_max_concurrency`].
166    pub max_concurrency: u32,
167    /// HTTP User-Agent header value.
168    pub user_agent: String,
169    /// Optional contact URL or email embedded in the default User-Agent.
170    pub contact: Option<String>,
171    /// Preferred human-message locale (`en` or `pt-BR`).
172    pub lang: Option<String>,
173    /// Resolved XDG (or override) config directory.
174    pub config_dir: Option<PathBuf>,
175    /// XDG (or override) root for HTTP response cache between process runs.
176    pub cache_dir: Option<PathBuf>,
177    /// Disk cache TTL in seconds (default 24h).
178    pub cache_ttl_secs: u64,
179    /// Soft cap on disk cache size in bytes (`0` = unlimited).
180    pub max_cache_bytes: u64,
181    /// When true, skip disk cache read/write (`--no-cache`).
182    pub no_cache: bool,
183    /// Origin for crates.io API (default `https://crates.io`). Overridable for offline mocks.
184    pub crates_io_origin: String,
185    /// Origin for docs.rs pages (default `https://docs.rs`). Overridable for offline mocks.
186    pub docs_rs_origin: String,
187    /// Layer that resolved [`Self::config_dir`].
188    pub config_path_source: PathSource,
189    /// Layer that resolved [`Self::cache_dir`].
190    pub cache_path_source: PathSource,
191    /// True when `config.toml` existed and was applied during load.
192    pub config_toml_loaded: bool,
193}
194
195impl Default for Config {
196    fn default() -> Self {
197        let contact = std::env::var("DOCSRS_CLI_CONTACT").ok();
198        let ua = default_user_agent(contact.as_deref());
199        Self {
200            timeout_secs: DEFAULT_TIMEOUT_SECS,
201            connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT_SECS,
202            max_body_bytes: DEFAULT_MAX_BODY_BYTES,
203            max_output_bytes: DEFAULT_MAX_OUTPUT_BYTES,
204            max_redirects: DEFAULT_MAX_REDIRECTS,
205            max_retries: DEFAULT_MAX_RETRIES,
206            retry_base_ms: DEFAULT_RETRY_BASE_MS,
207            retry_max_delay_ms: DEFAULT_RETRY_MAX_DELAY_MS,
208            disable_retry: false,
209            rate_limit_delay_ms: DEFAULT_RATE_LIMIT_DELAY_MS,
210            max_concurrency: 0,
211            user_agent: ua,
212            contact,
213            lang: None,
214            config_dir: None,
215            cache_dir: None,
216            cache_ttl_secs: DEFAULT_CACHE_TTL_SECS,
217            max_cache_bytes: DEFAULT_MAX_CACHE_BYTES,
218            no_cache: false,
219            crates_io_origin: format!("https://{HOST_CRATES_IO}"),
220            docs_rs_origin: format!("https://{HOST_DOCS_RS}"),
221            config_path_source: PathSource::Unresolved,
222            cache_path_source: PathSource::Unresolved,
223            config_toml_loaded: false,
224        }
225    }
226}
227
228/// Builds the default User-Agent, optionally including a contact token.
229pub fn default_user_agent(contact: Option<&str>) -> String {
230    match contact {
231        Some(c) if !c.is_empty() => {
232            if c.starts_with("http://") || c.starts_with("https://") {
233                format!("{APP_NAME}/{APP_VERSION} (+{c})")
234            } else {
235                format!("{APP_NAME}/{APP_VERSION} ({c})")
236            }
237        }
238        _ => format!("{APP_NAME}/{APP_VERSION} (+https://github.com/docsrs-cli/docsrs-cli)"),
239    }
240}
241
242/// Strip trailing slash from an origin base URL.
243pub fn normalize_origin(raw: &str) -> String {
244    raw.trim().trim_end_matches('/').to_string()
245}
246
247#[derive(Debug, Default, Deserialize)]
248struct TomlConfig {
249    timeout_secs: Option<u64>,
250    connect_timeout_secs: Option<u64>,
251    max_body_bytes: Option<u64>,
252    max_output_bytes: Option<u64>,
253    max_redirects: Option<u32>,
254    max_retries: Option<u32>,
255    retry_base_ms: Option<u64>,
256    retry_max_delay_ms: Option<u64>,
257    disable_retry: Option<bool>,
258    rate_limit_delay_ms: Option<u64>,
259    max_concurrency: Option<u32>,
260    user_agent: Option<String>,
261    contact: Option<String>,
262    lang: Option<String>,
263    crates_io_origin: Option<String>,
264    docs_rs_origin: Option<String>,
265    cache_ttl_secs: Option<u64>,
266    max_cache_bytes: Option<u64>,
267    no_cache: Option<bool>,
268}
269
270impl Config {
271    /// Loads configuration with an optional config-directory override.
272    ///
273    /// # Errors
274    ///
275    /// Returns [`ErrorKind::Config`] when the TOML file is unreadable or invalid.
276    pub fn load(config_dir_override: Option<PathBuf>) -> AppResult<Self> {
277        Self::load_with_cache_dir(config_dir_override, None)
278    }
279
280    /// Load config with optional config-dir and cache-dir overrides (CLI / tests).
281    ///
282    /// # Errors
283    ///
284    /// Returns [`ErrorKind::Config`] when `config.toml` is unreadable or invalid TOML.
285    pub fn load_with_cache_dir(
286        config_dir_override: Option<PathBuf>,
287        cache_dir_override: Option<PathBuf>,
288    ) -> AppResult<Self> {
289        let mut cfg = Self::default();
290
291        let (config_dir, config_source) = resolve_config_dir_with_source(config_dir_override);
292        cfg.config_path_source = config_source;
293
294        let (cache_dir, cache_source) =
295            crate::cache::resolve_cache_dir_with_source(cache_dir_override);
296        cfg.cache_dir = cache_dir;
297        cfg.cache_path_source = cache_source;
298
299        // Borrow for TOML load, then move into `cfg` (no PathBuf clone).
300        if let Some(dir) = &config_dir {
301            let path = dir.join("config.toml");
302            if path.is_file() {
303                let text = fs::read_to_string(&path).map_err(|e| {
304                    AppError::with_source(
305                        ErrorKind::Config,
306                        format!("failed to read {}", path.display()),
307                        e,
308                    )
309                })?;
310                let parsed: TomlConfig = toml::from_str(&text).map_err(|e| {
311                    AppError::with_source(ErrorKind::Config, "invalid config.toml", e)
312                })?;
313                cfg.apply_toml(parsed);
314                cfg.config_toml_loaded = true;
315            }
316        }
317        cfg.config_dir = config_dir;
318
319        cfg.apply_env()?;
320        cfg.clamp_resource_limits();
321        Ok(cfg)
322    }
323
324    /// Absolute path to `config.toml` under the resolved config directory, if any.
325    pub fn config_file_path(&self) -> Option<PathBuf> {
326        self.config_dir.as_ref().map(|d| d.join("config.toml"))
327    }
328
329    /// Clamp body/output budgets so config, env, or CLI cannot force multi-GiB allocs.
330    ///
331    /// Call after every mutation path (TOML, env, CLI). Values above the hard
332    /// ceilings are silently reduced to [`HARD_MAX_BODY_BYTES`] /
333    /// [`HARD_MAX_OUTPUT_BYTES`]. Zero is left as-is (fail-closed for body reads).
334    pub fn clamp_resource_limits(&mut self) {
335        self.max_body_bytes = self.max_body_bytes.min(HARD_MAX_BODY_BYTES);
336        self.max_output_bytes = self.max_output_bytes.min(HARD_MAX_OUTPUT_BYTES);
337        self.max_retries = self.max_retries.min(crate::retry::HARD_MAX_RETRIES);
338        if self.retry_base_ms == 0 {
339            self.retry_base_ms = DEFAULT_RETRY_BASE_MS;
340        }
341        if self.retry_max_delay_ms == 0 {
342            self.retry_max_delay_ms = DEFAULT_RETRY_MAX_DELAY_MS;
343        }
344        self.retry_max_delay_ms = self
345            .retry_max_delay_ms
346            .min(crate::retry::HARD_MAX_DELAY_MS)
347            .max(self.retry_base_ms);
348    }
349
350    fn apply_toml(&mut self, t: TomlConfig) {
351        if let Some(v) = t.timeout_secs {
352            self.timeout_secs = v;
353        }
354        if let Some(v) = t.connect_timeout_secs {
355            self.connect_timeout_secs = v;
356        }
357        if let Some(v) = t.max_body_bytes {
358            self.max_body_bytes = v;
359        }
360        if let Some(v) = t.max_output_bytes {
361            self.max_output_bytes = v;
362        }
363        if let Some(v) = t.max_redirects {
364            self.max_redirects = v;
365        }
366        if let Some(v) = t.max_retries {
367            self.max_retries = v;
368        }
369        if let Some(v) = t.retry_base_ms {
370            self.retry_base_ms = v;
371        }
372        if let Some(v) = t.retry_max_delay_ms {
373            self.retry_max_delay_ms = v;
374        }
375        if let Some(v) = t.disable_retry {
376            self.disable_retry = v;
377        }
378        if let Some(v) = t.rate_limit_delay_ms {
379            self.rate_limit_delay_ms = v;
380        }
381        if let Some(v) = t.max_concurrency {
382            self.max_concurrency = v;
383        }
384        if let Some(v) = t.contact {
385            self.contact = Some(v);
386        }
387        if let Some(v) = t.user_agent {
388            self.user_agent = v;
389        } else if let Some(c) = &self.contact {
390            self.user_agent = default_user_agent(Some(c));
391        }
392        if let Some(v) = t.lang {
393            self.lang = Some(v);
394        }
395        if let Some(v) = t.crates_io_origin {
396            self.crates_io_origin = normalize_origin(&v);
397        }
398        if let Some(v) = t.docs_rs_origin {
399            self.docs_rs_origin = normalize_origin(&v);
400        }
401        if let Some(v) = t.cache_ttl_secs {
402            self.cache_ttl_secs = v;
403        }
404        if let Some(v) = t.max_cache_bytes {
405            self.max_cache_bytes = v;
406        }
407        if let Some(v) = t.no_cache {
408            self.no_cache = v;
409        }
410    }
411
412    fn apply_env(&mut self) -> AppResult<()> {
413        if let Ok(v) = std::env::var("DOCSRS_CLI_TIMEOUT_SECS") {
414            self.timeout_secs = v.parse().map_err(|_| {
415                AppError::new(
416                    ErrorKind::Config,
417                    "DOCSRS_CLI_TIMEOUT_SECS must be a positive integer",
418                )
419            })?;
420        }
421        if let Ok(v) = std::env::var("DOCSRS_CLI_MAX_BODY_BYTES") {
422            self.max_body_bytes = v.parse().map_err(|_| {
423                AppError::new(
424                    ErrorKind::Config,
425                    "DOCSRS_CLI_MAX_BODY_BYTES must be a non-negative integer",
426                )
427            })?;
428        }
429        if let Ok(v) = std::env::var("DOCSRS_CLI_MAX_OUTPUT_BYTES") {
430            self.max_output_bytes = v.parse().map_err(|_| {
431                AppError::new(
432                    ErrorKind::Config,
433                    "DOCSRS_CLI_MAX_OUTPUT_BYTES must be a positive integer",
434                )
435            })?;
436        }
437        if let Ok(v) = std::env::var("DOCSRS_CLI_MAX_CONCURRENCY") {
438            self.max_concurrency = v.parse().map_err(|_| {
439                AppError::new(
440                    ErrorKind::Config,
441                    "DOCSRS_CLI_MAX_CONCURRENCY must be a non-negative integer (0 = auto)",
442                )
443            })?;
444        }
445        if let Ok(v) = std::env::var("DOCSRS_CLI_MAX_RETRIES") {
446            self.max_retries = v.parse().map_err(|_| {
447                AppError::new(
448                    ErrorKind::Config,
449                    "DOCSRS_CLI_MAX_RETRIES must be a non-negative integer",
450                )
451            })?;
452        }
453        if let Ok(v) = std::env::var("DOCSRS_CLI_RETRY_BASE_MS") {
454            self.retry_base_ms = v.parse().map_err(|_| {
455                AppError::new(
456                    ErrorKind::Config,
457                    "DOCSRS_CLI_RETRY_BASE_MS must be a non-negative integer",
458                )
459            })?;
460        }
461        if let Ok(v) = std::env::var("DOCSRS_CLI_RETRY_MAX_DELAY_MS") {
462            self.retry_max_delay_ms = v.parse().map_err(|_| {
463                AppError::new(
464                    ErrorKind::Config,
465                    "DOCSRS_CLI_RETRY_MAX_DELAY_MS must be a non-negative integer",
466                )
467            })?;
468        }
469        if let Ok(v) = std::env::var("DOCSRS_CLI_DISABLE_RETRY") {
470            let low = v.to_ascii_lowercase();
471            self.disable_retry = matches!(low.as_str(), "1" | "true" | "yes" | "on");
472        }
473        if let Ok(v) = std::env::var("DOCSRS_CLI_USER_AGENT") {
474            self.user_agent = v;
475        }
476        if let Ok(v) = std::env::var("DOCSRS_CLI_CONTACT") {
477            self.contact = Some(v.clone());
478            if std::env::var("DOCSRS_CLI_USER_AGENT").is_err() {
479                self.user_agent = default_user_agent(Some(&v));
480            }
481        }
482        if let Ok(v) = std::env::var("DOCSRS_CLI_LANG") {
483            self.lang = Some(v);
484        }
485        if let Ok(v) = std::env::var("DOCSRS_CLI_CRATES_IO_ORIGIN") {
486            self.crates_io_origin = normalize_origin(&v);
487        }
488        if let Ok(v) = std::env::var("DOCSRS_CLI_DOCS_RS_ORIGIN") {
489            self.docs_rs_origin = normalize_origin(&v);
490        }
491        if let Ok(v) = std::env::var("DOCSRS_CLI_CACHE_TTL_SECS") {
492            self.cache_ttl_secs = v.parse().map_err(|_| {
493                AppError::new(
494                    ErrorKind::Config,
495                    "DOCSRS_CLI_CACHE_TTL_SECS must be a non-negative integer",
496                )
497            })?;
498        }
499        if let Ok(v) = std::env::var("DOCSRS_CLI_MAX_CACHE_BYTES") {
500            self.max_cache_bytes = v.parse().map_err(|_| {
501                AppError::new(
502                    ErrorKind::Config,
503                    "DOCSRS_CLI_MAX_CACHE_BYTES must be a non-negative integer",
504                )
505            })?;
506        }
507        if let Ok(v) = std::env::var("DOCSRS_CLI_NO_CACHE") {
508            let low = v.to_ascii_lowercase();
509            self.no_cache = matches!(low.as_str(), "1" | "true" | "yes" | "on");
510        }
511        // Env cache dir / home wins over XDG when not already pinned by CLI override.
512        if self.cache_dir.is_none() {
513            let (dir, source) = crate::cache::resolve_cache_dir_with_source(None);
514            self.cache_dir = dir;
515            self.cache_path_source = source;
516        }
517        Ok(())
518    }
519}
520
521/// Resolve config directory: CLI/env override, then `DOCSRS_CLI_HOME/config`, then XDG.
522///
523/// Precedence:
524/// 1. Explicit override (`--config-dir` / `DOCSRS_CLI_CONFIG_DIR`)
525/// 2. `{DOCSRS_CLI_HOME}/config` when `DOCSRS_CLI_HOME` is set (sandbox / tests)
526/// 3. `directories::ProjectDirs` config dir (platform XDG / AppData / Library)
527pub fn resolve_config_dir(override_dir: Option<PathBuf>) -> Option<PathBuf> {
528    resolve_config_dir_with_source(override_dir).0
529}
530
531/// Resolve config directory and report which layer won.
532pub fn resolve_config_dir_with_source(override_dir: Option<PathBuf>) -> (Option<PathBuf>, PathSource) {
533    if let Some(p) = override_dir {
534        return (Some(p), PathSource::CliOrEnv);
535    }
536    if let Some(p) = std::env::var_os("DOCSRS_CLI_CONFIG_DIR") {
537        return (Some(PathBuf::from(p)), PathSource::CliOrEnv);
538    }
539    if let Some(p) = home_config_dir() {
540        return (Some(p), PathSource::HomeSandbox);
541    }
542    if let Some(p) = ProjectDirs::from("", "", APP_NAME).map(|d| d.config_dir().to_path_buf()) {
543        return (Some(p), PathSource::Xdg);
544    }
545    (None, PathSource::Unresolved)
546}
547
548/// `{DOCSRS_CLI_HOME}/config` when the home override is set.
549fn home_config_dir() -> Option<PathBuf> {
550    std::env::var_os("DOCSRS_CLI_HOME").map(|h| PathBuf::from(h).join("config"))
551}
552
553/// Result of `config init`.
554#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
555pub struct ConfigInitResult {
556    /// Absolute path written (or already present when not forced).
557    pub path: String,
558    /// Directory that holds the file.
559    pub config_dir: String,
560    /// Layer that resolved the directory.
561    pub source: PathSource,
562    /// True when the file was created or overwritten in this call.
563    pub created: bool,
564    /// True when an existing file was replaced (`--force`).
565    pub overwritten: bool,
566}
567
568/// Create default `config.toml` under the resolved config directory.
569///
570/// # Errors
571///
572/// - [`ErrorKind::Config`] when the directory cannot be resolved or created,
573///   when the file already exists without `force`, or on I/O failure.
574pub fn init_config_toml(
575    config_dir_override: Option<PathBuf>,
576    force: bool,
577) -> AppResult<ConfigInitResult> {
578    let (dir, source) = resolve_config_dir_with_source(config_dir_override);
579    let dir = dir.ok_or_else(|| {
580        AppError::new(
581            ErrorKind::Config,
582            "config directory could not be resolved (set --config-dir or DOCSRS_CLI_CONFIG_DIR)",
583        )
584    })?;
585    fs::create_dir_all(&dir).map_err(|e| {
586        AppError::with_source(
587            ErrorKind::Config,
588            format!("failed to create config dir {}", dir.display()),
589            e,
590        )
591    })?;
592    restrict_private_dir(&dir);
593
594    let path = dir.join("config.toml");
595    let existed = path.is_file();
596    if existed && !force {
597        return Err(AppError::new(
598            ErrorKind::Config,
599            format!(
600                "config already exists: {} (pass --force to overwrite)",
601                path.display()
602            ),
603        ));
604    }
605
606    // Atomic-ish write: tempfile in same dir then rename.
607    let tmp = dir.join("config.toml.docsrs-cli.tmp");
608    {
609        let mut f = fs::File::create(&tmp).map_err(|e| {
610            AppError::with_source(
611                ErrorKind::Config,
612                format!("failed to create {}", tmp.display()),
613                e,
614            )
615        })?;
616        f.write_all(DEFAULT_CONFIG_TOML.as_bytes()).map_err(|e| {
617            AppError::with_source(
618                ErrorKind::Config,
619                format!("failed to write {}", tmp.display()),
620                e,
621            )
622        })?;
623        f.sync_all().map_err(|e| {
624            AppError::with_source(
625                ErrorKind::Config,
626                format!("failed to sync {}", tmp.display()),
627                e,
628            )
629        })?;
630    }
631    restrict_private_file(&tmp);
632    fs::rename(&tmp, &path).map_err(|e| {
633        let _ = fs::remove_file(&tmp);
634        AppError::with_source(
635            ErrorKind::Config,
636            format!("failed to install {}", path.display()),
637            e,
638        )
639    })?;
640    restrict_private_file(&path);
641
642    Ok(ConfigInitResult {
643        path: path.display().to_string(),
644        config_dir: dir.display().to_string(),
645        source,
646        created: true,
647        overwritten: existed,
648    })
649}
650
651/// Path inventory for `config path` (agent-readable).
652#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
653pub struct ConfigPathData {
654    /// Resolved config directory, if any.
655    pub config_dir: Option<String>,
656    /// Layer that resolved the config directory.
657    pub config_source: PathSource,
658    /// Absolute `config.toml` path (even if the file does not exist yet).
659    pub config_file: Option<String>,
660    /// Whether `config.toml` is present on disk.
661    pub config_file_exists: bool,
662    /// Whether load applied TOML keys (same as exists for normal runs).
663    pub config_toml_loaded: bool,
664    /// Resolved cache directory, if any.
665    pub cache_dir: Option<String>,
666    /// Layer that resolved the cache directory.
667    pub cache_source: PathSource,
668    /// Product does not use `.env` at runtime after install.
669    pub dotenv_runtime: bool,
670    /// Product stores no API keys; keyring/cloud secret layers are unused.
671    pub secrets_layers: &'static str,
672}
673
674/// Build path inventory from a loaded [`Config`].
675pub fn config_path_data(cfg: &Config) -> ConfigPathData {
676    let config_file = cfg.config_file_path();
677    let exists = config_file.as_ref().is_some_and(|p| p.is_file());
678    ConfigPathData {
679        config_dir: cfg.config_dir.as_ref().map(|p| p.display().to_string()),
680        config_source: cfg.config_path_source,
681        config_file: config_file.as_ref().map(|p| p.display().to_string()),
682        config_file_exists: exists,
683        config_toml_loaded: cfg.config_toml_loaded,
684        cache_dir: cfg.cache_dir.as_ref().map(|p| p.display().to_string()),
685        cache_source: cfg.cache_path_source,
686        dotenv_runtime: false,
687        secrets_layers: "none (public HTTP only; no API keys)",
688    }
689}
690
691/// Ensure `path` is under a directory (used by tests / path display).
692pub fn config_toml_under(dir: &Path) -> PathBuf {
693    dir.join("config.toml")
694}
695
696impl Config {
697
698    /// Wall-clock timeout duration (at least one second).
699    pub fn timeout(&self) -> Duration {
700        Duration::from_secs(self.timeout_secs.max(1))
701    }
702
703    /// TCP connect timeout duration (at least one second).
704    pub fn connect_timeout(&self) -> Duration {
705        Duration::from_secs(self.connect_timeout_secs.max(1))
706    }
707
708    /// Per-host rate-limit delay duration.
709    pub fn rate_limit_delay(&self) -> Duration {
710        Duration::from_millis(self.rate_limit_delay_ms)
711    }
712
713    /// TTL for disk cache entries.
714    pub fn cache_ttl(&self) -> Duration {
715        Duration::from_secs(self.cache_ttl_secs)
716    }
717
718    /// Whether disk cache should be used for HTTP GET bodies.
719    pub fn cache_enabled(&self) -> bool {
720        !self.no_cache && self.cache_dir.is_some()
721    }
722}
723
724/// Validate crate name (compat wrapper over [`crate::domain::CrateName::parse`]).
725///
726/// # Errors
727///
728/// Propagates [`ErrorKind::InvalidInput`] from [`crate::domain::CrateName::parse`].
729pub fn validate_crate_name(name: &str) -> AppResult<()> {
730    crate::domain::CrateName::parse(name).map(|_| ())
731}
732
733/// True for Rust standard library crates documented on `doc.rust-lang.org`.
734pub fn is_stdlib_crate(name: &str) -> bool {
735    matches!(name, "std" | "core" | "alloc")
736}
737
738/// Resolve docs origin for a crate: stdlib → doc.rust-lang.org, else configured docs.rs origin.
739pub fn docs_origin_for_crate(cfg: &Config, crate_name: &str) -> String {
740    if is_stdlib_crate(crate_name) {
741        format!("https://{HOST_DOC_RUST_LANG_ORG}")
742    } else {
743        cfg.docs_rs_origin.clone()
744    }
745}
746
747/// Map CLI version token to a rustdoc channel for stdlib paths.
748///
749/// `latest` → `stable`. Accepts `stable` / `beta` / `nightly` and other path-safe tokens.
750pub fn stdlib_channel(version: &str) -> &str {
751    match version {
752        "latest" => "stable",
753        other => other,
754    }
755}
756
757/// Validate search query (compat wrapper over [`crate::domain::SearchQuery::parse`]).
758///
759/// # Errors
760///
761/// Propagates [`ErrorKind::InvalidInput`] from [`crate::domain::SearchQuery::parse`].
762pub fn validate_query(query: &str, allow_empty: bool) -> AppResult<()> {
763    crate::domain::SearchQuery::parse(query, allow_empty).map(|_| ())
764}
765
766/// Validate item path (compat wrapper over [`crate::domain::ItemPath::parse`]).
767///
768/// # Errors
769///
770/// Propagates [`ErrorKind::InvalidInput`] from [`crate::domain::ItemPath::parse`].
771pub fn validate_item_path(path: &str) -> AppResult<Vec<String>> {
772    crate::domain::ItemPath::parse(path).map(|p| p.into_segments())
773}
774
775/// Resolve version argument: `latest` or SemVer without `v` prefix / build metadata.
776///
777/// # Errors
778///
779/// Propagates [`ErrorKind::InvalidInput`] from [`crate::domain::VersionArg::parse_opt`].
780pub fn resolve_version_arg(raw: Option<&str>) -> AppResult<String> {
781    crate::domain::VersionArg::parse_opt(raw).map(|v| v.as_str().to_string())
782}
783
784#[cfg(test)]
785mod tests {
786    use super::*;
787    use std::fs;
788    use std::io::Write;
789
790    #[test]
791    fn crate_name_rules() {
792        assert!(validate_crate_name("serde").is_ok());
793        assert!(validate_crate_name("async-trait").is_ok());
794        // std/core/alloc are valid; docs are fetched from doc.rust-lang.org.
795        assert!(validate_crate_name("std").is_ok());
796        assert!(validate_crate_name("core").is_ok());
797        assert!(validate_crate_name("alloc").is_ok());
798        assert!(is_stdlib_crate("std"));
799        assert!(!is_stdlib_crate("serde"));
800        assert!(validate_crate_name("").is_err());
801        assert!(validate_crate_name("1bad").is_err());
802        assert!(validate_crate_name(&"a".repeat(MAX_CRATE_NAME_CHARS + 1)).is_err());
803    }
804
805    #[test]
806    fn version_policy() {
807        assert_eq!(resolve_version_arg(None).unwrap(), "latest");
808        assert_eq!(resolve_version_arg(Some("")).unwrap(), "latest");
809        assert_eq!(resolve_version_arg(Some("1.0.0")).unwrap(), "1.0.0");
810        assert_eq!(
811            resolve_version_arg(Some("1.0.0-rc.1")).unwrap(),
812            "1.0.0-rc.1"
813        );
814        assert!(resolve_version_arg(Some("v1.0.0")).is_err());
815        assert!(resolve_version_arg(Some("1.0.0+build")).is_err());
816        assert!(resolve_version_arg(Some("not-a-version")).is_err());
817    }
818
819    #[test]
820    fn query_and_path_rules() {
821        assert!(validate_query("serde", false).is_ok());
822        assert!(validate_query("", false).is_err());
823        assert!(validate_query("", true).is_ok());
824        assert!(validate_query(&"q".repeat(MAX_QUERY_CHARS + 1), true).is_err());
825        let segs = validate_item_path("clap::Parser").unwrap();
826        assert_eq!(segs, vec!["clap", "Parser"]);
827        assert!(validate_item_path("::").is_err());
828        assert!(validate_item_path("").is_err());
829        assert!(validate_item_path(&format!("a::{}", "b".repeat(MAX_ITEM_PATH_CHARS))).is_err());
830    }
831
832    #[test]
833    fn item_path_accepts_slash_and_rejects_bad_segments() {
834        let segs = validate_item_path("runtime/Runtime").unwrap();
835        assert_eq!(segs, vec!["runtime", "Runtime"]);
836        let mixed = validate_item_path("tokio::runtime/Runtime").unwrap();
837        assert_eq!(mixed, vec!["tokio", "runtime", "Runtime"]);
838        assert_eq!(
839            validate_item_path("async_trait").unwrap(),
840            vec!["async_trait"]
841        );
842        assert!(validate_item_path("has space").is_err());
843        assert!(validate_item_path("foo.bar").is_err());
844        assert!(validate_item_path("..").is_err());
845        assert!(validate_item_path("a/../b").is_err());
846        assert!(validate_item_path("/").is_err());
847    }
848
849    #[test]
850    fn default_user_agent_variants() {
851        let ua = default_user_agent(None);
852        assert!(ua.contains(APP_NAME));
853        let ua2 = default_user_agent(Some("dev@example.com"));
854        assert!(ua2.contains("dev@example.com"));
855        let ua3 = default_user_agent(Some("https://example.com"));
856        assert!(ua3.contains("+https://example.com"));
857    }
858
859    #[test]
860    fn config_load_toml_and_durations() {
861        let dir = tempfile::tempdir().unwrap();
862        let path = dir.path().join("config.toml");
863        let mut f = fs::File::create(&path).unwrap();
864        writeln!(
865            f,
866            "timeout_secs = 12\nrate_limit_delay_ms = 50\ncontact = \"a@b.c\"\ncrates_io_origin = \"http://127.0.0.1:9/\"\ndocs_rs_origin = \"http://127.0.0.1:9/\"\nlang = \"pt-BR\"\nmax_retries = 2\nmax_body_bytes = 1000\nmax_output_bytes = 2000\ncache_ttl_secs = 3600\nno_cache = false\n"
867        )
868        .unwrap();
869        let cache_dir = dir.path().join("cache");
870        let cfg =
871            Config::load_with_cache_dir(Some(dir.path().to_path_buf()), Some(cache_dir.clone()))
872                .unwrap();
873        assert_eq!(cfg.timeout_secs, 12);
874        assert_eq!(cfg.rate_limit_delay_ms, 50);
875        assert!(cfg.user_agent.contains("a@b.c"));
876        assert_eq!(cfg.timeout(), Duration::from_secs(12));
877        assert_eq!(cfg.rate_limit_delay(), Duration::from_millis(50));
878        assert!(cfg.connect_timeout() >= Duration::from_secs(1));
879        assert_eq!(cfg.crates_io_origin, "http://127.0.0.1:9");
880        assert_eq!(cfg.docs_rs_origin, "http://127.0.0.1:9");
881        assert_eq!(cfg.lang.as_deref(), Some("pt-BR"));
882        assert_eq!(cfg.max_retries, 2);
883        assert_eq!(cfg.max_body_bytes, 1000);
884        assert_eq!(cfg.max_output_bytes, 2000);
885        assert_eq!(cfg.cache_ttl_secs, 3600);
886        assert_eq!(cfg.cache_dir.as_deref(), Some(cache_dir.as_path()));
887        assert!(cfg.cache_enabled());
888    }
889
890    #[test]
891    fn config_invalid_toml_errors() {
892        let dir = tempfile::tempdir().unwrap();
893        fs::write(dir.path().join("config.toml"), "timeout_secs = [\n").unwrap();
894        let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
895        assert_eq!(err.kind(), ErrorKind::Config);
896    }
897
898    #[test]
899    fn normalize_origin_trims_slash() {
900        assert_eq!(normalize_origin(" https://docs.rs/ "), "https://docs.rs");
901    }
902
903    #[test]
904    fn resolve_config_dir_prefers_explicit_override() {
905        let explicit = PathBuf::from("/tmp/docsrs-cli-explicit-config");
906        let got = resolve_config_dir(Some(explicit.clone()));
907        assert_eq!(got.as_deref(), Some(explicit.as_path()));
908    }
909
910    #[test]
911    fn resolve_cache_dir_home_layout() {
912        // Pure path join contract (no env mutation): HOME root + "cache".
913        let home = PathBuf::from("/tmp/docsrs-cli-home-sandbox");
914        let cache = home.join("cache");
915        assert_eq!(cache.file_name().and_then(|s| s.to_str()), Some("cache"));
916        // resolve_cache_dir with explicit override must win over env/XDG.
917        let got = crate::cache::resolve_cache_dir(Some(cache.clone()));
918        assert_eq!(got.as_deref(), Some(cache.as_path()));
919    }
920
921    #[test]
922    fn config_defaults_positive() {
923        let cfg = Config::default();
924        assert!(cfg.timeout_secs >= 1);
925        assert!(cfg.max_body_bytes > 0);
926        assert!(cfg.user_agent.contains(APP_NAME));
927    }
928
929    #[test]
930    fn clamp_resource_limits_caps_body_and_output() {
931        let mut cfg = Config {
932            max_body_bytes: HARD_MAX_BODY_BYTES.saturating_mul(8),
933            max_output_bytes: HARD_MAX_OUTPUT_BYTES.saturating_mul(8),
934            ..Config::default()
935        };
936        cfg.clamp_resource_limits();
937        assert_eq!(cfg.max_body_bytes, HARD_MAX_BODY_BYTES);
938        assert_eq!(cfg.max_output_bytes, HARD_MAX_OUTPUT_BYTES);
939        // Lowering remains allowed (tests / tight budgets).
940        cfg.max_body_bytes = 64;
941        cfg.max_output_bytes = 32;
942        cfg.clamp_resource_limits();
943        assert_eq!(cfg.max_body_bytes, 64);
944        assert_eq!(cfg.max_output_bytes, 32);
945    }
946
947    #[test]
948    fn toml_cannot_raise_max_body_above_hard_ceiling() {
949        let dir = tempfile::tempdir().unwrap();
950        let path = dir.path().join("config.toml");
951        let huge_body = HARD_MAX_BODY_BYTES.saturating_mul(10);
952        let huge_out = HARD_MAX_OUTPUT_BYTES.saturating_mul(10);
953        fs::write(
954            &path,
955            format!("max_body_bytes = {huge_body}\nmax_output_bytes = {huge_out}\n"),
956        )
957        .unwrap();
958        let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
959        assert_eq!(cfg.max_body_bytes, HARD_MAX_BODY_BYTES);
960        assert_eq!(cfg.max_output_bytes, HARD_MAX_OUTPUT_BYTES);
961    }
962
963    #[test]
964    fn hard_ceilings_equal_defaults() {
965        // Product policy: operators may only lower body/output caps, never raise.
966        assert_eq!(HARD_MAX_BODY_BYTES, DEFAULT_MAX_BODY_BYTES);
967        assert_eq!(HARD_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_BYTES);
968        assert_eq!(Config::default().max_body_bytes, HARD_MAX_BODY_BYTES);
969        assert_eq!(Config::default().max_output_bytes, HARD_MAX_OUTPUT_BYTES);
970    }
971
972    #[test]
973    fn path_source_tokens_are_stable() {
974        assert_eq!(PathSource::CliOrEnv.as_str(), "cli-or-env");
975        assert_eq!(PathSource::HomeSandbox.as_str(), "home-sandbox");
976        assert_eq!(PathSource::Xdg.as_str(), "xdg");
977        assert_eq!(PathSource::Unresolved.as_str(), "unresolved");
978    }
979
980    #[test]
981    fn resolve_config_dir_with_source_reports_cli() {
982        let explicit = PathBuf::from("/tmp/docsrs-cli-src-explicit");
983        let (got, source) = resolve_config_dir_with_source(Some(explicit.clone()));
984        assert_eq!(got.as_deref(), Some(explicit.as_path()));
985        assert_eq!(source, PathSource::CliOrEnv);
986    }
987
988    #[test]
989    fn init_config_toml_creates_and_refuses_without_force() {
990        let dir = tempfile::tempdir().unwrap();
991        let r1 = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap();
992        assert!(r1.created);
993        assert!(!r1.overwritten);
994        assert!(Path::new(&r1.path).is_file());
995        let text = fs::read_to_string(&r1.path).unwrap();
996        assert!(text.contains("docsrs-cli XDG configuration"));
997        assert!(text.contains("No .env file is required"));
998        #[cfg(unix)]
999        {
1000            use std::os::unix::fs::PermissionsExt;
1001            let mode = fs::metadata(&r1.path).unwrap().permissions().mode() & 0o777;
1002            assert_eq!(mode, 0o600);
1003        }
1004        let err = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap_err();
1005        assert_eq!(err.kind(), ErrorKind::Config);
1006        let r2 = init_config_toml(Some(dir.path().to_path_buf()), true).unwrap();
1007        assert!(r2.created);
1008        assert!(r2.overwritten);
1009    }
1010
1011    #[test]
1012    fn config_load_marks_toml_loaded() {
1013        let dir = tempfile::tempdir().unwrap();
1014        fs::write(dir.path().join("config.toml"), "timeout_secs = 9\n").unwrap();
1015        let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
1016        assert!(cfg.config_toml_loaded);
1017        assert_eq!(cfg.timeout_secs, 9);
1018        assert_eq!(cfg.config_path_source, PathSource::CliOrEnv);
1019        let inv = config_path_data(&cfg);
1020        assert!(inv.config_file_exists);
1021        assert!(!inv.dotenv_runtime);
1022    }
1023
1024    #[test]
1025    fn config_load_without_toml_is_not_loaded() {
1026        let dir = tempfile::tempdir().unwrap();
1027        let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
1028        assert!(!cfg.config_toml_loaded);
1029        assert!(!config_path_data(&cfg).config_file_exists);
1030    }
1031}