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
use Bytes;
use ;
use ;
use ;
use HashSet;
use ;
use mem;
use crateUriEncoding;
use crate::;
/// An error occurred while writing a Set-Cookie header to a response.
///
;
/// Parse and manage the specified request and response cookies.
///
/// A bidirectional middleware that parses the cookie header of an incoming
/// request and extends the request's cookie jar with the extracted cookies,
/// then calls `next` to obtain a response and serializes any modified cookies
/// into `Set-Cookie` headers.
///
/// # Example
///
/// ```no_run
/// use cookie::{Cookie, SameSite};
/// use std::process::ExitCode;
/// use std::time::Duration;
/// use via::{Error, Next, Request, Response, ResultExt, Server, cookies};
///
/// async fn greet(request: Request, _: Next) -> via::Result {
/// // `should_set_name` indicates whether "name" was sourced from the
/// // request URI. When false, the "name" cookie should not be modified.
/// //
/// // `name` is a Cow that contains either the percent-decoded value of
/// // the "name" cookie or the percent-decoded value of the "name"
/// // parameter in the request URI.
/// let (should_set_name, name) = match request.cookies().get("name") {
/// Some(cookie) => (false, cookie.value().into()),
/// None => (true, request.param("name").percent_decode().or_bad_request()?),
/// };
///
/// // Build the greeting response using a reference to name.
/// let mut response = Response::build().text(format!("Hello, {}!", name.as_ref()))?;
///
/// // If "name" came from the request uri, set the "name" cookie.
/// if should_set_name {
/// response.cookies_mut().add(
/// Cookie::build(("name", name.into_owned()))
/// .http_only(true)
/// .max_age(Duration::from_hours(1).try_into()?)
/// .path("/")
/// .same_site(SameSite::Strict)
/// .secure(true),
/// );
/// }
///
/// Ok(response)
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<ExitCode, Error> {
/// let mut app = via::app(());
///
/// // Provide cookie support for downstream middleware.
/// app.middleware(via::cookies(["name"]).decode());
///
/// // Respond with a greeting when a user visits /hello/:name.
/// app.route("/hello/:name").to(via::get(greet));
///
/// // Start serving our application from http://localhost:8080/.
/// Server::new(app).listen(("127.0.0.1", 8080)).await
/// }
/// ```
///
/// # Errors
///
/// The Cookies middleware responds with a `500` error if any of the following
/// conditions are met:
///
/// - A Set-Cookie header cannot be constructed
/// - The maximum capacity of the response header map is exceeded
///
/// # Security
///
/// In production, we recommend using either a
/// [`SignedJar`](https://docs.rs/cookie/latest/cookie/struct.SignedJar.html)
/// or
/// [`PrivateJar`](https://docs.rs/cookie/latest/cookie/struct.PrivateJar.html)
/// to store security sensitive cookies.
///
/// A _signed jar_ signs all cookies added to it and verifies cookies retrieved
/// from it, preventing clients from tampering with or fabricating cookie data.
/// A _private jar_ both signs and encrypts cookies, providing all the
/// guarantees of a signed jar while also ensuring confidentiality.
///
/// ## Best Practices
///
/// As a best practice, in order to mitigate the vast majority of security
/// related concerns of shared state with a client via cookies–we recommend
/// setting `HttpOnly`, `Max-Age`, `SameSite=Strict`, and `Secure` for every
/// cookie used by your application.
///
/// - `HttpOnly`<br>
/// Prevents client-side scripts from accessing the cookie, mitigating cross-
/// site scripting (XSS) attacks. This should be enabled for any cookie that
/// does not need to be accessed directly from JavaScript. Requests made from
/// JavaScript using the Fetch API with `credentials: "include"` or
/// `"same-origin"` automatically include all relevant cookies for the
/// request's origin, including those marked as `HttpOnly`.
///
/// - `Max-Age`<br>
/// Limits how long the browser will store and send the cookie. This reduces
/// the window in which a leaked or stolen cookie can be used, and helps
/// prevent session accumulation on the client.
///
/// - `SameSite=Strict`<br>
/// Restricts cookies to same-site requests, mitigating CSRF attacks. If the
/// cookie does not need to be shared cross-site, this setting practically
/// eliminates CSRF risk in modern browsers. However, it prevents
/// authentication flows that involve redirects from external identity
/// providers (OAuth, SAML, etc.).
///
/// - `Secure`<br>
/// Instructs the client to only include the cookie in requests made using
/// the `https:` scheme or to `localhost`.
///
/// ```no_run
/// use cookie::{Cookie, SameSite};
/// use http::StatusCode;
/// use serde::Deserialize;
/// use std::process::ExitCode;
/// use std::time::Duration;
/// use via::{Error, Next, Payload, Request, Response, Server, cookies};
///
/// #[derive(Deserialize)]
/// struct Login {
/// username: String,
/// password: String,
/// }
///
/// async fn login(request: Request, _: Next) -> via::Result {
/// let (body, app) = request.into_future();
/// let params = body.await?.json::<Login>()?;
///
/// // Insert username and password verification here...
/// // For now, we'll just assert that the password is not empty.
/// if params.password.is_empty() {
/// via::raise!(401, message = "Invalid username or password.");
/// }
///
/// // Generate a response with no content.
/// //
/// // If we were verifying that a user with the provided username and
/// // password exists in a database table, we'd probably respond with the
/// // matching row as JSON.
/// let mut response = Response::build().status(204).finish()?;
///
/// // Add our session cookie that contains the username of the active user
/// // to our signed cookie jar. The value of the cookie will be signed
/// // and encrypted before it is included as a set-cookie header.
/// response.cookies_mut().add(
/// Cookie::build(("via-session", params.username))
/// .http_only(true)
/// .max_age(Duration::from_hours(1).try_into()?)
/// .path("/")
/// .same_site(SameSite::Strict)
/// .secure(true),
/// );
///
/// Ok(response)
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<ExitCode, Error> {
/// let mut app = via::app(());
///
/// // Unencoded cookie support.
/// app.middleware(via::cookies(["session"]));
///
/// // Add our login route to our application.
/// app.route("/auth/login").to(via::post(login));
///
/// // Start serving our application from http://localhost:8080/.
/// Server::new(app).listen(("127.0.0.1", 8080)).await
/// }
/// ```
///
/// Parse and manage the specified request and response cookies.
///
/// The default behavior of the Cookies middleware is to ignore all cookies
/// unless they are specified by name in the provided allow list.
///
/// This prevents irrelevant cookies from becoming a DoS vector by keeping
/// the length of the request and response cookie jars bounded.
///
/// # Example
///
/// ```
/// # let mut app = via::app(());
/// app.middleware(via::cookies(["session"]));
/// ```
///