Skip to main content

tuwunel_service/admin/
register.rs

1//! Synapse-compatible shared-secret registration backend.
2//!
3//! Pairs with the HTTP handlers in `tuwunel_api_admin` that serve
4//! `/_synapse/admin/v1/register`. Resolves the shared secret from
5//! `registration.shared_secret` or its `_file` companion at each use and
6//! maintains an in-memory nonce store with a 60-second TTL.
7//!
8//! The nonce store lives in RAM rather than RocksDB on purpose: each entry's
9//! useful lifespan is shorter than a single block-cache eviction tick, and
10//! the working set is bounded by [`NONCE_CAP`] regardless of traffic.
11
12use std::{
13	collections::BTreeMap,
14	time::{Duration, Instant},
15};
16
17use tuwunel_core::{
18	implement,
19	utils::{self, Secret, is_secret_set, resolve_secret},
20};
21
22type Nonces = BTreeMap<String, Instant>;
23
24const NONCE_LENGTH: usize = 32;
25const NONCE_TTL: Duration = Duration::from_mins(1);
26const NONCE_CAP: usize = 2048;
27
28#[implement(super::Service)]
29pub fn issue_register_nonce(&self) -> String {
30	let nonce = utils::random_string(NONCE_LENGTH);
31	let mut nonces = self
32		.register_nonces
33		.lock()
34		.expect("nonce mutex not poisoned");
35
36	gc_expired(&mut nonces);
37	if nonces.len() >= NONCE_CAP {
38		drop_oldest(&mut nonces);
39	}
40
41	nonces.insert(nonce.clone(), Instant::now());
42	nonce
43}
44
45/// Consume `nonce` if it exists and has not expired. The entry is removed
46/// either way; `true` means the caller may proceed.
47#[implement(super::Service)]
48pub fn consume_register_nonce(&self, nonce: &str) -> bool {
49	let mut nonces = self
50		.register_nonces
51		.lock()
52		.expect("nonce mutex not poisoned");
53
54	nonces
55		.remove(nonce)
56		.is_some_and(|issued| issued.elapsed() < NONCE_TTL)
57}
58
59/// Answered without opening the secret file, since the nonce endpoint this
60/// gates takes no authentication and is not rate limited.
61#[implement(super::Service)]
62pub fn register_is_enabled(&self) -> bool {
63	let config = &self.services.server.config;
64
65	is_secret_set(
66		config.registration.shared_secret_file.as_deref(),
67		config.registration.shared_secret.as_deref(),
68	)
69}
70
71/// Reads `registration.shared_secret_file` on every call.
72///
73/// A rotated secret takes effect without a restart.
74#[implement(super::Service)]
75pub fn register_shared_secret(&self) -> Option<Secret> {
76	let config = &self.services.server.config;
77
78	resolve_secret(
79		config.registration.shared_secret_file.as_deref(),
80		config.registration.shared_secret.as_deref(),
81		"registration shared secret",
82	)
83}
84
85fn drop_oldest(nonces: &mut Nonces) {
86	nonces
87		.iter()
88		.min_by_key(|(_, issued)| **issued)
89		.map(|(k, _)| k.clone())
90		.as_ref()
91		.map(|oldest| nonces.remove(oldest));
92}
93
94fn gc_expired(nonces: &mut Nonces) { nonces.retain(|_, issued| issued.elapsed() < NONCE_TTL); }