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
use openssl::{
pkey::PKey,
symm::Cipher
};
use crate::Error;
use rand::Rng;
use std::time::Duration;
use chrono::{DateTime, Utc};
pub use self::signed_cookie_session::SignedCookieSession;
mod signed_cookie_session;
pub use self::encrypted_cookie_session::EncryptedCookieSession;
mod encrypted_cookie_session;
/// Enum to indicate a same site policy in the cookie builder
#[derive(Clone)]
pub enum SameSite {
Strict,
Lax,
None
}
impl SameSite {
fn to_cookie_same_site(&self) -> cookie::SameSite {
match self {
SameSite::Strict => cookie::SameSite::Strict,
SameSite::Lax => cookie::SameSite::Lax,
SameSite::None => cookie::SameSite::None
}
}
}
/// Session builder implementation, cookie based.
#[derive(Clone)]
pub struct CookieSessionBuilder {
cookie_name: String,
path: Option<String>,
domain: Option<String>,
expires: Option<DateTime<Utc>>,
max_age: Option<Duration>,
secure: Option<bool>,
http_only: Option<bool>,
same_site: Option<SameSite>,
force_failure: bool
}
impl CookieSessionBuilder {
/// Creates a new cookie session creator
///
/// By default, the following rules apply to the cookie parameters
///
/// * `path`: No path provided (`None`)
/// * `domain`: No domain provided (`None`)
/// * `expires`: No expiration provided (`None`)
/// * `max_age`: No max age provided (`None`)
/// * `secure`: The secure flag is se to false
/// * `http_only`: The http only flag is set to false
/// * `same_site`: No same site policy is provided
/// * `force_failure`: The force failure flag is set to false
pub fn new() -> Self {
CookieSessionBuilder {
cookie_name: "cataclysm-session".to_string(),
path: None,
domain: None,
expires: None,
max_age: None,
secure: None,
http_only: None,
same_site: None,
force_failure: false
}
}
/// Sets a custom `name` for the cookie.
///
/// By default, `cataclysm-session` is used.
///
/// ```rust,no_run
/// use cataclysm::session::CookieSessionBuilder;
///
/// let cookie_session = CookieSessionBuilder::new()
/// .name("my-app-session");
/// ```
pub fn name<A: Into<String>>(mut self, name: A) -> Self {
self.cookie_name = name.into();
self
}
/// Sets a custom `path` for generated cookies
///
/// ```rust,no_run
/// use cataclysm::session::CookieSessionBuilder;
///
/// let cookie_session = CookieSessionBuilder::new()
/// .path("/applies/only/here");
/// ```
pub fn path<A: Into<String>>(mut self, path: A) -> Self {
self.path = Some(path.into());
self
}
/// Sets a custom `domain` for generated cookies
///
/// ```rust,no_run
/// use cataclysm::session::CookieSessionBuilder;
///
/// let cookie_session = CookieSessionBuilder::new()
/// .domain("example.com");
/// ```
pub fn domain<A: Into<String>>(mut self, domain: A) -> Self {
self.domain = Some(domain.into());
self
}
/// Sets a duration for the cookie (that is, using the `expires` field)
///
/// You should try to avoid this method, and use `max_age` instead.
///
/// ```rust,no_run
/// use cataclysm::session::CookieSessionBuilder;
/// use chrono::{DateTime, Utc, Duration};
///
/// let cookie_session = CookieSessionBuilder::new().expires(Utc::now() + Duration::weeks(52));
/// ```
///
/// Please note that the "expires" field will not update the provided date as time goes by. Use the [max_age](CookieSessionBuilder::max_age) method instead.
pub fn expires(mut self, expires: DateTime<Utc>) -> Self {
self.expires = Some(expires);
self
}
/// Sets a duration for the cookie (that is, using the `max_age` field)
///
/// ```rust,no_run
/// use cataclysm::session::CookieSessionBuilder;
/// use std::time::Duration;
///
/// let cookie_session = CookieSessionBuilder::new().max_age(Duration::from_secs(3_600 * 6));
/// ```
pub fn max_age(mut self, max_age: Duration) -> Self {
self.max_age = Some(max_age);
self
}
/// Sets the `secure` field in the cookie
///
/// ```rust,no_run
/// use cataclysm::session::CookieSessionBuilder;
///
/// let cookie_session = CookieSessionBuilder::new().secure(true);
/// ```
pub fn secure(mut self, secure: bool) -> Self {
self.secure = Some(secure);
self
}
/// Sets the `http_only` field in the cookie
///
/// ```rust,no_run
/// use cataclysm::session::CookieSessionBuilder;
///
/// let cookie_session = CookieSessionBuilder::new().http_only(true);
/// ```
pub fn http_only(mut self, http_only: bool) -> Self {
self.http_only = Some(http_only);
self
}
/// Sets the `same_site` field in the cookie
///
/// ```rust,no_run
/// use cataclysm::session::{CookieSessionBuilder, SameSite};
///
/// let cookie_session = CookieSessionBuilder::new().same_site(SameSite::Lax);
/// ```
pub fn same_site(mut self, same_site: SameSite) -> Self {
self.same_site = Some(same_site);
self
}
/// Forces errors at cookie parsing to return an error response instead of an empty session
///
/// ```rust,no_run
/// use cataclysm::session::{CookieSessionBuilder};
///
/// let cookie_session = CookieSessionBuilder::new().force_failure(true);
/// ```
pub fn force_failure(mut self, force_failure: bool) -> Self {
self.force_failure = force_failure;
self
}
/// Creates a cookie handler with signed cookies
///
/// ```rust,no_run
/// use cataclysm::session::CookieSessionBuilder;
///
/// let signed_cookie_session = CookieSessionBuilder::new()
/// .signed(Some("really secret!".to_string()));
/// // Much better to use `.signed(None)`
/// ```
///
/// If no secret is provided, a random 32 bit key will be used. It is recommended to use the function this way. Signatures are performed using the hmac algorithm, with sha256 as hash function.
pub fn signed(self, secret: Option<String>) -> Result<SignedCookieSession, Error> {
let raw_key = if let Some(secret) = secret {
secret.into_bytes()
} else {
let mut random_key: Vec<u8> = vec![0;32];
let mut rng = rand::rng();
rng.fill_bytes(random_key.as_mut_slice());
random_key
};
let key = PKey::hmac(&raw_key[..])?;
Ok(SignedCookieSession {
raw_key,
key,
cookie_name: self.cookie_name,
path: self.path,
domain: self.domain,
expires: self.expires,
max_age: self.max_age,
secure: self.secure,
http_only: self.http_only,
same_site: self.same_site,
force_failure: self.force_failure
})
}
/// Creates a cookie handler with signed cookies
///
/// ```rust,no_run
/// use cataclysm::session::CookieSessionBuilder;
///
/// let signed_cookie_session = CookieSessionBuilder::new()
/// .encrypted(Some("really secret!".to_string()));
/// // Much better to use `.encrypted(None)`
/// ```
///
/// If no secret is provided, a random 32 bit key will be used. It is recommended to use the function this way. Encryption is performed with AES-256 in CBC mode, with a 32 bit random initialization vector.
pub fn encrypted(self, secret: Option<String>) -> Result<EncryptedCookieSession, Error> {
let key = if let Some(secret) = secret {
secret.into_bytes()
} else {
let mut rng = rand::rng();
let mut random_key: Vec<u8> = vec![0;32];
rng.fill_bytes(random_key.as_mut_slice());
random_key
};
Ok(EncryptedCookieSession {
cipher: Cipher::aes_256_cbc(),
key,
cookie_name: self.cookie_name,
path: self.path,
domain: self.domain,
expires: self.expires,
max_age: self.max_age,
secure: self.secure,
http_only: self.http_only,
same_site: self.same_site,
force_failure: self.force_failure
})
}
}