Skip to main content

tuwunel_service/pusher/
request.rs

1use std::{fmt::Debug, mem::swap};
2
3use bytes::BytesMut;
4use http::Response as HttpResponse;
5use reqwest::{Error as ReqwestError, Response};
6use ruma::api::{
7	IncomingResponse, OutgoingRequest, OutgoingRequestExt, auth_scheme::AuthScheme,
8	path_builder::PathBuilder,
9};
10use tuwunel_core::{
11	Err, Result, debug_warn, err, error::error_chain, implement, trace, utils::string_from_bytes,
12	warn,
13};
14use url::Url;
15
16use crate::client::read_response_capped;
17
18#[implement(super::Service)]
19#[tracing::instrument(level = "debug", skip_all)]
20pub(super) async fn send_request<T>(&self, dest: &str, request: T) -> Result<T::IncomingResponse>
21where
22	T: OutgoingRequest + Debug + Send,
23	for<'a> T::Authentication: AuthScheme<Input<'a> = ()>,
24	for<'a> T::PathBuilder: PathBuilder<Input<'a> = ()>,
25{
26	let dest = if dest.contains(['?', '#']) {
27		let parsed = Url::parse(dest).ok();
28
29		warn!(
30			gateway_host = parsed
31				.as_ref()
32				.and_then(|url| url.host_str())
33				.unwrap_or("<invalid>"),
34			has_query = dest.contains('?'),
35			has_fragment = dest.contains('#'),
36			"Push gateway URL carries a query string or fragment, which is not supported; the \
37			 notification path is appended after it",
38		);
39
40		dest
41	} else {
42		let push_path = self
43			.services
44			.config
45			.push
46			.notification_path
47			.trim_end_matches('/');
48
49		let dest = dest.trim_end_matches('/');
50
51		dest.strip_suffix(push_path).unwrap_or(dest)
52	};
53
54	trace!("Push gateway destination: {dest}");
55
56	let http_request = request
57		.try_into_http_request::<BytesMut>(dest, (), ())
58		.map_err(|e| {
59			err!(BadServerResponse(warn!(
60				"Failed to find destination {dest} for push gateway: {e}"
61			)))
62		})?
63		.map(BytesMut::freeze);
64
65	let reqwest_request = reqwest::Request::try_from(http_request)?;
66
67	if self
68		.services
69		.client
70		.proxy
71		.resolver_alias(reqwest_request.url())
72	{
73		return Err!(BadServerResponse(
74			"Not allowed to request a locally resolved proxy endpoint"
75		));
76	}
77
78	trace!("Checking request URL for IP");
79	if !self
80		.services
81		.client
82		.valid_cidr_range_url(reqwest_request.url())
83	{
84		return Err!(BadServerResponse("Not allowed to send requests to this IP"));
85	}
86
87	match self
88		.services
89		.client
90		.pusher
91		.execute(reqwest_request)
92		.await
93	{
94		| Err(error) => handler_err(dest, error),
95		| Ok(response) => self.handle_ok::<T>(dest, response).await,
96	}
97}
98
99#[implement(super::Service)]
100async fn handle_ok<T>(&self, dest: &str, mut response: Response) -> Result<T::IncomingResponse>
101where
102	T: OutgoingRequest,
103{
104	trace!("Checking response destination's IP");
105	if let Some(remote_addr) = response.remote_addr()
106		&& !self
107			.services
108			.client
109			.valid_cidr_range_ip(remote_addr.ip())
110		&& !self.services.client.proxied(response.url())
111	{
112		return Err!(BadServerResponse("Not allowed to send requests to this IP"));
113	}
114
115	let status = response.status();
116	let mut http_response_builder = HttpResponse::builder()
117		.status(status)
118		.version(response.version());
119
120	swap(
121		response.headers_mut(),
122		http_response_builder
123			.headers_mut()
124			.expect("http::response::Builder is usable"),
125	);
126
127	let limit = self
128		.services
129		.config
130		.network
131		.http
132		.max_response_size;
133
134	let body = read_response_capped(response, limit).await?;
135
136	if !status.is_success() {
137		debug_warn!(body = ?string_from_bytes(&body), "Push gateway response");
138		return Err!(BadServerResponse(warn!(
139			"Push gateway {dest} returned unsuccessful HTTP response: {status}"
140		)));
141	}
142
143	let response = T::IncomingResponse::try_from_http_response(
144		http_response_builder
145			.body(body)
146			.expect("reqwest body is valid http body"),
147	);
148
149	response.map_err(|e| {
150		err!(BadServerResponse(warn!("Push gateway {dest} returned invalid response: {e}")))
151	})
152}
153
154fn handler_err<R>(dest: &str, error: ReqwestError) -> Result<R> {
155	warn!(%dest, chain = %error_chain(&error), "Could not send request to pusher");
156	Err(error.into())
157}