Skip to main content

pb_mapper_auth/
runtime.rs

1//! Public authentication runtime facade and hot-path credential checks.
2//!
3//! ```text
4//! process credential + persisted state
5//!                 |
6//!                 v
7//!       hot slot table (Weak leases) <---- request authentication
8//!                 |
9//!                 +----> lifecycle actor (strong leases + time wheel)
10//! ```
11//!
12//! Read-only authentication stays synchronous and allocation-light. Every administrator
13//! API captures a weak authority lease and sends it to the actor, where it is compared
14//! with the current lease immediately before the operation executes.
15
16use super::*;
17
18impl AuthRuntime {
19    pub async fn from_process(config: AuthConfig) -> Result<Self, AuthFailure> {
20        let state_lock = prepare_state_dir_and_lock(&config.state_dir)?;
21        let credential = load_server_admin_credential(&config.state_dir)?;
22        let Credential::Admin(admin_key) = credential else {
23            return Err(AuthFailure::new(
24                "administrator_key_required",
25                "the relay server must start with the administrator credential",
26                false,
27            ));
28        };
29        Self::start_locked(admin_key, config, true, state_lock).await
30    }
31
32    /// Start an embedded relay with an administrator key owned only by its state directory.
33    ///
34    /// This deliberately leaves the process credential untouched because the containing UI uses
35    /// that credential for its outbound register, connect, status, and stream connections.
36    pub async fn from_isolated_state(config: AuthConfig) -> Result<Self, AuthFailure> {
37        let state_lock = prepare_state_dir_and_lock(&config.state_dir)?;
38        let credential = load_isolated_server_admin_credential(&config.state_dir)?;
39        let Credential::Admin(admin_key) = credential else {
40            return Err(AuthFailure::new(
41                "administrator_key_required",
42                "the embedded relay must start with an administrator credential",
43                false,
44            ));
45        };
46        Self::start_locked(admin_key, config, false, state_lock).await
47    }
48
49    pub async fn start(admin_key: AesKeyType, config: AuthConfig) -> Result<Self, AuthFailure> {
50        let state_lock = prepare_state_dir_and_lock(&config.state_dir)?;
51        Self::start_locked(admin_key, config, true, state_lock).await
52    }
53
54    async fn start_locked(
55        admin_key: AesKeyType,
56        config: AuthConfig,
57        sync_process_credential: bool,
58        state_lock: Arc<File>,
59    ) -> Result<Self, AuthFailure> {
60        let instance_id = load_or_create_instance_id(&config.state_dir)?;
61        let instance_id =
62            recover_instance_id_after_reset(&config.state_dir, &admin_key, instance_id)?;
63        let (mut loaded, safe_mode) = load_persisted_state(&config, &admin_key, instance_id);
64        let now = unix_seconds();
65        if let Some(state) = loaded.as_mut()
66            && normalize_tombstone_times(state, now)
67        {
68            write_snapshot_and_truncate_wal(&config, &admin_key, state)?;
69        }
70        let mut slots = (0..config.max_temporary_keys)
71            .map(|_| SlotHot::default())
72            .collect::<Vec<_>>()
73            .into_boxed_slice();
74        let mut cold = HashMap::new();
75        let mut restored_leases = Vec::new();
76
77        let admin_lease = Arc::new(AuthLease::new(ADMIN_KEY_ID, None, u64::MAX));
78        if let Some(state) = loaded.as_ref() {
79            for (index, generation) in state.generations.iter().copied().enumerate() {
80                if let Some(slot) = slots.get_mut(index) {
81                    slot.generation = generation;
82                }
83            }
84            for entry in &state.entries {
85                let index = entry.key_id.slot().as_index();
86                let Some(slot) = slots.get_mut(index) else {
87                    continue;
88                };
89                if slot.generation != entry.key_id.generation() {
90                    continue;
91                }
92                let state = if entry.state == SlotState::Active && entry.expires_at <= now {
93                    SlotState::Expired
94                } else {
95                    entry.state
96                };
97                slot.state = state;
98                slot.expires_at = entry.expires_at;
99                cold.insert(
100                    entry.key_id,
101                    ColdMetadata {
102                        issued_at: entry.issued_at,
103                        label: entry.label.clone(),
104                        namespace: entry.namespace,
105                        tombstoned_at: match state {
106                            SlotState::Expired => entry.tombstoned_at.unwrap_or(entry.expires_at),
107                            SlotState::Revoked => entry.tombstoned_at.unwrap_or(now),
108                            SlotState::Free | SlotState::Active => 0,
109                        },
110                    },
111                );
112                if state == SlotState::Active {
113                    let lease = Arc::new(AuthLease::new(
114                        entry.key_id,
115                        entry.namespace,
116                        entry.expires_at,
117                    ));
118                    slot.lease = Arc::downgrade(&lease);
119                    // Held only until the schedule below adopts them; the wheel
120                    // is the lasting owner.
121                    restored_leases.push(lease);
122                }
123            }
124        }
125
126        let legacy_protocol = if safe_mode {
127            LegacyProtocolPolicy::Deny
128        } else {
129            loaded
130                .as_ref()
131                .map(|state| state.legacy_protocol)
132                .unwrap_or(config.legacy_protocol)
133        };
134        let mut admin_replay_order = loaded
135            .as_ref()
136            .map(|state| {
137                state
138                    .admin_replays
139                    .iter()
140                    .filter(|record| record.within_retention(now))
141                    .cloned()
142                    .collect::<VecDeque<_>>()
143            })
144            .unwrap_or_default();
145        while admin_replay_order.len() > ADMIN_REPLAY_CAPACITY {
146            admin_replay_order.pop_front();
147        }
148        let admin_replays = admin_replay_order
149            .iter()
150            .map(|record| record.fingerprint)
151            .collect::<HashSet<_>>();
152        let mut audit_records: VecDeque<AuditRecord> = loaded
153            .as_ref()
154            .map(|state| state.audit_records.iter().cloned().collect())
155            .unwrap_or_default();
156        while audit_records.len() > AUDIT_RECORD_CAPACITY {
157            audit_records.pop_front();
158        }
159        let (high_slot_generations, mut high_slot_entries) = loaded
160            .as_ref()
161            .map(|state| split_high_slot_state(state, config.max_temporary_keys))
162            .unwrap_or_default();
163        for entry in &mut high_slot_entries {
164            if entry.state == SlotState::Active && entry.expires_at <= now {
165                entry.state = SlotState::Expired;
166                entry.tombstoned_at = Some(entry.tombstoned_at.unwrap_or(entry.expires_at));
167            }
168        }
169        let namespace_high_water = restore_namespace_high_water(
170            &config.state_dir,
171            loaded
172                .as_ref()
173                .map_or(0, |state| state.namespace_high_water),
174        );
175        let inner = Arc::new(AuthStateInner {
176            admin: RwLock::new(AdminState {
177                key: admin_key,
178                lease: Arc::downgrade(&admin_lease),
179            }),
180            sync_process_credential,
181            instance_id: RwLock::new(instance_id),
182            slots: RwLock::new(slots),
183            high_slot_generations: RwLock::new(high_slot_generations),
184            high_slot_entries: RwLock::new(high_slot_entries),
185            safe_mode: AtomicBool::new(safe_mode),
186            legacy_protocol_allowed: AtomicBool::new(legacy_protocol.is_allowed()),
187            active_legacy_connections: AtomicU64::new(0),
188            last_legacy_connection_at: AtomicU64::new(0),
189            auth_successes: AtomicU64::new(0),
190            auth_failures: AtomicU64::new(0),
191            root_epoch: AtomicU64::new(loaded.as_ref().map(|state| state.root_epoch).unwrap_or(0)),
192            namespace_high_water: AtomicU64::new(namespace_high_water),
193            previous_root: RwLock::new(None),
194            audit_records: RwLock::new(audit_records),
195            cold: RwLock::new(cold),
196        });
197        let (command_tx, command_rx) = mpsc::channel(256);
198        let actor = tokio::spawn(run_auth_actor(
199            inner.clone(),
200            admin_lease,
201            command_rx,
202            config.clone(),
203            AuthActorState::new(
204                Leases::restored(&inner, now),
205                admin_replays,
206                admin_replay_order,
207            ),
208            state_lock.clone(),
209        ));
210        let actor_abort = actor.abort_handle();
211        let runtime = Self {
212            inner: Arc::downgrade(&inner),
213            command_tx,
214            config: config.clone(),
215            _state_lock: state_lock.clone(),
216            actor: Arc::new(Mutex::new(Some(actor))),
217            actor_abort,
218        };
219        Ok(runtime)
220    }
221
222    pub async fn shutdown_actor(&self) {
223        let (response, receiver) = oneshot::channel();
224        let _ = self
225            .command_tx
226            .send(AuthCommand::Shutdown { response })
227            .await;
228        let _ = receiver.await;
229        let handle = self.actor.lock().take();
230        if let Some(handle) = handle {
231            let _ = handle.await;
232        }
233    }
234
235    pub async fn abort_actor(&self) -> Result<(), AuthFailure> {
236        self.actor_abort.abort();
237        let handle = self.actor.lock().take();
238        if let Some(handle) = handle {
239            let _ = handle.await;
240        }
241        tokio::time::timeout(Duration::from_secs(5), async {
242            while self.inner.upgrade().is_some() {
243                tokio::time::sleep(Duration::from_millis(10)).await;
244            }
245        })
246        .await
247        .map_err(|_| {
248            AuthFailure::new(
249                "auth_state_unavailable",
250                "authentication actor did not drop after abort",
251                true,
252            )
253        })
254    }
255
256    pub fn config(&self) -> &AuthConfig {
257        &self.config
258    }
259
260    fn inner(&self) -> Result<Arc<AuthStateInner>, AuthFailure> {
261        self.inner.upgrade().ok_or_else(|| {
262            AuthFailure::new(
263                "auth_state_unavailable",
264                "authentication state manager is not running",
265                true,
266            )
267        })
268    }
269
270    pub fn admin_key(&self) -> Result<AesKeyType, AuthFailure> {
271        Ok(self.inner()?.admin_key())
272    }
273
274    pub fn derive_key(&self, key_id: KeyId) -> Result<AesKeyType, AuthFailure> {
275        let inner = self.inner()?;
276        if key_id.is_admin() {
277            return Ok(inner.admin_key());
278        }
279        derive_temporary_key(&inner.admin_key(), &inner.instance_id(), key_id)
280    }
281
282    #[cfg(test)]
283    pub(crate) fn high_slot_entry_count(&self) -> usize {
284        self.inner().map(|inner| inner.high().len()).unwrap_or(0)
285    }
286
287    pub fn derive_previous_key(&self, key_id: KeyId) -> Option<AesKeyType> {
288        let inner = self.inner().ok()?;
289        let previous = inner.previous_root.read().clone()?;
290        if key_id.is_admin() {
291            Some(previous.admin_key)
292        } else {
293            derive_temporary_key(&previous.admin_key, &previous.instance_id, key_id).ok()
294        }
295    }
296
297    pub fn authenticate_presented(
298        &self,
299        key_id: KeyId,
300        presented_key: &AesKeyType,
301    ) -> Result<AuthContext, AuthFailure> {
302        let inner = self.inner()?;
303        if key_id.is_admin() {
304            let admin = inner.admin.read();
305            if !bool::from(presented_key.ct_eq(&admin.key)) {
306                inner.auth_failures.fetch_add(1, Ordering::Relaxed);
307                return Err(AuthFailure::new(
308                    "administrator_key_invalid",
309                    "administrator credential does not match the active root key",
310                    false,
311                ));
312            }
313            let lease = admin.lease.upgrade().ok_or_else(|| {
314                AuthFailure::new(
315                    "administrator_key_rotated",
316                    "administrator credential was rotated",
317                    false,
318                )
319            })?;
320            inner.auth_successes.fetch_add(1, Ordering::Relaxed);
321            return Ok(AuthContext::from_lease(ADMIN_KEY_ID, true, &lease));
322        }
323        if inner.safe_mode.load(Ordering::Acquire) {
324            inner.auth_failures.fetch_add(1, Ordering::Relaxed);
325            return Err(AuthFailure::new(
326                "temporary_key_store_unavailable",
327                "temporary key state is unavailable; administrator reset is required",
328                false,
329            ));
330        }
331
332        let expected_key = derive_temporary_key(&inner.admin_key(), &inner.instance_id(), key_id)?;
333        if !bool::from(presented_key.ct_eq(&expected_key)) {
334            inner.auth_failures.fetch_add(1, Ordering::Relaxed);
335            return Err(temporary_key_material_mismatch(&inner, key_id));
336        }
337
338        let index = key_id.slot().as_index();
339        let generation = key_id.generation();
340        let slots = inner.slots();
341        let Some(slot) = slots.get(index) else {
342            inner.auth_failures.fetch_add(1, Ordering::Relaxed);
343            return Err(AuthFailure::new(
344                "temporary_key_not_found",
345                "temporary key id is outside the configured slot table",
346                false,
347            ));
348        };
349        if slot.generation != generation {
350            inner.auth_failures.fetch_add(1, Ordering::Relaxed);
351            return Err(AuthFailure::new(
352                "temporary_key_generation_mismatch",
353                "temporary key generation does not match the current slot",
354                false,
355            ));
356        }
357        let failure = match slot.state {
358            SlotState::Free => Some(AuthFailure::new(
359                "temporary_key_not_found",
360                "temporary key does not exist",
361                false,
362            )),
363            SlotState::Expired => Some(AuthFailure::new(
364                "temporary_key_expired",
365                "temporary key has expired",
366                false,
367            )),
368            SlotState::Revoked => Some(AuthFailure::new(
369                "temporary_key_revoked",
370                "temporary key was revoked",
371                false,
372            )),
373            SlotState::Active if slot.expires_at <= unix_seconds() => {
374                if let Some(lease) = slot.lease.upgrade() {
375                    lease.cancel_expired();
376                }
377                Some(AuthFailure::new(
378                    "temporary_key_expired",
379                    "temporary key has expired",
380                    false,
381                ))
382            }
383            SlotState::Active => None,
384        };
385        if let Some(failure) = failure {
386            inner.auth_failures.fetch_add(1, Ordering::Relaxed);
387            return Err(failure);
388        }
389        let lease = slot.lease.upgrade().ok_or_else(|| {
390            inner.auth_failures.fetch_add(1, Ordering::Relaxed);
391            AuthFailure::new(
392                "temporary_key_inactive",
393                "temporary key lease is no longer active",
394                true,
395            )
396        })?;
397        inner.auth_successes.fetch_add(1, Ordering::Relaxed);
398        Ok(AuthContext::from_lease(key_id, false, &lease))
399    }
400
401    pub fn legacy_protocol_allowed(&self) -> Result<bool, AuthFailure> {
402        Ok(self
403            .inner()?
404            .legacy_protocol_allowed
405            .load(Ordering::Acquire))
406    }
407
408    pub fn record_legacy_connection(&self) -> Result<LegacyConnectionGuard, AuthFailure> {
409        let inner = self.inner()?;
410        inner
411            .active_legacy_connections
412            .fetch_add(1, Ordering::AcqRel);
413        inner
414            .last_legacy_connection_at
415            .store(unix_seconds(), Ordering::Release);
416        Ok(LegacyConnectionGuard {
417            inner: Arc::downgrade(&inner),
418        })
419    }
420
421    async fn request<T>(
422        &self,
423        build: impl FnOnce(oneshot::Sender<Result<T, AuthFailure>>) -> AuthCommand,
424    ) -> Result<T, AuthFailure> {
425        let (response, receiver) = oneshot::channel();
426        self.command_tx.send(build(response)).await.map_err(|_| {
427            AuthFailure::new(
428                "auth_state_unavailable",
429                "authentication state manager is not running",
430                true,
431            )
432        })?;
433        receiver.await.map_err(|_| {
434            AuthFailure::new(
435                "auth_state_unavailable",
436                "authentication state manager dropped the response",
437                true,
438            )
439        })?
440    }
441
442    pub async fn claim_admin_mutation(
443        &self,
444        authorization: &AuthContext,
445        fingerprint: [u8; 32],
446        client_timestamp: u64,
447    ) -> Result<(), AuthFailure> {
448        let authority = authorization.admin_authority()?;
449        self.request(|response| AuthCommand::ClaimAdminMutation {
450            authority,
451            fingerprint,
452            client_timestamp,
453            response,
454        })
455        .await
456    }
457
458    pub async fn issue(
459        &self,
460        authorization: &AuthContext,
461        ttl: Duration,
462        label: Option<String>,
463    ) -> Result<IssuedTemporaryKey, AuthFailure> {
464        self.issue_scoped(authorization, None, ttl, label).await
465    }
466
467    /// Reserve a namespace that no key owns, for [`Self::issue_in_namespace`].
468    ///
469    /// A number is handed out once, ever. A caller that loses the response wastes
470    /// it and asks again.
471    pub async fn allocate_namespace(
472        &self,
473        authorization: &AuthContext,
474    ) -> Result<u64, AuthFailure> {
475        let authority = authorization.admin_authority()?;
476        self.request(|response| AuthCommand::AllocateNamespace {
477            authority,
478            response,
479        })
480        .await
481    }
482
483    /// Issue a key into a namespace from [`Self::allocate_namespace`].
484    ///
485    /// Every key in a namespace sees the same services and is revoked on its own.
486    /// A namespace that was not allocated is refused, including another key's own.
487    pub async fn issue_in_namespace(
488        &self,
489        authorization: &AuthContext,
490        namespace: u64,
491        ttl: Duration,
492        label: Option<String>,
493    ) -> Result<IssuedTemporaryKey, AuthFailure> {
494        self.issue_scoped(authorization, Some(namespace), ttl, label)
495            .await
496    }
497
498    async fn issue_scoped(
499        &self,
500        authorization: &AuthContext,
501        namespace: Option<u64>,
502        ttl: Duration,
503        label: Option<String>,
504    ) -> Result<IssuedTemporaryKey, AuthFailure> {
505        let authority = authorization.admin_authority()?;
506        self.request(|response| AuthCommand::Issue {
507            authority,
508            namespace,
509            ttl,
510            label,
511            response,
512        })
513        .await
514    }
515
516    pub async fn list(
517        &self,
518        authorization: &AuthContext,
519        page: u32,
520        page_size: u16,
521    ) -> Result<KeyPage, AuthFailure> {
522        let authority = authorization.admin_authority()?;
523        self.request(|response| AuthCommand::List {
524            authority,
525            page,
526            page_size,
527            response,
528        })
529        .await
530    }
531
532    pub async fn show(
533        &self,
534        authorization: &AuthContext,
535        key_id: KeyId,
536        reveal: bool,
537    ) -> Result<IssuedTemporaryKey, AuthFailure> {
538        let authority = authorization.admin_authority()?;
539        self.request(|response| AuthCommand::Show {
540            authority,
541            key_id,
542            reveal,
543            response,
544        })
545        .await
546    }
547
548    pub async fn renew(
549        &self,
550        authorization: &AuthContext,
551        key_id: KeyId,
552        ttl: Duration,
553    ) -> Result<IssuedTemporaryKey, AuthFailure> {
554        let authority = authorization.admin_authority()?;
555        self.request(|response| AuthCommand::Renew {
556            authority,
557            key_id,
558            ttl,
559            response,
560        })
561        .await
562    }
563
564    pub async fn revoke(
565        &self,
566        authorization: &AuthContext,
567        key_id: KeyId,
568    ) -> Result<TemporaryKeyMetadata, AuthFailure> {
569        let authority = authorization.admin_authority()?;
570        self.request(|response| AuthCommand::Revoke {
571            authority,
572            key_id,
573            response,
574        })
575        .await
576    }
577
578    pub async fn gc(&self, authorization: &AuthContext) -> Result<u64, AuthFailure> {
579        let authority = authorization.admin_authority()?;
580        self.request(|response| AuthCommand::Gc {
581            authority,
582            response,
583        })
584        .await
585    }
586
587    pub async fn reset(&self, authorization: &AuthContext) -> Result<(), AuthFailure> {
588        let authority = authorization.admin_authority()?;
589        self.request(|response| AuthCommand::Reset {
590            authority,
591            response,
592        })
593        .await
594    }
595
596    pub async fn rotate_root(
597        &self,
598        authorization: &AuthContext,
599        new_key: AesKeyType,
600    ) -> Result<(), AuthFailure> {
601        let authority = authorization.admin_authority()?;
602        self.request(|response| AuthCommand::RotateRoot {
603            authority,
604            new_key,
605            response,
606        })
607        .await
608    }
609
610    pub async fn set_legacy_protocol(
611        &self,
612        authorization: &AuthContext,
613        policy: LegacyProtocolPolicy,
614    ) -> Result<(), AuthFailure> {
615        let authority = authorization.admin_authority()?;
616        self.request(|response| AuthCommand::SetLegacyProtocol {
617            authority,
618            policy,
619            response,
620        })
621        .await
622    }
623
624    pub async fn status(&self, authorization: &AuthContext) -> Result<AuthStatus, AuthFailure> {
625        let authority = authorization.admin_authority()?;
626        self.request(|response| AuthCommand::Status {
627            authority,
628            response,
629        })
630        .await
631    }
632
633    pub async fn audit_admin(
634        &self,
635        authorization: &AuthContext,
636        action: impl Into<String>,
637        key_id: Option<KeyId>,
638        detail: Option<String>,
639    ) -> Result<(), AuthFailure> {
640        let authority = authorization.admin_authority()?;
641        let action = action.into();
642        self.request(|response| AuthCommand::Audit {
643            authority,
644            action,
645            key_id,
646            detail,
647            response,
648        })
649        .await
650    }
651}
652
653fn temporary_key_material_mismatch(inner: &AuthStateInner, key_id: KeyId) -> AuthFailure {
654    let index = key_id.slot().as_index();
655    let generation = key_id.generation();
656    let slots = inner.slots();
657    let current_generation = match slots.get(index) {
658        Some(slot) => Some(slot.generation),
659        None => {
660            let high = inner.high_slot_generations.read();
661            index
662                .checked_sub(slots.len())
663                .and_then(|offset| high.get(offset).copied())
664        }
665    };
666    let slot_is_active = slots
667        .get(index)
668        .is_some_and(|slot| slot.state == SlotState::Active && slot.generation == generation);
669    if slot_is_active {
670        return AuthFailure::new(
671            "temporary_key_invalid",
672            "temporary credential does not match the active relay key material",
673            false,
674        );
675    }
676    let current_epoch = inner.root_epoch.load(Ordering::Acquire);
677    if current_epoch > 0
678        && generation > Generation::FIRST
679        && current_generation.is_some_and(|issued| generation <= issued)
680    {
681        return AuthFailure::new(
682            "temporary_key_rotated",
683            "temporary credential was invalidated by administrator root rotation or auth-state reset",
684            false,
685        );
686    }
687    AuthFailure::new(
688        "temporary_key_invalid",
689        "temporary credential does not match the active relay key material",
690        false,
691    )
692}