use super::*;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum SlotState {
Free,
Active,
Expired,
Revoked,
}
pub(crate) struct SlotHot {
pub(crate) generation: Generation,
pub(crate) state: SlotState,
pub(crate) expires_at: u64,
pub(crate) lease: Weak<AuthLease>,
}
impl SlotHot {
pub(crate) fn holds(&self, key_id: KeyId) -> bool {
self.generation == key_id.generation() && self.state != SlotState::Free
}
pub(crate) fn is_collectable(&self, now: u64) -> bool {
match self.state {
SlotState::Expired | SlotState::Revoked => true,
SlotState::Active => self.expires_at <= now,
SlotState::Free => false,
}
}
pub(crate) fn retire(&mut self) {
*self = Self {
generation: self.generation,
..Self::default()
};
}
}
impl Default for SlotHot {
fn default() -> Self {
Self {
generation: Generation::FIRST,
state: SlotState::Free,
expires_at: 0,
lease: Weak::new(),
}
}
}
pub(crate) struct AdminState {
pub(crate) key: AesKeyType,
pub(crate) lease: Weak<AuthLease>,
}
#[derive(Clone)]
pub(crate) struct PreviousRoot {
pub(crate) admin_key: AesKeyType,
pub(crate) instance_id: [u8; INSTANCE_ID_LEN],
}
pub(crate) struct AuthStateInner {
pub(crate) admin: RwLock<AdminState>,
pub(crate) sync_process_credential: bool,
pub(crate) instance_id: RwLock<[u8; INSTANCE_ID_LEN]>,
pub(crate) temporary_root: RwLock<Prk>,
pub(crate) slots: RwLock<Box<[SlotHot]>>,
pub(crate) high_slot_generations: Box<[Generation]>,
pub(crate) high_slot_entries: RwLock<Vec<PersistedEntry>>,
pub(crate) cold: RwLock<HashMap<KeyId, ColdMetadata>>,
pub(crate) safe_mode: AtomicBool,
pub(crate) snapshot_stale: AtomicBool,
pub(crate) legacy_protocol_allowed: AtomicBool,
pub(crate) active_legacy_connections: AtomicU64,
pub(crate) last_legacy_connection_at: AtomicU64,
pub(crate) auth_successes: AtomicU64,
pub(crate) auth_failures: AtomicU64,
pub(crate) root_epoch: AtomicU64,
pub(crate) namespace_high_water: AtomicU64,
pub(crate) previous_root: RwLock<Option<PreviousRoot>>,
pub(crate) audit_records: RwLock<VecDeque<AuditRecord>>,
dropped: watch::Sender<()>,
}
impl AuthStateInner {
pub(crate) fn new(
admin_key: AesKeyType,
admin_lease: &Arc<AuthLease>,
sync_process_credential: bool,
instance_id: [u8; INSTANCE_ID_LEN],
safe_mode: bool,
restored: RestoredState,
) -> Self {
let RestoredState {
slots,
cold,
high_slot_generations,
high_slot_entries,
legacy_protocol,
audit_records,
root_epoch,
namespace_high_water,
} = restored;
Self {
admin: RwLock::new(AdminState {
key: admin_key,
lease: Arc::downgrade(admin_lease),
}),
sync_process_credential,
temporary_root: RwLock::new(temporary_root(&admin_key, &instance_id)),
instance_id: RwLock::new(instance_id),
slots: RwLock::new(slots),
high_slot_generations,
high_slot_entries: RwLock::new(high_slot_entries),
cold: RwLock::new(cold),
safe_mode: AtomicBool::new(safe_mode),
snapshot_stale: AtomicBool::new(true),
legacy_protocol_allowed: AtomicBool::new(legacy_protocol.is_allowed()),
active_legacy_connections: AtomicU64::new(0),
last_legacy_connection_at: AtomicU64::new(0),
auth_successes: AtomicU64::new(0),
auth_failures: AtomicU64::new(0),
root_epoch: AtomicU64::new(root_epoch),
namespace_high_water: AtomicU64::new(namespace_high_water),
previous_root: RwLock::new(None),
audit_records: RwLock::new(audit_records),
dropped: watch::Sender::new(()),
}
}
pub(crate) fn mark_snapshot_stale(&self) {
self.snapshot_stale.store(true, Ordering::Release);
}
pub(crate) fn subscribe_dropped(&self) -> watch::Receiver<()> {
self.dropped.subscribe()
}
pub(crate) fn high(&self) -> parking_lot::RwLockReadGuard<'_, Vec<PersistedEntry>> {
self.high_slot_entries.read()
}
pub(crate) fn high_mut(&self) -> parking_lot::RwLockWriteGuard<'_, Vec<PersistedEntry>> {
self.high_slot_entries.write()
}
pub(crate) fn slots(&self) -> parking_lot::RwLockReadGuard<'_, Box<[SlotHot]>> {
self.slots.read()
}
pub(crate) fn slots_mut(&self) -> parking_lot::RwLockWriteGuard<'_, Box<[SlotHot]>> {
self.slots.write()
}
pub(crate) fn cold(&self) -> parking_lot::RwLockReadGuard<'_, HashMap<KeyId, ColdMetadata>> {
self.cold.read()
}
pub(crate) fn cold_mut(
&self,
) -> parking_lot::RwLockWriteGuard<'_, HashMap<KeyId, ColdMetadata>> {
self.cold.write()
}
pub(crate) fn admin_key(&self) -> AesKeyType {
self.admin.read().key
}
pub(crate) fn instance_id(&self) -> [u8; INSTANCE_ID_LEN] {
*self.instance_id.read()
}
pub(crate) fn derive_temporary_key(&self, key_id: KeyId) -> Result<AesKeyType, AuthFailure> {
expand_temporary_key(&self.temporary_root.read(), key_id)
}
pub(crate) fn legacy_policy(&self) -> LegacyProtocolPolicy {
if self.legacy_protocol_allowed.load(Ordering::Acquire) {
LegacyProtocolPolicy::Allow
} else {
LegacyProtocolPolicy::Deny
}
}
}
pub(crate) struct ColdMetadata {
pub(crate) issued_at: u64,
pub(crate) label: Option<String>,
pub(crate) namespace: Option<u64>,
pub(crate) tombstoned_at: u64,
}
pub(crate) type LiveLeases = Vec<(KeyId, Arc<AuthLease>)>;
pub(crate) struct RestoredState {
pub(crate) slots: Box<[SlotHot]>,
pub(crate) cold: HashMap<KeyId, ColdMetadata>,
pub(crate) high_slot_generations: Box<[Generation]>,
pub(crate) high_slot_entries: Vec<PersistedEntry>,
pub(crate) legacy_protocol: LegacyProtocolPolicy,
pub(crate) audit_records: VecDeque<AuditRecord>,
pub(crate) root_epoch: u64,
pub(crate) namespace_high_water: u64,
}
impl RestoredState {
pub(crate) fn from_snapshot(
state: Option<&PersistedSnapshot>,
safe_mode: bool,
config: &AuthConfig,
now: u64,
) -> (Self, LiveLeases) {
let capacity = config.max_temporary_keys;
let (slots, cold, live) = restore_slots(state, capacity, now);
let (high_slot_generations, high_slot_entries) = restore_high_slots(state, capacity, now);
let legacy_protocol = if safe_mode {
LegacyProtocolPolicy::Deny
} else {
state
.map(|state| state.legacy_protocol)
.unwrap_or(config.legacy_protocol)
};
let mut audit_records: VecDeque<AuditRecord> = state
.map(|state| state.audit_records.iter().cloned().collect())
.unwrap_or_default();
while audit_records.len() > AUDIT_RECORD_CAPACITY {
audit_records.pop_front();
}
let restored = Self {
slots,
cold,
high_slot_generations,
high_slot_entries,
legacy_protocol,
audit_records,
root_epoch: state.map(|state| state.root_epoch).unwrap_or(0),
namespace_high_water: state.map_or(0, |state| state.namespace_high_water),
};
(restored, live)
}
}
fn restore_slots(
state: Option<&PersistedSnapshot>,
capacity: usize,
now: u64,
) -> (Box<[SlotHot]>, HashMap<KeyId, ColdMetadata>, LiveLeases) {
let mut slots = (0..capacity)
.map(|_| SlotHot::default())
.collect::<Vec<_>>()
.into_boxed_slice();
let mut cold = HashMap::new();
let mut built = Vec::new();
if let Some(state) = state {
for (index, generation) in state.generations.iter().copied().enumerate() {
if let Some(slot) = slots.get_mut(index) {
slot.generation = generation;
}
}
for entry in &state.entries {
let index = entry.key_id.slot().as_index();
let Some(slot) = slots.get_mut(index) else {
continue;
};
if slot.generation != entry.key_id.generation() {
continue;
}
let state = if entry.state == SlotState::Active && entry.expires_at <= now {
SlotState::Expired
} else {
entry.state
};
slot.state = state;
slot.expires_at = entry.expires_at;
cold.insert(
entry.key_id,
ColdMetadata {
issued_at: entry.issued_at,
label: entry.label.clone(),
namespace: entry.namespace,
tombstoned_at: match state {
SlotState::Expired => entry.tombstoned_at.unwrap_or(entry.expires_at),
SlotState::Revoked => entry.tombstoned_at.unwrap_or(now),
SlotState::Free | SlotState::Active => 0,
},
},
);
if state == SlotState::Active {
let lease = Arc::new(AuthLease::new(
entry.key_id,
entry.namespace,
entry.expires_at,
));
slot.lease = Arc::downgrade(&lease);
built.push(lease);
}
}
}
let live = slots
.iter()
.enumerate()
.filter(|(_, slot)| slot.state == SlotState::Active)
.filter_map(|(index, slot)| {
let key_id = KeyId::new(slot.generation, SlotIndex::from_index(index));
slot.lease.upgrade().map(|lease| (key_id, lease))
})
.collect();
drop(built);
(slots, cold, live)
}
fn restore_high_slots(
state: Option<&PersistedSnapshot>,
capacity: usize,
now: u64,
) -> (Box<[Generation]>, Vec<PersistedEntry>) {
let (high_slot_generations, mut high_slot_entries) = state
.map(|state| split_high_slot_state(state, capacity))
.unwrap_or_default();
for entry in &mut high_slot_entries {
if entry.state == SlotState::Active && entry.expires_at <= now {
entry.state = SlotState::Expired;
entry.tombstoned_at = Some(entry.tombstoned_at.unwrap_or(entry.expires_at));
}
}
(high_slot_generations.into_boxed_slice(), high_slot_entries)
}