Skip to main content

m4a_agent/engine/
http.rs

1//! HTTP execution of the engine's requests against one server: URL building (the spec prefix is
2//! kept only when the server was found to serve it), discovery, and the bearer.
3
4use std::time::Duration;
5
6use mail4agent_messenger::{HttpResponseDescriptor, OutgoingRequest};
7use reqwest::Url;
8
9use crate::error::{AgentError, Result};
10
11/// Same clipping the shell uses for text that may reach logs: no long opaque tokens.
12pub fn clip_public(text: String) -> String {
13    let mut out = String::new();
14    for token in text.split_whitespace() {
15        if token.len() > 80 {
16            out.push_str("[omitted]");
17        } else {
18            out.push_str(token);
19        }
20        out.push(' ');
21        if out.len() > 240 {
22            break;
23        }
24    }
25    out
26}
27
28pub fn percent_encode(value: &str) -> String {
29    let mut out = String::new();
30    for byte in value.bytes() {
31        match byte {
32            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(byte as char),
33            _ => out.push_str(&format!("%{byte:02X}")),
34        }
35    }
36    out
37}
38
39/// A server origin plus the decision whether it serves the Matrix paths under `/_matrix`.
40#[derive(Clone)]
41pub struct HttpExec {
42    client: reqwest::blocking::Client,
43    base: Url,
44    keep_prefix: bool,
45}
46
47pub(crate) fn parse_origin(raw: &str) -> Result<Url> {
48    let url = Url::parse(raw).map_err(|_| AgentError::Protocol("not a valid server URL".into()))?;
49    if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() || url.query().is_some() || !url.username().is_empty() || url.password().is_some() {
50        return Err(AgentError::Protocol("not a valid server URL".into()));
51    }
52    let mut url = url;
53    url.set_fragment(None);
54    Ok(url)
55}
56
57impl HttpExec {
58    pub fn new(base: &str) -> Result<Self> {
59        let client = reqwest::blocking::Client::builder().timeout(Duration::from_secs(60)).http1_only().build().map_err(|e| AgentError::Transport(clip_public(e.to_string())))?;
60        Ok(Self { client, base: parse_origin(base)?, keep_prefix: false })
61    }
62
63    /// Our own mounts serve `/client/v3` without the spec prefix. Anything else is asked, never
64    /// assumed: `GET /_matrix/client/versions` answering 2xx means the prefix is served.
65    pub fn probe_prefix(&mut self) -> bool {
66        self.keep_prefix = true; // ask with the prefix on
67        self.keep_prefix = self.get_status("/_matrix/client/versions").is_some_and(|s| (200..300).contains(&s));
68        self.keep_prefix
69    }
70
71    pub fn set_keep_prefix(&mut self, keep: bool) {
72        self.keep_prefix = keep;
73    }
74
75    pub fn keep_prefix(&self) -> bool {
76        self.keep_prefix
77    }
78
79    pub fn base(&self) -> &Url {
80        &self.base
81    }
82
83    pub fn client(&self) -> &reqwest::blocking::Client {
84        &self.client
85    }
86
87    /// Replaces the origin (`.well-known` told us the real one).
88    pub fn rebase(&mut self, origin: &str) -> Result<()> {
89        self.base = parse_origin(origin)?;
90        Ok(())
91    }
92
93    fn get_status(&self, path: &str) -> Option<u16> {
94        let url = self.url(path, &[]).ok()?;
95        self.client.get(url).send().ok().map(|r| r.status().as_u16())
96    }
97
98    /// `GET path` as JSON (no bearer): `(status, json)`.
99    pub fn get_json(&self, path: &str) -> Result<(u16, serde_json::Value)> {
100        let url = self.url(path, &[])?;
101        let r = self.client.get(url).send().map_err(|e| AgentError::Transport(clip_public(e.to_string())))?;
102        let st = r.status().as_u16();
103        Ok((st, r.json().unwrap_or(serde_json::Value::Null)))
104    }
105
106    /// `GET path` as JSON with a bearer: `(status, json)`.
107    pub fn get_json_as(&self, bearer: &str, path: &str) -> Result<(u16, serde_json::Value)> {
108        let url = self.url(path, &[])?;
109        let r = self.client.get(url).bearer_auth(bearer).send().map_err(|e| AgentError::Transport(clip_public(e.to_string())))?;
110        let st = r.status().as_u16();
111        Ok((st, r.json().unwrap_or(serde_json::Value::Null)))
112    }
113
114    /// `/_matrix/client/v3/x` becomes `/client/v3/x` unless the server serves the prefix. A path
115    /// already without it is left alone.
116    pub fn url(&self, path: &str, query: &[(String, String)]) -> Result<Url> {
117        let path = if self.keep_prefix { path } else { path.strip_prefix("/_matrix").unwrap_or(path) };
118        if !path.starts_with('/') {
119            return Err(AgentError::Protocol("path must start with a slash".into()));
120        }
121        let mut raw = self.base.as_str().trim_end_matches('/').to_string();
122        raw.push_str(path);
123        if !query.is_empty() {
124            raw.push('?');
125            for (i, (n, v)) in query.iter().enumerate() {
126                if i > 0 {
127                    raw.push('&');
128                }
129                raw.push_str(&percent_encode(n));
130                raw.push('=');
131                raw.push_str(&percent_encode(v));
132            }
133        }
134        Url::parse(&raw).map_err(|_| AgentError::Protocol("not a valid request URL".into()))
135    }
136
137    /// One engine request with `bearer`.
138    pub fn perform(&self, bearer: &str, request: &OutgoingRequest) -> Result<HttpResponseDescriptor> {
139        let url = self.url(&request.path, &request.query)?;
140        let method = reqwest::Method::from_bytes(request.method.as_str().as_bytes()).map_err(|_| AgentError::Protocol("unsupported method".into()))?;
141        let mut header = reqwest::header::HeaderValue::from_str(&format!("Bearer {bearer}")).map_err(|_| AgentError::Protocol("token is not a header value".into()))?;
142        header.set_sensitive(true);
143        let mut builder = self.client.request(method, url).header(reqwest::header::AUTHORIZATION, header);
144        if let Some(body) = &request.body {
145            let bytes = serde_json::to_vec(body).map_err(|e| AgentError::Protocol(e.to_string()))?;
146            builder = builder.header(reqwest::header::CONTENT_TYPE, "application/json").body(bytes);
147        }
148        let response = builder.send().map_err(|e| AgentError::Transport(clip_public(e.to_string())))?;
149        let status = response.status().as_u16();
150        let body = response.bytes().map_err(|e| AgentError::Transport(clip_public(e.to_string())))?.to_vec();
151        Ok(HttpResponseDescriptor { status, body })
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    #[test]
160    fn the_spec_prefix_is_kept_only_when_asked() {
161        let mut h = HttpExec::new("http://127.0.0.1:9").expect("base");
162        let q = [("timeout".to_string(), "5".to_string())];
163        assert_eq!(h.url("/_matrix/client/v3/sync", &q).unwrap().as_str(), "http://127.0.0.1:9/client/v3/sync?timeout=5");
164        assert_eq!(h.url("/client/v3/sync", &[]).unwrap().path(), "/client/v3/sync");
165        h.set_keep_prefix(true);
166        assert_eq!(h.url("/_matrix/client/v3/sync", &q).unwrap().as_str(), "http://127.0.0.1:9/_matrix/client/v3/sync?timeout=5");
167        assert!(HttpExec::new("ftp://x").is_err());
168        assert!(HttpExec::new("http://u:p@x").is_err());
169    }
170}