docsrs_cli/config/load/mod.rs
1//! Runtime [`Config`]: defaults, clamps, validation, and derived durations.
2//!
3//! Layout (SRP): `template` (commented `config.toml` body) · `toml_file`
4//! (capped read, schema, and the load pipeline) · `init` (`config init`) ·
5//! `paths` (`config path` inventory).
6
7use std::path::PathBuf;
8use std::time::Duration;
9
10use serde::{Deserialize, Serialize};
11
12use crate::domain::{AllowedOrigin, CrateName};
13use crate::error::AppResult;
14
15use super::constants::*;
16use super::path_source::PathSource;
17use super::validate::{default_user_agent, validate_contact, validate_user_agent};
18
19mod init;
20mod paths;
21mod template;
22mod toml_file;
23
24pub use init::{ConfigInitResult, init_config_toml};
25pub use paths::{ConfigPathData, config_path_data, config_toml_under};
26pub use template::default_config_toml;
27
28/// Runtime configuration resolved from defaults, XDG TOML, and CLI flags.
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct Config {
31 /// Wall-clock timeout in seconds for one operation.
32 pub timeout_secs: u64,
33 /// TCP connect timeout in seconds.
34 pub connect_timeout_secs: u64,
35 /// Maximum downloaded HTTP body size in bytes.
36 pub max_body_bytes: u64,
37 /// Maximum emitted stdout payload size in bytes.
38 pub max_output_bytes: u64,
39 /// Maximum HTTP redirects followed.
40 pub max_redirects: u32,
41 /// Maximum retries for transient HTTP errors.
42 pub max_retries: u32,
43 /// Base backoff delay in milliseconds between retries.
44 pub retry_base_ms: u64,
45 /// Ceiling for a single retry sleep in milliseconds.
46 pub retry_max_delay_ms: u64,
47 /// Total retry loop wall budget in milliseconds (`0` = derive from `timeout_secs`).
48 pub retry_max_elapsed_ms: u64,
49 /// Kill switch: when true, HTTP never retries (incident / debug).
50 pub disable_retry: bool,
51 /// Minimum delay between requests to the same host in milliseconds.
52 pub rate_limit_delay_ms: u64,
53 /// Max concurrent CPU (`spawn_blocking`) tasks; `0` = auto from CPUs/RAM.
54 ///
55 /// See [`crate::concurrency::resolve_max_concurrency`].
56 pub max_concurrency: u32,
57 /// HTTP User-Agent header value.
58 pub user_agent: String,
59 /// Optional contact URL or email embedded in the default User-Agent.
60 ///
61 /// Omitted from `config show` when unset — a `null` key is a dead field that
62 /// costs an agent tokens without carrying information.
63 #[serde(skip_serializing_if = "Option::is_none")]
64 pub contact: Option<String>,
65 /// Preferred human-message locale (`en` or `pt-BR`).
66 ///
67 /// Omitted from `config show` when unset (see [`Config::contact`]).
68 #[serde(skip_serializing_if = "Option::is_none")]
69 pub lang: Option<String>,
70 /// Default `tracing` filter directive when `-q` / `-v` are absent.
71 ///
72 /// This is the **only** way to steer stderr diagnostics beyond the CLI
73 /// flags: the process reads no product environment variable, so `RUST_LOG`
74 /// has no effect (ADR 0009). Omitted from `config show` when unset.
75 #[serde(skip_serializing_if = "Option::is_none")]
76 pub log_directive: Option<String>,
77 /// Resolved XDG (or override) config directory.
78 pub config_dir: Option<PathBuf>,
79 /// XDG (or override) root for HTTP response cache between process runs.
80 pub cache_dir: Option<PathBuf>,
81 /// Disk cache TTL in seconds (default 24h).
82 pub cache_ttl_secs: u64,
83 /// Soft cap on disk cache size in bytes (`0` = unlimited).
84 pub max_cache_bytes: u64,
85 /// When true, skip disk cache read/write (`--no-cache`).
86 pub no_cache: bool,
87 /// Origin for crates.io API (default `https://crates.io`). Overridable for offline mocks.
88 pub crates_io_origin: AllowedOrigin,
89 /// Origin for docs.rs pages (default `https://docs.rs`). Overridable for offline mocks.
90 pub docs_rs_origin: AllowedOrigin,
91 /// When true, SSRF allowlist accepts loopback (`127.0.0.1` / `localhost`) for offline mocks.
92 ///
93 /// Set only via XDG `config.toml` (`allow_loopback = true`) or CLI `--allow-loopback`.
94 /// Never read from environment variables (ADR 0009).
95 pub allow_loopback: bool,
96 /// Layer that resolved [`Self::config_dir`].
97 pub config_path_source: PathSource,
98 /// Layer that resolved [`Self::cache_dir`].
99 pub cache_path_source: PathSource,
100 /// True when `config.toml` existed and was applied during load.
101 pub config_toml_loaded: bool,
102}
103
104impl Default for Config {
105 fn default() -> Self {
106 // Contact comes from TOML `contact` or CLI `--user-agent`, not process env.
107 let contact: Option<String> = None;
108 let ua = default_user_agent(contact.as_deref());
109 Self {
110 timeout_secs: DEFAULT_TIMEOUT_SECS,
111 connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT_SECS,
112 max_body_bytes: DEFAULT_MAX_BODY_BYTES,
113 max_output_bytes: DEFAULT_MAX_OUTPUT_BYTES,
114 max_redirects: DEFAULT_MAX_REDIRECTS,
115 max_retries: DEFAULT_MAX_RETRIES,
116 retry_base_ms: DEFAULT_RETRY_BASE_MS,
117 retry_max_delay_ms: DEFAULT_RETRY_MAX_DELAY_MS,
118 retry_max_elapsed_ms: DEFAULT_RETRY_MAX_ELAPSED_MS,
119 disable_retry: false,
120 rate_limit_delay_ms: DEFAULT_RATE_LIMIT_DELAY_MS,
121 max_concurrency: 0,
122 user_agent: ua,
123 contact,
124 lang: None,
125 log_directive: None,
126 config_dir: None,
127 cache_dir: None,
128 cache_ttl_secs: DEFAULT_CACHE_TTL_SECS,
129 max_cache_bytes: DEFAULT_MAX_CACHE_BYTES,
130 no_cache: false,
131 crates_io_origin: AllowedOrigin::crates_io_default(),
132 docs_rs_origin: AllowedOrigin::docs_rs_default(),
133 allow_loopback: false,
134 config_path_source: PathSource::Unresolved,
135 cache_path_source: PathSource::Unresolved,
136 config_toml_loaded: false,
137 }
138 }
139}
140
141impl Config {
142 /// Re-validate origin fields after TOML/CLI mutation (fail-fast config).
143 ///
144 /// # Errors
145 ///
146 /// Returns [`crate::error::ErrorKind::Config`] when either origin is not a valid
147 /// allowlisted HTTP(S) URL (SSRF gate at config boundary).
148 pub fn validate_origins(&mut self) -> AppResult<()> {
149 // Re-parse to re-assert allowlist proof after any TOML/CLI mutation path.
150 self.crates_io_origin =
151 AllowedOrigin::parse_with(self.crates_io_origin.as_str(), self.allow_loopback)?;
152 self.docs_rs_origin =
153 AllowedOrigin::parse_with(self.docs_rs_origin.as_str(), self.allow_loopback)?;
154 Ok(())
155 }
156
157 /// Validate security-sensitive config fields (origins + User-Agent + contact).
158 ///
159 /// # Errors
160 ///
161 /// Returns [`crate::error::ErrorKind::Config`] on allowlist, contact, or
162 /// User-Agent policy failures.
163 pub fn validate_security(&mut self) -> AppResult<()> {
164 self.validate_origins()?;
165 if let Some(c) = &self.contact {
166 validate_contact(c)?;
167 }
168 // Rebuild UA from contact when UA was not explicitly set from a prior
169 // explicit user_agent key path — contact may have been applied already
170 // in `apply_toml`; always re-check the effective header string.
171 validate_user_agent(&self.user_agent)?;
172 Ok(())
173 }
174
175 /// Absolute path to `config.toml` under the resolved config directory, if any.
176 pub fn config_file_path(&self) -> Option<PathBuf> {
177 self.config_dir.as_ref().map(|d| d.join(CONFIG_FILE_NAME))
178 }
179
180 /// Clamp resource budgets to hard safety ceilings (defense in depth).
181 ///
182 /// Call after every mutation path (TOML, CLI). Operator-facing surfaces
183 /// (**CLI flags** and **TOML** body/output keys) reject values above
184 /// [`HARD_MAX_BODY_BYTES`] / [`HARD_MAX_OUTPUT_BYTES`] before this runs
185 /// (GAP-X-005). This method remains a last-line cap for other knobs and
186 /// accidental internal elevations. Zero body/output is left as-is
187 /// (fail-closed for body reads).
188 pub fn clamp_resource_limits(&mut self) {
189 self.max_body_bytes = self.max_body_bytes.min(HARD_MAX_BODY_BYTES);
190 self.max_output_bytes = self.max_output_bytes.min(HARD_MAX_OUTPUT_BYTES);
191 self.max_retries = self.max_retries.min(crate::retry::HARD_MAX_RETRIES);
192 self.max_redirects = self.max_redirects.min(HARD_MAX_REDIRECTS);
193 // Zero timeouts are rejected at CLI boundary; clamp absurd ceilings here.
194 if self.timeout_secs > HARD_MAX_TIMEOUT_SECS {
195 self.timeout_secs = HARD_MAX_TIMEOUT_SECS;
196 }
197 if self.connect_timeout_secs > HARD_MAX_CONNECT_TIMEOUT_SECS {
198 self.connect_timeout_secs = HARD_MAX_CONNECT_TIMEOUT_SECS;
199 }
200 if self.connect_timeout_secs > self.timeout_secs && self.timeout_secs > 0 {
201 self.connect_timeout_secs = self.timeout_secs;
202 }
203 if self.rate_limit_delay_ms > HARD_MAX_RATE_LIMIT_DELAY_MS {
204 self.rate_limit_delay_ms = HARD_MAX_RATE_LIMIT_DELAY_MS;
205 }
206 if self.retry_base_ms == 0 {
207 self.retry_base_ms = DEFAULT_RETRY_BASE_MS;
208 } else if self.retry_base_ms < crate::retry::MIN_RETRY_BASE_MS {
209 // Rules: never configure initial backoff below 50ms.
210 self.retry_base_ms = crate::retry::MIN_RETRY_BASE_MS;
211 }
212 if self.retry_max_delay_ms == 0 {
213 self.retry_max_delay_ms = DEFAULT_RETRY_MAX_DELAY_MS;
214 }
215 self.retry_max_delay_ms = self
216 .retry_max_delay_ms
217 .min(crate::retry::HARD_MAX_DELAY_MS)
218 .max(self.retry_base_ms);
219 // `0` keeps "derive from timeout" semantics in RetryConfig::from_config.
220 if self.retry_max_elapsed_ms > 0 {
221 self.retry_max_elapsed_ms = self
222 .retry_max_elapsed_ms
223 .min(crate::retry::HARD_MAX_ELAPSED_MS)
224 .max(self.retry_max_delay_ms);
225 }
226 // Soft-cap oversized UA strings (full charset validation is `validate_user_agent`).
227 if self.user_agent.chars().count() > MAX_USER_AGENT_CHARS {
228 self.user_agent = self.user_agent.chars().take(MAX_USER_AGENT_CHARS).collect();
229 }
230 }
231
232 /// Wall-clock timeout duration (at least one second).
233 pub fn timeout(&self) -> Duration {
234 Duration::from_secs(self.timeout_secs.max(1))
235 }
236
237 /// TCP connect timeout duration (at least one second).
238 pub fn connect_timeout(&self) -> Duration {
239 Duration::from_secs(self.connect_timeout_secs.max(1))
240 }
241
242 /// Per-host rate-limit delay duration.
243 pub fn rate_limit_delay(&self) -> Duration {
244 Duration::from_millis(self.rate_limit_delay_ms)
245 }
246
247 /// TTL for disk cache entries.
248 pub fn cache_ttl(&self) -> Duration {
249 Duration::from_secs(self.cache_ttl_secs)
250 }
251
252 /// Whether disk cache should be used for HTTP GET bodies.
253 pub fn cache_enabled(&self) -> bool {
254 !self.no_cache && self.cache_dir.is_some()
255 }
256}
257
258/// Resolve docs origin for a crate: stdlib → doc.rust-lang.org, else configured docs.rs origin.
259pub fn docs_origin_for_crate(cfg: &Config, crate_name: &CrateName) -> AllowedOrigin {
260 if crate_name.is_stdlib() {
261 AllowedOrigin::stdlib_docs_default()
262 } else {
263 cfg.docs_rs_origin.clone()
264 }
265}