Skip to main content

tuwunel_service/turn/
provider.rs

1//! Requests TURN credentials from the configured provider.
2//!
3//! Answers come in the TURN REST API shape or as WebRTC ICE servers, and both
4//! fold into the single username, password and URI list a Matrix client takes.
5//! Cloudflare credentials are capped at the 48-hour lifetime Cloudflare allows,
6//! and the port 53 URIs it offers, which browsers refuse, are dropped.
7
8#[cfg(test)]
9mod tests;
10
11use std::{iter::once, time::Duration};
12
13use reqwest::{Error as HttpError, RequestBuilder, Response};
14use serde::{Deserialize, Serialize};
15use tuwunel_core::{
16	Err, Result,
17	config::turn::{Cloudflare, Endpoint, Provider, Turn},
18	either::{self, Either},
19	err, implement,
20	utils::resolve_secret,
21};
22use url::Url;
23
24use super::{Credentials, Service};
25use crate::client::read_response_capped;
26
27/// Answer shapes accepted from a credential provider.
28///
29/// Serde tries the variants in order, so an answer carrying `uris` reads as the
30/// TURN REST API and anything else as WebRTC ICE servers.
31#[derive(Deserialize)]
32#[serde(untagged)]
33enum Answer {
34	/// TURN REST API, from the expired draft-uberti-behave-turn-rest-00.
35	Rest {
36		username: String,
37		password: String,
38		ttl: u64,
39		uris: Vec<String>,
40	},
41
42	/// WebRTC `RTCConfiguration`, as Cloudflare and STUNner's `/ice` return.
43	Configuration {
44		#[serde(rename = "iceServers")]
45		ice_servers: Vec<IceServer>,
46	},
47
48	/// WebRTC `RTCIceServer` entries without the configuration around them.
49	Servers(Vec<IceServer>),
50}
51
52#[derive(Deserialize)]
53struct IceServer {
54	/// One URL as a bare string or several as a list, both of which WebRTC allows.
55	#[serde(with = "either::serde_untagged")]
56	urls: Either<String, Vec<String>>,
57
58	username: Option<String>,
59	credential: Option<String>,
60}
61
62#[derive(Serialize)]
63struct GenerateIceServers {
64	ttl: u64,
65}
66
67/// Bound on one request to the provider.
68///
69/// Concurrent callers wait out the same request, so it stays short.
70const TIMEOUT: Duration = Duration::from_secs(10);
71
72/// Bound on the provider's answer.
73///
74/// Real answers are a few hundred bytes; the cap only stops a runaway provider.
75const MAX_ANSWER: usize = 64 * 1024;
76
77/// Longest credential lifetime Cloudflare grants.
78///
79/// Cloudflare refuses longer requests, so the configured lifetime is cut to it.
80const CLOUDFLARE_MAX_TTL: Duration = Duration::from_hours(48);
81
82#[implement(Service)]
83pub(super) async fn fetch(&self, turn: &Turn, provider: Provider<'_>) -> Result<Credentials> {
84	let ttl = Duration::from_secs(turn.ttl);
85
86	match provider {
87		| Provider::Endpoint(endpoint, url) => self.fetch_endpoint(endpoint, url, ttl).await,
88		| Provider::Cloudflare(cloudflare, key_id) =>
89			self.fetch_cloudflare(cloudflare, key_id, ttl.min(CLOUDFLARE_MAX_TTL))
90				.await,
91	}
92}
93
94#[implement(Service)]
95async fn fetch_endpoint(
96	&self,
97	endpoint: &Endpoint,
98	url: &Url,
99	ttl: Duration,
100) -> Result<Credentials> {
101	let token = resolve_secret(
102		endpoint.token_file.as_deref(),
103		endpoint.token.as_deref(),
104		"TURN endpoint token",
105	);
106
107	let request = self
108		.services
109		.client
110		.default
111		.get(with_query(url.clone(), ttl));
112
113	let request = token
114		.into_iter()
115		.fold(request, RequestBuilder::bearer_auth);
116
117	request_credentials(request, ttl, |_| true).await
118}
119
120fn with_query(mut url: Url, ttl: Duration) -> Url {
121	if url.query_pairs().any(|(key, _)| reserved(&key)) {
122		let original = url.clone();
123
124		url.query_pairs_mut().clear().extend_pairs(
125			original
126				.query_pairs()
127				.filter(|(key, _)| !reserved(key)),
128		);
129	}
130
131	url.query_pairs_mut()
132		.append_pair("service", "turn")
133		.append_pair("ttl", &ttl.as_secs().to_string());
134
135	url
136}
137
138fn reserved(key: &str) -> bool { matches!(key, "service" | "ttl") }
139
140#[implement(Service)]
141async fn fetch_cloudflare(
142	&self,
143	cloudflare: &Cloudflare,
144	key_id: &str,
145	ttl: Duration,
146) -> Result<Credentials> {
147	let token = resolve_secret(
148		cloudflare.token_file.as_deref(),
149		cloudflare.token.as_deref(),
150		"Cloudflare TURN token",
151	)
152	.ok_or_else(|| err!(Config("turn.cloudflare.token", "No API token is set.")))?;
153
154	let url = format!(
155		"https://rtc.live.cloudflare.com/v1/turn/keys/{key_id}/credentials/generate-ice-servers"
156	);
157
158	let request = self
159		.services
160		.client
161		.default
162		.post(url)
163		.bearer_auth(token)
164		.json(&GenerateIceServers { ttl: ttl.as_secs() });
165
166	request_credentials(request, ttl, |uri| !uses_port_53(uri)).await
167}
168
169/// Sends the request and converts the provider's answer into credentials.
170///
171/// The answer must parse as one of the accepted shapes, and only the TURN URIs
172/// `keep` accepts remain.
173#[tracing::instrument(level = "debug", skip_all)]
174async fn request_credentials<Keep>(
175	request: RequestBuilder,
176	ttl: Duration,
177	keep: Keep,
178) -> Result<Credentials>
179where
180	Keep: Fn(&str) -> bool,
181{
182	// The URL may carry an API key in its query, so errors drop it before logging.
183	let response = request
184		.timeout(TIMEOUT)
185		.send()
186		.await
187		.and_then(Response::error_for_status)
188		.map_err(HttpError::without_url)?;
189
190	let body = read_response_capped(response, MAX_ANSWER).await?;
191	let answer: Answer = serde_json::from_slice(&body)?;
192
193	answer.into_credentials(ttl, keep)
194}
195
196impl Answer {
197	/// Converts the answer into credentials, keeping only the TURN URIs `keep`
198	/// accepts.
199	///
200	/// The spec admits TURN URIs alone, though providers list STUN ones too. A
201	/// lifetime longer than the one requested is cut to it, and an answer left
202	/// with no URIs or no lifetime is an error.
203	fn into_credentials<Keep>(self, requested: Duration, keep: Keep) -> Result<Credentials>
204	where
205		Keep: Fn(&str) -> bool,
206	{
207		let keep = |uri: &str| is_turn(uri) && keep(uri);
208		let credentials = match self {
209			| Self::Configuration { ice_servers: servers } | Self::Servers(servers) =>
210				ice_credentials(servers, requested, keep)?,
211			| Self::Rest { username, password, ttl, uris } => Credentials {
212				username,
213				password,
214				uris: uris.into_iter().filter(|uri| keep(uri)).collect(),
215				ttl: Duration::from_secs(ttl).min(requested),
216			},
217		};
218
219		if credentials.uris.is_empty() || credentials.ttl.is_zero() {
220			return Err!(BadServerResponse("The answer holds no usable TURN URIs or lifetime."));
221		}
222
223		Ok(credentials)
224	}
225}
226
227fn is_turn(uri: &str) -> bool { uri.starts_with("turn:") || uri.starts_with("turns:") }
228
229/// Folds WebRTC ICE servers into the one username and password a Matrix client
230/// takes.
231///
232/// The first entry carrying credentials supplies them, and only the URIs of
233/// entries carrying the same credentials and accepted by `keep` remain. An
234/// answer with no entry carrying credentials is an error.
235fn ice_credentials<Keep>(
236	servers: Vec<IceServer>,
237	ttl: Duration,
238	keep: Keep,
239) -> Result<Credentials>
240where
241	Keep: Fn(&str) -> bool,
242{
243	let (username, password) = servers
244		.iter()
245		.find_map(IceServer::credentials)
246		.map(|(username, password)| (username.to_owned(), password.to_owned()))
247		.ok_or_else(|| err!(BadServerResponse("The answer holds no TURN credentials.")))?;
248
249	let chosen = Some((username.as_str(), password.as_str()));
250	let uris = servers
251		.into_iter()
252		.filter(|server| server.credentials() == chosen)
253		.flat_map(|server| server.urls.map_left(once).into_iter())
254		.filter(|uri| keep(uri))
255		.collect();
256
257	Ok(Credentials { username, password, uris, ttl })
258}
259
260impl IceServer {
261	#[inline]
262	fn credentials(&self) -> Option<(&str, &str)> {
263		self.username
264			.as_deref()
265			.zip(self.credential.as_deref())
266			.filter(|(username, password)| !username.is_empty() && !password.is_empty())
267	}
268}
269
270fn uses_port_53(uri: &str) -> bool {
271	uri.split_once(':')
272		.and_then(|(_, rest)| rest.split('?').next())
273		.and_then(|authority| authority.rsplit_once(':'))
274		.is_some_and(|(_, port)| port == "53")
275}