1use super::*;
17
18#[derive(Clone)]
21pub struct AuthRuntime {
22 shared: Arc<RuntimeShared>,
23}
24
25struct RuntimeShared {
26 inner: Weak<AuthStateInner>,
27 command_tx: mpsc::Sender<AuthCommand>,
30 config: AuthConfig,
31 _state_lock: Arc<File>,
32 actor: Mutex<Option<tokio::task::JoinHandle<()>>>,
33 actor_abort: tokio::task::AbortHandle,
34 state_dropped: watch::Receiver<()>,
36}
37
38pub struct LegacyConnectionGuard {
39 inner: Weak<AuthStateInner>,
40}
41
42impl Drop for LegacyConnectionGuard {
43 fn drop(&mut self) {
44 if let Some(inner) = self.inner.upgrade() {
45 inner
46 .active_legacy_connections
47 .fetch_sub(1, Ordering::AcqRel);
48 }
49 }
50}
51
52impl AuthRuntime {
53 pub async fn from_process(config: AuthConfig) -> Result<Self, AuthFailure> {
54 Self::launch(move || {
55 config.check_limits()?;
56 let state_lock = prepare_state_dir_and_lock(&config.state_dir)?;
57 let credential = load_server_admin_credential(&config.state_dir)?;
58 let Credential::Admin(admin_key) = credential else {
59 return Err(AuthFailure::new(
60 codes::ADMINISTRATOR_KEY_REQUIRED,
61 "the relay server must start with the administrator credential",
62 false,
63 ));
64 };
65 Loaded::restore(admin_key, config, true, state_lock)
66 })
67 .await
68 }
69
70 pub async fn from_isolated_state(config: AuthConfig) -> Result<Self, AuthFailure> {
75 Self::launch(move || {
76 config.check_limits()?;
77 let state_lock = prepare_state_dir_and_lock(&config.state_dir)?;
78 let credential = load_isolated_server_admin_credential(&config.state_dir)?;
79 let Credential::Admin(admin_key) = credential else {
80 return Err(AuthFailure::new(
81 codes::ADMINISTRATOR_KEY_REQUIRED,
82 "the embedded relay must start with an administrator credential",
83 false,
84 ));
85 };
86 Loaded::restore(admin_key, config, false, state_lock)
87 })
88 .await
89 }
90
91 pub async fn start(admin_key: AesKeyType, config: AuthConfig) -> Result<Self, AuthFailure> {
92 Self::launch(move || {
93 config.check_limits()?;
94 let state_lock = prepare_state_dir_and_lock(&config.state_dir)?;
95 Loaded::restore(admin_key, config, true, state_lock)
96 })
97 .await
98 }
99
100 async fn launch(
103 load: impl FnOnce() -> Result<Loaded, AuthFailure> + Send + 'static,
104 ) -> Result<Self, AuthFailure> {
105 let loaded = off_runtime(load)
106 .await
107 .ok_or_else(AuthFailure::state_manager_stopped)??;
108 Ok(loaded.spawn())
109 }
110
111 pub async fn shutdown_actor(&self) {
112 let (response, receiver) = oneshot::channel();
113 let _ = self
114 .shared
115 .command_tx
116 .send(AuthCommand::Shutdown { response })
117 .await;
118 let _ = receiver.await;
119 let handle = self.shared.actor.lock().take();
120 if let Some(handle) = handle {
121 let _ = handle.await;
122 }
123 }
124
125 pub async fn abort_actor(&self) -> Result<(), AuthFailure> {
126 self.shared.actor_abort.abort();
127 let handle = self.shared.actor.lock().take();
128 if let Some(handle) = handle {
129 let _ = handle.await;
130 }
131 let mut state_dropped = self.shared.state_dropped.clone();
134 tokio::time::timeout(Duration::from_secs(5), async {
135 while state_dropped.changed().await.is_ok() {}
137 })
138 .await
139 .map_err(|_| {
140 AuthFailure::new(
141 codes::AUTH_STATE_UNAVAILABLE,
142 "authentication actor did not drop after abort",
143 true,
144 )
145 })
146 }
147
148 pub fn config(&self) -> &AuthConfig {
149 &self.shared.config
150 }
151
152 fn inner(&self) -> Result<Arc<AuthStateInner>, AuthFailure> {
153 self.shared
154 .inner
155 .upgrade()
156 .ok_or_else(AuthFailure::state_manager_stopped)
157 }
158
159 pub fn admin_key(&self) -> Result<AesKeyType, AuthFailure> {
160 Ok(self.inner()?.admin_key())
161 }
162
163 pub fn derive_key(&self, key_id: KeyId) -> Result<AesKeyType, AuthFailure> {
164 let inner = self.inner()?;
165 if key_id.is_admin() {
166 return Ok(inner.admin_key());
167 }
168 inner.derive_temporary_key(key_id)
169 }
170
171 #[cfg(test)]
172 pub(crate) fn high_slot_entry_count(&self) -> usize {
173 self.inner().map(|inner| inner.high().len()).unwrap_or(0)
174 }
175
176 pub fn derive_previous_key(&self, key_id: KeyId) -> Option<AesKeyType> {
177 let inner = self.inner().ok()?;
178 let previous = inner.previous_root.read().clone()?;
179 if key_id.is_admin() {
180 Some(previous.admin_key)
181 } else {
182 derive_temporary_key(&previous.admin_key, &previous.instance_id, key_id).ok()
183 }
184 }
185
186 pub fn authenticate_presented(
187 &self,
188 key_id: KeyId,
189 presented_key: &AesKeyType,
190 ) -> Result<AuthContext, AuthFailure> {
191 let inner = self.inner()?;
192 let counted = |failure: AuthFailure| {
196 inner.auth_failures.fetch_add(1, Ordering::Relaxed);
197 failure
198 };
199 if key_id.is_admin() {
200 let admin = inner.admin.read();
201 if !bool::from(presented_key.ct_eq(&admin.key)) {
202 return Err(counted(AuthFailure::new(
203 codes::ADMINISTRATOR_KEY_INVALID,
204 "administrator credential does not match the active root key",
205 false,
206 )));
207 }
208 let lease = admin.lease.upgrade().ok_or_else(|| {
209 AuthFailure::new(
210 codes::ADMINISTRATOR_KEY_ROTATED,
211 "administrator credential was rotated",
212 false,
213 )
214 })?;
215 inner.auth_successes.fetch_add(1, Ordering::Relaxed);
216 return Ok(AuthContext::from_lease(ADMIN_KEY_ID, true, &lease));
217 }
218 if inner.safe_mode.load(Ordering::Acquire) {
219 return Err(counted(AuthFailure::new(
220 codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
221 "temporary key state is unavailable; administrator reset is required",
222 false,
223 )));
224 }
225
226 let expected_key = inner.derive_temporary_key(key_id)?;
227 if !bool::from(presented_key.ct_eq(&expected_key)) {
228 return Err(counted(temporary_key_material_mismatch(&inner, key_id)));
229 }
230
231 let index = key_id.slot().as_index();
232 let generation = key_id.generation();
233 let slots = inner.slots();
234 let Some(slot) = slots.get(index) else {
235 return Err(counted(AuthFailure::new(
236 codes::TEMPORARY_KEY_NOT_FOUND,
237 "temporary key id is outside the configured slot table",
238 false,
239 )));
240 };
241 if slot.generation != generation {
242 return Err(counted(AuthFailure::new(
243 codes::TEMPORARY_KEY_GENERATION_MISMATCH,
244 "temporary key generation does not match the current slot",
245 false,
246 )));
247 }
248 let failure = match slot.state {
249 SlotState::Free => Some(AuthFailure::new(
250 codes::TEMPORARY_KEY_NOT_FOUND,
251 "temporary key does not exist",
252 false,
253 )),
254 SlotState::Expired => Some(AuthFailure::key_expired()),
255 SlotState::Revoked => Some(AuthFailure::key_revoked()),
256 SlotState::Active if slot.expires_at <= unix_seconds() => {
257 if let Some(lease) = slot.lease.upgrade() {
258 lease.cancel_expired();
259 }
260 Some(AuthFailure::key_expired())
261 }
262 SlotState::Active => None,
263 };
264 if let Some(failure) = failure {
265 return Err(counted(failure));
266 }
267 let lease = slot
268 .lease
269 .upgrade()
270 .ok_or_else(|| counted(AuthFailure::key_lease_inactive()))?;
271 inner.auth_successes.fetch_add(1, Ordering::Relaxed);
272 Ok(AuthContext::from_lease(key_id, false, &lease))
273 }
274
275 pub fn legacy_protocol_allowed(&self) -> Result<bool, AuthFailure> {
276 Ok(self
277 .inner()?
278 .legacy_protocol_allowed
279 .load(Ordering::Acquire))
280 }
281
282 pub fn record_legacy_connection(&self) -> Result<LegacyConnectionGuard, AuthFailure> {
283 let inner = self.inner()?;
284 inner
285 .active_legacy_connections
286 .fetch_add(1, Ordering::AcqRel);
287 inner
288 .last_legacy_connection_at
289 .store(unix_seconds(), Ordering::Release);
290 Ok(LegacyConnectionGuard {
291 inner: Arc::downgrade(&inner),
292 })
293 }
294
295 async fn request<T>(
296 &self,
297 build: impl FnOnce(oneshot::Sender<Result<T, AuthFailure>>) -> AuthCommand,
298 ) -> Result<T, AuthFailure> {
299 let (response, receiver) = oneshot::channel();
300 self.shared
301 .command_tx
302 .send(build(response))
303 .await
304 .map_err(|_| AuthFailure::state_manager_stopped())?;
305 receiver.await.map_err(|_| {
306 AuthFailure::new(
307 codes::AUTH_STATE_UNAVAILABLE,
308 "authentication state manager dropped the response",
309 true,
310 )
311 })?
312 }
313
314 pub async fn claim_admin_mutation(
315 &self,
316 authorization: &AuthContext,
317 fingerprint: [u8; 32],
318 client_timestamp: u64,
319 ) -> Result<(), AuthFailure> {
320 let authority = authorization.admin_authority()?;
321 self.request(|response| AuthCommand::ClaimAdminMutation {
322 authority,
323 fingerprint,
324 client_timestamp,
325 response,
326 })
327 .await
328 }
329
330 pub async fn issue(
331 &self,
332 authorization: &AuthContext,
333 ttl: Duration,
334 label: Option<String>,
335 ) -> Result<IssuedTemporaryKey, AuthFailure> {
336 self.issue_scoped(authorization, None, ttl, label).await
337 }
338
339 pub async fn allocate_namespace(
344 &self,
345 authorization: &AuthContext,
346 ) -> Result<u64, AuthFailure> {
347 let authority = authorization.admin_authority()?;
348 self.request(|response| AuthCommand::AllocateNamespace {
349 authority,
350 response,
351 })
352 .await
353 }
354
355 pub async fn issue_in_namespace(
360 &self,
361 authorization: &AuthContext,
362 namespace: u64,
363 ttl: Duration,
364 label: Option<String>,
365 ) -> Result<IssuedTemporaryKey, AuthFailure> {
366 self.issue_scoped(authorization, Some(namespace), ttl, label)
367 .await
368 }
369
370 async fn issue_scoped(
371 &self,
372 authorization: &AuthContext,
373 namespace: Option<u64>,
374 ttl: Duration,
375 label: Option<String>,
376 ) -> Result<IssuedTemporaryKey, AuthFailure> {
377 let authority = authorization.admin_authority()?;
378 self.request(|response| AuthCommand::Issue {
379 authority,
380 namespace,
381 ttl,
382 label,
383 response,
384 })
385 .await
386 }
387
388 pub async fn list(
389 &self,
390 authorization: &AuthContext,
391 page: u32,
392 page_size: u16,
393 ) -> Result<KeyPage, AuthFailure> {
394 let authority = authorization.admin_authority()?;
395 self.request(|response| AuthCommand::List {
396 authority,
397 page,
398 page_size,
399 response,
400 })
401 .await
402 }
403
404 pub async fn show(
405 &self,
406 authorization: &AuthContext,
407 key_id: KeyId,
408 reveal: bool,
409 ) -> Result<IssuedTemporaryKey, AuthFailure> {
410 let authority = authorization.admin_authority()?;
411 self.request(|response| AuthCommand::Show {
412 authority,
413 key_id,
414 reveal,
415 response,
416 })
417 .await
418 }
419
420 pub async fn renew(
421 &self,
422 authorization: &AuthContext,
423 key_id: KeyId,
424 ttl: Duration,
425 ) -> Result<IssuedTemporaryKey, AuthFailure> {
426 let authority = authorization.admin_authority()?;
427 self.request(|response| AuthCommand::Renew {
428 authority,
429 key_id,
430 ttl,
431 response,
432 })
433 .await
434 }
435
436 pub async fn revoke(
437 &self,
438 authorization: &AuthContext,
439 key_id: KeyId,
440 ) -> Result<TemporaryKeyMetadata, AuthFailure> {
441 let authority = authorization.admin_authority()?;
442 self.request(|response| AuthCommand::Revoke {
443 authority,
444 key_id,
445 response,
446 })
447 .await
448 }
449
450 pub async fn gc(&self, authorization: &AuthContext) -> Result<u64, AuthFailure> {
451 let authority = authorization.admin_authority()?;
452 self.request(|response| AuthCommand::Gc {
453 authority,
454 response,
455 })
456 .await
457 }
458
459 pub async fn reset(&self, authorization: &AuthContext) -> Result<(), AuthFailure> {
460 let authority = authorization.admin_authority()?;
461 self.request(|response| AuthCommand::Reset {
462 authority,
463 response,
464 })
465 .await
466 }
467
468 pub async fn rotate_root(
469 &self,
470 authorization: &AuthContext,
471 new_key: AesKeyType,
472 ) -> Result<(), AuthFailure> {
473 let authority = authorization.admin_authority()?;
474 self.request(|response| AuthCommand::RotateRoot {
475 authority,
476 new_key,
477 response,
478 })
479 .await
480 }
481
482 pub async fn set_legacy_protocol(
483 &self,
484 authorization: &AuthContext,
485 policy: LegacyProtocolPolicy,
486 ) -> Result<(), AuthFailure> {
487 let authority = authorization.admin_authority()?;
488 self.request(|response| AuthCommand::SetLegacyProtocol {
489 authority,
490 policy,
491 response,
492 })
493 .await
494 }
495
496 pub async fn status(&self, authorization: &AuthContext) -> Result<AuthStatus, AuthFailure> {
497 let authority = authorization.admin_authority()?;
498 self.request(|response| AuthCommand::Status {
499 authority,
500 response,
501 })
502 .await
503 }
504
505 pub async fn audit_admin(
506 &self,
507 authorization: &AuthContext,
508 action: impl Into<String>,
509 key_id: Option<KeyId>,
510 detail: Option<String>,
511 ) -> Result<(), AuthFailure> {
512 let authority = authorization.admin_authority()?;
513 let action = action.into();
514 self.request(|response| AuthCommand::Audit {
515 authority,
516 action,
517 key_id,
518 detail,
519 response,
520 })
521 .await
522 }
523}
524
525struct Loaded {
528 actor: Actor,
529 inner: Weak<AuthStateInner>,
530 state_dropped: watch::Receiver<()>,
531 config: AuthConfig,
532 state_lock: Arc<File>,
533}
534
535impl Loaded {
536 fn restore(
538 admin_key: AesKeyType,
539 config: AuthConfig,
540 sync_process_credential: bool,
541 state_lock: Arc<File>,
542 ) -> Result<Self, AuthFailure> {
543 let instance_id = load_or_create_instance_id(&config.state_dir)?;
544 let instance_id =
545 recover_instance_id_after_reset(&config.state_dir, &admin_key, instance_id)?;
546 let (mut loaded, safe_mode) = load_persisted_state(&config, &admin_key, instance_id);
547 let now = unix_seconds();
548 if let Some(state) = loaded.as_mut()
549 && normalize_tombstone_times(state, now)
550 {
551 write_snapshot_and_truncate_wal(&config, &admin_key, state)?;
552 }
553 let (mut restored, live) =
554 RestoredState::from_snapshot(loaded.as_ref(), safe_mode, &config, now);
555 let admin_replays = AdminReplays::restored(
556 loaded.as_ref().map_or(&[], |state| &state.admin_replays),
557 now,
558 );
559 restored.namespace_high_water =
560 restore_namespace_high_water(&config.state_dir, restored.namespace_high_water);
561 let admin_lease = Arc::new(AuthLease::new(ADMIN_KEY_ID, None, u64::MAX));
562 let inner = Arc::new(AuthStateInner::new(
563 admin_key,
564 &admin_lease,
565 sync_process_credential,
566 instance_id,
567 safe_mode,
568 restored,
569 ));
570 let leases = Leases::restored(&inner, now, live);
572 Ok(Self {
573 inner: Arc::downgrade(&inner),
574 state_dropped: inner.subscribe_dropped(),
575 actor: Actor::new(
576 inner,
577 admin_lease,
578 config.clone(),
579 leases,
580 admin_replays,
581 state_lock.clone(),
582 now,
583 ),
584 config,
585 state_lock,
586 })
587 }
588
589 fn spawn(self) -> AuthRuntime {
592 let Self {
593 actor,
594 inner,
595 state_dropped,
596 config,
597 state_lock,
598 } = self;
599 let (command_tx, command_rx) = mpsc::channel(256);
600 let actor = tokio::spawn(actor.run(command_rx));
601 let actor_abort = actor.abort_handle();
602 AuthRuntime {
603 shared: Arc::new(RuntimeShared {
604 inner,
605 command_tx,
606 config,
607 _state_lock: state_lock,
608 actor: Mutex::new(Some(actor)),
609 actor_abort,
610 state_dropped,
611 }),
612 }
613 }
614}
615
616pub(crate) async fn off_runtime<T: Send + 'static>(
621 work: impl FnOnce() -> T + Send + 'static,
622) -> Option<T> {
623 let dispatch = tracing::dispatcher::get_default(tracing::Dispatch::clone);
624 let work = move || tracing::dispatcher::with_default(&dispatch, work);
625 match tokio::task::spawn_blocking(work).await {
626 Ok(output) => Some(output),
627 Err(error) => match error.try_into_panic() {
628 Ok(panic) => std::panic::resume_unwind(panic),
629 Err(_cancelled) => None,
630 },
631 }
632}
633
634fn temporary_key_material_mismatch(inner: &AuthStateInner, key_id: KeyId) -> AuthFailure {
635 let index = key_id.slot().as_index();
636 let generation = key_id.generation();
637 let slots = inner.slots();
638 let current_generation = match slots.get(index) {
639 Some(slot) => Some(slot.generation),
640 None => index
641 .checked_sub(slots.len())
642 .and_then(|offset| inner.high_slot_generations.get(offset).copied()),
643 };
644 let slot_is_active = slots
645 .get(index)
646 .is_some_and(|slot| slot.state == SlotState::Active && slot.generation == generation);
647 if slot_is_active {
648 return AuthFailure::key_material_mismatch();
649 }
650 let current_epoch = inner.root_epoch.load(Ordering::Acquire);
651 if current_epoch > 0
652 && generation > Generation::FIRST
653 && current_generation.is_some_and(|issued| generation <= issued)
654 {
655 return AuthFailure::key_rotated();
656 }
657 AuthFailure::key_material_mismatch()
658}