desirable 1.0.1

A minimal Rust web application framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Cookie-based session management for the desirable web framework.

use crate::Result;
use base64::Engine as _;
use chrono::{DateTime, Utc};
use hmac::{Hmac, Mac};
use hyper::header::HeaderMap;
use hyper::http;
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::collections::HashMap;
use std::sync::Arc;

type HmacSha256 = Hmac<Sha256>;
const DEFAULT_MAX_AGE_SECS: i64 = 30 * 24 * 60 * 60;
const SESSION_ID_LENGTH: usize = 32;
const DEFAULT_COOKIE_NAME: &str = "desirable_session";

#[derive(Debug, thiserror::Error)]
pub enum SessionError {
  #[error("invalid session cookie")]
  InvalidCookie,
  #[error("session signature mismatch")]
  SignatureMismatch,
  #[error("session expired")]
  Expired,
  #[error("session not found")]
  NotFound,
  #[error("key not found in session: {0}")]
  KeyNotFound(String),
  #[error("session serialization error: {0}")]
  Serialization(#[from] serde_json::Error),
}

#[derive(Clone, Debug)]
pub struct SessionConfig {
  pub cookie_name: String,
  pub path: String,
  pub domain: Option<String>,
  pub secure: bool,
  pub http_only: bool,
  pub same_site: cookie::SameSite,
  pub max_age_secs: Option<i64>,
  pub signing_key: Vec<u8>,
}

impl SessionConfig {
  pub fn new(signing_key: &[u8]) -> Self {
    assert!(
      signing_key.len() >= 32,
      "signing key must be at least 32 bytes"
    );
    Self {
      cookie_name: DEFAULT_COOKIE_NAME.to_string(),
      path: "/".to_string(),
      domain: None,
      secure: true,
      http_only: true,
      same_site: cookie::SameSite::Lax,
      max_age_secs: Some(DEFAULT_MAX_AGE_SECS),
      signing_key: signing_key.to_vec(),
    }
  }

  #[must_use]
  pub fn cookie_name(mut self, name: &str) -> Self {
    self.cookie_name = name.to_string();
    self
  }

  #[must_use]
  pub fn path(mut self, path: &str) -> Self {
    self.path = path.to_string();
    self
  }

  #[must_use]
  pub fn domain(mut self, domain: &str) -> Self {
    self.domain = Some(domain.to_string());
    self
  }

  #[must_use]
  pub fn secure(mut self, secure: bool) -> Self {
    self.secure = secure;
    self
  }

  #[must_use]
  pub fn http_only(mut self, http_only: bool) -> Self {
    self.http_only = http_only;
    self
  }

  #[must_use]
  pub fn same_site(mut self, same_site: cookie::SameSite) -> Self {
    self.same_site = same_site;
    self
  }

  #[must_use]
  pub fn max_age_secs(mut self, secs: i64) -> Self {
    self.max_age_secs = Some(secs);
    self
  }
}

impl Default for SessionConfig {
  fn default() -> Self {
    let mut key = [0u8; 32];
    rand::thread_rng().fill_bytes(&mut key);
    Self::new(&key)
  }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SessionData {
  pub id: String,
  pub created: DateTime<Utc>,
  pub accessed: DateTime<Utc>,
  #[serde(flatten)]
  pub data: HashMap<String, String>,
}

impl SessionData {
  pub fn new() -> Self {
    let now = Utc::now();
    let mut bytes = [0u8; SESSION_ID_LENGTH];
    rand::thread_rng().fill_bytes(&mut bytes);
    let id = base64::engine::general_purpose::URL_SAFE.encode(bytes);
    Self {
      id,
      created: now,
      accessed: now,
      data: HashMap::new(),
    }
  }
}

impl Default for SessionData {
  fn default() -> Self {
    Self::new()
  }
}

#[derive(Clone, Debug)]
pub struct Session {
  inner: SessionData,
  modified: bool,
}

impl Session {
  pub fn new(data: SessionData) -> Self {
    Self {
      inner: data,
      modified: false,
    }
  }

