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
use super::*;
/// Implementation for `CookieBuilder`.
impl CookieBuilder {
/// Creates a new cookie builder instance.
///
/// # Arguments
///
/// - `N` - The cookie name, which requires the `AsRef<str>` bound.
/// - `V` - The cookie value, which requires the `AsRef<str>` bound.
///
/// # Returns
///
/// - `CookieBuilder` - A new builder instance.
#[inline(always)]
pub fn new<N, V>(name: N, value: V) -> Self
where
N: AsRef<str>,
V: AsRef<str>,
{
Self {
name: name.as_ref().to_owned(),
value: value.as_ref().to_owned(),
expires: None,
max_age: None,
domain: None,
path: None,
secure: None,
http_only: None,
same_site: None,
}
}
/// Parses a `Set-Cookie` header string into a `CookieBuilder`.
///
/// This method takes a `Set-Cookie` header string and extracts the various
/// attributes of a cookie, populating a `CookieBuilder` instance.
///
/// A name that is not a token and a value that carries a control byte are
/// refused, because RFC 6265 Section 4.1.1 admits neither in a cookie
/// pair, and a name that carries a separator would turn the rest of the
/// name into an attribute. An attribute whose value carries a control byte
/// or a semicolon is skipped rather than kept, for the same reason.
///
/// # Arguments
///
/// - `C` - The `Set-Cookie` header string to parse, which requires the `AsRef<str>` bound.
///
/// # Returns
///
/// A `CookieBuilder` instance populated with the parsed cookie attributes.
pub fn parse<C>(cookie: C) -> Self
where
C: AsRef<str>,
{
let mut cookie_builder: Self = Self::default();
let parts: Vec<&str> = cookie.as_ref().split(SEMICOLON).collect();
if parts.is_empty() {
return cookie_builder;
}
if let Some(name_value_pair) = parts.first() {
let name_value_pair: &str = name_value_pair.trim();
if let Some((name, value)) = name_value_pair.split_once(EQUAL) {
let name: &str = name.trim();
let value: &str = value.trim();
if is_cookie_name_valid(name) && !value.bytes().any(is_control_byte) {
cookie_builder.name = name.to_owned();
cookie_builder.value = value.to_owned();
}
} else if is_cookie_name_valid(name_value_pair) {
cookie_builder.name = name_value_pair.to_owned();
cookie_builder.value = String::new();
}
}
for part in parts.iter().skip(1) {
let part: &str = part.trim();
if part.is_empty() {
continue;
}
if let Some((key, value)) = part.split_once(EQUAL) {
let key_lowercase: String = key.trim().to_lowercase();
let value: String = value.trim().to_string();
if !is_cookie_attribute_valid(&value) {
continue;
}
match key_lowercase.as_str() {
COOKIE_EXPIRES_LOWERCASE => {
cookie_builder.set_expires(value);
}
COOKIE_MAX_AGE_LOWERCASE => {
if let Ok(max_age_value) = value.parse::<i64>() {
cookie_builder.set_max_age(max_age_value);
}
}
COOKIE_DOMAIN_LOWERCASE => {
cookie_builder.set_domain(value);
}
COOKIE_PATH_LOWERCASE => {
cookie_builder.set_path(value);
}
COOKIE_SAME_SITE_LOWERCASE => {
cookie_builder.set_same_site(value);
}
_ => {}
}
} else {
let attribute_lowercase: String = part.to_lowercase();
match attribute_lowercase.as_str() {
COOKIE_SECURE_LOWERCASE => {
cookie_builder.secure = Some(true);
}
COOKIE_HTTP_ONLY_LOWERCASE => {
cookie_builder.http_only = Some(true);
}
_ => {}
}
}
}
cookie_builder
}
/// Sets the expiration date for the cookie.
///
/// # Arguments
///
/// - `E` - The expiration date, which requires the `AsRef<str>` bound.
///
/// # Returns
///
/// The `CookieBuilder` instance for method chaining.
#[inline(always)]
pub fn set_expires<E>(&mut self, expires: E) -> &mut Self
where
E: AsRef<str>,
{
self.expires = Some(expires.as_ref().to_owned());
self
}
/// Sets the maximum age for the cookie in seconds.
///
/// # Arguments
///
/// - `M` - The maximum age in seconds, which requires the `Into<i64>` bound.
///
/// # Returns
///
/// The `CookieBuilder` instance for method chaining.
#[inline(always)]
pub fn set_max_age<M>(&mut self, max_age: M) -> &mut Self
where
M: Into<i64>,
{
self.max_age = Some(max_age.into());
self
}
/// Sets the domain for the cookie.
///
/// # Arguments
///
/// - `D` - The domain for the cookie, which requires the `AsRef<str>` bound.
///
/// # Returns
///
/// The `CookieBuilder` instance for method chaining.
#[inline(always)]
pub fn set_domain<D>(&mut self, domain: D) -> &mut Self
where
D: AsRef<str>,
{
self.domain = Some(domain.as_ref().to_owned());
self
}
/// Sets the path for the cookie.
///
/// # Arguments
///
/// - `T` - The path for the cookie, which requires the `AsRef<str>` bound.
///
/// # Returns
///
/// The `CookieBuilder` instance for method chaining.
#[inline(always)]
pub fn set_path<T>(&mut self, path: T) -> &mut Self
where
T: AsRef<str>,
{
self.path = Some(path.as_ref().to_owned());
self
}
/// Sets the `Secure` flag for the cookie.
///
/// This flag indicates that the cookie should only be transmitted over secure (HTTPS) connections.
///
/// # Returns
///
/// The `CookieBuilder` instance for method chaining.
#[inline(always)]
pub fn secure(&mut self) -> &mut Self {
*self.get_mut_secure() = Some(true);
self
}
/// Sets the `HttpOnly` flag for the cookie.
///
/// This flag prevents client-side JavaScript from accessing the cookie.
///
/// # Returns
///
/// The `CookieBuilder` instance for method chaining.
#[inline(always)]
pub fn http_only(&mut self) -> &mut Self {
*self.get_mut_http_only() = Some(true);
self
}
/// Explicitly disables the `Secure` flag for the cookie.
///
/// This method explicitly sets the `Secure` flag to `false`, which may be useful
/// for overriding default secure settings or for testing purposes.
///
/// # Returns
///
/// The `CookieBuilder` instance for method chaining.
#[inline(always)]
pub fn disable_secure(&mut self) -> &mut Self {
*self.get_mut_secure() = Some(false);
self
}
/// Explicitly disables the `HttpOnly` flag for the cookie.
///
/// This method explicitly sets the `HttpOnly` flag to `false`, which may be useful
/// for overriding default HttpOnly settings or for testing purposes.
///
/// # Returns
///
/// The `CookieBuilder` instance for method chaining.
#[inline(always)]
pub fn disable_http_only(&mut self) -> &mut Self {
*self.get_mut_http_only() = Some(false);
self
}
/// Sets the `SameSite` policy for the cookie.
///
/// # Arguments
///
/// - `T` - The `SameSite` policy, which requires the `AsRef<str>` bound.
///
/// # Returns
///
/// The `CookieBuilder` instance for method chaining.
#[inline(always)]
pub fn set_same_site<T>(&mut self, same_site: T) -> &mut Self
where
T: AsRef<str>,
{
self.same_site = Some(same_site.as_ref().to_owned());
self
}
/// Builds the cookie string according to the `Set-Cookie` header format.
///
/// The name, the value and every attribute are checked against the
/// grammar of RFC 6265 Section 4.1.1 first, so a value that carries a
/// control byte cannot end the header line and turn the rest of the
/// cookie into a second header. A cookie that fails the check is not
/// emitted at all, which is safer than emitting a truncated one.
///
/// # Returns
///
/// - `String` - A formatted cookie string ready to be sent in a `Set-Cookie` header.
pub fn build(&self) -> String {
self.try_build().unwrap_or_default()
}
/// Builds the cookie string, reporting why a cookie may not be built.
///
/// The name, the value and every attribute are checked against the
/// grammar of RFC 6265 Section 4.1.1. A name that is not a token would
/// end early and turn the rest of it into an attribute, a value that
/// carries a control byte would end the header line, and an attribute
/// that carries a semicolon would start another attribute.
///
/// # Returns
///
/// - `Result<String, CookieError>` - The formatted cookie string, or the
/// reason the cookie cannot be represented.
pub fn try_build(&self) -> Result<String, CookieError> {
if self.get_name().is_empty() {
return Err(CookieError::InvalidName);
}
if !is_cookie_name_valid(self.get_name()) {
return Err(CookieError::InvalidName);
}
if !is_cookie_value_valid(self.get_value()) {
return Err(CookieError::InvalidValue);
}
if let Some(expires_value) = self.try_get_expires()
&& !is_cookie_attribute_valid(expires_value)
{
return Err(CookieError::InvalidAttribute);
}
if let Some(domain_value) = self.try_get_domain()
&& !is_cookie_attribute_valid(domain_value)
{
return Err(CookieError::InvalidAttribute);
}
if let Some(path_value) = self.try_get_path()
&& !is_cookie_attribute_valid(path_value)
{
return Err(CookieError::InvalidAttribute);
}
if let Some(same_site_value) = self.try_get_same_site()
&& !is_cookie_attribute_valid(same_site_value)
{
return Err(CookieError::InvalidAttribute);
}
let mut cookie_string: String = format!("{}={}", self.get_name(), self.get_value());
if let Some(expires_value) = self.try_get_expires() {
cookie_string.push_str(COOKIE_EXPIRES_ATTRIBUTE_LOWERCASE);
cookie_string.push_str(expires_value);
}
if let Some(max_age_value) = self.try_get_max_age() {
cookie_string.push_str(COOKIE_MAX_AGE_ATTRIBUTE_LOWERCASE);
cookie_string.push_str(&max_age_value.to_string());
}
if let Some(domain_value) = self.try_get_domain() {
cookie_string.push_str(COOKIE_DOMAIN_ATTRIBUTE_LOWERCASE);
cookie_string.push_str(domain_value);
}
if let Some(path_value) = self.try_get_path() {
cookie_string.push_str(COOKIE_PATH_ATTRIBUTE_LOWERCASE);
cookie_string.push_str(path_value);
}
if let Some(true) = self.try_get_secure() {
cookie_string.push_str(COOKIE_SECURE_ATTRIBUTE_LOWERCASE);
}
if let Some(true) = self.try_get_http_only() {
cookie_string.push_str(COOKIE_HTTP_ONLY_ATTRIBUTE_LOWERCASE);
}
if let Some(same_site_value) = self.try_get_same_site() {
cookie_string.push_str(COOKIE_SAME_SITE_ATTRIBUTE_LOWERCASE);
cookie_string.push_str(same_site_value);
}
Ok(cookie_string)
}
}
/// Implementation for `Cookie`.
impl Cookie {
/// Parses a `Cookie` header string into a collection of key-value pairs.
///
/// This method takes a `Cookie` header string (typically from a `Cookie` request header)
/// and parses it into a map of cookie names to their values.
///
/// A pair whose name is not a token and a pair whose value carries a
/// control byte are skipped, because RFC 6265 Section 4.1.1 admits
/// neither, and a name that carries a separator would let the rest of
/// the name be read as part of the value.
///
/// # Arguments
///
/// - `C` - The `Cookie` header string to parse, which requires the `AsRef<str>` bound.
///
/// # Returns
///
/// A `Cookies` collection (a hash map) containing all parsed cookie key-value pairs.
pub fn parse<C>(cookie: C) -> Cookies
where
C: AsRef<str>,
{
let cookie_ref: &str = cookie.as_ref();
let mut cookies: Cookies = hash_map_xx_hash3_64();
if cookie_ref.trim().is_empty() {
return cookies;
}
let parts: Vec<&str> = cookie_ref.split(SEMICOLON).collect();
for part in parts {
let part: &str = part.trim();
if part.is_empty() {
continue;
}
if let Some((name, value)) = part.split_once(EQUAL) {
let name: &str = name.trim();
let value: &str = value.trim();
if is_cookie_name_valid(name) && !value.bytes().any(is_control_byte) {
cookies.insert(name.to_owned(), value.to_owned());
}
} else if is_cookie_name_valid(part) {
cookies.insert(part.to_owned(), String::new());
}
}
cookies
}
}