1use std::collections::{HashMap, HashSet, VecDeque};
13use std::sync::Mutex;
14use std::sync::atomic::{AtomicBool, Ordering};
15
16use axum::extract::{Request, State};
17use axum::http::header::AUTHORIZATION;
18use axum::http::{HeaderValue, StatusCode};
19use axum::middleware::Next;
20use axum::response::{IntoResponse, Response};
21
22use crate::{ApiError, Gateway, bearer, constant_time_eq};
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26pub enum SharedStationToken {
27 #[default]
31 Auto,
32 Allowed,
34 Refused,
36}
37
38impl SharedStationToken {
39 #[must_use]
41 pub fn parse(text: &str) -> Option<Self> {
42 match text.trim().to_ascii_lowercase().as_str() {
43 "auto" => Some(Self::Auto),
44 "on" | "true" | "allow" => Some(Self::Allowed),
45 "off" | "false" | "refuse" => Some(Self::Refused),
46 _ => None,
47 }
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub(crate) enum StationCaller {
54 Station { id: String, serial: u64 },
56 Shared,
58}
59
60impl StationCaller {
61 pub(crate) fn admits(&self, claimed: &str) -> Result<(), ApiError> {
64 match self {
65 Self::Station { id, .. } if id != claimed => Err(ApiError::forbidden()),
66 _ => Ok(()),
67 }
68 }
69}
70
71#[derive(Default)]
73struct Replay {
74 seen: HashMap<String, f64>,
75 order: VecDeque<(f64, String)>,
76}
77
78impl Replay {
79 fn admit(&mut self, nonce: &str, now: f64, expires: f64, capacity: usize) -> bool {
82 while let Some((until, _)) = self.order.front() {
83 if *until > now {
84 break;
85 }
86 if let Some((_, old)) = self.order.pop_front() {
87 self.seen.remove(&old);
88 }
89 }
90 if self.seen.contains_key(nonce) || self.seen.len() >= capacity {
91 return false;
92 }
93 self.seen.insert(nonce.to_owned(), expires);
94 self.order.push_back((expires, nonce.to_owned()));
95 true
96 }
97}
98
99const MAX_VERIFIED_SERIALS: usize = 16_384;
101
102#[derive(Default)]
103struct VerifiedSerials {
104 seen: HashSet<(String, u64)>,
105 order: VecDeque<(String, u64)>,
106}
107
108impl VerifiedSerials {
109 fn contains(&self, key: &(String, u64)) -> bool {
110 self.seen.contains(key)
111 }
112
113 fn insert(&mut self, key: (String, u64)) {
114 if self.seen.insert(key.clone()) {
115 self.order.push_back(key);
116 if self.order.len() > MAX_VERIFIED_SERIALS
117 && let Some(oldest) = self.order.pop_front()
118 {
119 self.seen.remove(&oldest);
120 }
121 }
122 }
123}
124
125pub(crate) struct StationAuth {
127 shared: SharedStationToken,
128 replay_entries: usize,
129 replay: Mutex<Replay>,
130 verified_serials: Mutex<VerifiedSerials>,
131 refused_said: AtomicBool,
132 shared_said: AtomicBool,
133}
134
135pub const DEFAULT_REPLAY_ENTRIES: usize = 100_000;
137
138impl Default for StationAuth {
139 fn default() -> Self {
140 Self::new(SharedStationToken::default(), DEFAULT_REPLAY_ENTRIES)
141 }
142}
143
144impl StationAuth {
145 pub(crate) fn new(shared: SharedStationToken, replay_entries: usize) -> Self {
146 Self {
147 shared,
148 replay_entries,
149 replay: Mutex::default(),
150 verified_serials: Mutex::default(),
151 refused_said: AtomicBool::new(false),
152 shared_said: AtomicBool::new(false),
153 }
154 }
155
156 pub(crate) fn shared(&self) -> SharedStationToken {
157 self.shared
158 }
159}
160
161impl Gateway {
162 #[must_use]
166 pub fn with_station_auth(mut self, shared: SharedStationToken, replay_entries: usize) -> Self {
167 self.station_auth = std::sync::Arc::new(StationAuth::new(shared, replay_entries));
168 self
169 }
170
171 #[must_use]
173 pub fn shared_station_token_accepted(&self) -> bool {
174 match self.station_auth.shared() {
175 SharedStationToken::Allowed => true,
176 SharedStationToken::Refused => false,
177 SharedStationToken::Auto => {
178 #[cfg(feature = "cli")]
179 {
180 !self.secret_trust.pins_roots()
181 }
182 #[cfg(not(feature = "cli"))]
183 {
184 true
185 }
186 }
187 }
188 }
189
190 #[must_use]
194 pub fn station_auth_weakenings(&self) -> Vec<String> {
195 let mut found = Vec::new();
196 if self.shared_station_token_accepted() {
197 found.push(match self.station_auth.shared() {
198 SharedStationToken::Allowed => "the shared Station token is accepted \
199 (AI6_EXPORTS_SHARED_STATION_TOKEN=on): any Station that holds it can report, \
200 poll and answer as any other Station"
201 .to_owned(),
202 _ => "the shared Station token is accepted because this gateway pins no root \
203 (AI6_EXPORTS_SECRET_TRUST): any Station that holds it can report, poll and \
204 answer as any other Station; certify the Stations and pin their root to \
205 refuse it"
206 .to_owned(),
207 });
208 }
209 found
210 }
211
212 async fn station_caller(
214 &self,
215 method: &axum::http::Method,
216 uri: &axum::http::Uri,
217 headers: &axum::http::HeaderMap,
218 ) -> Result<StationCaller, ApiError> {
219 #[cfg(feature = "cli")]
220 if let Some(value) = headers.get(ai6::directorates::q::sealing::STATION_PROOF_HEADER) {
221 let value = value
222 .to_str()
223 .map_err(|_| ApiError::unauthorized())?
224 .to_owned();
225 let target = uri
226 .path_and_query()
227 .map_or("/", |target| target.as_str())
228 .to_owned();
229 let method = method.as_str().to_owned();
230 let (trust, registry) = (self.secret_trust.clone(), self.registry.clone());
231 let now = crate::unix_timestamp()?;
232 let verified = tokio::task::spawn_blocking(move || {
233 if let Some(registry) = ®istry {
236 let _ = trust.refresh_revocations(registry.as_ref(), now);
237 }
238 trust.verify_station_proof(&value, &method, &target, now)
239 })
240 .await
241 .map_err(|_| ApiError::internal())?;
242 let verified = match verified {
243 Ok(verified) => verified,
244 Err(why) => {
245 eprintln!("universal-exports: a Station's proof was refused: {why}");
246 return Err(ApiError::unauthorized());
247 }
248 };
249 let skew = self.secret_trust.clock_skew();
250 let admitted = self
251 .station_auth
252 .replay
253 .lock()
254 .unwrap_or_else(std::sync::PoisonError::into_inner)
255 .admit(
256 &verified.nonce,
257 now,
258 now + 2.0 * skew,
259 self.station_auth.replay_entries,
260 );
261 if !admitted {
262 eprintln!(
263 "universal-exports: a Station's proof was refused: a proof is used once, and \
264 this one was seen or the nonces kept are all in use"
265 );
266 return Err(ApiError::unauthorized());
267 }
268 return Ok(StationCaller::Station {
269 id: verified.station,
270 serial: verified.serial,
271 });
272 }
273 let presented = bearer(headers)?;
274 if !constant_time_eq(self.config.station_token.as_bytes(), presented.as_bytes()) {
275 return Err(ApiError::unauthorized());
276 }
277 if !self.shared_station_token_accepted() {
278 if !self.station_auth.refused_said.swap(true, Ordering::Relaxed) {
279 eprintln!(
280 "universal-exports: warning: the shared Station token was refused: this gateway pins a \
281 root, so a Station proves itself with its certificate; certify it with `ai6 \
282 secret-trust certify-station`, or set AI6_EXPORTS_SHARED_STATION_TOKEN=on to \
283 accept the token as a weakening"
284 );
285 }
286 return Err(ApiError::unauthorized());
287 }
288 if !self.station_auth.shared_said.swap(true, Ordering::Relaxed) {
289 eprintln!(
290 "universal-exports: info: a Station request used the shared Station token (the first \
291 since this gateway started); no line like this after a few minutes means every \
292 Station proves itself with its certificate"
293 );
294 }
295 Ok(StationCaller::Shared)
296 }
297}
298
299pub(crate) async fn station_guard(
302 State(gateway): State<Gateway>,
303 mut request: Request,
304 next: Next,
305) -> Response {
306 if !request.uri().path().starts_with("/v1/station/") {
307 return next.run(request).await;
308 }
309 let (method, uri, headers) = (
310 request.method().clone(),
311 request.uri().clone(),
312 request.headers().clone(),
313 );
314 let caller = match gateway.station_caller(&method, &uri, &headers).await {
315 Ok(caller) => caller,
316 Err(refused) => return refused.into_response(),
317 };
318 if let StationCaller::Station { id: own, .. } = &caller {
319 if let Some(query) = request.uri().query()
322 && url::form_urlencoded::parse(query.as_bytes())
323 .any(|(name, value)| name == "station" && value != own.as_str())
324 {
325 return StatusCode::FORBIDDEN.into_response();
326 }
327 let token = format!("Bearer {}", gateway.config.station_token);
330 let Ok(mut token) = HeaderValue::from_str(&token) else {
331 return ApiError::internal().into_response();
332 };
333 token.set_sensitive(true);
334 request.headers_mut().insert(AUTHORIZATION, token);
335 }
336 #[cfg(feature = "cli")]
337 request
338 .headers_mut()
339 .remove(ai6::directorates::q::sealing::STATION_PROOF_HEADER);
340 request.extensions_mut().insert(caller);
341 next.run(request).await
342}
343
344pub(crate) async fn credential(
348 State(gateway): State<Gateway>,
349 axum::extract::Extension(caller): axum::extract::Extension<StationCaller>,
350) -> Result<Response, ApiError> {
351 let StationCaller::Station { id, serial } = caller else {
352 return Err(ApiError::unauthorized());
353 };
354 let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
355 let key = (id.clone(), serial);
356 let already_cached = gateway
357 .station_auth
358 .verified_serials
359 .lock()
360 .unwrap_or_else(std::sync::PoisonError::into_inner)
361 .contains(&key);
362 if !already_cached {
363 let actor = format!("station:{id}");
364 let target = format!("serial {serial}");
365 let event = ai6::AuditRecord {
366 id: format!("station-cert-{}", uuid::Uuid::new_v4().simple()),
367 actor: actor.clone(),
368 action: "station.certificate.verified".to_owned(),
369 operation: String::new(),
370 resource: Some(actor.clone()),
371 target: target.clone(),
372 at: crate::unix_timestamp()?,
373 };
374 tokio::task::spawn_blocking(move || {
375 let already_audited = registry.list_audit(200)?.into_iter().any(|entry| {
376 entry.action == "station.certificate.verified"
377 && entry.actor == actor
378 && entry.target == target
379 });
380 if !already_audited {
381 registry.record_audit(&event)?;
382 }
383 Ok::<_, std::io::Error>(())
384 })
385 .await
386 .map_err(|_| ApiError::internal())?
387 .map_err(|_| ApiError::internal())?;
388 gateway
389 .station_auth
390 .verified_serials
391 .lock()
392 .unwrap_or_else(std::sync::PoisonError::into_inner)
393 .insert(key);
394 }
395 Ok((
396 [(axum::http::header::CACHE_CONTROL, "no-store")],
397 axum::Json(ai6::wire::credential::CredentialAnswer {
398 station_id: id,
399 serial,
400 }),
401 )
402 .into_response())
403}
404
405#[cfg(test)]
406mod tests {
407 use super::*;
408
409 #[test]
410 fn a_proof_is_taken_once_until_its_nonce_is_forgotten() {
411 let mut replay = Replay::default();
412 assert!(replay.admit("a", 100.0, 300.0, 4));
413 assert!(!replay.admit("a", 101.0, 301.0, 4), "the same proof again");
414 assert!(replay.admit("b", 101.0, 301.0, 4));
415 assert!(replay.admit("a", 301.0, 501.0, 4), "forgotten once expired");
416 }
417
418 #[test]
419 fn a_full_replay_table_refuses_instead_of_forgetting() {
420 let mut replay = Replay::default();
421 assert!(replay.admit("a", 0.0, 100.0, 2));
422 assert!(replay.admit("b", 0.0, 100.0, 2));
423 assert!(!replay.admit("c", 1.0, 101.0, 2));
424 assert!(
425 replay.admit("c", 100.0, 200.0, 2),
426 "room again once they expire"
427 );
428 }
429
430 #[test]
431 fn the_shared_token_setting_reads_its_three_words() {
432 assert_eq!(
433 SharedStationToken::parse("auto"),
434 Some(SharedStationToken::Auto)
435 );
436 assert_eq!(
437 SharedStationToken::parse("on"),
438 Some(SharedStationToken::Allowed)
439 );
440 assert_eq!(
441 SharedStationToken::parse("off"),
442 Some(SharedStationToken::Refused)
443 );
444 assert_eq!(SharedStationToken::parse("maybe"), None);
445 }
446
447 #[test]
448 fn a_certified_station_may_claim_only_itself() {
449 let station = StationCaller::Station {
450 id: "alpha".to_owned(),
451 serial: 1,
452 };
453 assert!(station.admits("alpha").is_ok());
454 assert!(station.admits("beta").is_err());
455 assert!(StationCaller::Shared.admits("beta").is_ok());
456 }
457}