http_type/cookie/impl.rs
1use super::*;
2
3/// Implements the `std::error::Error` trait for `CookieError`.
4impl Error for CookieError {}
5
6/// Implements the `Display` trait for `CookieError`.
7impl Display for CookieError {
8 /// Formats the `CookieError` variant into a human-readable string.
9 ///
10 /// # Arguments
11 ///
12 /// - `&mut Formatter<'_>` - The formatter used for writing the formatted string.
13 ///
14 /// # Returns
15 ///
16 /// - `fmt::Result` - The formatting result.
17 #[inline(always)]
18 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
19 match self {
20 Self::InvalidName => write!(f, "Invalid cookie name"),
21 Self::InvalidValue => write!(f, "Invalid cookie value"),
22 Self::InvalidAttribute => write!(f, "Invalid cookie attribute"),
23 Self::Unknown => write!(f, "Unknown cookie error"),
24 }
25 }
26}
27
28/// Implementation for `CookieBuilder`.
29impl CookieBuilder {
30 /// Creates a new cookie builder instance.
31 ///
32 /// # Arguments
33 ///
34 /// - `N` - The cookie name, which requires the `AsRef<str>` bound.
35 /// - `V` - The cookie value, which requires the `AsRef<str>` bound.
36 ///
37 /// # Returns
38 ///
39 /// - `CookieBuilder` - A new builder instance.
40 #[inline(always)]
41 pub fn new<N, V>(name: N, value: V) -> Self
42 where
43 N: AsRef<str>,
44 V: AsRef<str>,
45 {
46 Self {
47 name: name.as_ref().to_owned(),
48 value: value.as_ref().to_owned(),
49 expires: None,
50 max_age: None,
51 domain: None,
52 path: None,
53 secure: None,
54 http_only: None,
55 same_site: None,
56 }
57 }
58
59 /// Parses a `Set-Cookie` header string into a `CookieBuilder`.
60 ///
61 /// This method takes a `Set-Cookie` header string and extracts the various
62 /// attributes of a cookie, populating a `CookieBuilder` instance.
63 ///
64 /// A name that is not a token and a value that carries a control byte are
65 /// refused, because RFC 6265 Section 4.1.1 admits neither in a cookie
66 /// pair, and a name that carries a separator would turn the rest of the
67 /// name into an attribute. An attribute whose value carries a control byte
68 /// or a semicolon is skipped rather than kept, for the same reason.
69 ///
70 /// # Arguments
71 ///
72 /// - `C` - The `Set-Cookie` header string to parse, which requires the `AsRef<str>` bound.
73 ///
74 /// # Returns
75 ///
76 /// A `CookieBuilder` instance populated with the parsed cookie attributes.
77 pub fn parse<C>(cookie: C) -> Self
78 where
79 C: AsRef<str>,
80 {
81 let mut cookie_builder: Self = Self::default();
82 let parts: Vec<&str> = cookie.as_ref().split(SEMICOLON).collect();
83 if parts.is_empty() {
84 return cookie_builder;
85 }
86 if let Some(name_value_pair) = parts.first() {
87 let name_value_pair: &str = name_value_pair.trim();
88 if let Some((name, value)) = name_value_pair.split_once(EQUAL) {
89 let name: &str = name.trim();
90 let value: &str = value.trim();
91 if is_cookie_name_valid(name) && !value.bytes().any(is_control_byte) {
92 cookie_builder.set_name(name);
93 cookie_builder.set_value(value);
94 }
95 }
96 }
97 for part in parts.iter().skip(1) {
98 let part: &str = part.trim();
99 if part.is_empty() {
100 continue;
101 }
102 if let Some((key, value)) = part.split_once(EQUAL) {
103 let key_lowercase: String = key.trim().to_lowercase();
104 let value: String = value.trim().to_string();
105 if !is_cookie_attribute_valid(&value) {
106 continue;
107 }
108 match key_lowercase.as_str() {
109 COOKIE_EXPIRES_LOWERCASE => {
110 cookie_builder.set_expires(value);
111 }
112 COOKIE_MAX_AGE_LOWERCASE => {
113 if let Ok(max_age_value) = value.parse::<i64>() {
114 cookie_builder.set_max_age(max_age_value);
115 }
116 }
117 COOKIE_DOMAIN_LOWERCASE => {
118 cookie_builder.set_domain(value);
119 }
120 COOKIE_PATH_LOWERCASE => {
121 cookie_builder.set_path(value);
122 }
123 COOKIE_SAME_SITE_LOWERCASE => {
124 cookie_builder.set_same_site(value);
125 }
126 _ => {}
127 }
128 } else {
129 let attribute_lowercase: String = part.to_lowercase();
130 match attribute_lowercase.as_str() {
131 COOKIE_SECURE_LOWERCASE => {
132 cookie_builder.secure = Some(true);
133 }
134 COOKIE_HTTP_ONLY_LOWERCASE => {
135 cookie_builder.http_only = Some(true);
136 }
137 _ => {}
138 }
139 }
140 }
141 cookie_builder
142 }
143
144 /// Sets the expiration date for the cookie.
145 ///
146 /// # Arguments
147 ///
148 /// - `E` - The expiration date, which requires the `AsRef<str>` bound.
149 ///
150 /// # Returns
151 ///
152 /// The `CookieBuilder` instance for method chaining.
153 #[inline(always)]
154 pub fn set_expires<E>(&mut self, expires: E) -> &mut Self
155 where
156 E: AsRef<str>,
157 {
158 self.expires = Some(expires.as_ref().to_owned());
159 self
160 }
161
162 /// Sets the maximum age for the cookie in seconds.
163 ///
164 /// # Arguments
165 ///
166 /// - `M` - The maximum age in seconds, which requires the `Into<i64>` bound.
167 ///
168 /// # Returns
169 ///
170 /// The `CookieBuilder` instance for method chaining.
171 #[inline(always)]
172 pub fn set_max_age<M>(&mut self, max_age: M) -> &mut Self
173 where
174 M: Into<i64>,
175 {
176 self.max_age = Some(max_age.into());
177 self
178 }
179
180 /// Sets the domain for the cookie.
181 ///
182 /// # Arguments
183 ///
184 /// - `D` - The domain for the cookie, which requires the `AsRef<str>` bound.
185 ///
186 /// # Returns
187 ///
188 /// The `CookieBuilder` instance for method chaining.
189 #[inline(always)]
190 pub fn set_domain<D>(&mut self, domain: D) -> &mut Self
191 where
192 D: AsRef<str>,
193 {
194 self.domain = Some(domain.as_ref().to_owned());
195 self
196 }
197
198 /// Sets the path for the cookie.
199 ///
200 /// # Arguments
201 ///
202 /// - `T` - The path for the cookie, which requires the `AsRef<str>` bound.
203 ///
204 /// # Returns
205 ///
206 /// The `CookieBuilder` instance for method chaining.
207 #[inline(always)]
208 pub fn set_path<T>(&mut self, path: T) -> &mut Self
209 where
210 T: AsRef<str>,
211 {
212 self.path = Some(path.as_ref().to_owned());
213 self
214 }
215
216 /// Sets the `Secure` flag for the cookie.
217 ///
218 /// This flag indicates that the cookie should only be transmitted over secure (HTTPS) connections.
219 ///
220 /// # Returns
221 ///
222 /// The `CookieBuilder` instance for method chaining.
223 #[inline(always)]
224 pub fn secure(&mut self) -> &mut Self {
225 *self.get_mut_secure() = Some(true);
226 self
227 }
228
229 /// Sets the `HttpOnly` flag for the cookie.
230 ///
231 /// This flag prevents client-side JavaScript from accessing the cookie.
232 ///
233 /// # Returns
234 ///
235 /// The `CookieBuilder` instance for method chaining.
236 #[inline(always)]
237 pub fn http_only(&mut self) -> &mut Self {
238 *self.get_mut_http_only() = Some(true);
239 self
240 }
241
242 /// Explicitly disables the `Secure` flag for the cookie.
243 ///
244 /// This method explicitly sets the `Secure` flag to `false`, which may be useful
245 /// for overriding default secure settings or for testing purposes.
246 ///
247 /// # Returns
248 ///
249 /// The `CookieBuilder` instance for method chaining.
250 #[inline(always)]
251 pub fn disable_secure(&mut self) -> &mut Self {
252 *self.get_mut_secure() = Some(false);
253 self
254 }
255
256 /// Explicitly disables the `HttpOnly` flag for the cookie.
257 ///
258 /// This method explicitly sets the `HttpOnly` flag to `false`, which may be useful
259 /// for overriding default HttpOnly settings or for testing purposes.
260 ///
261 /// # Returns
262 ///
263 /// The `CookieBuilder` instance for method chaining.
264 #[inline(always)]
265 pub fn disable_http_only(&mut self) -> &mut Self {
266 *self.get_mut_http_only() = Some(false);
267 self
268 }
269
270 /// Sets the `SameSite` policy for the cookie.
271 ///
272 /// # Arguments
273 ///
274 /// - `T` - The `SameSite` policy, which requires the `AsRef<str>` bound.
275 ///
276 /// # Returns
277 ///
278 /// The `CookieBuilder` instance for method chaining.
279 #[inline(always)]
280 pub fn set_same_site<T>(&mut self, same_site: T) -> &mut Self
281 where
282 T: AsRef<str>,
283 {
284 self.same_site = Some(same_site.as_ref().to_owned());
285 self
286 }
287
288 /// Builds the cookie string according to the `Set-Cookie` header format.
289 ///
290 /// The name, the value and every attribute are checked against the
291 /// grammar of RFC 6265 Section 4.1.1 first, so a value that carries a
292 /// control byte cannot end the header line and turn the rest of the
293 /// cookie into a second header. A cookie that fails the check is not
294 /// emitted at all, which is safer than emitting a truncated one.
295 ///
296 /// # Returns
297 ///
298 /// - `String` - A formatted cookie string ready to be sent in a `Set-Cookie` header.
299 pub fn build(&self) -> String {
300 self.try_build().unwrap_or_default()
301 }
302
303 /// Builds the cookie string, reporting why a cookie may not be built.
304 ///
305 /// The name, the value and every attribute are checked against the
306 /// grammar of RFC 6265 Section 4.1.1. A name that is not a token would
307 /// end early and turn the rest of it into an attribute, a value that
308 /// carries a control byte would end the header line, and an attribute
309 /// that carries a semicolon would start another attribute.
310 ///
311 /// # Returns
312 ///
313 /// - `Result<String, CookieError>` - The formatted cookie string, or the
314 /// reason the cookie cannot be represented.
315 pub fn try_build(&self) -> Result<String, CookieError> {
316 if self.get_name().is_empty() {
317 return Err(CookieError::InvalidName);
318 }
319 if !is_cookie_name_valid(self.get_name()) {
320 return Err(CookieError::InvalidName);
321 }
322 if !is_cookie_value_valid(self.get_value()) {
323 return Err(CookieError::InvalidValue);
324 }
325 if let Some(expires_value) = self.try_get_expires()
326 && !is_cookie_attribute_valid(expires_value)
327 {
328 return Err(CookieError::InvalidAttribute);
329 }
330 if let Some(domain_value) = self.try_get_domain()
331 && !is_cookie_attribute_valid(domain_value)
332 {
333 return Err(CookieError::InvalidAttribute);
334 }
335 if let Some(path_value) = self.try_get_path()
336 && !is_cookie_attribute_valid(path_value)
337 {
338 return Err(CookieError::InvalidAttribute);
339 }
340 if let Some(same_site_value) = self.try_get_same_site()
341 && !is_cookie_attribute_valid(same_site_value)
342 {
343 return Err(CookieError::InvalidAttribute);
344 }
345 let mut cookie_string: String = format!("{}={}", self.get_name(), self.get_value());
346 if let Some(expires_value) = self.try_get_expires() {
347 cookie_string.push_str(COOKIE_EXPIRES_ATTRIBUTE_LOWERCASE);
348 cookie_string.push_str(expires_value);
349 }
350 if let Some(max_age_value) = self.try_get_max_age() {
351 cookie_string.push_str(COOKIE_MAX_AGE_ATTRIBUTE_LOWERCASE);
352 cookie_string.push_str(&max_age_value.to_string());
353 }
354 if let Some(domain_value) = self.try_get_domain() {
355 cookie_string.push_str(COOKIE_DOMAIN_ATTRIBUTE_LOWERCASE);
356 cookie_string.push_str(domain_value);
357 }
358 if let Some(path_value) = self.try_get_path() {
359 cookie_string.push_str(COOKIE_PATH_ATTRIBUTE_LOWERCASE);
360 cookie_string.push_str(path_value);
361 }
362 if let Some(true) = self.try_get_secure() {
363 cookie_string.push_str(COOKIE_SECURE_ATTRIBUTE_LOWERCASE);
364 }
365 if let Some(true) = self.try_get_http_only() {
366 cookie_string.push_str(COOKIE_HTTP_ONLY_ATTRIBUTE_LOWERCASE);
367 }
368 if let Some(same_site_value) = self.try_get_same_site() {
369 cookie_string.push_str(COOKIE_SAME_SITE_ATTRIBUTE_LOWERCASE);
370 cookie_string.push_str(same_site_value);
371 }
372 Ok(cookie_string)
373 }
374}
375
376/// Implementation for `Cookie`.
377impl Cookie {
378 /// Parses a `Cookie` header string into a collection of key-value pairs.
379 ///
380 /// This method takes a `Cookie` header string (typically from a `Cookie` request header)
381 /// and parses it into a map of cookie names to their values.
382 ///
383 /// A pair whose name is not a token and a pair whose value carries a
384 /// control byte are skipped, because RFC 6265 Section 4.1.1 admits
385 /// neither, and a name that carries a separator would let the rest of
386 /// the name be read as part of the value.
387 ///
388 /// # Arguments
389 ///
390 /// - `C` - The `Cookie` header string to parse, which requires the `AsRef<str>` bound.
391 ///
392 /// # Returns
393 ///
394 /// A `Cookies` collection (a hash map) containing all parsed cookie key-value pairs.
395 pub fn parse<C>(cookie: C) -> Cookies
396 where
397 C: AsRef<str>,
398 {
399 let cookie_ref: &str = cookie.as_ref();
400 let mut cookies: Cookies = hash_map_xx_hash3_64();
401 if cookie_ref.trim().is_empty() {
402 return cookies;
403 }
404 let parts: Vec<&str> = cookie_ref.split(SEMICOLON).collect();
405 for part in parts {
406 let part: &str = part.trim();
407 if part.is_empty() {
408 continue;
409 }
410 if let Some((name, value)) = part.split_once(EQUAL) {
411 let name: &str = name.trim();
412 let value: &str = value.trim();
413 if is_cookie_name_valid(name) && !value.bytes().any(is_control_byte) {
414 cookies
415 .entry(name.to_owned())
416 .or_insert_with(|| value.to_owned());
417 }
418 }
419 }
420 cookies
421 }
422}