use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::fmt;
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
#[cfg(unix)]
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Weak};
use std::time::Duration;
use parking_lot::{Mutex, RwLock};
use rand::RngExt;
use ring::aead::{AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey};
use ring::hkdf::{HKDF_SHA256, Prk, Salt};
use serde::{Deserialize, Serialize};
use subtle::ConstantTimeEq;
use tokio::sync::{mpsc, oneshot, watch};
use tokio_util::sync::CancellationToken;
use pb_mapper_core::checksum::{
AesKeyType, Credential, MACHINE_MSG_HEADER_KEY_PATH, encode_temporary_credential,
env_safe_admin_key_error, get_process_credential, is_env_safe_admin_key, parse_credential,
process_credential_configured, set_process_msg_header_key,
};
use pb_mapper_core::time::unix_seconds;
pub const ADMIN_NAMESPACE: u64 = ADMIN_KEY_ID.as_u64();
pub const CAPABILITY_KEY_NAMESPACES: &str = "key_namespaces";
pub const ADMIN_SCHEMA_VERSION: u16 = 1;
pub const DEFAULT_AUTH_STATE_DIR: &str = "/var/lib/pb-mapper/auth";
pub const DEFAULT_TEMP_KEY_CAPACITY: usize = 65_536;
pub const MAX_TEMP_KEY_CAPACITY: usize = 1_048_576;
pub const DEFAULT_MAX_TEMP_KEY_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);
pub const MIN_TEMP_KEY_TTL: Duration = Duration::from_secs(10);
pub const MAX_TEMP_KEY_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60);
const TOMBSTONE_RETENTION: Duration = Duration::from_secs(60);
const MAX_SCHEDULABLE_DELAY: Duration =
Duration::from_secs(MAX_TEMP_KEY_TTL.as_secs() + TOMBSTONE_RETENTION.as_secs());
const SNAPSHOT_COMPACTION_INTERVAL: Duration = Duration::from_secs(5 * 60);
const SNAPSHOT_SCHEMA_VERSION: u16 = 1;
const STATE_BLOB_MAGIC: &[u8; 5] = b"PBAS1";
const STATE_AAD: &[u8] = b"pb-mapper-auth-state-v1";
const INSTANCE_ID_LEN: usize = 16;
const ADMIN_REPLAY_RETENTION: Duration = Duration::from_secs(10 * 60);
const ADMIN_REPLAY_CAPACITY: usize = 65_536;
const AUDIT_RECORD_CAPACITY: usize = 4096;
const _: () = assert!(
MAX_TEMP_KEY_CAPACITY as u64 <= u32::MAX as u64 + 1,
"every slot index has to fit SlotIndex's 32 bits"
);
const _: () = assert!(
DEFAULT_TEMP_KEY_CAPACITY <= MAX_TEMP_KEY_CAPACITY,
"the default capacity has to be one the configuration accepts"
);
const _: () = assert!(
MIN_TEMP_KEY_TTL.as_secs() <= DEFAULT_MAX_TEMP_KEY_TTL.as_secs()
&& DEFAULT_MAX_TEMP_KEY_TTL.as_secs() <= MAX_TEMP_KEY_TTL.as_secs(),
"the default maximum TTL has to be one the configuration accepts"
);
mod actor;
pub mod codes;
mod config;
mod ids;
mod keys;
mod lease;
mod leases;
mod persistence;
mod runtime;
mod state;
#[cfg(test)]
mod tests;
mod timing_wheel;
mod types;
pub use config::{AuthConfigOverrides, default_auth_state_dir};
pub use ids::{ADMIN_KEY_ID, Generation, KeyId, MAX_ALLOCATED_NAMESPACE, SlotIndex};
pub use keys::derive_temporary_key;
pub use lease::{AuthContext, AuthLease};
pub use persistence::{
ADMIN_KEY_FILE, acquire_state_dir_lock, admin_key_path, discard_staged_admin_key,
encrypted_auth_state_exists, generate_admin_key, initialize_admin_key,
stage_admin_key_candidate, staged_admin_key_path, write_admin_key_file,
};
pub use runtime::{AuthRuntime, LegacyConnectionGuard};
pub use types::{
AuthConfig, AuthFailure, AuthStatus, IssuedTemporaryKey, KeyPage, LegacyProtocolPolicy,
TemporaryKeyMetadata,
};
use actor::{Actor, AdminReplays, AuthCommand};
use keys::{
expand_temporary_key, load_isolated_server_admin_credential, load_server_admin_credential,
temporary_root,
};
use leases::Leases;
use persistence::{
AdminReplayRecord, AuditRecord, PersistedEntry, PersistedSnapshot, StateMutation, WalRecord,
append_audit, append_mutation, append_record, atomic_write, audit_action, build_snapshot,
cancel_all_temporary_leases, empty_snapshot, hex, instance_id_path, load_or_create_instance_id,
load_persisted_state, normalize_tombstone_times, persist_recovery_admin_key,
prepare_state_dir_and_lock, push_audit_record, push_persisted_audit, random_instance_id,
read_admin_key, read_namespace_high_water, recover_admin_key_after_rotation,
recover_instance_id_after_reset, reset_already_installed, restore_namespace_high_water,
rotation_already_installed, rotation_key_path, split_high_slot_state, staged_instance_id_path,
validate_admin_key, write_admin_key, write_namespace_high_water,
write_snapshot_and_truncate_wal,
};
use runtime::off_runtime;
use state::{
AdminState, AuthStateInner, ColdMetadata, LiveLeases, PreviousRoot, RestoredState, SlotHot,
SlotState,
};
use timing_wheel::{Timer, TimingWheel};