1use 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
94pub const ADMIN_NAMESPACE: u64 = ADMIN_KEY_ID.as_u64();
97pub 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);
107const 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#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
407#[serde(rename_all = "snake_case")]
408enum SlotState {
409 Free,
411 Active,
413 Expired,
415 Revoked,
416}
417
418#[derive(Debug)]
420struct SlotHot {
421 generation: Generation,
422 state: SlotState,
423 expires_at: u64,
424 lease: Weak<AuthLease>,
427}
428
429impl SlotHot {
430 fn holds(&self, key_id: KeyId) -> bool {
434 self.generation == key_id.generation() && self.state != SlotState::Free
435 }
436
437 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 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 slots: RwLock<Box<[SlotHot]>>,
488 high_slot_generations: RwLock<Vec<Generation>>,
501 high_slot_entries: RwLock<Vec<PersistedEntry>>,
502 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 namespace_high_water: AtomicU64,
516 previous_root: RwLock<Option<PreviousRoot>>,
517 audit_records: RwLock<VecDeque<AuditRecord>>,
518}
519
520impl AuthStateInner {
521 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 #[serde(default, skip_serializing_if = "Option::is_none")]
577 pub namespace: Option<u64>,
578}
579
580impl TemporaryKeyMetadata {
581 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 #[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 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 #[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 #[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 #[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 #[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;