Skip to main content

docsrs_cli/config/load/
toml_file.rs

1//! Capped `config.toml` read, strict schema, and the load pipeline.
2
3use std::fs;
4use std::path::{Path, PathBuf};
5
6use serde::Deserialize;
7
8use crate::config::constants::*;
9use crate::config::path_source::resolve_config_dir_with_source;
10use crate::config::validate::default_user_agent;
11use crate::domain::AllowedOrigin;
12use crate::error::{AppError, AppResult, ErrorDetail, IoOp, Subject, ValueSource, io_at};
13
14use super::Config;
15
16/// Read `config.toml` with a hard size cap (poisoned-config / TOML bomb guard).
17///
18/// Uses `fs::read` + length check (not unbounded `read_to_string`). Metadata
19/// size is an early reject; the post-read length is authoritative (TOCTOU-safe).
20///
21/// # Errors
22///
23/// Returns [`crate::error::ErrorKind::Config`] when the file is unreadable, over
24/// [`MAX_CONFIG_TOML_BYTES`], or not valid UTF-8.
25fn read_config_toml_capped(path: &Path) -> AppResult<String> {
26    if let Ok(meta) = fs::metadata(path)
27        && meta.len() > MAX_CONFIG_TOML_BYTES
28    {
29        return Err(AppError::of(ErrorDetail::ConfigTomlTooLarge {
30            max_bytes: MAX_CONFIG_TOML_BYTES,
31        }));
32    }
33    let bytes = fs::read(path).map_err(io_at(IoOp::Read, path))?;
34    if (bytes.len() as u64) > MAX_CONFIG_TOML_BYTES {
35        return Err(AppError::of(ErrorDetail::ConfigTomlTooLarge {
36            max_bytes: MAX_CONFIG_TOML_BYTES,
37        }));
38    }
39    String::from_utf8(bytes)
40        .map_err(|e| AppError::of_with_source(ErrorDetail::ConfigTomlNotUtf8, e))
41}
42
43/// XDG `config.toml` keys only — unknown keys fail closed (typo ≠ silent ignore).
44#[derive(Debug, Default, Deserialize)]
45#[serde(deny_unknown_fields)]
46struct TomlConfig {
47    timeout_secs: Option<u64>,
48    connect_timeout_secs: Option<u64>,
49    max_body_bytes: Option<u64>,
50    max_output_bytes: Option<u64>,
51    max_redirects: Option<u32>,
52    max_retries: Option<u32>,
53    retry_base_ms: Option<u64>,
54    retry_max_delay_ms: Option<u64>,
55    retry_max_elapsed_ms: Option<u64>,
56    disable_retry: Option<bool>,
57    rate_limit_delay_ms: Option<u64>,
58    max_concurrency: Option<u32>,
59    user_agent: Option<String>,
60    contact: Option<String>,
61    lang: Option<String>,
62    log_directive: Option<String>,
63    crates_io_origin: Option<String>,
64    docs_rs_origin: Option<String>,
65    allow_loopback: Option<bool>,
66    cache_ttl_secs: Option<u64>,
67    max_cache_bytes: Option<u64>,
68    no_cache: Option<bool>,
69}
70
71impl Config {
72    /// Loads configuration with an optional config-directory override.
73    ///
74    /// # Errors
75    ///
76    /// Returns [`crate::error::ErrorKind::Config`] when the TOML file is unreadable or invalid.
77    pub fn load(config_dir_override: Option<PathBuf>) -> AppResult<Self> {
78        Self::load_with_cache_dir(config_dir_override, None)
79    }
80
81    /// Load config with optional config-dir and cache-dir overrides (CLI / tests).
82    ///
83    /// # Errors
84    ///
85    /// Returns [`crate::error::ErrorKind::Config`] when `config.toml` is unreadable or invalid TOML.
86    pub fn load_with_cache_dir(
87        config_dir_override: Option<PathBuf>,
88        cache_dir_override: Option<PathBuf>,
89    ) -> AppResult<Self> {
90        Self::load_with_options(config_dir_override, cache_dir_override, false)
91    }
92
93    /// Load config with optional path overrides and a CLI loopback seed.
94    ///
95    /// `allow_loopback` is applied **before** TOML origin parsing so
96    /// `--allow-loopback` works with mock origins in the same invocation
97    /// (ADR 0009 — never via env).
98    ///
99    /// # Errors
100    ///
101    /// Returns [`crate::error::ErrorKind::Config`] when `config.toml` is unreadable or invalid TOML.
102    pub fn load_with_options(
103        config_dir_override: Option<PathBuf>,
104        cache_dir_override: Option<PathBuf>,
105        allow_loopback: bool,
106    ) -> AppResult<Self> {
107        let mut cfg = Self::default();
108        if allow_loopback {
109            cfg.allow_loopback = true;
110        }
111
112        let (config_dir, config_source) = resolve_config_dir_with_source(config_dir_override);
113        cfg.config_path_source = config_source;
114
115        let (cache_dir, cache_source) =
116            crate::cache::resolve_cache_dir_with_source(cache_dir_override);
117        cfg.cache_dir = cache_dir;
118        cfg.cache_path_source = cache_source;
119
120        // Borrow for TOML load, then move into `cfg` (no PathBuf clone).
121        if let Some(dir) = &config_dir {
122            let path = dir.join(CONFIG_FILE_NAME);
123            if path.is_file() {
124                let text = read_config_toml_capped(&path)?;
125                let parsed: TomlConfig = toml::from_str(&text)
126                    .map_err(|e| AppError::of_with_source(ErrorDetail::ConfigTomlInvalid, e))?;
127                cfg.apply_toml(parsed)?;
128                cfg.config_toml_loaded = true;
129            }
130        }
131        cfg.config_dir = config_dir;
132
133        cfg.apply_cache_path_defaults()?;
134        cfg.clamp_resource_limits();
135        cfg.validate_security()?;
136        Ok(cfg)
137    }
138
139    fn apply_toml(&mut self, t: TomlConfig) -> AppResult<()> {
140        // Same invariant as the flags, same failure, different exit code. A zero
141        // timeout is rejected on the command line (exit 65) but used to be
142        // accepted here, so `--timeout 0` and `timeout_secs = 0` disagreed about
143        // the very same knob. `ValueSource::ConfigFile` is what makes the two
144        // paths report the one shared rule with the remediation each caller can
145        // actually act on: fix the argument, or fix the file.
146        if let Some(v) = t.timeout_secs {
147            if v == 0 {
148                return Err(AppError::of(ErrorDetail::MustBeAtLeastOneSecond {
149                    subject: Subject::Timeout,
150                    source: ValueSource::ConfigFile,
151                }));
152            }
153            self.timeout_secs = v;
154        }
155        if let Some(v) = t.connect_timeout_secs {
156            if v == 0 {
157                return Err(AppError::of(ErrorDetail::MustBeAtLeastOneSecond {
158                    subject: Subject::ConnectTimeout,
159                    source: ValueSource::ConfigFile,
160                }));
161            }
162            self.connect_timeout_secs = v;
163        }
164        if let Some(v) = t.max_body_bytes {
165            // Fail-closed for operator honesty (GAP-X-005): TOML cannot raise above HARD_MAX.
166            if v > HARD_MAX_BODY_BYTES {
167                return Err(AppError::of(ErrorDetail::AboveHardMaximum {
168                    subject: Subject::MaxBodyBytes,
169                    hard_max: HARD_MAX_BODY_BYTES,
170                    source: ValueSource::ConfigFile,
171                }));
172            }
173            self.max_body_bytes = v;
174        }
175        if let Some(v) = t.max_output_bytes {
176            if v > HARD_MAX_OUTPUT_BYTES {
177                return Err(AppError::of(ErrorDetail::AboveHardMaximum {
178                    subject: Subject::MaxOutputBytes,
179                    hard_max: HARD_MAX_OUTPUT_BYTES,
180                    source: ValueSource::ConfigFile,
181                }));
182            }
183            self.max_output_bytes = v;
184        }
185        if let Some(v) = t.max_redirects {
186            self.max_redirects = v;
187        }
188        if let Some(v) = t.max_retries {
189            self.max_retries = v;
190        }
191        if let Some(v) = t.retry_base_ms {
192            self.retry_base_ms = v;
193        }
194        if let Some(v) = t.retry_max_delay_ms {
195            self.retry_max_delay_ms = v;
196        }
197        if let Some(v) = t.retry_max_elapsed_ms {
198            self.retry_max_elapsed_ms = v;
199        }
200        if let Some(v) = t.disable_retry {
201            self.disable_retry = v;
202        }
203        if let Some(v) = t.rate_limit_delay_ms {
204            self.rate_limit_delay_ms = v;
205        }
206        if let Some(v) = t.max_concurrency {
207            self.max_concurrency = v;
208        }
209        if let Some(v) = t.contact {
210            self.contact = Some(v);
211        }
212        if let Some(v) = t.user_agent {
213            self.user_agent = v;
214        } else if let Some(c) = &self.contact {
215            self.user_agent = default_user_agent(Some(c));
216        }
217        if let Some(v) = t.lang {
218            self.lang = Some(v);
219        }
220        if let Some(v) = t.log_directive {
221            // Validate here, not at subscriber install time. `init_tracing` runs
222            // before any structured error path exists, so its only option is to
223            // swallow a bad value and fall back — which leaves the operator with
224            // a knob that is silently ignored and no way to find out why. That is
225            // the same shape as the ambient override this key replaced. Parsing
226            // is pure and cheap, so the failure becomes representable exactly
227            // where `config.toml` is read, and joins every other bad TOML value
228            // at exit 78. The fallback in `init_tracing` stays as defence in
229            // depth for callers that bypass this path.
230            if tracing_subscriber::EnvFilter::try_new(&v).is_err() {
231                return Err(AppError::of(ErrorDetail::Invalid {
232                    subject: Subject::LogDirective,
233                    value: v,
234                }));
235            }
236            self.log_directive = Some(v);
237        }
238        // Apply loopback gate before parsing origins so mock hosts validate.
239        if let Some(v) = t.allow_loopback {
240            self.allow_loopback = v;
241        }
242        if let Some(v) = t.crates_io_origin {
243            self.crates_io_origin = AllowedOrigin::parse_with(&v, self.allow_loopback)?;
244        }
245        if let Some(v) = t.docs_rs_origin {
246            self.docs_rs_origin = AllowedOrigin::parse_with(&v, self.allow_loopback)?;
247        }
248        if let Some(v) = t.cache_ttl_secs {
249            self.cache_ttl_secs = v;
250        }
251        if let Some(v) = t.max_cache_bytes {
252            self.max_cache_bytes = v;
253        }
254        if let Some(v) = t.no_cache {
255            self.no_cache = v;
256        }
257        Ok(())
258    }
259
260    /// Resolve cache path when still unset (XDG / test sandbox).
261    ///
262    /// Resolve cache path defaults from CLI override / XDG only (no product env).
263    fn apply_cache_path_defaults(&mut self) -> AppResult<()> {
264        if self.cache_dir.is_none() {
265            let (dir, source) = crate::cache::resolve_cache_dir_with_source(None);
266            self.cache_dir = dir;
267            self.cache_path_source = source;
268        }
269        Ok(())
270    }
271}