  pub fn id(&self) -> &str {
    &self.inner.id
  }
  pub fn created(&self) -> DateTime<Utc> {
    self.inner.created
  }
  pub fn accessed(&self) -> DateTime<Utc> {
    self.inner.accessed
  }
  pub fn len(&self) -> usize {
    self.inner.data.len()
  }
  pub fn is_empty(&self) -> bool {
    self.inner.data.is_empty()
  }
  pub fn data(&self) -> &HashMap<String, String> {
    &self.inner.data
  }
  pub fn contains_key(&self, key: &str) -> bool {
    self.inner.data.contains_key(key)
  }
  pub fn is_modified(&self) -> bool {
    self.modified
  }

  pub fn get<T>(&self, key: &str) -> Result<Option<T>>
  where
    T: for<'de> serde::de::Deserialize<'de>,
  {
    if let Some(value) = self.inner.data.get(key) {
      Ok(Some(serde_json::from_str(value)?))
    } else {
      Ok(None)
    }
  }

  pub fn get_str(&self, key: &str) -> Option<&str> {
    self.inner.data.get(key).map(|s| s.as_str())
  }

  pub fn insert<T>(&mut self, key: &str, value: T) -> Result<()>
  where
    T: Serialize,
  {
    let json = serde_json::to_string(&value)?;
    self.inner.data.insert(key.to_string(), json);
    self.modified = true;
    Ok(())
  }

  pub fn remove<T>(&mut self, key: &str) -> Result<Option<T>>
  where
    T: for<'de> serde::de::Deserialize<'de>,
  {
    if let Some(value) = self.inner.data.remove(key) {
      self.modified = true;
      Ok(Some(serde_json::from_str(&value)?))
    } else {
      Ok(None)
    }
  }

  pub fn remove_str(&mut self, key: &str) -> Option<String> {
    let removed = self.inner.data.remove(key);
    if removed.is_some() {
      self.modified = true;
    }
    removed
  }

  pub fn clear(&mut self) {
    if !self.inner.data.is_empty() {
      self.inner.data.clear();
      self.modified = true;
    }
  }

  pub fn regenerate_id(&mut self) {
    let mut bytes = [0u8; SESSION_ID_LENGTH];
    rand::thread_rng().fill_bytes(&mut bytes);
    self.inner.id = base64::engine::general_purpose::URL_SAFE.encode(bytes);
    self.modified = true;
  }

  pub fn touch(&mut self) {
    self.inner.accessed = Utc::now();
  }
  pub fn into_data(self) -> SessionData {
    self.inner
  }
  pub fn data_mut(&mut self) -> &mut HashMap<String, String> {
    self.modified = true;
    &mut self.inner.data
  }
}

impl Default for Session {
  fn default() -> Self {
    Self::new(SessionData::new())
  }
}

#[derive(Clone, Debug)]
pub struct SessionManager {
  config: Arc<SessionConfig>,
}

impl SessionManager {
  pub fn new(config: SessionConfig) -> Self {
    Self {
      config: Arc::new(config),
    }
  }

  pub fn with_random_key() -> Self {
    Self::new(SessionConfig::default())
  }

  pub fn config(&self) -> &SessionConfig {
    &self.config
  }
  pub fn create_session(&self) -> Session {
    Session::new(SessionData::new())
  }

  pub fn read_session(&self, cookie_value: &str) -> Result<Option<Session>> {
    if cookie_value.is_empty() {
      return Ok(None);
    }
    let decoded = base64::engine::general_purpose::URL_SAFE
      .decode(cookie_value)
      .map_err(|_| SessionError::InvalidCookie)?;
    let pos = decoded.iter().position(|&c| c == b'|');
    if let Some(idx) = pos {
      let (data_bytes, signature_bytes) = decoded.split_at(idx);
      if signature_bytes.is_empty() || signature_bytes[0] != b'|' {
        return Err(SessionError::InvalidCookie.into());
      }
      let sig = &signature_bytes[1..];
      let mut mac = HmacSha256::new_from_slice(&self.config.signing_key)
        .map_err(|_| SessionError::InvalidCookie)?;
      mac.update(data_bytes);
      mac
        .verify_slice(sig)
        .map_err(|_| SessionError::SignatureMismatch)?;
      let session_data: SessionData =
        serde_json::from_slice(data_bytes).map_err(|_| SessionError::InvalidCookie)?;
      Ok(Some(Session::new(session_data)))
    } else {
      Err(SessionError::InvalidCookie.into())
    }
  }

