tuwunel_service/admin/
register.rs1use 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#[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#[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#[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); }