Skip to main content

docsrs_cli/config/
validate.rs

1//! UA/contact validation and re-exports for origin allowlist / domain helpers.
2//!
3//! Fail-closed SSRF host policy lives in [`super::allowlist`]. Domain input
4//! (crate name, query, path, version) lives in [`crate::domain`] (ADR 0006).
5
6use crate::domain::AllowedOrigin;
7use crate::error::{AppError, AppResult, ErrorKind};
8
9use super::constants::{APP_NAME, APP_VERSION, DEFAULT_CONTACT_URL, MAX_USER_AGENT_CHARS};
10
11// Re-export stdlib name check from the single domain source (DRY-L-001).
12pub use crate::domain::is_stdlib_name as is_stdlib_crate;
13
14/// Builds the default User-Agent, optionally including a contact token.
15pub fn default_user_agent(contact: Option<&str>) -> String {
16    match contact {
17        Some(c) if !c.is_empty() => {
18            if c.starts_with("http://") || c.starts_with("https://") {
19                format!("{APP_NAME}/{APP_VERSION} (+{c})")
20            } else {
21                format!("{APP_NAME}/{APP_VERSION} ({c})")
22            }
23        }
24        _ => format!("{APP_NAME}/{APP_VERSION} (+{DEFAULT_CONTACT_URL})"),
25    }
26}
27
28/// Parse an allowlisted origin (compat wrapper over [`AllowedOrigin::parse`]).
29///
30/// Prefer [`AllowedOrigin`] at call sites so the type carries the allowlist proof.
31///
32/// # Errors
33///
34/// Propagates [`ErrorKind::Config`] from [`AllowedOrigin::parse`].
35pub fn validate_origin(raw: &str) -> AppResult<AllowedOrigin> {
36    AllowedOrigin::parse(raw)
37}
38
39/// Parse an origin with an explicit loopback policy (CLI/XDG `allow_loopback`).
40///
41/// # Errors
42///
43/// Propagates [`ErrorKind::Config`] from [`AllowedOrigin::parse_with`].
44pub fn validate_origin_with(raw: &str, allow_loopback: bool) -> AppResult<AllowedOrigin> {
45    AllowedOrigin::parse_with(raw, allow_loopback)
46}
47
48/// Validate User-Agent: non-empty, length-capped, visible ASCII only (HTTP header).
49///
50/// # Errors
51///
52/// Returns [`ErrorKind::Config`] when empty, over [`MAX_USER_AGENT_CHARS`], or
53/// containing control / non-ASCII bytes (would fail `HeaderValue::from_str`).
54pub fn validate_user_agent(ua: &str) -> AppResult<()> {
55    if ua.is_empty() {
56        return Err(AppError::new(
57            ErrorKind::Config,
58            "user-agent must not be empty",
59        ));
60    }
61    if ua.chars().count() > MAX_USER_AGENT_CHARS {
62        return Err(AppError::new(
63            ErrorKind::Config,
64            format!("user-agent exceeds {MAX_USER_AGENT_CHARS} characters"),
65        ));
66    }
67    // RFC 9110 field values: reject CTL and non-ASCII so HeaderValue cannot fail later.
68    if !ua.bytes().all(|b| (0x20..=0x7e).contains(&b)) {
69        return Err(AppError::new(
70            ErrorKind::Config,
71            "user-agent must be visible ASCII (no control characters or non-ASCII)",
72        ));
73    }
74    Ok(())
75}
76
77/// Validate optional `contact` token embedded into the default User-Agent.
78///
79/// Same visible-ASCII policy as [`validate_user_agent`] (contact is interpolated
80/// into the UA string). Empty contact is rejected when present as `Some("")`.
81///
82/// # Errors
83///
84/// Returns [`ErrorKind::Config`] when empty, over [`MAX_USER_AGENT_CHARS`], or
85/// not visible ASCII.
86pub fn validate_contact(contact: &str) -> AppResult<()> {
87    if contact.is_empty() {
88        return Err(AppError::new(
89            ErrorKind::Config,
90            "contact must not be empty when set",
91        ));
92    }
93    if contact.chars().count() > MAX_USER_AGENT_CHARS {
94        return Err(AppError::new(
95            ErrorKind::Config,
96            format!("contact exceeds {MAX_USER_AGENT_CHARS} characters"),
97        ));
98    }
99    if !contact.bytes().all(|b| (0x20..=0x7e).contains(&b)) {
100        return Err(AppError::new(
101            ErrorKind::Config,
102            "contact must be visible ASCII (no control characters or non-ASCII)",
103        ));
104    }
105    Ok(())
106}