Skip to main content

yaiko_core/
session.rs

1use crate::{Middleware, Request, Response};
2use async_trait::async_trait;
3use cookie::{Cookie, SameSite};
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use std::sync::{Arc, Mutex};
7use uuid::Uuid;
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct Session {
11    pub id: String,
12    pub data: HashMap<String, serde_json::Value>,
13    pub created_at: chrono::DateTime<chrono::Utc>,
14    pub expires_at: chrono::DateTime<chrono::Utc>,
15}
16
17impl Session {
18    pub fn new(duration: chrono::Duration) -> Self {
19        let now = chrono::Utc::now();
20        Session {
21            id: Uuid::new_v4().to_string(),
22            data: HashMap::new(),
23            created_at: now,
24            expires_at: now + duration,
25        }
26    }
27
28    pub fn get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
29        self.data
30            .get(key)
31            .and_then(|value| serde_json::from_value(value.clone()).ok())
32    }
33
34    pub fn set<T: Serialize>(&mut self, key: &str, value: T) -> Result<(), serde_json::Error> {
35        self.data
36            .insert(key.to_string(), serde_json::to_value(value)?);
37        Ok(())
38    }
39
40    pub fn remove(&mut self, key: &str) -> Option<serde_json::Value> {
41        self.data.remove(key)
42    }
43
44    pub fn clear(&mut self) {
45        self.data.clear();
46    }
47
48    pub fn is_expired(&self) -> bool {
49        chrono::Utc::now() > self.expires_at
50    }
51
52    pub fn renew_id(&mut self) -> String {
53        let previous = self.id.clone();
54        self.id = Uuid::new_v4().to_string();
55        previous
56    }
57
58    pub fn extend(&mut self, duration: chrono::Duration) {
59        self.expires_at = chrono::Utc::now() + duration;
60    }
61}
62
63#[derive(Debug, Clone)]
64pub struct SessionHandle {
65    inner: Arc<Mutex<SessionState>>,
66}
67
68#[derive(Debug, Clone)]
69struct SessionState {
70    session: Session,
71    destroy: bool,
72    previous_ids: Vec<String>,
73}
74
75#[derive(Debug, Clone)]
76struct PersistedSession {
77    session: Session,
78    destroy: bool,
79    previous_ids: Vec<String>,
80}
81
82impl SessionHandle {
83    pub fn new(session: Session) -> Self {
84        Self {
85            inner: Arc::new(Mutex::new(SessionState {
86                session,
87                destroy: false,
88                previous_ids: Vec::new(),
89            })),
90        }
91    }
92
93    pub fn id(&self) -> String {
94        self.inner.lock().unwrap().session.id.clone()
95    }
96
97    pub fn get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
98        self.inner.lock().unwrap().session.get(key)
99    }
100
101    pub fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), serde_json::Error> {
102        self.inner.lock().unwrap().session.set(key, value)
103    }
104
105    pub fn remove(&self, key: &str) -> Option<serde_json::Value> {
106        self.inner.lock().unwrap().session.remove(key)
107    }
108
109    pub fn clear(&self) {
110        self.inner.lock().unwrap().session.clear();
111    }
112
113    pub fn destroy(&self) {
114        let mut state = self.inner.lock().unwrap();
115        state.destroy = true;
116        state.session.clear();
117    }
118
119    pub fn rotate_id(&self) {
120        let mut state = self.inner.lock().unwrap();
121        let previous = state.session.renew_id();
122        state.previous_ids.push(previous);
123    }
124
125    pub fn extend(&self, duration: chrono::Duration) {
126        self.inner.lock().unwrap().session.extend(duration);
127    }
128
129    fn snapshot(&self) -> PersistedSession {
130        let state = self.inner.lock().unwrap();
131        PersistedSession {
132            session: state.session.clone(),
133            destroy: state.destroy,
134            previous_ids: state.previous_ids.clone(),
135        }
136    }
137}
138
139#[async_trait]
140pub trait SessionStore: Send + Sync {
141    async fn get(
142        &self,
143        id: &str,
144    ) -> Result<Option<Session>, Box<dyn std::error::Error + Send + Sync>>;
145    async fn set(&self, session: Session) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
146    async fn delete(&self, id: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
147    async fn cleanup(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
148}
149
150pub struct MemorySessionStore {
151    sessions: Arc<tokio::sync::RwLock<HashMap<String, Session>>>,
152}
153
154impl Default for MemorySessionStore {
155    fn default() -> Self {
156        Self::new()
157    }
158}
159
160impl MemorySessionStore {
161    pub fn new() -> Self {
162        MemorySessionStore {
163            sessions: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
164        }
165    }
166}
167
168#[async_trait]
169impl SessionStore for MemorySessionStore {
170    async fn get(
171        &self,
172        id: &str,
173    ) -> Result<Option<Session>, Box<dyn std::error::Error + Send + Sync>> {
174        let sessions = self.sessions.read().await;
175        Ok(sessions.get(id).cloned())
176    }
177
178    async fn set(&self, session: Session) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
179        let mut sessions = self.sessions.write().await;
180        sessions.insert(session.id.clone(), session);
181        Ok(())
182    }
183
184    async fn delete(&self, id: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
185        let mut sessions = self.sessions.write().await;
186        sessions.remove(id);
187        Ok(())
188    }
189
190    async fn cleanup(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
191        let mut sessions = self.sessions.write().await;
192        let now = chrono::Utc::now();
193        sessions.retain(|_, session| session.expires_at > now);
194        Ok(())
195    }
196}
197
198pub struct SessionMiddleware {
199    store: Arc<dyn SessionStore>,
200    cookie_name: String,
201    session_duration: chrono::Duration,
202    secure_cookies: Option<bool>,
203    same_site: SameSite,
204}
205
206impl SessionMiddleware {
207    pub fn new(store: Arc<dyn SessionStore>) -> Self {
208        let cleanup_store = store.clone();
209        tokio::spawn(async move {
210            let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(300));
211            loop {
212                interval.tick().await;
213                if let Err(error) = cleanup_store.cleanup().await {
214                    tracing::error!("Session cleanup failed: {}", error);
215                }
216            }
217        });
218
219        SessionMiddleware {
220            store,
221            cookie_name: "yaiko_session".to_string(),
222            session_duration: chrono::Duration::hours(24),
223            secure_cookies: None,
224            same_site: SameSite::Lax,
225        }
226    }
227
228    pub fn cookie_name(mut self, name: &str) -> Self {
229        self.cookie_name = name.to_string();
230        self
231    }
232
233    pub fn duration(mut self, duration: chrono::Duration) -> Self {
234        self.session_duration = duration;
235        self
236    }
237
238    pub fn secure(mut self, secure: bool) -> Self {
239        self.secure_cookies = Some(secure);
240        self
241    }
242
243    pub fn same_site(mut self, same_site: SameSite) -> Self {
244        self.same_site = same_site;
245        self
246    }
247
248    fn cookie_is_secure(&self) -> bool {
249        self.secure_cookies
250            .unwrap_or_else(|| std::env::var("APP_ENV").unwrap_or_default() == "production")
251    }
252
253    fn session_cookie(&self, session: &Session) -> Cookie<'static> {
254        Cookie::build(self.cookie_name.clone(), session.id.clone())
255            .http_only(true)
256            .secure(self.cookie_is_secure())
257            .same_site(self.same_site)
258            .path("/")
259            .max_age(cookie::time::Duration::seconds(
260                self.session_duration.num_seconds(),
261            ))
262            .finish()
263    }
264
265    fn expired_cookie(&self) -> Cookie<'static> {
266        Cookie::build(self.cookie_name.clone(), "")
267            .http_only(true)
268            .secure(self.cookie_is_secure())
269            .same_site(self.same_site)
270            .path("/")
271            .max_age(cookie::time::Duration::seconds(0))
272            .finish()
273    }
274}
275
276#[async_trait]
277impl Middleware for SessionMiddleware {
278    async fn handle(
279        &self,
280        mut req: Request,
281        next: Arc<dyn crate::Handler>,
282    ) -> Result<Response, Box<dyn std::error::Error + Send + Sync>> {
283        let incoming_session_id = req.header("cookie").and_then(|cookie_header| {
284            cookie_header.split(';').find_map(|cookie| {
285                Cookie::parse(cookie.trim())
286                    .ok()
287                    .filter(|parsed| parsed.name() == self.cookie_name)
288                    .map(|parsed| parsed.value().to_string())
289            })
290        });
291
292        let loaded_session = if let Some(id) = incoming_session_id.as_deref() {
293            match self.store.get(id).await? {
294                Some(session) if !session.is_expired() => session,
295                _ => Session::new(self.session_duration),
296            }
297        } else {
298            Session::new(self.session_duration)
299        };
300
301        let handle = SessionHandle::new(loaded_session);
302        req.session = Some(handle.clone());
303
304        let mut response = next.handle(req).await?;
305        let persisted = handle.snapshot();
306
307        for previous_id in &persisted.previous_ids {
308            self.store.delete(previous_id).await?;
309        }
310
311        if persisted.destroy {
312            if let Some(original_id) = incoming_session_id.as_deref() {
313                self.store.delete(original_id).await?;
314            }
315            self.store.delete(&persisted.session.id).await?;
316            response = response.set_cookie_raw(&self.expired_cookie().to_string());
317            return Ok(response);
318        }
319
320        self.store.set(persisted.session.clone()).await?;
321        response = response.set_cookie_raw(&self.session_cookie(&persisted.session).to_string());
322        Ok(response)
323    }
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329    use crate::StatusCode;
330    use hyper::Body;
331
332    #[tokio::test]
333    async fn session_mutations_persist_across_requests() {
334        let store = Arc::new(MemorySessionStore::new());
335        let middleware = SessionMiddleware::new(store.clone()).secure(false);
336
337        let login = Arc::new(|req: Request| async move {
338            let session = req.session.as_ref().unwrap();
339            session.set("user_id", "abc123").unwrap();
340            Ok(Response::new().text("ok"))
341        });
342
343        let first_req = Request::from_hyper(
344            hyper::Request::builder()
345                .method("GET")
346                .uri("/login")
347                .body(Body::empty())
348                .unwrap(),
349        )
350        .await
351        .unwrap();
352        let login_response = middleware.handle(first_req, login).await.unwrap();
353        let set_cookie = login_response.headers.get("Set-Cookie").unwrap().clone();
354
355        let me = Arc::new(|req: Request| async move {
356            let user_id = req
357                .session
358                .as_ref()
359                .and_then(|session| session.get::<String>("user_id"))
360                .unwrap_or_default();
361            Ok(Response::new().text(&user_id))
362        });
363
364        let second_req = Request::from_hyper(
365            hyper::Request::builder()
366                .method("GET")
367                .uri("/me")
368                .header("cookie", set_cookie)
369                .body(Body::empty())
370                .unwrap(),
371        )
372        .await
373        .unwrap();
374        let second_response = middleware.handle(second_req, me).await.unwrap();
375        let body = hyper::body::to_bytes(second_response.body).await.unwrap();
376
377        assert_eq!(&body[..], b"abc123");
378    }
379
380    #[tokio::test]
381    async fn destroyed_sessions_clear_cookie_and_store() {
382        let store = Arc::new(MemorySessionStore::new());
383        let middleware = SessionMiddleware::new(store.clone()).secure(false);
384
385        let login = Arc::new(|req: Request| async move {
386            req.session
387                .as_ref()
388                .unwrap()
389                .set("user_id", "abc123")
390                .unwrap();
391            Ok(Response::new().status(StatusCode::OK))
392        });
393        let first_req = Request::from_hyper(
394            hyper::Request::builder()
395                .method("GET")
396                .uri("/login")
397                .body(Body::empty())
398                .unwrap(),
399        )
400        .await
401        .unwrap();
402        let login_response = middleware.handle(first_req, login).await.unwrap();
403        let set_cookie = login_response.headers.get("Set-Cookie").unwrap().clone();
404
405        let logout = Arc::new(|req: Request| async move {
406            req.session.as_ref().unwrap().destroy();
407            Ok(Response::new().status(StatusCode::OK))
408        });
409        let logout_req = Request::from_hyper(
410            hyper::Request::builder()
411                .method("POST")
412                .uri("/logout")
413                .header("cookie", &set_cookie)
414                .body(Body::empty())
415                .unwrap(),
416        )
417        .await
418        .unwrap();
419        let logout_response = middleware.handle(logout_req, logout).await.unwrap();
420
421        let cookie = logout_response.headers.get("Set-Cookie").unwrap();
422        assert!(cookie.contains("Max-Age=0"));
423    }
424}