1pub(crate) mod allowlist;
6mod constants;
7mod load;
8mod path_source;
9mod validate;
10
11pub use allowlist::{is_allowlisted_host, is_allowed_origin_scheme_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::path::{Path, PathBuf};
22 use std::time::Duration;
23 use std::fs;
24 use std::io::Write;
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!("# {}\ntimeout_secs = 9\n", "x".repeat(MAX_CONFIG_TOML_BYTES as usize));
92 fs::write(&path, huge).unwrap();
93 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
94 assert_eq!(err.kind(), ErrorKind::Config);
95 assert!(err.to_string().contains("max size"));
96 }
97
98 #[test]
99 fn config_load_rejects_non_allowlisted_origin() {
100 let dir = tempfile::tempdir().unwrap();
101 fs::write(
102 dir.path().join("config.toml"),
103 "docs_rs_origin = \"https://evil.example\"\n",
104 )
105 .unwrap();
106 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
107 assert_eq!(err.kind(), ErrorKind::Config);
108 assert!(err.to_string().contains("allowlisted"));
109 }
110
111 #[test]
112 fn default_config_toml_embeds_cargo_metadata() {
113 let text = default_config_toml();
114 assert!(text.contains("docsrs-cli XDG configuration"));
115 assert!(text.contains(APP_VERSION));
116 assert!(text.contains(DEFAULT_CONTACT_URL));
117 assert!(text.contains(HOST_CRATES_IO));
118 assert!(text.contains(HOST_DOCS_RS));
119 assert!(text.contains(&format!("{APP_NAME}/{APP_VERSION}")));
120 }
121
122 #[test]
123 fn config_load_rejects_invalid_origin() {
124 let dir = tempfile::tempdir().unwrap();
125 fs::write(
126 dir.path().join("config.toml"),
127 "docs_rs_origin = \"not-a-url\"\n",
128 )
129 .unwrap();
130 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
131 assert_eq!(err.kind(), ErrorKind::Config);
132 }
133
134 #[test]
135 fn config_load_toml_and_durations() {
136 let dir = tempfile::tempdir().unwrap();
137 let path = dir.path().join("config.toml");
138 let mut f = fs::File::create(&path).unwrap();
139 writeln!(
140 f,
141 "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"
142 )
143 .unwrap();
144 let cache_dir = dir.path().join("cache");
145 let cfg =
146 Config::load_with_cache_dir(Some(dir.path().to_path_buf()), Some(cache_dir.clone()))
147 .unwrap();
148 assert_eq!(cfg.timeout_secs, 12);
149 assert_eq!(cfg.rate_limit_delay_ms, 50);
150 assert!(cfg.user_agent.contains("a@b.c"));
151 assert_eq!(cfg.timeout(), Duration::from_secs(12));
152 assert_eq!(cfg.rate_limit_delay(), Duration::from_millis(50));
153 assert!(cfg.connect_timeout() >= Duration::from_secs(1));
154 assert_eq!(cfg.crates_io_origin.as_str(), "http://127.0.0.1:9");
155 assert_eq!(cfg.docs_rs_origin.as_str(), "http://127.0.0.1:9");
156 assert_eq!(cfg.lang.as_deref(), Some("pt-BR"));
157 assert_eq!(cfg.max_retries, 2);
158 assert_eq!(cfg.max_body_bytes, 1000);
159 assert_eq!(cfg.max_output_bytes, 2000);
160 assert_eq!(cfg.cache_ttl_secs, 3600);
161 assert_eq!(cfg.cache_dir.as_deref(), Some(cache_dir.as_path()));
162 assert!(cfg.cache_enabled());
163 }
164
165 #[test]
166 fn config_invalid_toml_errors() {
167 let dir = tempfile::tempdir().unwrap();
168 fs::write(dir.path().join("config.toml"), "timeout_secs = [\n").unwrap();
169 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
170 assert_eq!(err.kind(), ErrorKind::Config);
171 }
172
173 #[test]
174 fn config_load_rejects_unknown_toml_keys() {
175 let dir = tempfile::tempdir().unwrap();
177 fs::write(
178 dir.path().join("config.toml"),
179 "timeout_secs = 9\nmax_body_bytez = 1\n",
180 )
181 .unwrap();
182 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
183 assert_eq!(err.kind(), ErrorKind::Config);
184 }
185
186 #[test]
187 fn validate_contact_rejects_control_and_non_ascii() {
188 assert!(validate_contact("https://example.com").is_ok());
189 assert!(validate_contact("a@b.c").is_ok());
190 assert!(validate_contact("").is_err());
191 assert!(validate_contact("bad\nline").is_err());
192 assert!(validate_contact("café").is_err());
193 assert!(validate_contact(&"x".repeat(MAX_USER_AGENT_CHARS + 1)).is_err());
194 }
195
196 #[test]
197 fn normalize_origin_trims_slash() {
198 assert_eq!(normalize_origin(" https://docs.rs/ "), "https://docs.rs");
199 }
200
201 #[test]
202 fn resolve_config_dir_prefers_explicit_override() {
203 let explicit = PathBuf::from("/tmp/docsrs-cli-explicit-config");
204 let got = resolve_config_dir(Some(explicit.clone()));
205 assert_eq!(got.as_deref(), Some(explicit.as_path()));
206 }
207
208 #[test]
209 fn resolve_cache_dir_home_layout() {
210 let home = PathBuf::from("/tmp/docsrs-cli-home-sandbox");
212 let cache = home.join("cache");
213 assert_eq!(cache.file_name().and_then(|s| s.to_str()), Some("cache"));
214 let got = crate::cache::resolve_cache_dir(Some(cache.clone()));
216 assert_eq!(got.as_deref(), Some(cache.as_path()));
217 }
218
219 #[test]
220 fn config_defaults_positive() {
221 let cfg = Config::default();
222 assert!(cfg.timeout_secs >= 1);
223 assert!(cfg.max_body_bytes > 0);
224 assert!(cfg.user_agent.contains(APP_NAME));
225 }
226
227 #[test]
228 fn clamp_resource_limits_caps_body_and_output() {
229 let mut cfg = Config {
230 max_body_bytes: HARD_MAX_BODY_BYTES.saturating_mul(8),
231 max_output_bytes: HARD_MAX_OUTPUT_BYTES.saturating_mul(8),
232 ..Config::default()
233 };
234 cfg.clamp_resource_limits();
235 assert_eq!(cfg.max_body_bytes, HARD_MAX_BODY_BYTES);
236 assert_eq!(cfg.max_output_bytes, HARD_MAX_OUTPUT_BYTES);
237 cfg.max_body_bytes = 64;
239 cfg.max_output_bytes = 32;
240 cfg.clamp_resource_limits();
241 assert_eq!(cfg.max_body_bytes, 64);
242 assert_eq!(cfg.max_output_bytes, 32);
243 }
244
245 #[test]
246 fn toml_cannot_raise_max_body_above_hard_ceiling() {
247 let dir = tempfile::tempdir().unwrap();
249 let path = dir.path().join("config.toml");
250 let huge_body = HARD_MAX_BODY_BYTES.saturating_mul(10);
251 let huge_out = HARD_MAX_OUTPUT_BYTES.saturating_mul(10);
252 fs::write(
253 &path,
254 format!("max_body_bytes = {huge_body}\nmax_output_bytes = {huge_out}\n"),
255 )
256 .unwrap();
257 let err = Config::load(Some(dir.path().to_path_buf())).expect_err("over hard max must fail");
258 assert_eq!(err.kind(), crate::error::ErrorKind::Config);
259 assert!(
260 err.message().contains("hard maximum"),
261 "message={}",
262 err.message()
263 );
264 }
265
266 #[test]
267 fn hard_ceilings_equal_defaults() {
268 assert_eq!(HARD_MAX_BODY_BYTES, DEFAULT_MAX_BODY_BYTES);
270 assert_eq!(HARD_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_BYTES);
271 assert_eq!(Config::default().max_body_bytes, HARD_MAX_BODY_BYTES);
272 assert_eq!(Config::default().max_output_bytes, HARD_MAX_OUTPUT_BYTES);
273 }
274
275 #[test]
276 fn path_source_tokens_are_stable() {
277 assert_eq!(PathSource::CliFlag.as_str(), "cli");
278 assert_eq!(PathSource::Xdg.as_str(), "xdg");
279 assert_eq!(PathSource::Unresolved.as_str(), "unresolved");
280 }
281
282 #[test]
283 fn resolve_config_dir_with_source_reports_cli() {
284 let explicit = PathBuf::from("/tmp/docsrs-cli-src-explicit");
285 let (got, source) = resolve_config_dir_with_source(Some(explicit.clone()));
286 assert_eq!(got.as_deref(), Some(explicit.as_path()));
287 assert_eq!(source, PathSource::CliFlag);
288 }
289
290 #[test]
291 fn init_config_toml_creates_and_refuses_without_force() {
292 let dir = tempfile::tempdir().unwrap();
293 let r1 = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap();
294 assert!(r1.created);
295 assert!(!r1.overwritten);
296 assert!(Path::new(&r1.path).is_file());
297 let text = fs::read_to_string(&r1.path).unwrap();
298 assert!(text.contains("docsrs-cli XDG configuration"));
299 assert!(text.contains("No .env file is required"));
300 #[cfg(unix)]
301 {
302 use std::os::unix::fs::PermissionsExt;
303 let mode = fs::metadata(&r1.path).unwrap().permissions().mode() & 0o777;
304 assert_eq!(mode, 0o600);
305 }
306 let err = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap_err();
307 assert_eq!(err.kind(), ErrorKind::Config);
308 let r2 = init_config_toml(Some(dir.path().to_path_buf()), true).unwrap();
309 assert!(r2.created);
310 assert!(r2.overwritten);
311 }
312
313 #[test]
314 fn config_load_marks_toml_loaded() {
315 let dir = tempfile::tempdir().unwrap();
316 fs::write(dir.path().join("config.toml"), "timeout_secs = 9\n").unwrap();
317 let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
318 assert!(cfg.config_toml_loaded);
319 assert_eq!(cfg.timeout_secs, 9);
320 assert_eq!(cfg.config_path_source, PathSource::CliFlag);
321 let inv = config_path_data(&cfg);
322 assert!(inv.config_file_exists);
323 assert!(!inv.dotenv_runtime);
324 }
325
326 #[test]
327 fn config_load_without_toml_is_not_loaded() {
328 let dir = tempfile::tempdir().unwrap();
329 let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
330 assert!(!cfg.config_toml_loaded);
331 assert!(!config_path_data(&cfg).config_file_exists);
332 }
333
334 #[test]
336 fn product_paths_ignore_docsrs_cli_env() {
337 let explicit = PathBuf::from("/tmp/docsrs-cli-policy-explicit-config");
340 let (got, source) = resolve_config_dir_with_source(Some(explicit.clone()));
341 assert_eq!(got.as_deref(), Some(explicit.as_path()));
342 assert_eq!(source, PathSource::CliFlag);
343
344 let (cache, csource) =
345 crate::cache::resolve_cache_dir_with_source(Some(PathBuf::from("/tmp/docsrs-cli-policy-cache")));
346 assert_eq!(
347 cache.as_deref(),
348 Some(Path::new("/tmp/docsrs-cli-policy-cache"))
349 );
350 assert_eq!(csource, PathSource::CliFlag);
351 }
352}