1pub(crate) mod allowlist;
6mod constants;
7mod load;
8mod path_source;
9mod validate;
10
11pub use allowlist::{is_allowed_origin_scheme_host, is_allowlisted_host, normalize_origin};
12pub use constants::*;
13pub use load::*;
14pub use path_source::{PathSource, resolve_config_dir, resolve_config_dir_with_source};
15pub use validate::*;
16
17#[cfg(test)]
18mod tests {
19 use super::*;
20 use crate::error::ErrorKind;
21 use std::fs;
22 use std::io::Write;
23 use std::path::{Path, PathBuf};
24 use std::time::Duration;
25
26 #[test]
27 fn stdlib_crate_reexport() {
28 assert!(is_stdlib_crate("std"));
29 assert!(is_stdlib_crate("core"));
30 assert!(is_stdlib_crate("alloc"));
31 assert!(!is_stdlib_crate("serde"));
32 }
33
34 #[test]
35 fn default_user_agent_variants() {
36 let ua = default_user_agent(None);
37 assert!(ua.contains(APP_NAME));
38 assert!(ua.contains(DEFAULT_CONTACT_URL));
39 let ua2 = default_user_agent(Some("dev@example.com"));
40 assert!(ua2.contains("dev@example.com"));
41 let ua3 = default_user_agent(Some("https://example.com"));
42 assert!(ua3.contains("+https://example.com"));
43 }
44
45 #[test]
46 fn validate_origin_accepts_https_and_rejects_garbage() {
47 assert_eq!(
48 validate_origin("https://docs.rs/").unwrap().as_str(),
49 format!("{SCHEME_HTTPS}://{HOST_DOCS_RS}")
50 );
51 assert!(validate_origin("http://127.0.0.1:9/").is_err());
53 assert_eq!(
54 validate_origin_with("http://127.0.0.1:9/", true)
55 .unwrap()
56 .as_str(),
57 "http://127.0.0.1:9"
58 );
59 assert!(validate_origin("").is_err());
60 assert!(validate_origin("not a url").is_err());
61 assert!(validate_origin("ftp://docs.rs").is_err());
62 assert!(validate_origin("https://evil.example/").is_err());
64 assert!(validate_origin("http://docs.rs/").is_err()); assert!(validate_user_agent("docsrs-cli/1.0 (+https://example.com)").is_ok());
66 assert!(validate_user_agent("bad\nua").is_err());
67 assert!(validate_user_agent("").is_err());
68 assert!(validate_user_agent(&"x".repeat(MAX_USER_AGENT_CHARS + 1)).is_err());
69 }
70
71 #[test]
72 fn clamp_caps_redirects_timeouts_and_rate_limit() {
73 let mut cfg = Config {
74 max_redirects: 999,
75 timeout_secs: HARD_MAX_TIMEOUT_SECS.saturating_mul(4),
76 connect_timeout_secs: HARD_MAX_CONNECT_TIMEOUT_SECS.saturating_mul(4),
77 rate_limit_delay_ms: HARD_MAX_RATE_LIMIT_DELAY_MS.saturating_mul(2),
78 ..Config::default()
79 };
80 cfg.clamp_resource_limits();
81 assert_eq!(cfg.max_redirects, HARD_MAX_REDIRECTS);
82 assert_eq!(cfg.timeout_secs, HARD_MAX_TIMEOUT_SECS);
83 assert_eq!(cfg.connect_timeout_secs, HARD_MAX_CONNECT_TIMEOUT_SECS);
84 assert_eq!(cfg.rate_limit_delay_ms, HARD_MAX_RATE_LIMIT_DELAY_MS);
85 }
86
87 #[test]
88 fn config_load_rejects_oversized_toml() {
89 let dir = tempfile::tempdir().unwrap();
90 let path = dir.path().join("config.toml");
91 let huge = format!(
92 "# {}\ntimeout_secs = 9\n",
93 "x".repeat(MAX_CONFIG_TOML_BYTES as usize)
94 );
95 fs::write(&path, huge).unwrap();
96 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
97 assert_eq!(err.kind(), ErrorKind::Config);
98 assert!(err.to_string().contains("max size"));
99 }
100
101 #[test]
102 fn config_load_rejects_non_allowlisted_origin() {
103 let dir = tempfile::tempdir().unwrap();
104 fs::write(
105 dir.path().join("config.toml"),
106 "docs_rs_origin = \"https://evil.example\"\n",
107 )
108 .unwrap();
109 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
110 assert_eq!(err.kind(), ErrorKind::Config);
111 assert!(err.to_string().contains("allowlisted"));
112 }
113
114 #[test]
115 fn default_config_toml_embeds_cargo_metadata() {
116 let text = default_config_toml();
117 assert!(text.contains("docsrs-cli XDG configuration"));
118 assert!(text.contains(APP_VERSION));
119 assert!(text.contains(DEFAULT_CONTACT_URL));
120 assert!(text.contains(HOST_CRATES_IO));
121 assert!(text.contains(HOST_DOCS_RS));
122 assert!(text.contains(&format!("{APP_NAME}/{APP_VERSION}")));
123 }
124
125 #[test]
126 fn config_load_rejects_invalid_origin() {
127 let dir = tempfile::tempdir().unwrap();
128 fs::write(
129 dir.path().join("config.toml"),
130 "docs_rs_origin = \"not-a-url\"\n",
131 )
132 .unwrap();
133 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
134 assert_eq!(err.kind(), ErrorKind::Config);
135 }
136
137 #[test]
143 fn zero_timeouts_in_toml_fail_the_way_the_flag_does() {
144 for key in ["timeout_secs", "connect_timeout_secs"] {
145 let dir = tempfile::tempdir().unwrap();
146 fs::write(dir.path().join("config.toml"), format!("{key} = 0\n")).unwrap();
147 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
148 assert_eq!(err.kind(), ErrorKind::Config, "{key}");
150 assert!(err.message().contains("must be >= 1 second"), "{key}");
151 }
152 }
153
154 #[test]
159 fn unparseable_log_directive_is_rejected_not_swallowed() {
160 let dir = tempfile::tempdir().unwrap();
161 fs::write(
162 dir.path().join("config.toml"),
163 "log_directive = \"docsrs_cli=not_a_level\"\n",
164 )
165 .unwrap();
166 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
167 assert_eq!(err.kind(), ErrorKind::Config);
168 assert!(err.message().contains("log_directive"), "{}", err.message());
169
170 let ok_dir = tempfile::tempdir().unwrap();
172 fs::write(
173 ok_dir.path().join("config.toml"),
174 "log_directive = \"docsrs_cli=debug\"\n",
175 )
176 .unwrap();
177 let cfg = Config::load(Some(ok_dir.path().to_path_buf())).unwrap();
178 assert_eq!(cfg.log_directive.as_deref(), Some("docsrs_cli=debug"));
179 }
180
181 #[test]
182 fn config_load_toml_and_durations() {
183 let dir = tempfile::tempdir().unwrap();
184 let path = dir.path().join("config.toml");
185 let mut f = fs::File::create(&path).unwrap();
186 writeln!(
187 f,
188 "timeout_secs = 12\nrate_limit_delay_ms = 50\ncontact = \"a@b.c\"\nallow_loopback = true\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"
189 )
190 .unwrap();
191 let cache_dir = dir.path().join("cache");
192 let cfg =
193 Config::load_with_cache_dir(Some(dir.path().to_path_buf()), Some(cache_dir.clone()))
194 .unwrap();
195 assert_eq!(cfg.timeout_secs, 12);
196 assert_eq!(cfg.rate_limit_delay_ms, 50);
197 assert!(cfg.user_agent.contains("a@b.c"));
198 assert_eq!(cfg.timeout(), Duration::from_secs(12));
199 assert_eq!(cfg.rate_limit_delay(), Duration::from_millis(50));
200 assert!(cfg.connect_timeout() >= Duration::from_secs(1));
201 assert_eq!(cfg.crates_io_origin.as_str(), "http://127.0.0.1:9");
202 assert_eq!(cfg.docs_rs_origin.as_str(), "http://127.0.0.1:9");
203 assert_eq!(cfg.lang.as_deref(), Some("pt-BR"));
204 assert_eq!(cfg.max_retries, 2);
205 assert_eq!(cfg.max_body_bytes, 1000);
206 assert_eq!(cfg.max_output_bytes, 2000);
207 assert_eq!(cfg.cache_ttl_secs, 3600);
208 assert_eq!(cfg.cache_dir.as_deref(), Some(cache_dir.as_path()));
209 assert!(cfg.cache_enabled());
210 }
211
212 #[test]
213 fn config_invalid_toml_errors() {
214 let dir = tempfile::tempdir().unwrap();
215 fs::write(dir.path().join("config.toml"), "timeout_secs = [\n").unwrap();
216 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
217 assert_eq!(err.kind(), ErrorKind::Config);
218 }
219
220 #[test]
221 fn config_load_rejects_unknown_toml_keys() {
222 let dir = tempfile::tempdir().unwrap();
224 fs::write(
225 dir.path().join("config.toml"),
226 "timeout_secs = 9\nmax_body_bytez = 1\n",
227 )
228 .unwrap();
229 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
230 assert_eq!(err.kind(), ErrorKind::Config);
231 }
232
233 #[test]
234 fn validate_contact_rejects_control_and_non_ascii() {
235 assert!(validate_contact("https://example.com").is_ok());
236 assert!(validate_contact("a@b.c").is_ok());
237 assert!(validate_contact("").is_err());
238 assert!(validate_contact("bad\nline").is_err());
239 assert!(validate_contact("café").is_err());
240 assert!(validate_contact(&"x".repeat(MAX_USER_AGENT_CHARS + 1)).is_err());
241 }
242
243 #[test]
244 fn normalize_origin_trims_slash() {
245 assert_eq!(normalize_origin(" https://docs.rs/ "), "https://docs.rs");
246 }
247
248 #[test]
249 fn resolve_config_dir_prefers_explicit_override() {
250 let explicit = PathBuf::from("/tmp/docsrs-cli-explicit-config");
251 let got = resolve_config_dir(Some(explicit.clone()));
252 assert_eq!(got.as_deref(), Some(explicit.as_path()));
253 }
254
255 #[test]
256 fn resolve_cache_dir_home_layout() {
257 let home = PathBuf::from("/tmp/docsrs-cli-home-sandbox");
259 let cache = home.join("cache");
260 assert_eq!(cache.file_name().and_then(|s| s.to_str()), Some("cache"));
261 let got = crate::cache::resolve_cache_dir(Some(cache.clone()));
263 assert_eq!(got.as_deref(), Some(cache.as_path()));
264 }
265
266 #[test]
267 fn config_defaults_positive() {
268 let cfg = Config::default();
269 assert!(cfg.timeout_secs >= 1);
270 assert!(cfg.max_body_bytes > 0);
271 assert!(cfg.user_agent.contains(APP_NAME));
272 }
273
274 #[test]
275 fn clamp_resource_limits_caps_body_and_output() {
276 let mut cfg = Config {
277 max_body_bytes: HARD_MAX_BODY_BYTES.saturating_mul(8),
278 max_output_bytes: HARD_MAX_OUTPUT_BYTES.saturating_mul(8),
279 ..Config::default()
280 };
281 cfg.clamp_resource_limits();
282 assert_eq!(cfg.max_body_bytes, HARD_MAX_BODY_BYTES);
283 assert_eq!(cfg.max_output_bytes, HARD_MAX_OUTPUT_BYTES);
284 cfg.max_body_bytes = 64;
286 cfg.max_output_bytes = 32;
287 cfg.clamp_resource_limits();
288 assert_eq!(cfg.max_body_bytes, 64);
289 assert_eq!(cfg.max_output_bytes, 32);
290 }
291
292 #[test]
293 fn toml_cannot_raise_max_body_above_hard_ceiling() {
294 let dir = tempfile::tempdir().unwrap();
296 let path = dir.path().join("config.toml");
297 let huge_body = HARD_MAX_BODY_BYTES.saturating_mul(10);
298 let huge_out = HARD_MAX_OUTPUT_BYTES.saturating_mul(10);
299 fs::write(
300 &path,
301 format!("max_body_bytes = {huge_body}\nmax_output_bytes = {huge_out}\n"),
302 )
303 .unwrap();
304 let err =
305 Config::load(Some(dir.path().to_path_buf())).expect_err("over hard max must fail");
306 assert_eq!(err.kind(), crate::error::ErrorKind::Config);
307 assert!(
308 err.message().contains("hard maximum"),
309 "message={}",
310 err.message()
311 );
312 }
313
314 #[test]
315 fn hard_ceilings_equal_defaults() {
316 assert_eq!(HARD_MAX_BODY_BYTES, DEFAULT_MAX_BODY_BYTES);
318 assert_eq!(HARD_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_BYTES);
319 assert_eq!(Config::default().max_body_bytes, HARD_MAX_BODY_BYTES);
320 assert_eq!(Config::default().max_output_bytes, HARD_MAX_OUTPUT_BYTES);
321 }
322
323 #[test]
324 fn path_source_tokens_are_stable() {
325 assert_eq!(PathSource::CliFlag.as_str(), "cli");
326 assert_eq!(PathSource::Xdg.as_str(), "xdg");
327 assert_eq!(PathSource::Unresolved.as_str(), "unresolved");
328 }
329
330 #[test]
331 fn resolve_config_dir_with_source_reports_cli() {
332 let explicit = PathBuf::from("/tmp/docsrs-cli-src-explicit");
333 let (got, source) = resolve_config_dir_with_source(Some(explicit.clone()));
334 assert_eq!(got.as_deref(), Some(explicit.as_path()));
335 assert_eq!(source, PathSource::CliFlag);
336 }
337
338 #[test]
339 fn init_config_toml_creates_and_refuses_without_force() {
340 let dir = tempfile::tempdir().unwrap();
341 let r1 = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap();
342 assert!(r1.created);
343 assert!(!r1.overwritten);
344 assert!(Path::new(&r1.path).is_file());
345 let text = fs::read_to_string(&r1.path).unwrap();
346 assert!(text.contains("docsrs-cli XDG configuration"));
347 assert!(text.contains("No .env file is required"));
348 #[cfg(unix)]
349 {
350 use std::os::unix::fs::PermissionsExt;
351 let mode = fs::metadata(&r1.path).unwrap().permissions().mode() & 0o777;
352 assert_eq!(mode, 0o600);
353 }
354 let err = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap_err();
355 assert_eq!(err.kind(), ErrorKind::Config);
356 let r2 = init_config_toml(Some(dir.path().to_path_buf()), true).unwrap();
357 assert!(r2.created);
358 assert!(r2.overwritten);
359 }
360
361 #[test]
362 fn config_load_marks_toml_loaded() {
363 let dir = tempfile::tempdir().unwrap();
364 fs::write(dir.path().join("config.toml"), "timeout_secs = 9\n").unwrap();
365 let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
366 assert!(cfg.config_toml_loaded);
367 assert_eq!(cfg.timeout_secs, 9);
368 assert_eq!(cfg.config_path_source, PathSource::CliFlag);
369 let inv = config_path_data(&cfg);
370 assert!(inv.config_file_exists);
371 assert!(!inv.dotenv_runtime);
372 }
373
374 #[test]
375 fn config_load_without_toml_is_not_loaded() {
376 let dir = tempfile::tempdir().unwrap();
377 let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
378 assert!(!cfg.config_toml_loaded);
379 assert!(!config_path_data(&cfg).config_file_exists);
380 }
381
382 #[test]
384 fn product_paths_ignore_docsrs_cli_env() {
385 let explicit = PathBuf::from("/tmp/docsrs-cli-policy-explicit-config");
388 let (got, source) = resolve_config_dir_with_source(Some(explicit.clone()));
389 assert_eq!(got.as_deref(), Some(explicit.as_path()));
390 assert_eq!(source, PathSource::CliFlag);
391
392 let (cache, csource) = crate::cache::resolve_cache_dir_with_source(Some(PathBuf::from(
393 "/tmp/docsrs-cli-policy-cache",
394 )));
395 assert_eq!(
396 cache.as_deref(),
397 Some(Path::new("/tmp/docsrs-cli-policy-cache"))
398 );
399 assert_eq!(csource, PathSource::CliFlag);
400 }
401}