  pub fn write_session(&self, session: &Session) -> String {
    let data_bytes = serde_json::to_vec(&session.inner).unwrap_or_default();
    let mut mac = HmacSha256::new_from_slice(&self.config.signing_key).unwrap();
    mac.update(&data_bytes);
    let signature = mac.finalize().into_bytes();
    let mut combined = data_bytes;
    combined.push(b'|');
    combined.extend_from_slice(&signature);
    base64::engine::general_purpose::URL_SAFE.encode(&combined)
  }

  pub fn make_cookie_header(&self, session: &Session) -> http::HeaderValue {
    let cookie_value = self.write_session(session);
    let mut builder = cookie::CookieBuilder::new(self.config.cookie_name.clone(), cookie_value)
      .path(self.config.path.clone())
      .http_only(self.config.http_only)
      .same_site(self.config.same_site);
    if let Some(max_age) = self.config.max_age_secs {
      builder = builder.max_age(time::Duration::seconds(max_age));
    }
    if self.config.secure {
      builder = builder.secure(true);
    }
    if let Some(ref domain) = self.config.domain {
      builder = builder.domain(domain.clone());
    }
    builder.build().to_string().parse().unwrap()
  }

  pub fn make_deletion_cookie(&self) -> http::HeaderValue {
    let mut builder = cookie::CookieBuilder::new(self.config.cookie_name.clone(), "")
      .path(self.config.path.clone())
      .http_only(self.config.http_only)
      .same_site(self.config.same_site)
      .max_age(time::Duration::seconds(0));
    if self.config.secure {
      builder = builder.secure(true);
    }
    if let Some(ref domain) = self.config.domain {
      builder = builder.domain(domain.clone());
    }
    builder.build().to_string().parse().unwrap()
  }

  pub fn get_cookie_value(&self, headers: &HeaderMap) -> Option<String> {
    headers
      .get(http::header::COOKIE)
      .and_then(|v| v.to_str().ok())
      .and_then(|cookie_str| {
        cookie_str
          .split(';')
          .map(|s| s.trim())
          .find(|s| s.starts_with(&format!("{}=", self.config.cookie_name)))
          .and_then(|s| s.split('=').nth(1).map(|s| s.to_string()))
      })
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_session_new() {
    let session = Session::new(SessionData::new());
    assert!(!session.id().is_empty());
    assert!(session.is_empty());
    assert!(!session.is_modified());
  }

  #[test]
  fn test_session_insert_get() {
    let mut session = Session::new(SessionData::new());
    session.insert("user_id", 42).unwrap();
    session.insert("name", "Alice").unwrap();
    assert_eq!(session.len(), 2);
    assert!(session.is_modified());

    let user_id: Option<i32> = session.get("user_id").unwrap();
    assert_eq!(user_id, Some(42));

    let name: Option<String> = session.get("name").unwrap();
    assert_eq!(name, Some("Alice".to_string()));
  }

  #[test]
  fn test_session_remove() {
    let mut session = Session::new(SessionData::new());
    session.insert("key", "value").unwrap();
    let removed: Option<String> = session.remove("key").unwrap();
    assert_eq!(removed, Some("value".to_string()));
    assert!(session.is_empty());
  }

  #[test]
  fn test_session_manager_roundtrip() {
    let key = b"this-is-a-32-byte-secret-key-!!!";
    let manager = SessionManager::new(SessionConfig::new(key));

    let mut session = manager.create_session();
    session.insert("user_id", 123).unwrap();
    session.insert("name", "Bob").unwrap();

    let cookie_value = manager.write_session(&session);
    assert!(!cookie_value.is_empty());

    let loaded = manager.read_session(&cookie_value).unwrap().unwrap();
    assert_eq!(loaded.id(), session.id());
    let user_id: Option<i32> = loaded.get("user_id").unwrap();
    assert_eq!(user_id, Some(123));
  }

  #[test]
  fn test_session_cookie_header() {
    let key = b"this-is-a-32-byte-secret-key-!!!";
    let config = SessionConfig::new(key).secure(false).http_only(true);
    let manager = SessionManager::new(config);

    let session = manager.create_session();
    let header = manager.make_cookie_header(&session);
    assert!(!header.to_str().unwrap().is_empty());
    assert!(header.to_str().unwrap().contains("HttpOnly"));
  }
}