Skip to main content

reth_rpc_builder/
cors.rs

1use http::{header::ORIGIN, HeaderValue, Method, Request, Response, StatusCode};
2use jsonrpsee::server::{ws, HttpBody};
3use tower_http::{
4    cors::{AllowOrigin, Any, CorsLayer},
5    validate_request::ValidateRequest,
6};
7
8/// Error thrown when parsing cors domains went wrong
9#[derive(Debug, thiserror::Error)]
10pub enum CorsDomainError {
11    /// Represents an invalid header value for a domain
12    #[error("{domain} is an invalid header value")]
13    InvalidHeader {
14        /// The domain that caused the invalid header
15        domain: String,
16    },
17
18    /// Indicates that a wildcard origin was used incorrectly in a list
19    #[error("wildcard origin (`*`) cannot be passed as part of a list: {input}")]
20    WildCardNotAllowed {
21        /// The input string containing the incorrectly used wildcard
22        input: String,
23    },
24}
25
26/// Creates a [`CorsLayer`] from the given domains
27pub(crate) fn create_cors_layer(http_cors_domains: &str) -> Result<CorsLayer, CorsDomainError> {
28    let cors = match parse_origins(http_cors_domains)? {
29        None => CorsLayer::new()
30            .allow_methods([Method::GET, Method::POST])
31            .allow_origin(Any)
32            .allow_headers(Any),
33        Some(origins) => {
34            let origin = AllowOrigin::list(origins);
35            CorsLayer::new()
36                .allow_methods([Method::GET, Method::POST])
37                .allow_origin(origin)
38                .allow_headers(Any)
39        }
40    };
41    Ok(cors)
42}
43
44/// Origin policy for `WebSocket` upgrades.
45#[derive(Clone, Debug)]
46pub(crate) enum WsOriginValidator {
47    Local,
48    Any,
49    List(Vec<HeaderValue>),
50}
51
52impl WsOriginValidator {
53    pub(crate) fn new(domains: Option<&str>) -> Result<Self, CorsDomainError> {
54        let Some(domains) = domains else { return Ok(Self::Local) };
55        Ok(match parse_origins(domains)? {
56            Some(origins) => Self::List(origins),
57            None => Self::Any,
58        })
59    }
60}
61
62impl<B> ValidateRequest<B> for WsOriginValidator {
63    type ResponseBody = HttpBody;
64
65    fn validate(&mut self, request: &mut Request<B>) -> Result<(), Response<HttpBody>> {
66        if ws::is_upgrade_request(request) {
67            let mut origins = request.headers().get_all(ORIGIN).iter();
68            // Native clients can omit Origin.
69            let Some(origin) = origins.next() else { return Ok(()) };
70            let allowed = match self {
71                Self::Any => return Ok(()),
72                Self::Local => is_local_origin(origin),
73                Self::List(allowed) => allowed.contains(origin),
74            };
75            if !allowed || origins.next().is_some() {
76                let mut response = Response::new(HttpBody::empty());
77                *response.status_mut() = StatusCode::FORBIDDEN;
78                return Err(response)
79            }
80        }
81        Ok(())
82    }
83}
84
85fn is_local_origin(origin: &HeaderValue) -> bool {
86    let Ok(origin) = origin.to_str() else { return false };
87    let Some(("http" | "https", authority)) = origin.split_once("://") else { return false };
88    // Browser origins contain only a scheme, host and optional port.
89    let host = match authority.rsplit_once(':') {
90        Some((host, port)) if !port.starts_with('+') && port.parse::<u16>().is_ok() => host,
91        _ => authority,
92    };
93    matches!(host, "localhost" | "127.0.0.1" | "[::1]")
94}
95
96fn parse_origins(domains: &str) -> Result<Option<Vec<HeaderValue>>, CorsDomainError> {
97    if domains.trim() == "*" {
98        return Ok(None)
99    }
100    let iter = domains.split(',').map(str::trim);
101    if iter.clone().any(|origin| origin == "*") {
102        return Err(CorsDomainError::WildCardNotAllowed { input: domains.to_string() })
103    }
104    iter.map(|domain| {
105        domain.parse().map_err(|_| CorsDomainError::InvalidHeader { domain: domain.to_string() })
106    })
107    .collect::<Result<Vec<_>, _>>()
108    .map(Some)
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    #[test]
116    fn test_wildcard_with_spaces_rejected() {
117        // Wildcard with leading space should still be rejected
118        let result = create_cors_layer("http://example.com, *");
119        assert!(matches!(result, Err(CorsDomainError::WildCardNotAllowed { .. })));
120    }
121}