Skip to main content

tuwunel_api/router/
proxy.rs

1//! MSC4512: forwarding the paths an appservice claims.
2//!
3//! A request no route matched is checked against the appservices' claims; a
4//! claimed one is authenticated as a native route would be and sent on, and
5//! any other stays the plain 404.
6
7use std::any::TypeId;
8
9use axum::{
10	RequestExt,
11	body::Body,
12	extract::Path,
13	response::{IntoResponse, Response},
14};
15use bytes::Bytes;
16use http::{
17	HeaderMap, HeaderName, Method, Request as HttpRequest, Response as HttpResponse, StatusCode,
18	Uri,
19	header::{ACCEPT, ACCEPT_LANGUAGE, CONNECTION, CONTENT_TYPE},
20};
21use itertools::Itertools;
22use reqwest::{Body as ReqwestBody, Response as ReqwestResponse};
23use ruma::{
24	CanonicalJsonValue,
25	api::{
26		auth_scheme::AccessToken, error::ErrorKind, federation::authentication::ServerSignatures,
27	},
28};
29use tuwunel_core::{
30	Err, Error, Result, err,
31	utils::{BoolExt, url::is_plain_path},
32};
33use tuwunel_service::{
34	Services,
35	appservice::{
36		RegistrationInfo,
37		proxy::{Root, split_path},
38	},
39};
40use url::form_urlencoded::parse as parse_query;
41
42use super::{
43	args::{parse_json, record_auth_context, serialize_body},
44	auth::{Auth, AuthDispatch, Scheme, auth},
45	request::{PathParams, Request, from_parts},
46};
47
48/// Marks a proxied request in the authentication checks keyed by route.
49///
50/// No route-keyed exemption names it, so a locked account is refused and a
51/// missing token is too.
52struct Proxied;
53
54/// Request headers passed to the appservice.
55///
56/// Every other header, the caller's credentials and cookies included, stays
57/// here.
58const FORWARDED_HEADERS: [HeaderName; 3] = [CONTENT_TYPE, ACCEPT, ACCEPT_LANGUAGE];
59
60/// Response headers never relayed from the appservice.
61///
62/// The hop-by-hop set, then those whose meaning belongs to this server:
63/// cookies, and the CORS and framing policy its own layers set.
64const DROPPED_HEADERS: [&str; 12] = [
65	"connection",
66	"keep-alive",
67	"proxy-authenticate",
68	"proxy-authorization",
69	"te",
70	"trailer",
71	"trailers",
72	"transfer-encoding",
73	"upgrade",
74	"set-cookie",
75	"content-security-policy",
76	"x-frame-options",
77];
78
79const USER_IDENTIFIER: HeaderName = HeaderName::from_static("x-matrix-user-identifier");
80
81const ORIGIN: HeaderName = HeaderName::from_static("x-matrix-origin");
82
83/// Answers a request no route matched.
84///
85/// A path an appservice claims (MSC4512) is authenticated and forwarded to
86/// it, the response streaming back; any other request is 404 before it is
87/// authenticated or its body read.
88#[tracing::instrument(level = "debug", skip_all)]
89pub async fn proxy(services: &Services, request: HttpRequest<Body>) -> Result<Response> {
90	let (root, appservice) = claim(services, request.method(), request.uri())
91		.await
92		.ok_or_else(not_found)?;
93
94	// The forwarding URL is parsed again, which would rewrite such a path.
95	if !is_plain_path(request.uri().path()) {
96		return Err!(Request(InvalidParam("Proxied path is not a plain path.")));
97	}
98
99	let (parts, body) = request.with_limited_body().into_parts();
100	let request = from_parts(services, parts, body, Path(PathParams::new())).await?;
101	let (request, auth, signed) = authenticate(services, request, root).await?;
102
103	if let Some(span) = request.parts.extensions.get::<tracing::Span>() {
104		record_auth_context(span, &auth);
105	}
106
107	let upstream = upstream_request(request, root, &auth, signed.as_ref())?;
108	let response = services
109		.appservice
110		.send_proxied(&appservice, upstream)
111		.await
112		.map_err(|_| {
113			Error::Request(
114				ErrorKind::Unknown,
115				"Appservice unreachable.".into(),
116				StatusCode::BAD_GATEWAY,
117			)
118		})?;
119
120	Ok(downstream_response(response))
121}
122
123/// The API and registration a request is proxied to.
124///
125/// Every method but TRACE qualifies, since the MSC forwards any authenticated
126/// request under a claim, while a TRACE must carry no credential its echo could
127/// disclose (RFC 9110 §9.3.8) and the forwarded request carries the `hs_token`.
128/// A path qualifies when an appservice validly claims its remainder after the
129/// version.
130#[tracing::instrument(level = "trace", skip_all)]
131async fn claim(
132	services: &Services,
133	method: &Method,
134	uri: &Uri,
135) -> Option<(Root, RegistrationInfo)> {
136	method.ne(&Method::TRACE).into_option()?;
137
138	let (root, remainder) = split_path(uri.path())?;
139	let appservice = services
140		.appservice
141		.find_proxy_claim(remainder)
142		.await?;
143
144	Some((root, appservice))
145}
146
147/// The 404 every unmatched and unclaimed request receives.
148///
149/// It is the same answer as for an endpoint this server lacks, so a probe
150/// cannot tell an unclaimed path from an unknown one.
151fn not_found() -> Error {
152	Error::Request(ErrorKind::Unrecognized, "Not Found".into(), StatusCode::NOT_FOUND)
153}
154
155/// Authenticates a proxied request as the claimed API's native routes do.
156///
157/// A client path takes an access token, an appservice's masquerade included;
158/// a federation path takes a server signature over the canonical body, which
159/// comes back as the content the signature covered.
160#[tracing::instrument(level = "debug", skip_all)]
161async fn authenticate(
162	services: &Services,
163	request: Request,
164	root: Root,
165) -> Result<(Request, Auth, Option<CanonicalJsonValue>)> {
166	let route = TypeId::of::<Proxied>();
167
168	match root {
169		| Root::Client => {
170			let (request, auth) =
171				authenticated::<AccessToken>(services, request, None, route).await?;
172
173			Ok((request, auth, None))
174		},
175		| Root::Federation => {
176			let signed = parse_json(&request, route, Scheme::ServerSignatures)?;
177			let (request, auth) =
178				authenticated::<ServerSignatures>(services, request, signed.as_ref(), route)
179					.await?;
180
181			Ok((request, auth, signed))
182		},
183	}
184}
185
186async fn authenticated<A: AuthDispatch>(
187	services: &Services,
188	mut request: Request,
189	json_body: Option<&CanonicalJsonValue>,
190	route: TypeId,
191) -> Result<(Request, Auth)> {
192	let auth = auth::<A>(services, &mut request, json_body, route).await?;
193
194	Ok((request, auth))
195}
196
197/// The request sent on to the appservice, before its credentials are added.
198///
199/// The path is the original raw one. A client request's body goes as
200/// received; a federation request's goes as the canonical content its
201/// signature covered, so the appservice reads what was verified. The caller's
202/// access token, cookies, other headers and any header its `Connection`
203/// names stay here; the identity it authenticated as rides in an MSC4512
204/// header.
205fn upstream_request(
206	request: Request,
207	root: Root,
208	auth: &Auth,
209	signed: Option<&CanonicalJsonValue>,
210) -> Result<HttpRequest<Bytes>> {
211	let identity = match root {
212		| Root::Client => auth
213			.sender_user
214			.as_ref()
215			.map(|user| (USER_IDENTIFIER, user.as_str())),
216		| Root::Federation => auth
217			.origin
218			.as_ref()
219			.map(|origin| (ORIGIN, origin.as_str())),
220	};
221
222	let (name, value) =
223		identity.ok_or_else(|| err!(Request(Forbidden("Proxied request has no identity."))))?;
224
225	let body = match root {
226		| Root::Client => request.body,
227		| Root::Federation => signed.map(serialize_body).unwrap_or_default(),
228	};
229
230	let headers = &request.parts.headers;
231	let builder = HttpRequest::builder()
232		.method(request.parts.method.clone())
233		.uri(upstream_path(&request.parts.uri));
234
235	FORWARDED_HEADERS
236		.iter()
237		.filter(|name| !listed_in_connection(headers, name.as_str()))
238		.flat_map(|name| {
239			headers
240				.get_all(name)
241				.iter()
242				.map(move |value| (name, value))
243		})
244		.fold(builder, |builder, (name, value)| builder.header(name, value))
245		.header(name, value)
246		.body(body)
247		.map_err(|e| err!(Request(InvalidParam("Proxied request is malformed: {e}"))))
248}
249
250/// The raw path and query, without any query pair carrying an access token.
251///
252/// Keys are compared decoded, as the token is read from them; every other
253/// pair is kept byte for byte, and empty ones are dropped.
254fn upstream_path(uri: &Uri) -> String {
255	let pairs = uri
256		.query()
257		.unwrap_or_default()
258		.split('&')
259		.filter(|pair| !pair.is_empty() && !is_access_token(pair));
260
261	pairs
262		.clone()
263		.next()
264		.map(|_| format!("{}?{}", uri.path(), pairs.format("&")))
265		.unwrap_or_else(|| uri.path().to_owned())
266}
267
268fn is_access_token(pair: &str) -> bool {
269	parse_query(pair.as_bytes())
270		.next()
271		.is_some_and(|(key, _)| key == "access_token")
272}
273
274/// The appservice's response, relayed with its body streaming.
275///
276/// The status passes through unchanged; the headers lose those
277/// [`relayed_headers`] withholds.
278fn downstream_response(response: ReqwestResponse) -> Response {
279	let (parts, body) = HttpResponse::<ReqwestBody>::from(response).into_parts();
280	let headers = relayed_headers(parts.headers);
281
282	(parts.status, headers, Body::new(body)).into_response()
283}
284
285/// The response headers this server relays.
286///
287/// Those [`DROPPED_HEADERS`] names go, as do every `access-control-*` one and
288/// any the response's `Connection` header lists.
289fn relayed_headers(mut headers: HeaderMap) -> HeaderMap {
290	let dropped: Vec<HeaderName> = headers
291		.keys()
292		.filter(|name| is_dropped(&headers, name))
293		.cloned()
294		.collect();
295
296	for name in &dropped {
297		headers.remove(name);
298	}
299
300	headers
301}
302
303fn is_dropped(headers: &HeaderMap, name: &HeaderName) -> bool {
304	let name = name.as_str();
305
306	DROPPED_HEADERS.contains(&name)
307		|| name.starts_with("access-control-")
308		|| listed_in_connection(headers, name)
309}
310
311/// Whether a message's `Connection` header names `name`.
312///
313/// A header so named is hop-by-hop for that message (RFC 9110 §7.6.1), so it
314/// is never passed on.
315fn listed_in_connection(headers: &HeaderMap, name: &str) -> bool {
316	headers
317		.get_all(CONNECTION)
318		.iter()
319		.filter_map(|value| value.to_str().ok())
320		.flat_map(|value| value.split(','))
321		.any(|listed| listed.trim().eq_ignore_ascii_case(name))
322}
323
324#[cfg(test)]
325mod tests {
326	use http::{HeaderMap, HeaderName, HeaderValue, Uri};
327	use itertools::Itertools;
328
329	use super::{relayed_headers, upstream_path};
330
331	#[test]
332	fn upstream_path_drops_every_access_token_pair() {
333		for (uri, expected) in [
334			("/p", "/p"),
335			("/p?", "/p"),
336			("/p?access_token=t", "/p"),
337			("/p?access_token", "/p"),
338			("/p?a=1&access_token=t&b=%20+", "/p?a=1&b=%20+"),
339			("/p?access%5Ftoken=t&a=1", "/p?a=1"),
340			("/p?access_tokens=t", "/p?access_tokens=t"),
341			("/p?a=%2F&a=2", "/p?a=%2F&a=2"),
342			("/p?&a=1&&b=2&", "/p?a=1&b=2"),
343		] {
344			let uri: Uri = uri.parse().expect("valid uri");
345
346			assert_eq!(upstream_path(&uri), expected, "{uri}");
347		}
348	}
349
350	#[test]
351	fn relayed_headers_drop_hop_by_hop_and_server_policy() {
352		let headers: HeaderMap = [
353			("connection", "x-hop"),
354			("x-hop", "1"),
355			("keep-alive", "timeout=5"),
356			("transfer-encoding", "chunked"),
357			("set-cookie", "a=b"),
358			("access-control-allow-origin", "*"),
359			("content-security-policy", "default-src 'none'"),
360			("x-frame-options", "DENY"),
361			("content-type", "application/json"),
362			("x-kept", "1"),
363		]
364		.into_iter()
365		.map(|(name, value)| (name.parse().expect("name"), HeaderValue::from_static(value)))
366		.collect();
367
368		let relayed = relayed_headers(headers);
369		let names: Vec<_> = relayed
370			.keys()
371			.map(HeaderName::as_str)
372			.sorted_unstable()
373			.collect();
374
375		assert_eq!(names, ["content-type", "x-kept"]);
376	}
377}