Skip to main content

saml2_sp/
http.rs

1// SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC
2// SPDX-License-Identifier: MIT
3
4use std::io::Read;
5use std::time::Duration;
6
7use crate::error::{err, SamlError};
8
9const MAX_BYTES: u64 = 2 * 1024 * 1024;
10
11/// Trust and client certificate for the back channel.
12#[derive(Clone, Default)]
13pub struct TlsOptions {
14    pub ca: String,
15    pub cert: String,
16    pub key: String,
17}
18
19pub(crate) struct HttpAnswer {
20    pub status: u16,
21    pub body: String,
22}
23
24pub(crate) fn send(raw_url: &str, method: &str, headers: &[(&str, &str)], body: &str, tls: Option<&TlsOptions>, code: &str) -> Result<HttpAnswer, SamlError> {
25    if !(raw_url.starts_with("https://") || raw_url.starts_with("http://")) {
26        return Err(err(code, format!("{raw_url} is not an http(s) URL")));
27    }
28    refuse_whitespace_or_control(raw_url, code)?;
29    // Every fetch this library makes comes through here: the identity
30    // provider's metadata (its signing keys), the ArtifactResolve (the signed
31    // request out, the assertion back) and the Shared Signals transmitter
32    // (SETs and the bearer token). None of them may travel in the clear off
33    // this machine, so plain http is refused before any DNS lookup or
34    // connection unless the host is loopback, and so is every redirect, which
35    // is why redirects are followed here rather than by ureq.
36    let agent = agent(tls, code)?;
37    let mut target = raw_url.to_string();
38    let mut method = method.to_string();
39    let mut body = body.to_string();
40    let mut hop = 0;
41    let (status, response) = loop {
42        let mut request = agent.request(&method, &target);
43        let url = request.request_url().map_err(|e| err(code, format!("{raw_url}: {e}")))?;
44        refuse_plain_http_off_loopback(&url, code)?;
45        for (key, value) in headers {
46            request = request.set(key, value);
47        }
48        let result = if method.eq_ignore_ascii_case("GET") || method.eq_ignore_ascii_case("HEAD") || (body.is_empty() && !method.eq_ignore_ascii_case("POST") && !method.eq_ignore_ascii_case("PUT")) {
49            request.call()
50        } else {
51            request.send_string(&body)
52        };
53        let (status, response) = match result {
54            Ok(response) => (response.status(), response),
55            Err(ureq::Error::Status(status, response)) => (status, response),
56            Err(ureq::Error::Transport(transport)) => {
57                let message = transport.to_string();
58                let lower = message.to_ascii_lowercase();
59                if lower.contains("timeout") || lower.contains("timed out") {
60                    return Err(err(code, format!("{raw_url} did not answer within 15 s")));
61                }
62                return Err(err(code, format!("{raw_url}: {message}")));
63            }
64        };
65        if matches!(status, 301 | 302 | 303 | 307 | 308) && hop < MAX_REDIRECTS {
66            let location = response.header("location").unwrap_or("").to_string();
67            refuse_whitespace_or_control(&location, code)?;
68            if let Some(next) = url.as_url().join(&location).ok().filter(|_| !location.is_empty()) {
69                // As ureq does: never from https down to http, and never to
70                // anything but http(s); then the 3xx is the answer.
71                let downgrade = url.as_url().scheme() == "https" && next.scheme() == "http";
72                if !downgrade && (next.scheme() == "http" || next.scheme() == "https") {
73                    if status == 303 && !method.eq_ignore_ascii_case("HEAD") || matches!(status, 301 | 302) && method.eq_ignore_ascii_case("POST") {
74                        method = "GET".to_string();
75                        body.clear();
76                    }
77                    target = next.to_string();
78                    hop += 1;
79                    continue;
80                }
81            }
82        }
83        break (status, response);
84    };
85    let mut payload = Vec::new();
86    response.into_reader().take(MAX_BYTES + 1).read_to_end(&mut payload)
87        .map_err(|e| err(code, format!("{raw_url}: {e}")))?;
88    if payload.len() as u64 > MAX_BYTES {
89        return Err(err(code, format!("{raw_url} answered more than {MAX_BYTES} bytes")));
90    }
91    let body = String::from_utf8_lossy(&payload).into_owned();
92    Ok(HttpAnswer { status, body })
93}
94
95const MAX_REDIRECTS: u32 = 5;
96
97/// Refuses a URL holding whitespace or a control character. The URL parser
98/// ureq uses silently drops tabs and newlines and trims spaces, so such a URL
99/// can name one host to a reader and another to the dial; none is ever valid.
100/// The message never repeats the URL.
101fn refuse_whitespace_or_control(raw: &str, code: &str) -> Result<(), SamlError> {
102    if raw.chars().any(|c| c.is_whitespace() || c.is_control()) {
103        return Err(err(code, "the URL is refused: it holds whitespace or a control character"));
104    }
105    Ok(())
106}
107
108/// Refuses a plain http URL unless its host is loopback: 127.0.0.0/8, ::1 or
109/// the name localhost, where the bytes never leave the machine. The URL is the
110/// one ureq would dial, parsed the same way, and nothing here resolves a name.
111/// A URL with userinfo is never loopback, so `http://localhost:80@host/` cannot
112/// pass as localhost. The message names the scheme and host[:port] only: never
113/// userinfo, path, query or a secret.
114fn refuse_plain_http_off_loopback(request_url: &ureq::RequestUrl, code: &str) -> Result<(), SamlError> {
115    let url = request_url.as_url();
116    if url.scheme() != "http" {
117        return Ok(());
118    }
119    let host = url.host_str().unwrap_or("");
120    if url.username().is_empty() && url.password().is_none() && is_loopback_host(host) {
121        return Ok(());
122    }
123    let shown = match url.port() {
124        Some(port) => format!("{host}:{port}"),
125        None => host.to_string(),
126    };
127    Err(err(code, format!("http://{shown} is refused: plain http is allowed only to a loopback host (127.0.0.0/8, ::1, localhost); use https")))
128}
129
130pub(crate) fn is_loopback_host(host: &str) -> bool {
131    if host.eq_ignore_ascii_case("localhost") {
132        return true;
133    }
134    if let Ok(v4) = host.parse::<std::net::Ipv4Addr>() {
135        return v4.octets()[0] == 127;
136    }
137    if let Some(literal) = host.strip_prefix('[').and_then(|rest| rest.strip_suffix(']')) {
138        return literal.parse::<std::net::Ipv6Addr>().map(|v6| v6 == std::net::Ipv6Addr::LOCALHOST).unwrap_or(false);
139    }
140    false
141}
142
143/// Every certificate in `ca`, each one a root of the trust store.
144///
145/// `ca` is a PEM file that may hold a whole chain, as iya-sts publishes it at
146/// `GET /tls/server-certificate`: leaf, TLS Issuing CA, Intermediate, Root.
147/// `native_tls::Certificate::from_pem` reads only the first block, which is the
148/// leaf; OpenSSL then cannot end the path at a self-signed certificate and
149/// refuses the handshake. So each block is read and added, and the Root is
150/// among them.
151pub(crate) fn trust_anchors(ca: &str) -> Result<Vec<native_tls::Certificate>, String> {
152    const BEGIN: &str = "-----BEGIN CERTIFICATE-----";
153    const END: &str = "-----END CERTIFICATE-----";
154    let mut out = Vec::new();
155    let mut rest = ca;
156    while let Some(start) = rest.find(BEGIN) {
157        let Some(length) = rest[start..].find(END) else {
158            return Err("the CA certificate cannot be read: a PEM block has no END line".to_string());
159        };
160        let block = &rest[start..start + length + END.len()];
161        let certificate = native_tls::Certificate::from_pem(block.as_bytes())
162            .map_err(|e| format!("the CA certificate cannot be read: {e}"))?;
163        out.push(certificate);
164        rest = &rest[start + length + END.len()..];
165    }
166    if out.is_empty() {
167        return Err("the CA certificate cannot be read: it holds no PEM certificate".to_string());
168    }
169    Ok(out)
170}
171
172fn agent(tls: Option<&TlsOptions>, code: &str) -> Result<ureq::Agent, SamlError> {
173    let mut builder = ureq::AgentBuilder::new().timeout(Duration::from_secs(15)).redirects(0);
174    if let Some(opt) = tls {
175        if !opt.ca.is_empty() || (!opt.cert.is_empty() && !opt.key.is_empty()) {
176            let mut tls_builder = native_tls::TlsConnector::builder();
177            tls_builder.min_protocol_version(Some(native_tls::Protocol::Tlsv12));
178            if !opt.ca.is_empty() {
179                for ca in trust_anchors(&opt.ca).map_err(|message| err(code, message))? {
180                    tls_builder.add_root_certificate(ca);
181                }
182            }
183            if !opt.cert.is_empty() && !opt.key.is_empty() {
184                let identity = native_tls::Identity::from_pkcs8(opt.cert.as_bytes(), opt.key.as_bytes()).map_err(|e| err(code, format!("the client certificate cannot be read: {e}")))?;
185                tls_builder.identity(identity);
186            }
187            let connector = tls_builder.build().map_err(|e| err(code, format!("the TLS configuration cannot be used: {e}")))?;
188            builder = builder.tls_connector(std::sync::Arc::new(connector));
189        }
190    }
191    Ok(builder.build())
192}