Skip to main content

tuwunel_service/appservice/
proxy.rs

1//! MSC4512: the paths an appservice claims and the requests forwarded to it.
2//!
3//! The claim grammar is shared with `fed_proxy`; the send goes through the
4//! appservice's own client pool, so a proxy URL takes the forms `url` does.
5
6use bytes::Bytes;
7use http::{
8	Error as HttpError, HeaderValue, Request as HttpRequest, Uri, header::AUTHORIZATION,
9	uri::PathAndQuery,
10};
11use reqwest::{Request, Response};
12use tuwunel_core::{Result, err, implement, warn};
13
14use super::RegistrationInfo;
15
16/// MSC4512: the API a proxied path belongs to.
17///
18/// It decides how the forwarded request is authenticated and which identity
19/// header carries the caller.
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum Root {
22	/// `/_matrix/client/`, authenticated by an access token.
23	Client,
24
25	/// `/_matrix/federation/`, authenticated by a server signature.
26	Federation,
27}
28
29/// MSC4512: splits a raw request path into its API and the remainder after
30/// the version.
31///
32/// The version is one `v<x>` segment or the two segments `unstable/<ns>`.
33/// The remainder is what a proxy claim is matched against.
34#[must_use]
35pub fn split_path(path: &str) -> Option<(Root, &str)> {
36	let (root, versioned) = path
37		.strip_prefix("/_matrix/client/")
38		.map(|rest| (Root::Client, rest))
39		.or_else(|| {
40			path.strip_prefix("/_matrix/federation/")
41				.map(|rest| (Root::Federation, rest))
42		})?;
43
44	let (version, rest) = versioned.split_once('/')?;
45	let remainder = match version {
46		| "unstable" => rest
47			.split_once('/')
48			.filter(|(namespace, _)| !namespace.is_empty())
49			.map(|(_, remainder)| remainder)?,
50		| _ if version.len() > 1 && version.starts_with('v') => rest,
51		| _ => return None,
52	};
53
54	Some((root, remainder))
55}
56
57/// MSC4512: forwards a proxied request to the appservice holding the claim.
58///
59/// The request's URI is the path and query to append to the claim's URL; its
60/// headers are already filtered. The `hs_token` goes in as a bearer token,
61/// never in the query. The response comes back unread, so its body can
62/// stream to the caller.
63#[implement(super::Service)]
64#[tracing::instrument(name = "proxy", level = "debug", skip_all)]
65pub async fn send_proxied(
66	&self,
67	appservice: &RegistrationInfo,
68	request: HttpRequest<Bytes>,
69) -> Result<Response> {
70	let id = &appservice.registration.id;
71	let url = appservice
72		.proxy_url()
73		.ok_or_else(|| err!("Appservice {id} claims no proxy prefix"))?;
74
75	let (base, client) = self.transport(url)?;
76	let request = with_credentials(request, base, &appservice.registration.hs_token)?;
77	let request = Request::try_from(request)?;
78
79	client.execute(request).await.map_err(|e| {
80		let e = e.without_url();
81
82		warn!(appservice = %id, error = ?e, "Could not forward a proxied request");
83		e.into()
84	})
85}
86
87fn with_credentials(
88	request: HttpRequest<Bytes>,
89	base: &str,
90	hs_token: &str,
91) -> Result<HttpRequest<Bytes>> {
92	let (mut parts, body) = request.into_parts();
93	let path = parts
94		.uri
95		.path_and_query()
96		.map_or("/", PathAndQuery::as_str);
97
98	parts.uri = Uri::try_from(format!("{base}{path}")).map_err(HttpError::from)?;
99	parts
100		.headers
101		.insert(AUTHORIZATION, HeaderValue::try_from(format!("Bearer {hs_token}"))?);
102
103	Ok(HttpRequest::from_parts(parts, body))
104}