Files
zesdex/crates/zesdex-iam/src/infrastructure/persistence/session_repo.rs
T

108 lines
4.1 KiB
Rust
Raw Normal View History

//! Filesystem-backed `SessionRepository` implementation.
//!
//! Each session is stored as `<base_dir>/sessions/<id>/session.json`.
//! Writes use a write-then-rename + fsync pattern for crash safety.
//!
//! # Flow
//!
//! - **`list_sessions`** — enumerate `<base_dir>/sessions/` subdirectories,
//! attempt `load_session` on each (silently skipping failures).
//! - **`load_session`** — validates id (path-traversal check), reads JSON.
//! - **`save_session`** — creates session directory, writes JSON atomically.
//! - **`delete_session`** — validates id, removes the session directory.
//!
//! # Security
//!
//! All methods that accept a user-supplied `id` string reject ids containing
//! `/`, `\\`, or `..` to prevent directory-traversal attacks.
//!
//! # Components
//!
//! - `FileSystemSessionRepository` — stateless singleton implementing `SessionRepository`
use std::path::Path;
use tracing;
use zesdex_utils::write_json_atomic;
use crate::domain::error::RepositoryError;
use crate::domain::repository::SessionRepository;
use crate::domain::session::Session;
/// Validate a session id, rejecting path-traversal patterns.
fn validate_id(id: &str) -> Result<(), RepositoryError> {
if id.contains('/') || id.contains('\\') || id.contains("..") {
return Err(RepositoryError::InvalidId(format!(
"session id '{id}' must not contain path separators"
)));
}
Ok(())
}
/// Concrete filesystem session repository.
#[derive(Debug, Clone, Default)]
pub struct FileSystemSessionRepository;
impl FileSystemSessionRepository {
/// Create a new filesystem session repository.
pub fn new() -> Self {
FileSystemSessionRepository
}
}
impl SessionRepository for FileSystemSessionRepository {
fn list_sessions(&self, base_dir: &Path) -> Result<Vec<Session>, RepositoryError> {
let sessions_dir = base_dir.join("sessions");
let entries = match std::fs::read_dir(&sessions_dir) {
Ok(e) => e,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::warn!(path = %sessions_dir.display(), "sessions directory not found");
return Ok(Vec::new());
}
Err(e) => return Err(RepositoryError::Io(e)),
};
let mut sessions = Vec::new();
for entry in entries.flatten() {
if !entry.path().is_dir() {
continue;
}
let id = entry.file_name().to_string_lossy().to_string();
if let Ok(session) = self.load_session(base_dir, &id) {
sessions.push(session);
}
}
tracing::debug!(count = sessions.len(), "listed sessions");
Ok(sessions)
}
fn load_session(&self, base_dir: &Path, id: &str) -> Result<Session, RepositoryError> {
validate_id(id)?;
let path = base_dir.join("sessions").join(id).join("session.json");
if !path.exists() {
return Err(RepositoryError::NotFound(format!("session not found: {id}")));
}
tracing::debug!(session_id = %id, path = %path.display(), "loading session");
let data = std::fs::read_to_string(&path)?; // → RepositoryError
let session: Session = serde_json::from_str(&data)?; // → RepositoryError
Ok(session)
}
fn save_session(&self, base_dir: &Path, session: &Session) -> Result<(), RepositoryError> {
let dir = session.session_dir(base_dir);
std::fs::create_dir_all(&dir)?; // → RepositoryError
let path = dir.join("session.json");
tracing::debug!(session_id = %session.id, path = %path.display(), "saving session");
write_json_atomic(&path, session, None).map_err(RepositoryError::from_anyhow)?;
Ok(())
}
fn delete_session(&self, base_dir: &Path, id: &str) -> Result<(), RepositoryError> {
validate_id(id)?;
let dir = base_dir.join("sessions").join(id);
tracing::debug!(session_id = %id, path = %dir.display(), "deleting session");
if dir.exists() {
std::fs::remove_dir_all(&dir)?; // → RepositoryError
}
Ok(())
}
}