Skip to main content

phoenix_security/
session_backend.rs

1use std::{
2    collections::HashMap,
3    sync::{Arc, Mutex},
4};
5
6use phoenix_http::BoxFuture;
7use serde_json::Value;
8
9/// Versioned server-side session state returned by a shared backend.
10#[derive(Clone, PartialEq)]
11pub struct SessionSnapshot {
12    pub values: HashMap<String, Value>,
13    pub version: u64,
14    pub expires_at: u64,
15}
16
17impl std::fmt::Debug for SessionSnapshot {
18    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        formatter
20            .debug_struct("SessionSnapshot")
21            .field("values", &"[REDACTED]")
22            .field("version", &self.version)
23            .field("expires_at", &self.expires_at)
24            .finish()
25    }
26}
27
28/// Result of an atomic session mutation.
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30pub enum SessionWrite {
31    Saved { version: u64 },
32    Conflict,
33    Missing,
34    Collision,
35}
36
37/// Sanitized backend error. The detail is available to operators, not HTTP clients.
38#[derive(Clone, Debug, Eq, PartialEq)]
39pub struct SessionBackendError(pub String);
40
41impl std::fmt::Display for SessionBackendError {
42    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        formatter.write_str("session backend failed")
44    }
45}
46
47impl std::error::Error for SessionBackendError {}
48
49/// Distributed session contract.
50///
51/// Implementations must make each mutation atomic and enforce the supplied version.
52pub trait SessionBackend: Send + Sync + 'static {
53    fn load(
54        &self,
55        id: String,
56        now: u64,
57        refresh_expires_at: u64,
58    ) -> BoxFuture<Result<Option<SessionSnapshot>, SessionBackendError>>;
59
60    fn create(
61        &self,
62        id: String,
63        values: HashMap<String, Value>,
64        expires_at: u64,
65    ) -> BoxFuture<Result<SessionWrite, SessionBackendError>>;
66
67    fn save(
68        &self,
69        id: String,
70        expected_version: u64,
71        values: HashMap<String, Value>,
72        expires_at: u64,
73    ) -> BoxFuture<Result<SessionWrite, SessionBackendError>>;
74
75    fn rotate(
76        &self,
77        old_id: String,
78        new_id: String,
79        expected_version: u64,
80        values: HashMap<String, Value>,
81        expires_at: u64,
82    ) -> BoxFuture<Result<SessionWrite, SessionBackendError>>;
83
84    fn delete(
85        &self,
86        id: String,
87        expected_version: u64,
88    ) -> BoxFuture<Result<SessionWrite, SessionBackendError>>;
89}
90
91/// Shared in-memory reference backend used by local applications and contract tests.
92#[derive(Clone, Default)]
93pub struct MemorySessionBackend {
94    records: Arc<Mutex<HashMap<String, SessionSnapshot>>>,
95}
96
97impl std::fmt::Debug for MemorySessionBackend {
98    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        formatter
100            .debug_struct("MemorySessionBackend")
101            .finish_non_exhaustive()
102    }
103}
104
105impl MemorySessionBackend {
106    #[must_use]
107    pub fn new() -> Self {
108        Self::default()
109    }
110}
111
112impl SessionBackend for MemorySessionBackend {
113    fn load(
114        &self,
115        id: String,
116        now: u64,
117        refresh_expires_at: u64,
118    ) -> BoxFuture<Result<Option<SessionSnapshot>, SessionBackendError>> {
119        let records = Arc::clone(&self.records);
120        Box::pin(async move {
121            let mut records = lock(&records);
122            records.retain(|_, record| record.expires_at > now);
123            Ok(records.get_mut(&id).map(|record| {
124                record.expires_at = record.expires_at.max(refresh_expires_at);
125                record.clone()
126            }))
127        })
128    }
129
130    fn create(
131        &self,
132        id: String,
133        values: HashMap<String, Value>,
134        expires_at: u64,
135    ) -> BoxFuture<Result<SessionWrite, SessionBackendError>> {
136        let records = Arc::clone(&self.records);
137        Box::pin(async move {
138            let mut records = lock(&records);
139            if records.contains_key(&id) {
140                return Ok(SessionWrite::Collision);
141            }
142            records.insert(
143                id,
144                SessionSnapshot {
145                    values,
146                    version: 1,
147                    expires_at,
148                },
149            );
150            Ok(SessionWrite::Saved { version: 1 })
151        })
152    }
153
154    fn save(
155        &self,
156        id: String,
157        expected_version: u64,
158        values: HashMap<String, Value>,
159        expires_at: u64,
160    ) -> BoxFuture<Result<SessionWrite, SessionBackendError>> {
161        let records = Arc::clone(&self.records);
162        Box::pin(async move {
163            let mut records = lock(&records);
164            let Some(record) = records.get_mut(&id) else {
165                return Ok(SessionWrite::Missing);
166            };
167            if record.version != expected_version {
168                return Ok(SessionWrite::Conflict);
169            }
170            record.version = record.version.saturating_add(1);
171            record.values = values;
172            record.expires_at = expires_at;
173            Ok(SessionWrite::Saved {
174                version: record.version,
175            })
176        })
177    }
178
179    fn rotate(
180        &self,
181        old_id: String,
182        new_id: String,
183        expected_version: u64,
184        values: HashMap<String, Value>,
185        expires_at: u64,
186    ) -> BoxFuture<Result<SessionWrite, SessionBackendError>> {
187        let records = Arc::clone(&self.records);
188        Box::pin(async move {
189            let mut records = lock(&records);
190            if records.contains_key(&new_id) {
191                return Ok(SessionWrite::Collision);
192            }
193            let Some(old) = records.get(&old_id) else {
194                return Ok(SessionWrite::Missing);
195            };
196            if old.version != expected_version {
197                return Ok(SessionWrite::Conflict);
198            }
199            let version = old.version.saturating_add(1);
200            records.remove(&old_id);
201            records.insert(
202                new_id,
203                SessionSnapshot {
204                    values,
205                    version,
206                    expires_at,
207                },
208            );
209            Ok(SessionWrite::Saved { version })
210        })
211    }
212
213    fn delete(
214        &self,
215        id: String,
216        expected_version: u64,
217    ) -> BoxFuture<Result<SessionWrite, SessionBackendError>> {
218        let records = Arc::clone(&self.records);
219        Box::pin(async move {
220            let mut records = lock(&records);
221            let Some(record) = records.get(&id) else {
222                return Ok(SessionWrite::Missing);
223            };
224            if record.version != expected_version {
225                return Ok(SessionWrite::Conflict);
226            }
227            records.remove(&id);
228            Ok(SessionWrite::Saved {
229                version: expected_version.saturating_add(1),
230            })
231        })
232    }
233}
234
235fn lock(
236    records: &Mutex<HashMap<String, SessionSnapshot>>,
237) -> std::sync::MutexGuard<'_, HashMap<String, SessionSnapshot>> {
238    records
239        .lock()
240        .unwrap_or_else(std::sync::PoisonError::into_inner)
241}
242
243#[cfg(test)]
244mod tests {
245    use serde_json::json;
246
247    use super::*;
248
249    #[tokio::test]
250    async fn two_handles_observe_cas_conflicts_rotation_delete_and_ttl() {
251        let first = MemorySessionBackend::new();
252        let second = first.clone();
253        assert_eq!(
254            first
255                .create(
256                    "old".to_owned(),
257                    HashMap::from([("n".to_owned(), json!(1))]),
258                    200
259                )
260                .await
261                .unwrap(),
262            SessionWrite::Saved { version: 1 }
263        );
264        assert_eq!(
265            second
266                .create("old".to_owned(), HashMap::new(), 200)
267                .await
268                .unwrap(),
269            SessionWrite::Collision
270        );
271        let left = first
272            .load("old".to_owned(), 100, 250)
273            .await
274            .unwrap()
275            .unwrap();
276        let right = second
277            .load("old".to_owned(), 100, 250)
278            .await
279            .unwrap()
280            .unwrap();
281        assert_eq!(
282            first
283                .save("old".to_owned(), left.version, HashMap::new(), 300)
284                .await
285                .unwrap(),
286            SessionWrite::Saved { version: 2 }
287        );
288        assert_eq!(
289            second
290                .save("old".to_owned(), right.version, HashMap::new(), 300)
291                .await
292                .unwrap(),
293            SessionWrite::Conflict
294        );
295        assert_eq!(
296            second
297                .rotate("old".to_owned(), "new".to_owned(), 2, HashMap::new(), 400)
298                .await
299                .unwrap(),
300            SessionWrite::Saved { version: 3 }
301        );
302        assert!(
303            first
304                .load("old".to_owned(), 150, 400)
305                .await
306                .unwrap()
307                .is_none()
308        );
309        assert_eq!(
310            first.delete("new".to_owned(), 3).await.unwrap(),
311            SessionWrite::Saved { version: 4 }
312        );
313        assert_eq!(
314            second.delete("new".to_owned(), 3).await.unwrap(),
315            SessionWrite::Missing
316        );
317        first
318            .create("expired".to_owned(), HashMap::new(), 10)
319            .await
320            .unwrap();
321        assert!(
322            second
323                .load("expired".to_owned(), 11, 20)
324                .await
325                .unwrap()
326                .is_none()
327        );
328    }
329}