Skip to main content

docsrs_cli/config/
allowlist.rs

1//! SSRF host/origin allowlist helpers (no domain dependency — used by `AllowedOrigin`).
2
3use 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
8/// Strip trailing slash from an origin base URL.
9pub fn normalize_origin(raw: &str) -> String {
10    raw.trim().trim_end_matches('/').to_string()
11}
12
13/// True when `host` is a product HTTP allowlist entry (SSRF gate).
14///
15/// Production: `crates.io`, `docs.rs`, `static.docs.rs`, `doc.rust-lang.org`.
16/// Loopback (`127.0.0.1` / `localhost`) only when `allow_loopback` is true
17/// (CLI `--allow-loopback` or XDG TOML `allow_loopback = true` — never env).
18pub 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
25/// True when scheme+host is a legal origin for product config (defense in depth).
26///
27/// Production allowlisted hosts require `https`. Loopback (when `allow_loopback`)
28/// allows `http` or `https` for offline mocks.
29pub 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}