Skip to main content

docsrs_cli/domain/
origin.rs

1//! Allowlisted HTTP(S) origin (SSRF gate proof in the type).
2
3use std::fmt;
4
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6use url::Url;
7
8use crate::config::{
9    HOST_CRATES_IO, HOST_DOC_RUST_LANG_ORG, HOST_DOCS_RS, HOST_STATIC_DOCS_RS, SCHEME_HTTPS,
10    is_allowed_origin_scheme_host, normalize_origin,
11};
12use crate::error::{AppError, AppResult, ErrorDetail, InternalOp, Subject};
13
14/// HTTPS (or gated loopback) origin that passed the product SSRF allowlist.
15///
16/// Construct only via [`AllowedOrigin::parse`] / [`AllowedOrigin::parse_with`].
17/// Field is private so callers cannot assign an arbitrary host without
18/// re-validation (TYPE-L-004 / ADR 0006).
19#[repr(transparent)]
20#[derive(Debug, Clone, PartialEq, Eq, Hash)]
21pub struct AllowedOrigin(String);
22
23impl AllowedOrigin {
24    /// Parse and normalize an HTTP(S) origin with production allowlist
25    /// (`allow_loopback = false`).
26    ///
27    /// For offline wiremock / loopback origins use [`Self::parse_with`].
28    ///
29    /// # Errors
30    ///
31    /// Returns [`crate::error::ErrorKind::Config`] when the string is not a valid `http`/`https` URL
32    /// with a host (empty, bare path, unsupported scheme, or non-allowlisted host).
33    pub fn parse(raw: &str) -> AppResult<Self> {
34        Self::parse_with(raw, false)
35    }
36
37    /// Parse and normalize an HTTP(S) origin (scheme + host, no path required).
38    ///
39    /// Hosts must pass the product SSRF allowlist. When `allow_loopback` is true,
40    /// `127.0.0.1` / `localhost` with `http` or `https` are accepted (CLI
41    /// `--allow-loopback` or XDG TOML `allow_loopback = true` — never env).
42    /// Arbitrary origins such as `https://evil.example` are always rejected.
43    ///
44    /// # Errors
45    ///
46    /// Returns [`crate::error::ErrorKind::Config`] when the string is not a valid `http`/`https` URL
47    /// with a host (empty, bare path, unsupported scheme, or non-allowlisted host).
48    pub fn parse_with(raw: &str, allow_loopback: bool) -> AppResult<Self> {
49        let normalized = normalize_origin(raw);
50        if normalized.is_empty() {
51            return Err(AppError::of(ErrorDetail::Empty {
52                subject: Subject::Origin,
53            }));
54        }
55        let url = url::Url::parse(&normalized).map_err(|e| {
56            AppError::of_with_source(
57                ErrorDetail::Invalid {
58                    subject: Subject::Origin,
59                    value: normalized.to_string(),
60                },
61                e,
62            )
63        })?;
64        let scheme = url.scheme();
65        if scheme != "http" && scheme != "https" {
66            return Err(AppError::of(ErrorDetail::OriginBadScheme {
67                scheme: scheme.to_string(),
68            }));
69        }
70        let Some(host) = url.host_str() else {
71            return Err(AppError::of(ErrorDetail::OriginMissingHost {
72                url: normalized.to_string(),
73            }));
74        };
75        if !is_allowed_origin_scheme_host(scheme, host, allow_loopback) {
76            return Err(AppError::of(ErrorDetail::OriginNotAllowlisted {
77                host: host.to_string(),
78                allowed: format!(
79                    "{HOST_CRATES_IO}, {HOST_DOCS_RS}, {HOST_STATIC_DOCS_RS}, {HOST_DOC_RUST_LANG_ORG}"
80                ),
81            }));
82        }
83        // Drop path/query/fragment so origins stay host-level bases.
84        let port = url.port().map(|p| format!(":{p}")).unwrap_or_default();
85        Ok(Self(format!("{scheme}://{host}{port}")))
86    }
87
88    /// Default crates.io API origin (valid by construction).
89    #[must_use]
90    pub fn crates_io_default() -> Self {
91        Self(format!("{SCHEME_HTTPS}://{HOST_CRATES_IO}"))
92    }
93
94    /// Default docs.rs origin (valid by construction).
95    #[must_use]
96    pub fn docs_rs_default() -> Self {
97        Self(format!("{SCHEME_HTTPS}://{HOST_DOCS_RS}"))
98    }
99
100    /// Default stdlib docs origin on doc.rust-lang.org (valid by construction).
101    #[must_use]
102    pub fn stdlib_docs_default() -> Self {
103        Self(format!("{SCHEME_HTTPS}://{HOST_DOC_RUST_LANG_ORG}"))
104    }
105
106    /// Borrow the origin string (no trailing slash).
107    #[must_use]
108    pub fn as_str(&self) -> &str {
109        &self.0
110    }
111
112    /// Re-parse this validated origin into a WHATWG [`Url`] (fail-closed).
113    ///
114    /// Used by URL builders that need a typed base. The stored string was produced
115    /// by [`Self::parse`] (or a default constructor), so failure is treated as an
116    /// internal invariant break rather than user input (ADR 0008).
117    ///
118    /// # Errors
119    ///
120    /// Returns [`crate::error::ErrorKind::Internal`] if the stored origin is not a valid URL
121    /// (should not happen for values constructed via this type).
122    pub fn to_url(&self) -> AppResult<Url> {
123        Url::parse(self.as_str()).map_err(|e| {
124            AppError::of_with_source(
125                ErrorDetail::Internal {
126                    op: InternalOp::AllowedOriginUnparseable,
127                },
128                e,
129            )
130        })
131    }
132}
133
134impl AsRef<str> for AllowedOrigin {
135    fn as_ref(&self) -> &str {
136        self.as_str()
137    }
138}
139
140impl fmt::Display for AllowedOrigin {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        f.write_str(self.as_str())
143    }
144}
145
146impl Serialize for AllowedOrigin {
147    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
148        serializer.serialize_str(self.as_str())
149    }
150}
151
152impl<'de> Deserialize<'de> for AllowedOrigin {
153    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
154        let s = String::deserialize(deserializer)?;
155        Self::parse(&s).map_err(serde::de::Error::custom)
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn parse_accepts_https_and_rejects_garbage() {
165        assert_eq!(
166            AllowedOrigin::parse("https://docs.rs/").unwrap().as_str(),
167            format!("{SCHEME_HTTPS}://{HOST_DOCS_RS}")
168        );
169        assert!(AllowedOrigin::parse("https://evil.example").is_err());
170        assert!(AllowedOrigin::parse("not-a-url").is_err());
171        assert!(AllowedOrigin::parse("").is_err());
172        assert!(AllowedOrigin::parse("http://127.0.0.1:9").is_err());
173        assert_eq!(
174            AllowedOrigin::parse_with("http://127.0.0.1:9/", true)
175                .unwrap()
176                .as_str(),
177            "http://127.0.0.1:9"
178        );
179    }
180
181    #[test]
182    fn defaults_round_trip() {
183        assert_eq!(
184            AllowedOrigin::crates_io_default().as_str(),
185            format!("{SCHEME_HTTPS}://{HOST_CRATES_IO}")
186        );
187        assert_eq!(
188            AllowedOrigin::docs_rs_default().as_str(),
189            format!("{SCHEME_HTTPS}://{HOST_DOCS_RS}")
190        );
191    }
192
193    #[test]
194    fn to_url_round_trips_defaults() {
195        let o = AllowedOrigin::docs_rs_default();
196        let u = o.to_url().unwrap();
197        assert_eq!(u.scheme(), SCHEME_HTTPS);
198        assert_eq!(u.host_str(), Some(HOST_DOCS_RS));
199        assert_eq!(u.as_str().trim_end_matches('/'), o.as_str());
200    }
201}