1use 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
18pub 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#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct Config {
68 pub timeout_secs: u64,
70 pub connect_timeout_secs: u64,
72 pub max_body_bytes: u64,
74 pub max_output_bytes: u64,
76 pub max_redirects: u32,
78 pub max_retries: u32,
80 pub retry_base_ms: u64,
82 pub retry_max_delay_ms: u64,
84 pub retry_max_elapsed_ms: u64,
86 pub disable_retry: bool,
88 pub rate_limit_delay_ms: u64,
90 pub max_concurrency: u32,
94 pub user_agent: String,
96 pub contact: Option<String>,
98 pub lang: Option<String>,
100 pub config_dir: Option<PathBuf>,
102 pub cache_dir: Option<PathBuf>,
104 pub cache_ttl_secs: u64,
106 pub max_cache_bytes: u64,
108 pub no_cache: bool,
110 pub crates_io_origin: AllowedOrigin,
112 pub docs_rs_origin: AllowedOrigin,
114 pub allow_loopback: bool,
119 pub config_path_source: PathSource,
121 pub cache_path_source: PathSource,
123 pub config_toml_loaded: bool,
125}
126
127impl Default for Config {
128 fn default() -> Self {
129 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
163fn 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#[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 pub fn load(config_dir_override: Option<PathBuf>) -> AppResult<Self> {
242 Self::load_with_cache_dir(config_dir_override, None)
243 }
244
245 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 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 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 pub fn validate_origins(&mut self) -> AppResult<()> {
311 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 pub fn validate_security(&mut self) -> AppResult<()> {
325 self.validate_origins()?;
326 if let Some(c) = &self.contact {
327 validate_contact(c)?;
328 }
329 validate_user_agent(&self.user_agent)?;
333 Ok(())
334 }
335
336 pub fn config_file_path(&self) -> Option<PathBuf> {
338 self.config_dir.as_ref().map(|d| d.join("config.toml"))
339 }
340
341 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 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 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 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 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 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 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 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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
495pub struct ConfigInitResult {
496 pub path: String,
498 pub config_dir: String,
500 pub source: PathSource,
502 pub created: bool,
504 pub overwritten: bool,
506}
507
508pub 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 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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
594pub struct ConfigPathData {
595 pub config_dir: Option<String>,
597 pub config_source: PathSource,
599 pub config_file: Option<String>,
601 pub config_file_exists: bool,
603 pub config_toml_loaded: bool,
605 pub cache_dir: Option<String>,
607 pub cache_source: PathSource,
609 pub dotenv_runtime: bool,
611 pub secrets_layers: &'static str,
613}
614
615pub 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
632pub fn config_toml_under(dir: &Path) -> PathBuf {
634 dir.join("config.toml")
635}
636
637impl Config {
638 pub fn timeout(&self) -> Duration {
640 Duration::from_secs(self.timeout_secs.max(1))
641 }
642
643 pub fn connect_timeout(&self) -> Duration {
645 Duration::from_secs(self.connect_timeout_secs.max(1))
646 }
647
648 pub fn rate_limit_delay(&self) -> Duration {
650 Duration::from_millis(self.rate_limit_delay_ms)
651 }
652
653 pub fn cache_ttl(&self) -> Duration {
655 Duration::from_secs(self.cache_ttl_secs)
656 }
657
658 pub fn cache_enabled(&self) -> bool {
660 !self.no_cache && self.cache_dir.is_some()
661 }
662}
663
664pub 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