Skip to main content

pb_mapper_auth/
lib.rs

1//! Authentication state for protocol-v2 connections and administrator operations.
2//!
3//! # How a temporary credential works
4//!
5//! Nothing secret is stored per key. A temporary credential is *derived* from the
6//! root key, the server instance id, and the key id, so the server can verify a
7//! credential it holds no copy of, and a key id is all the state a key needs:
8//!
9//! ```text
10//! issue:  root key + instance id + key id  --HKDF-->  credential handed to the client
11//! verify: root key + instance id + key id  --HKDF-->  compare against what was presented
12//! ```
13//!
14//! Because the material is derived, invalidating every key at once is a matter of
15//! changing an input: a root rotation replaces the root key, a state reset replaces
16//! the instance id. Neither has to touch individual keys.
17//!
18//! # Where the state lives
19//!
20//! ```text
21//!                    key_id = generation:slot
22//!                             |
23//!   request ──> derive & compare ──> slots[slot]  ── lifecycle: Free/Active/
24//!                                        │            Expired/Revoked, expires_at
25//!                                        │
26//!                                   Weak lease ──> Arc lease, owned by the actor's
27//!                                        ^          timing wheel — the single place
28//!                                        │          a lease's lifetime ends
29//!   AuthContext (also Weak) ─────────────┘
30//! ```
31//!
32//! The slot table is a preallocated array indexed straight off the key id, so
33//! verification costs an array index and churn does not grow memory. The
34//! `SlotState` docs below cover the table's layout, why generations exist, and
35//! why dead rows linger. `Leases` (`leases.rs`) owns the three structures a
36//! key's lifetime spans; `timing_wheel.rs` schedules the expiries.
37//!
38//! # Namespaces
39//!
40//! A namespace decides which services a credential can see. By default a key owns
41//! one named by its own id, so revoking it takes the namespace with it. The
42//! administrator can instead allocate a namespace that no key owns and issue
43//! several keys into it, which lets one tenant hold a separately revocable key
44//! per device without moving the others:
45//!
46//! ```text
47//! allocate_namespace() --> 7
48//! issue_in_namespace(7) --> key A ─┐  same services; revoking A leaves B working,
49//! issue_in_namespace(7) --> key B ─┘  and namespace 7 is never handed out again
50//! ```
51//!
52//! A key's namespace is fixed at issue and read off its lease, so authentication
53//! does no extra work for it. `ids.rs` shows why the two kinds cannot collide, and
54//! `persistence/namespaces.rs` why the allocator lives outside the encrypted state.
55//!
56//! # Where mutations happen
57//!
58//! ```text
59//! AuthRuntime (facade) ──channel──> one actor ──> encrypted snapshot + WAL
60//! ```
61//!
62//! Every mutation is serialized through a single actor, so a request authorized
63//! before a root rotation cannot execute against the state that replaced it.
64//!
65//! The facade and model types stay in this root module; runtime checks, actor
66//! mutations, persistence, expiry scheduling, and tests live in the children.
67
68use std::collections::{HashMap, HashSet, VecDeque};
69use std::fmt;
70use std::fs::{File, OpenOptions};
71use std::io::{Read, Write};
72#[cfg(unix)]
73use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
74use std::path::{Path, PathBuf};
75use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
76use std::sync::{Arc, Weak};
77use std::time::{Duration, SystemTime, UNIX_EPOCH};
78
79use parking_lot::{Mutex, RwLock};
80use rand::RngExt;
81use ring::aead::{AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey};
82use ring::hkdf::{HKDF_SHA256, Salt};
83use serde::{Deserialize, Serialize};
84use subtle::ConstantTimeEq;
85use tokio::sync::{mpsc, oneshot};
86use tokio_util::sync::CancellationToken;
87
88use pb_mapper_core::checksum::{
89    AesKeyType, Credential, MACHINE_MSG_HEADER_KEY_PATH, encode_temporary_credential,
90    env_safe_admin_key_error, get_process_credential, is_env_safe_admin_key, parse_credential,
91    process_credential_configured, set_process_msg_header_key,
92};
93
94/// The namespace administrator connections operate in. A key that was not issued
95/// into a namespace owns the one its id names, so this mirrors [`ADMIN_KEY_ID`].
96pub const ADMIN_NAMESPACE: u64 = ADMIN_KEY_ID.as_u64();
97/// Reported in [`AuthStatus::capabilities`] by a relay that can allocate
98/// namespaces, issue keys into them, and persist each key's namespace.
99pub const CAPABILITY_KEY_NAMESPACES: &str = "key_namespaces";
100pub const DEFAULT_AUTH_STATE_DIR: &str = "/var/lib/pb-mapper/auth";
101pub const DEFAULT_TEMP_KEY_CAPACITY: usize = 65_536;
102pub const MAX_TEMP_KEY_CAPACITY: usize = 1_048_576;
103pub const DEFAULT_MAX_TEMP_KEY_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);
104pub const MIN_TEMP_KEY_TTL: Duration = Duration::from_secs(10);
105pub const MAX_TEMP_KEY_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60);
106const TOMBSTONE_RETENTION: Duration = Duration::from_secs(60);
107/// Longest delay any scheduled cleanup can ask for, so the timing wheel can tell
108/// a plausible wait from a clock correction.
109const MAX_SCHEDULABLE_DELAY: Duration =
110    Duration::from_secs(MAX_TEMP_KEY_TTL.as_secs() + TOMBSTONE_RETENTION.as_secs());
111const SNAPSHOT_COMPACTION_INTERVAL: Duration = Duration::from_secs(5 * 60);
112const SNAPSHOT_SCHEMA_VERSION: u16 = 1;
113const STATE_BLOB_MAGIC: &[u8; 5] = b"PBAS1";
114const STATE_AAD: &[u8] = b"pb-mapper-auth-state-v1";
115const INSTANCE_ID_LEN: usize = 16;
116const ADMIN_REPLAY_RETENTION: Duration = Duration::from_secs(10 * 60);
117const ADMIN_REPLAY_CAPACITY: usize = 65_536;
118const AUDIT_RECORD_CAPACITY: usize = 4096;
119
120#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
121#[serde(rename_all = "snake_case")]
122pub enum LegacyProtocolPolicy {
123    Allow,
124    Deny,
125}
126
127impl LegacyProtocolPolicy {
128    pub fn is_allowed(self) -> bool {
129        matches!(self, Self::Allow)
130    }
131}
132
133#[derive(Clone, Debug)]
134pub struct AuthConfig {
135    pub state_dir: PathBuf,
136    pub max_temporary_keys: usize,
137    pub max_temporary_key_ttl: Duration,
138    pub legacy_protocol: LegacyProtocolPolicy,
139}
140
141#[derive(Clone, Debug, Serialize, Deserialize)]
142pub struct AuthFailure {
143    pub code: String,
144    pub message: String,
145    pub retryable: bool,
146}
147
148impl AuthFailure {
149    pub fn new(code: impl Into<String>, message: impl Into<String>, retryable: bool) -> Self {
150        Self {
151            code: code.into(),
152            message: message.into(),
153            retryable,
154        }
155    }
156
157    pub fn internal(message: impl Into<String>) -> Self {
158        Self::new("auth_internal_error", message, false)
159    }
160}
161
162impl fmt::Display for AuthFailure {
163    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
164        write!(formatter, "{}: {}", self.code, self.message)
165    }
166}
167
168impl std::error::Error for AuthFailure {}
169
170const LEASE_CANCEL_NONE: u8 = 0;
171const LEASE_CANCEL_EXPIRED: u8 = 1;
172const LEASE_CANCEL_REVOKED: u8 = 2;
173const LEASE_CANCEL_ROTATED: u8 = 3;
174
175#[derive(Debug)]
176pub struct AuthLease {
177    key_id: KeyId,
178    namespace: u64,
179    expires_at: AtomicU64,
180    cancellation: CancellationToken,
181    cancel_reason: AtomicU8,
182}
183
184impl AuthLease {
185    fn new(key_id: KeyId, issued_into: Option<u64>, expires_at: u64) -> Self {
186        Self {
187            key_id,
188            namespace: key_id.namespace(issued_into),
189            expires_at: AtomicU64::new(expires_at),
190            cancellation: CancellationToken::new(),
191            cancel_reason: AtomicU8::new(LEASE_CANCEL_NONE),
192        }
193    }
194
195    pub fn key_id(&self) -> KeyId {
196        self.key_id
197    }
198
199    pub fn expires_at(&self) -> u64 {
200        self.expires_at.load(Ordering::Acquire)
201    }
202
203    pub fn cancellation_token(&self) -> CancellationToken {
204        self.cancellation.clone()
205    }
206
207    fn record_cancel(&self, reason: u8) {
208        let _ = self.cancel_reason.compare_exchange(
209            LEASE_CANCEL_NONE,
210            reason,
211            Ordering::AcqRel,
212            Ordering::Acquire,
213        );
214        self.cancellation.cancel();
215    }
216
217    pub(crate) fn cancel_expired(&self) {
218        self.record_cancel(LEASE_CANCEL_EXPIRED);
219    }
220
221    pub(crate) fn cancel_revoked(&self) {
222        self.record_cancel(LEASE_CANCEL_REVOKED);
223    }
224
225    pub(crate) fn cancel_rotated(&self) {
226        self.record_cancel(LEASE_CANCEL_ROTATED);
227    }
228
229    #[cfg(test)]
230    pub(crate) fn expire_now(&self) {
231        self.expires_at.store(0, Ordering::Release);
232    }
233}
234
235#[derive(Clone, Debug)]
236pub struct AuthContext {
237    pub key_id: KeyId,
238    pub namespace: u64,
239    pub is_admin: bool,
240    lease: Weak<AuthLease>,
241}
242
243impl AuthContext {
244    fn from_lease(key_id: KeyId, is_admin: bool, lease: &Arc<AuthLease>) -> Self {
245        Self {
246            key_id,
247            namespace: lease.namespace,
248            is_admin,
249            lease: Arc::downgrade(lease),
250        }
251    }
252
253    pub fn ensure_active(&self) -> Result<Arc<AuthLease>, AuthFailure> {
254        let lease = self.lease.upgrade().ok_or_else(|| {
255            AuthFailure::new(
256                if self.is_admin {
257                    "administrator_key_rotated"
258                } else {
259                    "temporary_key_inactive"
260                },
261                "credential lease is no longer active",
262                false,
263            )
264        })?;
265        if lease.cancellation.is_cancelled() {
266            return Err(cancelled_lease_failure(self.is_admin, &lease));
267        }
268        if !self.is_admin && lease.expires_at() <= unix_seconds() {
269            lease.cancel_expired();
270            return Err(AuthFailure::new(
271                "temporary_key_expired",
272                "temporary key has expired",
273                false,
274            ));
275        }
276        Ok(lease)
277    }
278
279    pub fn cancellation_token(&self) -> Result<CancellationToken, AuthFailure> {
280        Ok(self.ensure_active()?.cancellation_token())
281    }
282
283    pub fn admin_cancellation_token(&self) -> Result<CancellationToken, AuthFailure> {
284        self.require_admin()?;
285        self.cancellation_token()
286    }
287
288    fn admin_authority(&self) -> Result<Weak<AuthLease>, AuthFailure> {
289        self.require_admin()?;
290        self.ensure_active()?;
291        Ok(self.lease.clone())
292    }
293
294    fn require_admin(&self) -> Result<(), AuthFailure> {
295        if self.is_admin {
296            Ok(())
297        } else {
298            Err(AuthFailure::new(
299                "admin_permission_required",
300                "administrator credential is required for this operation",
301                false,
302            ))
303        }
304    }
305}
306
307fn cancelled_lease_failure(is_admin: bool, lease: &AuthLease) -> AuthFailure {
308    if is_admin {
309        return AuthFailure::new(
310            "administrator_key_rotated",
311            "credential lease has been cancelled",
312            false,
313        );
314    }
315    match lease.cancel_reason.load(Ordering::Acquire) {
316        LEASE_CANCEL_EXPIRED => {
317            AuthFailure::new("temporary_key_expired", "temporary key has expired", false)
318        }
319        LEASE_CANCEL_ROTATED => AuthFailure::new(
320            "temporary_key_rotated",
321            "temporary credential was invalidated by administrator root rotation or auth-state reset",
322            false,
323        ),
324        LEASE_CANCEL_REVOKED => {
325            AuthFailure::new("temporary_key_revoked", "temporary key was revoked", false)
326        }
327        _ => AuthFailure::new(
328            "temporary_key_inactive",
329            "credential lease has been cancelled",
330            false,
331        ),
332    }
333}
334
335/// # The slot table
336///
337/// A temporary key is never stored. It is *derived* on demand from
338/// `(root key, instance id, key id)`, so the server can verify a credential it
339/// has no copy of. That makes the key id the whole identity of a key, and a
340/// key id is a slot index plus a generation counter:
341///
342/// ```text
343///  key_id: u64
344/// ┌───────────────────────────┬───────────────────────────┐
345/// │  generation (high 32)     │  slot index (low 32)      │
346/// └───────────────────────────┴───────────────────────────┘
347///        ^ bumped on reuse            ^ where the row lives
348/// ```
349///
350/// The slot index is a direct offset into `AuthStateInner::slots`, a
351/// preallocated `Box<[SlotHot]>`. So verifying a credential is an array index,
352/// not a map lookup or a scan, and the table's memory does not grow with churn:
353///
354/// ```text
355/// slots: [ SlotHot; max_temporary_keys ]
356///   idx 0  gen 7  Active   expires_at=…  lease─┐
357///   idx 1  gen 0  Free                         │  Weak, so the actor's
358///   idx 2  gen 3  Expired  (tombstoned)        │  timing wheel is the
359///   idx 3  gen 9  Active   expires_at=…  lease─┴─ only strong owner
360/// ```
361///
362/// ## Why the generation counter
363///
364/// A freed slot is reused, so the index alone would let a *retired* credential
365/// authenticate against the *new* tenant of that row. The generation bump makes
366/// the old key id refer to a row that no longer exists:
367///
368/// ```text
369/// issue   -> idx 2, gen 3  =>  key_id 0x0000_0003_0000_0002
370/// expire  -> idx 2 retired, generation kept at 3
371/// reissue -> idx 2, gen 4  =>  key_id 0x0000_0004_0000_0002
372///            the old key id still names gen 3, which nothing matches
373/// ```
374///
375/// This is why [`SlotHot::retire`] clears the row but preserves `generation`,
376/// and why expiry, GC, root rotation and a state reset all keep it. The one
377/// exception is a reset out of a damaged snapshot, which cannot know the generations
378/// and starts them over. Only the rotated instance id then keeps an old credential
379/// from authenticating, so a key id from before it may name a different key.
380///
381/// ## The lifecycle
382///
383/// ```text
384///          issue                  deadline passes / revoke
385///   Free ─────────> Active ──────────────────────────────> Expired
386///     ^               │                                    Revoked
387///     │               └── renew: same row, later expires_at    │
388///     │                                                        │
389///     └──────────── retire, after TOMBSTONE_RETENTION ─────────┘
390/// ```
391///
392/// `Expired`/`Revoked` are tombstones, not garbage. A row lingers in that state
393/// for `TOMBSTONE_RETENTION` so a client that presents a dead credential is told
394/// *why* ("expired", "revoked") instead of receiving the indistinguishable
395/// "unknown key" it would get from an already-recycled row. `Leases` owns that
396/// delay; see `leases.rs`.
397///
398/// ## Slots above capacity
399///
400/// `max_temporary_keys` is configurable, so a restart can shrink the table below
401/// what the persisted state used. Those rows cannot be indexed any more, but
402/// their generations still have to be honoured — otherwise growing the table
403/// again would reissue a key id that was already handed out. They are retained
404/// out-of-line in `high_slot_generations` / `high_slot_entries`, which is why so
405/// many operations check the array first and fall back to a scan of that vector.
406#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
407#[serde(rename_all = "snake_case")]
408enum SlotState {
409    /// Never used, or retired and past its tombstone.
410    Free,
411    /// A live credential. `expires_at` is authoritative.
412    Active,
413    /// Dead. Retained for `TOMBSTONE_RETENTION` so the reason survives.
414    Expired,
415    Revoked,
416}
417
418/// One row of the slot table. `generation` outlives every other field.
419#[derive(Debug)]
420struct SlotHot {
421    generation: Generation,
422    state: SlotState,
423    expires_at: u64,
424    /// `Weak`, because the actor's timing wheel holds the strong reference and is
425    /// the single place a lease's lifetime ends. See `timing_wheel.rs`.
426    lease: Weak<AuthLease>,
427}
428
429impl SlotHot {
430    /// Whether this row still belongs to `key_id`'s generation. A row that has
431    /// been reissued belongs to a newer tenant and must not be touched on the
432    /// old one's behalf.
433    fn holds(&self, key_id: KeyId) -> bool {
434        self.generation == key_id.generation() && self.state != SlotState::Free
435    }
436
437    /// Whether a garbage collection should free this row: it is already dead, or
438    /// it is active but past its deadline.
439    fn is_collectable(&self, now: u64) -> bool {
440        match self.state {
441            SlotState::Expired | SlotState::Revoked => true,
442            SlotState::Active => self.expires_at <= now,
443            SlotState::Free => false,
444        }
445    }
446
447    /// Frees the slot for reuse while keeping its generation, so a key id that
448    /// has been handed out is never issued a second time.
449    fn retire(&mut self) {
450        *self = Self {
451            generation: self.generation,
452            ..Self::default()
453        };
454    }
455}
456
457impl Default for SlotHot {
458    fn default() -> Self {
459        Self {
460            generation: Generation::FIRST,
461            state: SlotState::Free,
462            expires_at: 0,
463            lease: Weak::new(),
464        }
465    }
466}
467
468#[derive(Debug)]
469struct AdminState {
470    key: AesKeyType,
471    lease: Weak<AuthLease>,
472}
473
474#[derive(Clone, Debug)]
475struct PreviousRoot {
476    admin_key: AesKeyType,
477    instance_id: [u8; INSTANCE_ID_LEN],
478}
479
480#[derive(Debug)]
481struct AuthStateInner {
482    admin: RwLock<AdminState>,
483    sync_process_credential: bool,
484    instance_id: RwLock<[u8; INSTANCE_ID_LEN]>,
485    /// Preallocated, indexed directly by `key_slot(key_id)`. Documented on
486    /// [`SlotState`].
487    slots: RwLock<Box<[SlotHot]>>,
488    /// Rows the configured capacity no longer covers, because a restart shrank
489    /// the table below what the persisted state used:
490    ///
491    /// ```text
492    ///  slots: [ 0 1 2 3 ]  <- indexable
493    ///  high:          [ 4 5 ]  <- generations still honoured, out-of-line
494    /// ```
495    ///
496    /// Their generations must be kept so growing the table again cannot reissue
497    /// a key id that was already handed out, and their entries so a still-live
498    /// credential in that range keeps working. This is the fallback path that
499    /// operations take after missing in `slots`.
500    high_slot_generations: RwLock<Vec<Generation>>,
501    high_slot_entries: RwLock<Vec<PersistedEntry>>,
502    /// Per-key description that no authentication check needs, kept out of the
503    /// hot slot row. Lives here rather than inside the actor so a key's handle
504    /// can drop it without the actor being involved; see `leases.rs`.
505    cold: RwLock<HashMap<KeyId, ColdMetadata>>,
506    safe_mode: AtomicBool,
507    legacy_protocol_allowed: AtomicBool,
508    active_legacy_connections: AtomicU64,
509    last_legacy_connection_at: AtomicU64,
510    auth_successes: AtomicU64,
511    auth_failures: AtomicU64,
512    root_epoch: AtomicU64,
513    /// The encrypted state's copy of the allocator's mark, which snapshots carry. See
514    /// `persistence/namespaces.rs` for the other copy.
515    namespace_high_water: AtomicU64,
516    previous_root: RwLock<Option<PreviousRoot>>,
517    audit_records: RwLock<VecDeque<AuditRecord>>,
518}
519
520impl AuthStateInner {
521    /// Rows the configured capacity no longer covers. See the field's docs; the
522    /// fallback is a scan because the range is small and rarely touched.
523    fn high(&self) -> parking_lot::RwLockReadGuard<'_, Vec<PersistedEntry>> {
524        self.high_slot_entries.read()
525    }
526
527    fn high_mut(&self) -> parking_lot::RwLockWriteGuard<'_, Vec<PersistedEntry>> {
528        self.high_slot_entries.write()
529    }
530
531    fn slots(&self) -> parking_lot::RwLockReadGuard<'_, Box<[SlotHot]>> {
532        self.slots.read()
533    }
534
535    fn slots_mut(&self) -> parking_lot::RwLockWriteGuard<'_, Box<[SlotHot]>> {
536        self.slots.write()
537    }
538
539    fn cold(&self) -> parking_lot::RwLockReadGuard<'_, HashMap<KeyId, ColdMetadata>> {
540        self.cold.read()
541    }
542
543    fn cold_mut(&self) -> parking_lot::RwLockWriteGuard<'_, HashMap<KeyId, ColdMetadata>> {
544        self.cold.write()
545    }
546
547    fn admin_key(&self) -> AesKeyType {
548        self.admin.read().key
549    }
550
551    fn instance_id(&self) -> [u8; INSTANCE_ID_LEN] {
552        *self.instance_id.read()
553    }
554}
555
556#[derive(Clone)]
557pub struct AuthRuntime {
558    inner: Weak<AuthStateInner>,
559    command_tx: mpsc::Sender<AuthCommand>,
560    config: AuthConfig,
561    _state_lock: Arc<File>,
562    actor: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
563    actor_abort: tokio::task::AbortHandle,
564}
565
566#[derive(Clone, Debug, Serialize, Deserialize)]
567pub struct TemporaryKeyMetadata {
568    pub key_id: KeyId,
569    pub state: String,
570    pub issued_at: u64,
571    pub expires_at: u64,
572    pub label: Option<String>,
573    /// The namespace this key was issued into. Absent for a key that owns the one
574    /// its id names, which is also how a relay without namespaces reports every
575    /// key; [`Self::effective_namespace`] covers both.
576    #[serde(default, skip_serializing_if = "Option::is_none")]
577    pub namespace: Option<u64>,
578}
579
580impl TemporaryKeyMetadata {
581    /// The namespace this key's credential operates in.
582    pub fn effective_namespace(&self) -> u64 {
583        self.key_id.namespace(self.namespace)
584    }
585}
586
587#[derive(Clone, Debug, Serialize, Deserialize)]
588pub struct IssuedTemporaryKey {
589    #[serde(flatten)]
590    pub metadata: TemporaryKeyMetadata,
591    pub credential: String,
592}
593
594#[derive(Clone, Debug, Serialize, Deserialize)]
595pub struct KeyPage {
596    pub schema_version: u16,
597    pub items: Vec<TemporaryKeyMetadata>,
598    pub next_page: Option<u32>,
599}
600
601#[derive(Clone, Debug, Serialize, Deserialize)]
602pub struct AuthStatus {
603    pub schema_version: u16,
604    pub safe_mode: bool,
605    pub capacity: usize,
606    pub active_keys: usize,
607    pub expired_keys: usize,
608    pub revoked_keys: usize,
609    pub legacy_protocol: LegacyProtocolPolicy,
610    pub active_legacy_connections: u64,
611    pub last_legacy_connection_at: Option<u64>,
612    pub auth_successes: u64,
613    pub auth_failures: u64,
614    pub server_instance_id: String,
615    /// What this relay supports beyond the base protocol, such as
616    /// [`CAPABILITY_KEY_NAMESPACES`]. A relay older than the field reports none.
617    #[serde(default, skip_serializing_if = "Vec::is_empty")]
618    pub capabilities: Vec<String>,
619}
620
621#[derive(Clone, Debug)]
622struct ColdMetadata {
623    issued_at: u64,
624    label: Option<String>,
625    /// The namespace this key was issued into, if any. See [`KeyId::namespace`].
626    namespace: Option<u64>,
627    tombstoned_at: u64,
628}
629
630enum AuthCommand {
631    ClaimAdminMutation {
632        authority: Weak<AuthLease>,
633        fingerprint: [u8; 32],
634        client_timestamp: u64,
635        response: oneshot::Sender<Result<(), AuthFailure>>,
636    },
637    AllocateNamespace {
638        authority: Weak<AuthLease>,
639        response: oneshot::Sender<Result<u64, AuthFailure>>,
640    },
641    Issue {
642        authority: Weak<AuthLease>,
643        namespace: Option<u64>,
644        ttl: Duration,
645        label: Option<String>,
646        response: oneshot::Sender<Result<IssuedTemporaryKey, AuthFailure>>,
647    },
648    List {
649        authority: Weak<AuthLease>,
650        page: u32,
651        page_size: u16,
652        response: oneshot::Sender<Result<KeyPage, AuthFailure>>,
653    },
654    Show {
655        authority: Weak<AuthLease>,
656        key_id: KeyId,
657        reveal: bool,
658        response: oneshot::Sender<Result<IssuedTemporaryKey, AuthFailure>>,
659    },
660    Renew {
661        authority: Weak<AuthLease>,
662        key_id: KeyId,
663        ttl: Duration,
664        response: oneshot::Sender<Result<IssuedTemporaryKey, AuthFailure>>,
665    },
666    Revoke {
667        authority: Weak<AuthLease>,
668        key_id: KeyId,
669        response: oneshot::Sender<Result<TemporaryKeyMetadata, AuthFailure>>,
670    },
671    Gc {
672        authority: Weak<AuthLease>,
673        response: oneshot::Sender<Result<u64, AuthFailure>>,
674    },
675    Reset {
676        authority: Weak<AuthLease>,
677        response: oneshot::Sender<Result<(), AuthFailure>>,
678    },
679    RotateRoot {
680        authority: Weak<AuthLease>,
681        new_key: AesKeyType,
682        response: oneshot::Sender<Result<(), AuthFailure>>,
683    },
684    SetLegacyProtocol {
685        authority: Weak<AuthLease>,
686        policy: LegacyProtocolPolicy,
687        response: oneshot::Sender<Result<(), AuthFailure>>,
688    },
689    Status {
690        authority: Weak<AuthLease>,
691        response: oneshot::Sender<Result<AuthStatus, AuthFailure>>,
692    },
693    Audit {
694        authority: Weak<AuthLease>,
695        action: String,
696        key_id: Option<KeyId>,
697        detail: Option<String>,
698        response: oneshot::Sender<Result<(), AuthFailure>>,
699    },
700    Shutdown {
701        response: oneshot::Sender<()>,
702    },
703}
704
705mod config;
706pub use config::default_auth_state_dir;
707#[cfg(all(test, not(any(windows, target_os = "macos"))))]
708pub(crate) use config::linux_default_auth_state_dir;
709#[cfg(test)]
710pub(crate) use config::parse_legacy_protocol_policy;
711#[cfg(test)]
712pub(crate) use config::platform_default_auth_state_dir;
713#[cfg(all(test, not(any(windows, target_os = "macos"))))]
714pub(crate) use config::{linux_system_auth_dir_usable, unix_effective_uid};
715mod keys;
716pub use keys::derive_temporary_key;
717#[cfg(test)]
718pub(crate) use keys::recover_admin_key_after_rotation;
719pub(crate) use keys::{load_isolated_server_admin_credential, load_server_admin_credential};
720mod runtime;
721
722pub struct LegacyConnectionGuard {
723    inner: Weak<AuthStateInner>,
724}
725
726impl Drop for LegacyConnectionGuard {
727    fn drop(&mut self) {
728        if let Some(inner) = self.inner.upgrade() {
729            inner
730                .active_legacy_connections
731                .fetch_sub(1, Ordering::AcqRel);
732        }
733    }
734}
735
736#[derive(Clone, Debug, Serialize, Deserialize)]
737struct PersistedEntry {
738    key_id: KeyId,
739    state: SlotState,
740    issued_at: u64,
741    expires_at: u64,
742    label: Option<String>,
743    #[serde(default)]
744    tombstoned_at: Option<u64>,
745    /// The namespace this key was issued into. Absent for a key that owns the one
746    /// its id names, which is every entry written before namespaces existed.
747    #[serde(default, skip_serializing_if = "Option::is_none")]
748    namespace: Option<u64>,
749}
750
751#[derive(Clone, Debug, Serialize, Deserialize)]
752struct PersistedSnapshot {
753    schema_version: u16,
754    instance_id: [u8; INSTANCE_ID_LEN],
755    generations: Vec<Generation>,
756    entries: Vec<PersistedEntry>,
757    legacy_protocol: LegacyProtocolPolicy,
758    #[serde(default)]
759    admin_replays: Vec<AdminReplayRecord>,
760    #[serde(default)]
761    audit_records: VecDeque<AuditRecord>,
762    #[serde(default)]
763    root_epoch: u64,
764    /// The last namespace handed out as of this snapshot. See
765    /// `persistence/namespaces.rs`.
766    #[serde(default)]
767    namespace_high_water: u64,
768}
769
770#[derive(Clone, Debug, Serialize, Deserialize)]
771struct AdminReplayRecord {
772    fingerprint: [u8; 32],
773    client_timestamp: u64,
774    /// Server receipt time used for retention. Older snapshots omit this field
775    /// (`0` after serde default) and fall back to `client_timestamp`.
776    #[serde(default)]
777    accepted_at: u64,
778}
779
780impl AdminReplayRecord {
781    fn within_retention(&self, now: u64) -> bool {
782        let anchor = if self.accepted_at == 0 {
783            self.client_timestamp
784        } else {
785            self.accepted_at
786        };
787        now.saturating_sub(anchor) <= ADMIN_REPLAY_RETENTION.as_secs()
788    }
789}
790
791#[derive(Clone, Debug, Serialize, Deserialize)]
792enum StateMutation {
793    Issue(PersistedEntry),
794    Renew { key_id: KeyId, expires_at: u64 },
795    Revoke { key_id: KeyId, at: u64 },
796    LegacyProtocol(LegacyProtocolPolicy),
797}
798
799#[derive(Clone, Debug, Serialize, Deserialize)]
800struct AuditRecord {
801    at: u64,
802    action: String,
803    key_id: Option<KeyId>,
804    label: Option<String>,
805    /// The namespace an allocation handed out. Replaying this is how the encrypted
806    /// state learns the allocator's mark, in a field an older relay ignores rather
807    /// than a WAL record it could not decode.
808    #[serde(default, skip_serializing_if = "Option::is_none")]
809    namespace: Option<u64>,
810}
811
812#[derive(Clone, Debug, Serialize, Deserialize)]
813enum WalRecord {
814    Mutation {
815        mutation: StateMutation,
816        audit: AuditRecord,
817    },
818    Audit(AuditRecord),
819    AdminReplay(AdminReplayRecord),
820}
821
822mod actor;
823use actor::{AuthActorState, run_auth_actor};
824mod persistence;
825pub use persistence::*;
826pub(crate) use persistence::{
827    append_audit, append_mutation, append_wal, atomic_write, auth_snapshot_path, build_snapshot,
828    cancel_all_temporary_leases, compaction_is_allowed, empty_snapshot,
829    fail_closed_on_uncertain_wal, hex, key_matches_existing_state, load_or_create_instance_id,
830    load_persisted_state, normalize_tombstone_times, open_blob, prepare_state_dir_and_lock,
831    push_audit_record, push_persisted_audit, random_instance_id, read_namespace_high_water,
832    recover_instance_id_after_reset, reset_already_installed, restore_namespace_high_water,
833    rotation_already_installed, split_high_slot_state, truncate_auth_wal, unix_seconds,
834    write_admin_key, write_namespace_high_water, write_snapshot_and_truncate_wal,
835};
836#[cfg(test)]
837pub(crate) use persistence::{prepare_state_dir, read_instance_id_file, try_load_persisted_state};
838mod ids;
839pub use ids::{ADMIN_KEY_ID, Generation, KeyId, MAX_ALLOCATED_NAMESPACE, SlotIndex};
840mod leases;
841use leases::Leases;
842mod timing_wheel;
843use timing_wheel::{Timer, TimingWheel};
844#[cfg(test)]
845mod tests;