Skip to main content

tuwunel_core/config/
turn.rs

1//! Configures TURN relay credentials and servers.
2//!
3//! Shared secrets generate credentials, with static credentials and external
4//! credential providers available as alternatives. URI, lifetime, and
5//! guest-access settings govern client use.
6
7use serde::Deserialize;
8use smallstr::SmallString;
9use tuwunel_macros::config_example_generator;
10use url::Url;
11
12use super::PathBuf;
13use crate::implement;
14
15type KeyId = SmallString<[u8; 32]>;
16
17/// TURN relay for calls
18///
19/// Tells clients which TURN servers relay their legacy Matrix calls, and
20/// with what credentials, through `/_matrix/client/v3/voip/turnServer`.
21/// No TURN server is built in; the guide at
22/// <https://tuwunel.chat/calls/turn.html> uses coturn. With `uris` empty
23/// and no provider configured (the default), `turnServer` answers 404.
24///
25/// Pick one credential source:
26///
27/// - Shared secret (recommended for your own TURN server): `secret` or
28///   `secret_file`, equal to coturn's `static-auth-secret`. Each request
29///   gets a fresh username `<expiry>:<user_id>` and HMAC-SHA1 password,
30///   valid for `ttl` seconds.
31/// - Static: `username` and `password`, sent to every client as they are;
32///   ignored while a secret is set.
33/// - Provider: `[global.turn.cloudflare]` for Cloudflare's hosted TURN, or
34///   `[global.turn.endpoint]` for any HTTP endpoint that issues expiring
35///   credentials. The server URIs come from the provider too, so `uris`,
36///   the secret and the static credentials are ignored.
37///
38/// With `uris` set and no source, startup logs a warning and clients
39/// receive an empty username and password.
40///
41/// Minimal example:
42///
43/// ```toml
44///     [global.turn]
45///     uris = ["turn:turn.example.com?transport=udp"]
46///     secret_file = "/etc/tuwunel/.turn_secret"
47/// ```
48///
49/// Tips:
50/// - `secret_file` is read on every request, so rotating the secret needs
51///   no reload or restart.
52/// - Guests get 403 from `turnServer` unless `allow_guests` is on.
53#[expect(rustdoc::broken_intra_doc_links, rustdoc::bare_urls)]
54// No Debug: secrets are reachable from this section.
55#[derive(Clone, Deserialize)]
56#[config_example_generator(
57	filename = "tuwunel-example.toml",
58	section = "global.turn",
59	group = "true",
60	ignore = "endpoint cloudflare"
61)]
62pub struct Turn {
63	/// Allows guest users to access TURN credentials.
64	///
65	/// This is equivalent to Synapse's `turn_allow_guests` setting and permits
66	/// guests to call `/_matrix/client/v3/voip/turnServer`.
67	///
68	/// reloadable: yes
69	/// legacy: turn_allow_guests
70	#[serde(default)]
71	pub allow_guests: bool,
72
73	/// Supplies a static TURN username when the recommended shared secret
74	/// `turn.secret` is not used.
75	///
76	/// reloadable: yes
77	/// legacy: turn_username
78	#[serde(default)]
79	pub username: String,
80
81	/// Supplies a static TURN password when the recommended shared secret
82	/// `turn.secret` is not used.
83	///
84	/// display: sensitive
85	/// reloadable: yes
86	/// legacy: turn_password
87	#[serde(default)]
88	pub password: String,
89
90	#[expect(clippy::doc_link_with_quotes)]
91	/// Lists TURN server URIs.
92	///
93	/// Replace "example.turn.uri" with the TURN domain, such as coturn's
94	/// `realm` setting. For TURN over TLS, replace the `turn:` prefix with
95	/// `turns:`.
96	///
97	/// reloadable: yes
98	/// example: ["turn:example.turn.uri?transport=udp",
99	/// "turn:example.turn.uri?transport=tcp"]
100	///
101	/// default: []
102	/// legacy: turn_uris
103	#[serde(default)]
104	pub uris: Vec<String>,
105
106	/// Supplies the TURN shared secret for HMAC-SHA1 credential generation,
107	/// which is more secure than the traditional static username-and-password
108	/// credentials that remain available when needed.
109	///
110	/// display: sensitive
111	/// reloadable: yes
112	/// legacy: turn_secret
113	#[serde(default)]
114	pub secret: Option<String>,
115
116	/// Reads the TURN shared secret from a file.
117	///
118	/// This takes precedence over `turn.secret` and falls back to it when the
119	/// file cannot be opened. Surrounding whitespace is trimmed so a trailing
120	/// newline is not part of the secret. A present but blank file resolves to
121	/// no secret without falling back.
122	///
123	/// reloadable: yes
124	/// example: "/etc/tuwunel/.turn_secret"
125	/// legacy: turn_secret_file
126	pub secret_file: Option<PathBuf>,
127
128	/// Sets the TURN lifetime in seconds.
129	///
130	/// reloadable: yes
131	/// default: 86400
132	/// legacy: turn_ttl
133	#[serde(default = "default_ttl")]
134	pub ttl: u64,
135
136	/// Settings for an HTTP endpoint issuing TURN credentials.
137	///
138	/// display: section
139	#[serde(default)]
140	pub endpoint: Endpoint,
141
142	/// Settings for Cloudflare's hosted TURN service.
143	///
144	/// display: section
145	#[serde(default)]
146	pub cloudflare: Cloudflare,
147}
148
149/// TURN credentials from an HTTP endpoint
150///
151/// Fetches TURN credentials and server URIs from an HTTP endpoint, for a
152/// TURN service that issues expiring credentials through an API rather
153/// than sharing a secret. Tuwunel sends `GET <url>` with `service=turn`
154/// and `ttl=<turn.ttl>` added to the query, and accepts either answer:
155///
156/// - TURN REST API: `{"username", "password", "ttl", "uris"}`, as the
157///   STUNner auth service returns from `/`.
158/// - WebRTC ICE servers: `{"iceServers": [...]}` or a bare list, each
159///   entry holding `urls`, `username` and `credential`, as STUNner's
160///   `/ice` returns. Clients take one username and password, so entries
161///   whose credentials differ from the first entry's are dropped.
162///
163/// Only `turn:` and `turns:` URIs reach clients, as the Matrix spec
164/// requires; any `stun:` URIs in the answer are left out.
165///
166/// A service with another request or answer shape needs a small adapter
167/// in front of it. While `url` is set, `turn.uris`, the shared secret and
168/// the static credentials are ignored.
169///
170/// ```toml
171///     [global.turn.endpoint]
172///     url = "http://127.0.0.1:8088/"
173///     token_file = "/etc/tuwunel/.turn_endpoint_token"
174/// ```
175///
176/// Tips:
177/// - Query parameters already in `url`, other than `service` and `ttl`,
178///   are kept, for a service that takes its API key in the query.
179/// - One set of credentials is shared by every user and renewed after
180///   half its lifetime, so the endpoint sees about two requests per
181///   credential lifetime however many clients ask. No Matrix user ID is
182///   sent.
183/// - After a failed request the endpoint is not asked again for a minute;
184///   meanwhile clients get whatever credentials are still unexpired, or
185///   502.
186#[expect(rustdoc::broken_intra_doc_links, rustdoc::bare_urls)]
187// No Debug: secrets are reachable from this section.
188#[derive(Clone, Default, Deserialize)]
189#[config_example_generator(
190	filename = "tuwunel-example.toml",
191	section = "global.turn.endpoint",
192	group = "true"
193)]
194pub struct Endpoint {
195	/// URL of the credential endpoint.
196	///
197	/// display: sensitive
198	/// reloadable: yes
199	/// example: "http://127.0.0.1:8088/"
200	pub url: Option<Url>,
201
202	/// Supplies a bearer token sent in the `Authorization` header.
203	///
204	/// display: sensitive
205	/// reloadable: yes
206	pub token: Option<String>,
207
208	/// Reads the bearer token from a file.
209	///
210	/// This takes precedence over `token` and falls back to it when the file
211	/// cannot be opened. Surrounding whitespace is trimmed.
212	///
213	/// reloadable: yes
214	/// example: "/etc/tuwunel/.turn_endpoint_token"
215	pub token_file: Option<PathBuf>,
216}
217
218/// Cloudflare Realtime TURN
219///
220/// Fetches expiring TURN credentials and server URIs from Cloudflare's
221/// hosted TURN service. Create a TURN key in the Cloudflare dashboard and
222/// set its key ID and API token here. Cloudflare credentials live at most
223/// 48 hours, so a longer `turn.ttl` is shortened to that. Only its TURN
224/// URIs reach clients, without the port 53 ones browsers block.
225///
226/// While `key_id` is set, `turn.uris`, the shared secret and the static
227/// credentials are ignored. Set this section or `[global.turn.endpoint]`,
228/// not both.
229///
230/// ```toml
231///     [global.turn.cloudflare]
232///     key_id = "0123456789abcdef0123456789abcdef"
233///     token_file = "/etc/tuwunel/.cloudflare_turn_token"
234/// ```
235///
236/// Tips:
237/// - One set of credentials is shared by every user and renewed after
238///   half its lifetime, so Cloudflare sees about two requests per
239///   credential lifetime however many clients ask. No Matrix user ID is
240///   sent.
241/// - `token_file` is read at each renewal, so rotating the token needs no
242///   reload or restart.
243/// - After a failed request Cloudflare is not asked again for a minute;
244///   meanwhile clients get whatever credentials are still unexpired, or
245///   502.
246#[expect(rustdoc::broken_intra_doc_links, rustdoc::bare_urls)]
247// No Debug: secrets are reachable from this section.
248#[derive(Clone, Default, Deserialize)]
249#[config_example_generator(
250	filename = "tuwunel-example.toml",
251	section = "global.turn.cloudflare",
252	group = "true"
253)]
254pub struct Cloudflare {
255	/// ID of the Cloudflare TURN key; setting it selects this provider.
256	///
257	/// reloadable: yes
258	/// default: ""
259	#[serde(default)]
260	pub key_id: KeyId,
261
262	/// API token of the Cloudflare TURN key.
263	///
264	/// display: sensitive
265	/// reloadable: yes
266	pub token: Option<String>,
267
268	/// Reads the API token from a file.
269	///
270	/// This takes precedence over `token` and falls back to it when the file
271	/// cannot be opened. Surrounding whitespace is trimmed.
272	///
273	/// reloadable: yes
274	/// example: "/etc/tuwunel/.cloudflare_turn_token"
275	pub token_file: Option<PathBuf>,
276}
277
278/// External source of TURN credentials, when one is configured.
279///
280/// Each variant borrows its section together with the setting that selects
281/// it, so a caller need not check that setting again.
282#[derive(Clone, Copy)]
283pub enum Provider<'a> {
284	/// `[global.turn.endpoint]` and its URL.
285	Endpoint(&'a Endpoint, &'a Url),
286
287	/// `[global.turn.cloudflare]` and its TURN key ID.
288	Cloudflare(&'a Cloudflare, &'a str),
289}
290
291impl Default for Turn {
292	fn default() -> Self {
293		Self {
294			allow_guests: Default::default(),
295			username: Default::default(),
296			password: Default::default(),
297			uris: Default::default(),
298			secret: Default::default(),
299			secret_file: None,
300			ttl: default_ttl(),
301			endpoint: Default::default(),
302			cloudflare: Default::default(),
303		}
304	}
305}
306
307/// Selects the configured credential provider.
308///
309/// `[global.turn.endpoint]` wins when both provider sections are set,
310/// though startup rejects that configuration.
311#[implement(Turn)]
312#[must_use]
313pub fn provider(&self) -> Option<Provider<'_>> { self.providers().next() }
314
315/// Lists every configured credential provider, the endpoint first.
316///
317/// More than one is a configuration startup rejects, so every caller but
318/// that check wants [`Turn::provider`].
319#[implement(Turn)]
320pub fn providers(&self) -> impl Iterator<Item = Provider<'_>> {
321	let endpoint = self
322		.endpoint
323		.url
324		.as_ref()
325		.map(|url| Provider::Endpoint(&self.endpoint, url));
326
327	let cloudflare = Some(self.cloudflare.key_id.as_str())
328		.filter(|key_id| !key_id.is_empty())
329		.map(|key_id| Provider::Cloudflare(&self.cloudflare, key_id));
330
331	endpoint.into_iter().chain(cloudflare)
332}
333
334fn default_ttl() -> u64 { 60 * 60 * 24 }