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 (`state.rs`) 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//! This root module holds the constants and the module map. The facade is in
66//! `runtime.rs`, the shared state in `state.rs`, the actor in `actor/`, the
67//! files in `persistence/`, and the expiry schedule in `leases.rs`.
68
69use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
70use std::fmt;
71use std::fs::{File, OpenOptions};
72use std::io::{Read, Write};
73#[cfg(unix)]
74use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
75use std::path::{Path, PathBuf};
76use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
77use std::sync::{Arc, Weak};
78use std::time::Duration;
79
80use parking_lot::{Mutex, RwLock};
81use rand::RngExt;
82use ring::aead::{AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey};
83use ring::hkdf::{HKDF_SHA256, Prk, Salt};
84use serde::{Deserialize, Serialize};
85use subtle::ConstantTimeEq;
86use tokio::sync::{mpsc, oneshot, watch};
87use tokio_util::sync::CancellationToken;
88
89use pb_mapper_core::checksum::{
90    AesKeyType, Credential, MACHINE_MSG_HEADER_KEY_PATH, encode_temporary_credential,
91    env_safe_admin_key_error, get_process_credential, is_env_safe_admin_key, parse_credential,
92    process_credential_configured, set_process_msg_header_key,
93};
94use pb_mapper_core::time::unix_seconds;
95
96/// The namespace administrator connections operate in. A key that was not issued
97/// into a namespace owns the one its id names, so this mirrors [`ADMIN_KEY_ID`].
98pub const ADMIN_NAMESPACE: u64 = ADMIN_KEY_ID.as_u64();
99/// Reported in [`AuthStatus::capabilities`] by a relay that can allocate
100/// namespaces, issue keys into them, and persist each key's namespace.
101pub const CAPABILITY_KEY_NAMESPACES: &str = "key_namespaces";
102/// The `schema_version` every administrator answer carries: the [`KeyPage`]
103/// and [`AuthStatus`] this crate builds, and the relay's service and
104/// connection pages.
105pub const ADMIN_SCHEMA_VERSION: u16 = 1;
106pub const DEFAULT_AUTH_STATE_DIR: &str = "/var/lib/pb-mapper/auth";
107pub const DEFAULT_TEMP_KEY_CAPACITY: usize = 65_536;
108pub const MAX_TEMP_KEY_CAPACITY: usize = 1_048_576;
109pub const DEFAULT_MAX_TEMP_KEY_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);
110pub const MIN_TEMP_KEY_TTL: Duration = Duration::from_secs(10);
111pub const MAX_TEMP_KEY_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60);
112const TOMBSTONE_RETENTION: Duration = Duration::from_secs(60);
113/// Longest delay any scheduled cleanup can ask for, so the timing wheel can tell
114/// a plausible wait from a clock correction.
115const MAX_SCHEDULABLE_DELAY: Duration =
116    Duration::from_secs(MAX_TEMP_KEY_TTL.as_secs() + TOMBSTONE_RETENTION.as_secs());
117const SNAPSHOT_COMPACTION_INTERVAL: Duration = Duration::from_secs(5 * 60);
118const SNAPSHOT_SCHEMA_VERSION: u16 = 1;
119const STATE_BLOB_MAGIC: &[u8; 5] = b"PBAS1";
120const STATE_AAD: &[u8] = b"pb-mapper-auth-state-v1";
121const INSTANCE_ID_LEN: usize = 16;
122const ADMIN_REPLAY_RETENTION: Duration = Duration::from_secs(10 * 60);
123const ADMIN_REPLAY_CAPACITY: usize = 65_536;
124const AUDIT_RECORD_CAPACITY: usize = 4096;
125
126const _: () = assert!(
127    MAX_TEMP_KEY_CAPACITY as u64 <= u32::MAX as u64 + 1,
128    "every slot index has to fit SlotIndex's 32 bits"
129);
130const _: () = assert!(
131    DEFAULT_TEMP_KEY_CAPACITY <= MAX_TEMP_KEY_CAPACITY,
132    "the default capacity has to be one the configuration accepts"
133);
134const _: () = assert!(
135    MIN_TEMP_KEY_TTL.as_secs() <= DEFAULT_MAX_TEMP_KEY_TTL.as_secs()
136        && DEFAULT_MAX_TEMP_KEY_TTL.as_secs() <= MAX_TEMP_KEY_TTL.as_secs(),
137    "the default maximum TTL has to be one the configuration accepts"
138);
139
140mod actor;
141pub mod codes;
142mod config;
143mod ids;
144mod keys;
145mod lease;
146mod leases;
147mod persistence;
148mod runtime;
149mod state;
150#[cfg(test)]
151mod tests;
152mod timing_wheel;
153mod types;
154
155// The published API. Each name is listed, so nothing becomes public by accident.
156pub use config::{AuthConfigOverrides, default_auth_state_dir};
157pub use ids::{ADMIN_KEY_ID, Generation, KeyId, MAX_ALLOCATED_NAMESPACE, SlotIndex};
158pub use keys::derive_temporary_key;
159pub use lease::{AuthContext, AuthLease};
160pub use persistence::{
161    ADMIN_KEY_FILE, acquire_state_dir_lock, admin_key_path, discard_staged_admin_key,
162    encrypted_auth_state_exists, generate_admin_key, initialize_admin_key,
163    stage_admin_key_candidate, staged_admin_key_path, write_admin_key_file,
164};
165pub use runtime::{AuthRuntime, LegacyConnectionGuard};
166pub use types::{
167    AuthConfig, AuthFailure, AuthStatus, IssuedTemporaryKey, KeyPage, LegacyProtocolPolicy,
168    TemporaryKeyMetadata,
169};
170
171// What the child modules share through their `use super::*`.
172use actor::{Actor, AdminReplays, AuthCommand};
173use keys::{
174    expand_temporary_key, load_isolated_server_admin_credential, load_server_admin_credential,
175    temporary_root,
176};
177use leases::Leases;
178use persistence::{
179    AdminReplayRecord, AuditRecord, PersistedEntry, PersistedSnapshot, StateMutation, WalRecord,
180    append_audit, append_mutation, append_record, atomic_write, audit_action, build_snapshot,
181    cancel_all_temporary_leases, empty_snapshot, hex, instance_id_path, load_or_create_instance_id,
182    load_persisted_state, normalize_tombstone_times, persist_recovery_admin_key,
183    prepare_state_dir_and_lock, push_audit_record, push_persisted_audit, random_instance_id,
184    read_admin_key, read_namespace_high_water, recover_admin_key_after_rotation,
185    recover_instance_id_after_reset, reset_already_installed, restore_namespace_high_water,
186    rotation_already_installed, rotation_key_path, split_high_slot_state, staged_instance_id_path,
187    validate_admin_key, write_admin_key, write_namespace_high_water,
188    write_snapshot_and_truncate_wal,
189};
190use runtime::off_runtime;
191use state::{
192    AdminState, AuthStateInner, ColdMetadata, LiveLeases, PreviousRoot, RestoredState, SlotHot,
193    SlotState,
194};
195use timing_wheel::{Timer, TimingWheel};