use crate::error::{Error, Result};
use crate::http::Request;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub mod config_adapter;
pub mod factory;
pub mod manager;
#[cfg(feature = "redis")]
pub mod redis;
pub mod security;
pub mod storage;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionFingerprint {
pub ip: String,
pub user_agent: String,
pub created_at: u64,
}
impl SessionFingerprint {
pub fn from_request(request: &Request) -> Self {
let created_at = unix_timestamp();
let ip = request.client_ip();
let user_agent = request.user_agent().unwrap_or("unknown").to_string();
Self {
ip,
user_agent,
created_at,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum FingerprintMode {
Disabled,
Soft,
Strict,
}
impl Default for FingerprintMode {
fn default() -> Self {
Self::Soft
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum SameSite {
Strict,
Lax,
None,
}
impl Default for SameSite {
fn default() -> Self {
Self::Lax
}
}
impl std::fmt::Display for SameSite {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Strict => write!(f, "Strict"),
Self::Lax => write!(f, "Lax"),
Self::None => write!(f, "None"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionData {
pub data: Value,
pub flash: Value,
pub fingerprint: Option<SessionFingerprint>,
pub created_at: u64,
pub last_accessed: u64,
pub absolute_timeout: u64,
pub privilege_level: u32,
}
impl Default for SessionData {
fn default() -> Self {
Self::new()
}
}
impl SessionData {
pub fn new() -> Self {
let now = unix_timestamp();
Self {
data: Value::Object(serde_json::Map::new()),
flash: Value::Object(serde_json::Map::new()),
fingerprint: None,
created_at: now,
last_accessed: now,
absolute_timeout: now + (24 * 60 * 60), privilege_level: 0,
}
}
pub fn new_with_security(fingerprint: SessionFingerprint, absolute_timeout_secs: u64) -> Self {
let now = unix_timestamp();
Self {
data: Value::Object(serde_json::Map::new()),
flash: Value::Object(serde_json::Map::new()),
fingerprint: Some(fingerprint),
created_at: now,
last_accessed: now,
absolute_timeout: now + absolute_timeout_secs,
privilege_level: 0,
}
}
pub fn touch(&mut self) {
self.last_accessed = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
}
pub fn is_expired(&self, idle_timeout_secs: u64) -> bool {
let now = unix_timestamp();
if now > self.absolute_timeout {
return true;
}
(now - self.last_accessed) > idle_timeout_secs
}
}
pub fn unix_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
pub fn generate_secure_id(length: usize) -> String {
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
thread_rng()
.sample_iter(&Alphanumeric)
.take(length)
.map(char::from)
.collect()
}
#[async_trait]
pub trait SessionStorage: Send + Sync {
async fn get(
&self,
session_id: &str,
current_fingerprint: Option<&SessionFingerprint>,
) -> Result<Option<SessionData>>;
async fn set(&self, session_id: &str, data: &SessionData, ttl: Duration) -> Result<()>;
async fn delete(&self, session_id: &str) -> Result<()>;
async fn exists(&self, session_id: &str) -> Result<bool>;
async fn cleanup_expired(&self) -> Result<usize>;
fn generate_id(&self) -> String {
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
thread_rng()
.sample_iter(&Alphanumeric)
.take(32)
.map(char::from)
.collect()
}
fn backend_name(&self) -> &'static str;
async fn stats(&self) -> Result<StorageStats> {
Ok(StorageStats::default())
}
}
#[derive(Debug, Clone, Default)]
pub struct StorageStats {
pub total_sessions: usize,
pub active_sessions: usize,
pub expired_sessions: usize,
pub backend_metrics: HashMap<String, String>,
}
#[derive(Clone)]
pub struct SessionStore {
storage: Arc<dyn SessionStorage>,
session_timeout: Duration,
}
#[derive(Clone)]
pub struct Session {
id: String,
data: Arc<RwLock<Value>>,
flash: Arc<RwLock<Value>>,
fingerprint: Option<SessionFingerprint>,
created_at: u64,
last_accessed: Arc<Mutex<u64>>,
absolute_timeout: u64,
privilege_level: Arc<Mutex<u32>>,
requires_rotation: Arc<Mutex<bool>>,
destroyed: Arc<Mutex<bool>>,
dirty: Arc<Mutex<bool>>,
}
impl Default for Session {
fn default() -> Self {
let now = unix_timestamp();
Self {
id: String::new(),
data: Arc::new(RwLock::new(Value::Object(Map::new()))),
flash: Arc::new(RwLock::new(Value::Object(Map::new()))),
fingerprint: None,
created_at: now,
last_accessed: Arc::new(Mutex::new(now)),
absolute_timeout: now + (24 * 60 * 60), privilege_level: Arc::new(Mutex::new(0)),
requires_rotation: Arc::new(Mutex::new(false)),
destroyed: Arc::new(Mutex::new(false)),
dirty: Arc::new(Mutex::new(false)),
}
}
}
impl Session {
pub fn new(id: &str) -> Self {
let now = unix_timestamp();
Self {
id: id.to_string(),
data: Arc::new(RwLock::new(Value::Object(Map::new()))),
flash: Arc::new(RwLock::new(Value::Object(Map::new()))),
fingerprint: None,
created_at: now,
last_accessed: Arc::new(Mutex::new(now)),
absolute_timeout: now + (24 * 60 * 60), privilege_level: Arc::new(Mutex::new(0)),
requires_rotation: Arc::new(Mutex::new(false)),
destroyed: Arc::new(Mutex::new(false)),
dirty: Arc::new(Mutex::new(false)),
}
}
pub fn new_secure(
id: String,
fingerprint: SessionFingerprint,
_idle_timeout_secs: u64,
absolute_timeout_secs: u64,
) -> Self {
let now = unix_timestamp();
Self {
id,
data: Arc::new(RwLock::new(Value::Object(Map::new()))),
flash: Arc::new(RwLock::new(Value::Object(Map::new()))),
fingerprint: Some(fingerprint),
created_at: now,
last_accessed: Arc::new(Mutex::new(now)),
absolute_timeout: now + absolute_timeout_secs,
privilege_level: Arc::new(Mutex::new(0)),
requires_rotation: Arc::new(Mutex::new(false)),
destroyed: Arc::new(Mutex::new(false)),
dirty: Arc::new(Mutex::new(false)),
}
}
pub fn from_data(id: &str, session_data: SessionData) -> Self {
Self {
id: id.to_string(),
data: Arc::new(RwLock::new(session_data.data)),
flash: Arc::new(RwLock::new(session_data.flash)),
fingerprint: session_data.fingerprint,
created_at: session_data.created_at,
last_accessed: Arc::new(Mutex::new(session_data.last_accessed)),
absolute_timeout: session_data.absolute_timeout,
privilege_level: Arc::new(Mutex::new(session_data.privilege_level)),
requires_rotation: Arc::new(Mutex::new(false)),
destroyed: Arc::new(Mutex::new(false)),
dirty: Arc::new(Mutex::new(false)),
}
}
pub fn to_data(&self) -> Result<SessionData> {
let data = self
.data
.read()
.map_err(|_| {
Error::Session("Failed to acquire read lock for session data".to_string())
})?
.clone();
let flash = self
.flash
.read()
.map_err(|_| Error::Session("Failed to acquire read lock for flash data".to_string()))?
.clone();
let last_accessed = *self
.last_accessed
.lock()
.map_err(|_| Error::Session("Failed to acquire lock for last_accessed".to_string()))?;
let privilege_level = *self.privilege_level.lock().map_err(|_| {
Error::Session("Failed to acquire lock for privilege_level".to_string())
})?;
Ok(SessionData {
data,
flash,
fingerprint: self.fingerprint.clone(),
created_at: self.created_at,
last_accessed,
absolute_timeout: self.absolute_timeout,
privilege_level,
})
}
pub fn set<T: serde::Serialize>(&self, key: &str, value: T) -> Result<()> {
let value = serde_json::to_value(value)?;
let mut data = self.data.write().map_err(|_| {
Error::Session("Failed to acquire write lock for session data".to_string())
})?;
if let Value::Object(ref mut map) = *data {
map.insert(key.to_string(), value);
}
*self
.dirty
.lock()
.map_err(|_| Error::Session("Failed to acquire lock for dirty flag".to_string()))? =
true;
Ok(())
}
pub fn get<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
let data = self.data.read().ok()?;
if let Value::Object(ref map) = *data {
map.get(key)
.and_then(|v| serde_json::from_value(v.clone()).ok())
} else {
None
}
}
pub fn remove(&self, key: &str) -> Option<Value> {
let mut data = self.data.write().ok()?;
let result = if let Value::Object(ref mut map) = *data {
map.remove(key)
} else {
None
};
if result.is_some() {
if let Ok(mut dirty) = self.dirty.lock() {
*dirty = true;
}
}
result
}
pub fn flash_set<T: serde::Serialize>(&self, key: &str, value: T) -> Result<()> {
let value = serde_json::to_value(value)?;
let mut flash = self.flash.write().map_err(|_| {
Error::Session("Failed to acquire write lock for flash data".to_string())
})?;
if let Value::Object(ref mut map) = *flash {
map.insert(key.to_string(), value);
}
*self
.dirty
.lock()
.map_err(|_| Error::Session("Failed to acquire lock for dirty flag".to_string()))? =
true;
Ok(())
}
pub fn flash_get<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
let mut flash = self.flash.write().ok()?;
if let Value::Object(ref mut map) = *flash {
let removed = map.remove(key);
if removed.is_some() {
if let Ok(mut dirty) = self.dirty.lock() {
*dirty = true;
}
}
removed.and_then(|v| serde_json::from_value(v).ok())
} else {
None
}
}
pub fn flash_get_all(&self) -> HashMap<String, Value> {
let mut flash = match self.flash.write() {
Ok(f) => f,
Err(_) => return HashMap::new(),
};
if let Value::Object(ref mut map) = *flash {
let all_flash: HashMap<String, Value> = map.clone().into_iter().collect();
if !map.is_empty() {
map.clear();
if let Ok(mut dirty) = self.dirty.lock() {
*dirty = true;
}
}
all_flash
} else {
HashMap::new()
}
}
pub fn flash_clear(&self) {
if let Ok(mut flash) = self.flash.write() {
if let Value::Object(ref mut map) = *flash {
if !map.is_empty() {
map.clear();
if let Ok(mut dirty) = self.dirty.lock() {
*dirty = true;
}
}
}
}
}
pub fn flash_remove(&self, key: &str) -> Option<Value> {
let mut flash = self.flash.write().ok()?;
if let Value::Object(ref mut map) = *flash {
let removed = map.remove(key);
if removed.is_some() {
if let Ok(mut dirty) = self.dirty.lock() {
*dirty = true;
}
}
removed
} else {
None
}
}
pub fn flash_peek_all(&self) -> HashMap<String, Value> {
let flash = match self.flash.read() {
Ok(f) => f,
Err(_) => return HashMap::new(),
};
if let Value::Object(ref map) = *flash {
map.clone().into_iter().collect()
} else {
HashMap::new()
}
}
pub fn id(&self) -> &str {
&self.id
}
pub fn is_empty(&self) -> bool {
let data = match self.data.read() {
Ok(d) => d,
Err(_) => return true, };
let flash = match self.flash.read() {
Ok(f) => f,
Err(_) => return true, };
let data_empty = if let Value::Object(ref map) = *data {
map.is_empty()
} else {
true
};
let flash_empty = if let Value::Object(ref map) = *flash {
map.is_empty()
} else {
true
};
data_empty && flash_empty
}
pub fn data_count(&self) -> usize {
let data = match self.data.read() {
Ok(d) => d,
Err(_) => return 0,
};
if let Value::Object(ref map) = *data {
map.len()
} else {
0
}
}
pub fn flash_count(&self) -> usize {
let flash = match self.flash.read() {
Ok(f) => f,
Err(_) => return 0,
};
if let Value::Object(ref map) = *flash {
map.len()
} else {
0
}
}
pub fn clear(&self) {
let data_had_items = if let Ok(mut data) = self.data.write() {
if let Value::Object(ref mut map) = *data {
let had_items = !map.is_empty();
map.clear();
had_items
} else {
false
}
} else {
false
};
let flash_had_items = if let Ok(mut flash) = self.flash.write() {
if let Value::Object(ref mut map) = *flash {
let had_items = !map.is_empty();
map.clear();
had_items
} else {
false
}
} else {
false
};
if data_had_items || flash_had_items {
if let Ok(mut dirty) = self.dirty.lock() {
*dirty = true;
}
}
}
pub fn flush(&self) {
self.clear();
}
pub fn regenerate_id(&mut self) {
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
self.id = thread_rng()
.sample_iter(&Alphanumeric)
.take(32)
.map(char::from)
.collect();
}
pub fn destroy(&self) {
self.clear();
self.mark_for_rotation();
if let Ok(mut destroyed) = self.destroyed.lock() {
*destroyed = true;
}
}
pub fn is_destroyed(&self) -> bool {
self.destroyed.lock().map(|d| *d).unwrap_or(false)
}
pub fn to_value(&self) -> Value {
self.data
.read()
.map(|d| d.clone())
.unwrap_or_else(|_| Value::Object(Map::new()))
}
pub fn is_dirty(&self) -> bool {
self.dirty.lock().map(|d| *d).unwrap_or(false)
}
pub fn mark_clean(&self) {
if let Ok(mut dirty) = self.dirty.lock() {
*dirty = false;
}
}
pub fn is_expired(&self, idle_timeout_secs: u64) -> bool {
let now = unix_timestamp();
let last_accessed = self.last_accessed.lock().map(|l| *l).unwrap_or(0);
if now > self.absolute_timeout {
return true;
}
if now - last_accessed > idle_timeout_secs {
return true;
}
false
}
pub fn touch(&self) {
if let Ok(mut last_accessed) = self.last_accessed.lock() {
*last_accessed = unix_timestamp();
}
}
pub fn fingerprint(&self) -> Option<&SessionFingerprint> {
self.fingerprint.as_ref()
}
pub fn mark_for_rotation(&self) {
if let Ok(mut requires_rotation) = self.requires_rotation.lock() {
*requires_rotation = true;
}
}
pub fn needs_rotation(&self) -> bool {
self.requires_rotation.lock().map(|r| *r).unwrap_or(false)
}
pub fn set_privilege_level(&self, level: u32) {
if let Ok(mut current) = self.privilege_level.lock() {
if level > *current {
self.mark_for_rotation();
}
*current = level;
}
}
pub fn privilege_level(&self) -> u32 {
self.privilege_level.lock().map(|p| *p).unwrap_or(0)
}
pub fn set_user_id(&self, user_id: i64) -> Result<()> {
self.set("uid", user_id)
}
pub fn get_user_id(&self) -> Option<i64> {
self.get("uid")
}
pub fn is_authenticated(&self) -> bool {
self.get_user_id().is_some()
}
}
impl Default for SessionStore {
fn default() -> Self {
Self::new()
}
}
impl SessionStore {
pub fn new() -> Self {
use crate::session::storage::MemorySessionStorage;
Self::with_storage(Arc::new(MemorySessionStorage::new()))
}
pub fn with_storage(storage: Arc<dyn SessionStorage>) -> Self {
Self {
storage,
session_timeout: Duration::from_secs(30 * 60), }
}
pub fn with_timeout(storage: Arc<dyn SessionStorage>, session_timeout: Duration) -> Self {
Self {
storage,
session_timeout,
}
}
pub async fn get_or_create(&self, session_id: &str) -> crate::error::Result<Session> {
match self.storage.get(session_id, None).await? {
Some(session_data) => {
Ok(Session::from_data(session_id, session_data))
}
None => {
let session = Session::new(session_id);
let session_data = session.to_data()?;
self.storage
.set(session_id, &session_data, self.session_timeout)
.await?;
Ok(session)
}
}
}
pub async fn get(&self, session_id: &str) -> crate::error::Result<Option<Session>> {
if let Some(session_data) = self.storage.get(session_id, None).await? {
Ok(Some(Session::from_data(session_id, session_data)))
} else {
Ok(None)
}
}
pub async fn remove_session(&self, session_id: &str) -> crate::error::Result<()> {
self.storage.delete(session_id).await
}
pub async fn cleanup_expired(&self) -> crate::error::Result<usize> {
self.storage.cleanup_expired().await
}
pub async fn stats(&self) -> crate::error::Result<StorageStats> {
self.storage.stats().await
}
pub fn backend_name(&self) -> &'static str {
self.storage.backend_name()
}
pub async fn save_session(&self, session: &Session) -> crate::error::Result<()> {
let session_data = session.to_data()?;
self.storage
.set(session.id(), &session_data, self.session_timeout)
.await
}
pub async fn exists(&self, session_id: &str) -> crate::error::Result<bool> {
self.storage.exists(session_id).await
}
pub async fn destroy_session(&self, session_id: &str) -> crate::error::Result<()> {
self.storage.delete(session_id).await
}
pub async fn regenerate_session_id(
&self,
old_session_id: &str,
) -> crate::error::Result<Option<Session>> {
if let Some(mut session) = self.get(old_session_id).await? {
session.regenerate_id();
let new_session_id = session.id().to_string();
self.save_session(&session).await?;
self.storage.delete(old_session_id).await?;
log::debug!(
"Session ID regenerated: {} -> {}",
old_session_id,
new_session_id
);
Ok(Some(session))
} else {
Ok(None)
}
}
pub async fn clear_session(&self, session_id: &str) -> crate::error::Result<()> {
if let Some(session) = self.get(session_id).await? {
session.clear();
self.save_session(&session).await?;
}
Ok(())
}
}