docsrs_cli/config/
allowlist.rs1use super::constants::{
4 HOST_CRATES_IO, HOST_DOC_RUST_LANG_ORG, HOST_DOCS_RS, HOST_LOCALHOST, HOST_LOOPBACK_IPV4,
5 HOST_STATIC_DOCS_RS, SCHEME_HTTPS,
6};
7
8pub fn normalize_origin(raw: &str) -> String {
10 raw.trim().trim_end_matches('/').to_string()
11}
12
13pub fn is_allowlisted_host(host: &str, allow_loopback: bool) -> bool {
19 matches!(
20 host,
21 HOST_CRATES_IO | HOST_DOCS_RS | HOST_STATIC_DOCS_RS | HOST_DOC_RUST_LANG_ORG
22 ) || (allow_loopback && (host == HOST_LOOPBACK_IPV4 || host == HOST_LOCALHOST))
23}
24
25pub fn is_allowed_origin_scheme_host(scheme: &str, host: &str, allow_loopback: bool) -> bool {
30 if !is_allowlisted_host(host, allow_loopback) {
31 return false;
32 }
33 if host == HOST_LOOPBACK_IPV4 || host == HOST_LOCALHOST {
34 return scheme == "http" || scheme == "https";
35 }
36 scheme == SCHEME_HTTPS
37}
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42
43 #[test]
44 fn loopback_requires_explicit_flag() {
45 assert!(!is_allowlisted_host(HOST_LOOPBACK_IPV4, false));
46 assert!(!is_allowlisted_host(HOST_LOCALHOST, false));
47 assert!(is_allowlisted_host(HOST_LOOPBACK_IPV4, true));
48 assert!(is_allowlisted_host(HOST_LOCALHOST, true));
49 assert!(is_allowlisted_host(HOST_DOCS_RS, false));
50 assert!(!is_allowlisted_host("evil.example", true));
51 }
52
53 #[test]
54 fn production_hosts_require_https() {
55 assert!(is_allowed_origin_scheme_host("https", HOST_DOCS_RS, false));
56 assert!(!is_allowed_origin_scheme_host("http", HOST_DOCS_RS, false));
57 assert!(is_allowed_origin_scheme_host(
58 "http",
59 HOST_LOOPBACK_IPV4,
60 true
61 ));
62 assert!(!is_allowed_origin_scheme_host(
63 "http",
64 HOST_LOOPBACK_IPV4,
65 false
66 ));
67 }
68}