rocket/request/from_request.rs
1use std::fmt::Debug;
2use std::convert::Infallible;
3use std::net::{IpAddr, SocketAddr};
4
5use crate::{Request, Route};
6use crate::outcome::{self, IntoOutcome, Outcome::*};
7
8use crate::http::uri::{Host, Origin};
9use crate::http::{Status, ContentType, Accept, Method, ProxyProto, CookieJar};
10use crate::listener::Endpoint;
11
12/// Type alias for the `Outcome` of a `FromRequest` conversion.
13pub type Outcome<S, E> = outcome::Outcome<S, (Status, E), Status>;
14
15/// Trait implemented by request guards to derive a value from incoming
16/// requests.
17///
18/// # Request Guards
19///
20/// A request guard is a type that represents an arbitrary validation policy.
21/// The validation policy is implemented through `FromRequest`. In other words,
22/// every type that implements `FromRequest` is a request guard.
23///
24/// Request guards appear as inputs to handlers. An arbitrary number of request
25/// guards can appear as arguments in a route handler. Rocket will automatically
26/// invoke the `FromRequest` implementation for request guards before calling
27/// the handler. Rocket only dispatches requests to a handler when all of its
28/// guards pass.
29///
30/// ## Async Trait
31///
32/// [`FromRequest`] is an _async_ trait. Implementations of `FromRequest` must
33/// be decorated with an attribute of `#[rocket::async_trait]`:
34///
35/// ```rust
36/// use rocket::request::{self, Request, FromRequest};
37/// # struct MyType;
38/// # type MyError = String;
39///
40/// #[rocket::async_trait]
41/// impl<'r> FromRequest<'r> for MyType {
42/// type Error = MyError;
43///
44/// async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
45/// /* .. */
46/// # unimplemented!()
47/// }
48/// }
49/// ```
50///
51/// ## Example
52///
53/// The following dummy handler makes use of three request guards, `A`, `B`, and
54/// `C`. An input type can be identified as a request guard if it is not named
55/// in the route attribute. This is why, for instance, `param` is not a request
56/// guard.
57///
58/// ```rust
59/// # #[macro_use] extern crate rocket;
60/// # use rocket::http::Method;
61/// # type A = Method; type B = Method; type C = Method; type T = ();
62/// #[get("/<param>")]
63/// fn index(param: isize, a: A, b: B, c: C) -> T { /* ... */ }
64/// # fn main() {}
65/// ```
66///
67/// Request guards always fire in left-to-right declaration order. In the
68/// example above, the order is `a` followed by `b` followed by `c`. Errors are
69/// short-circuiting; if one guard errors, the remaining are not attempted.
70///
71/// # Outcomes
72///
73/// The returned [`Outcome`] of a `from_request` call determines how the
74/// incoming request will be processed.
75///
76/// * **Success**(S)
77///
78/// If the `Outcome` is [`Success`], then the `Success` value will be used as
79/// the value for the corresponding parameter. As long as all other guards
80/// succeed, the request will be handled.
81///
82/// * **Error**(Status, E)
83///
84/// If the `Outcome` is [`Error`], the request will fail with the given
85/// status code and error. The designated error [`Catcher`](crate::Catcher)
86/// will be used to respond to the request. Note that users can request types
87/// of `Result<S, E>` and `Option<S>` to catch `Error`s and retrieve the
88/// error value.
89///
90/// * **Forward**(Status)
91///
92/// If the `Outcome` is [`Forward`], the request will be forwarded to the next
93/// matching route until either one succeeds or there are no further matching
94/// routes to attempt. In the latter case, the request will be sent to the
95/// [`Catcher`](crate::Catcher) for the designated `Status`. Note that users
96/// can request an `Option<S>` to catch `Forward`s.
97///
98/// # Provided Implementations
99///
100/// Rocket implements `FromRequest` for several built-in types. Their behavior
101/// is documented here.
102///
103/// * **Method**
104///
105/// Extracts the [`Method`] from the incoming request.
106///
107/// _This implementation always returns successfully._
108///
109/// * **&Origin**
110///
111/// Extracts the [`Origin`] URI from the incoming request.
112///
113/// _This implementation always returns successfully._
114///
115/// * **&Host**
116///
117/// Extracts the [`Host`] from the incoming request, if it exists. See
118/// [`Request::host()`] for details. If it does not exist, the request is
119/// forwarded with a 500 Internal Server Error status.
120///
121/// * **&Route**
122///
123/// Extracts the [`Route`] from the request if one is available. When used
124/// as a request guard in a route handler, this will always succeed. Outside
125/// of a route handler, a route may not be available, and the request is
126/// forwarded with a 500 Internal Server Error status.
127///
128/// For more information on when an `&Route` is available, see
129/// [`Request::route()`].
130///
131/// * **&CookieJar**
132///
133/// Returns a borrow to the [`CookieJar`] in the incoming request. Note that
134/// `CookieJar` implements internal mutability, so a handle to a `CookieJar`
135/// allows you to get _and_ set cookies in the request.
136///
137/// _This implementation always returns successfully._
138///
139/// * **&[`Config`]**
140///
141/// Extracts the application [`Config`].
142///
143/// _This implementation always returns successfully._
144///
145/// * **&ContentType**
146///
147/// Extracts the [`ContentType`] header from the incoming request via
148/// [`Request::content_type()`]. If the request didn't specify a
149/// Content-Type, the request is forwarded with a 500 Internal Server Error
150/// status.
151///
152/// * **&Accept**
153///
154/// Extracts the [`Accept`] header from the incoming request via
155/// [`Request::accept()`]. If the request didn't specify an `Accept`, the
156/// request is forwarded with a 500 Internal Server Error status.
157///
158/// * ***IpAddr**
159///
160/// Extracts the client ip address of the incoming request as an [`IpAddr`]
161/// via [`Request::client_ip()`]. If the client's IP address is not known,
162/// the request is forwarded with a 500 Internal Server Error status.
163///
164/// **Warning:** By default, the address can be chosen by the client via
165/// the `X-Real-IP` header. See [`Config::ip_header`] before using this
166/// guard for access control, rate limiting, or audit attribution.
167///
168/// * **ProxyProto**
169///
170/// Extracts the protocol of the incoming request as a [`ProxyProto`] via
171/// [`Request::proxy_proto()`]. If no such header is present, the request is
172/// forwarded with a 500 Internal Server Error status.
173///
174/// * **SocketAddr**
175///
176/// Extracts the remote address of the incoming request as a [`SocketAddr`]
177/// via [`Request::remote()`]. If the remote address is not known, the
178/// request is forwarded with a 500 Internal Server Error status.
179///
180/// * **Option<T>** _where_ **T: FromRequest**
181///
182/// The type `T` is derived from the incoming request using `T`'s
183/// `FromRequest` implementation. If the derivation is a `Success`, the
184/// derived value is returned in `Some`. Otherwise, a `None` is returned.
185///
186/// _This implementation always returns successfully._
187///
188/// * **Result<T, T::Error>** _where_ **T: FromRequest**
189///
190/// The type `T` is derived from the incoming request using `T`'s
191/// `FromRequest` implementation. If derivation is a `Success`, the value is
192/// returned in `Ok`. If the derivation is an `Error`, the error value is
193/// returned in `Err`. If the derivation is a `Forward`, the request is
194/// forwarded with the same status code as the original forward.
195///
196/// [`Config`]: crate::config::Config
197/// [`Config::ip_header`]: crate::config::Config::ip_header
198///
199/// # Example
200///
201/// Imagine you're running an authenticated API service that requires that some
202/// requests be sent along with a valid API key in a header field. You want to
203/// ensure that the handlers corresponding to these requests don't get called
204/// unless there is an API key in the request and the key is valid. The
205/// following example implements this using an `ApiKey` type and a `FromRequest`
206/// implementation for that type. The `ApiKey` type is then used in the
207/// `sensitive` handler.
208///
209/// ```rust
210/// # #[macro_use] extern crate rocket;
211/// #
212/// use rocket::http::Status;
213/// use rocket::request::{self, Outcome, Request, FromRequest};
214///
215/// struct ApiKey<'r>(&'r str);
216///
217/// #[derive(Debug)]
218/// enum ApiKeyError {
219/// Missing,
220/// Invalid,
221/// }
222///
223/// #[rocket::async_trait]
224/// impl<'r> FromRequest<'r> for ApiKey<'r> {
225/// type Error = ApiKeyError;
226///
227/// async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
228/// /// Returns true if `key` is a valid API key string.
229/// fn is_valid(key: &str) -> bool {
230/// key == "valid_api_key"
231/// }
232///
233/// match req.headers().get_one("x-api-key") {
234/// None => Outcome::Error((Status::BadRequest, ApiKeyError::Missing)),
235/// Some(key) if is_valid(key) => Outcome::Success(ApiKey(key)),
236/// Some(_) => Outcome::Error((Status::BadRequest, ApiKeyError::Invalid)),
237/// }
238/// }
239/// }
240///
241/// #[get("/sensitive")]
242/// fn sensitive(key: ApiKey<'_>) -> &'static str {
243/// "Sensitive data."
244/// }
245/// ```
246///
247/// # Request-Local State
248///
249/// Request guards that perform expensive operations, such as those that query a
250/// database or an external service, should use the [request-local state] cache
251/// to store results if they might be invoked multiple times during the routing
252/// of a single request.
253///
254/// For example, consider a pair of `User` and `Admin` guards and a pair of
255/// routes (`admin_dashboard` and `user_dashboard`):
256///
257/// ```rust
258/// # #[macro_use] extern crate rocket;
259/// # #[cfg(feature = "secrets")] mod wrapper {
260/// # use rocket::outcome::{IntoOutcome, try_outcome};
261/// # use rocket::request::{self, Outcome, FromRequest, Request};
262/// # use rocket::http::Status;
263/// # struct User { id: String, is_admin: bool }
264/// # struct Database;
265/// # impl Database {
266/// # fn get_user(&self, id: String) -> Result<User, ()> {
267/// # Ok(User { id, is_admin: false })
268/// # }
269/// # }
270/// # #[rocket::async_trait]
271/// # impl<'r> FromRequest<'r> for Database {
272/// # type Error = ();
273/// # async fn from_request(request: &'r Request<'_>) -> Outcome<Database, ()> {
274/// # Outcome::Success(Database)
275/// # }
276/// # }
277/// #
278/// # struct Admin { user: User }
279/// #
280/// #[rocket::async_trait]
281/// impl<'r> FromRequest<'r> for User {
282/// type Error = ();
283///
284/// async fn from_request(request: &'r Request<'_>) -> Outcome<User, ()> {
285/// let db = try_outcome!(request.guard::<Database>().await);
286/// request.cookies()
287/// .get_private("user_id")
288/// .and_then(|cookie| cookie.value().parse().ok())
289/// .and_then(|id| db.get_user(id).ok())
290/// .or_forward(Status::Unauthorized)
291/// }
292/// }
293///
294/// #[rocket::async_trait]
295/// impl<'r> FromRequest<'r> for Admin {
296/// type Error = ();
297///
298/// async fn from_request(request: &'r Request<'_>) -> Outcome<Admin, ()> {
299/// // This will unconditionally query the database!
300/// let user = try_outcome!(request.guard::<User>().await);
301/// if user.is_admin {
302/// Outcome::Success(Admin { user })
303/// } else {
304/// Outcome::Forward(Status::Unauthorized)
305/// }
306/// }
307/// }
308///
309/// #[get("/dashboard")]
310/// fn admin_dashboard(admin: Admin) { }
311///
312/// #[get("/dashboard", rank = 2)]
313/// fn user_dashboard(user: User) { }
314/// # } // end of cfg wrapper
315/// ```
316///
317/// When a non-admin user is logged in, the database will be queried twice: once
318/// via the `Admin` guard invoking the `User` guard, and a second time via the
319/// `User` guard directly. For cases like these, request-local state should be
320/// used, as illustrated below:
321///
322/// ```rust
323/// # #[macro_use] extern crate rocket;
324/// # #[cfg(feature = "secrets")] mod wrapper {
325/// # use rocket::outcome::{IntoOutcome, try_outcome};
326/// # use rocket::request::{self, Outcome, FromRequest, Request};
327/// # use rocket::http::Status;
328/// # struct User { id: String, is_admin: bool }
329/// # struct Database;
330/// # impl Database {
331/// # fn get_user(&self, id: String) -> Result<User, ()> {
332/// # Ok(User { id, is_admin: false })
333/// # }
334/// # }
335/// # #[rocket::async_trait]
336/// # impl<'r> FromRequest<'r> for Database {
337/// # type Error = ();
338/// # async fn from_request(request: &'r Request<'_>) -> Outcome<Database, ()> {
339/// # Outcome::Success(Database)
340/// # }
341/// # }
342/// #
343/// # struct Admin<'a> { user: &'a User }
344/// #
345/// #[rocket::async_trait]
346/// impl<'r> FromRequest<'r> for &'r User {
347/// type Error = std::convert::Infallible;
348///
349/// async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
350/// // This closure will execute at most once per request, regardless of
351/// // the number of times the `User` guard is executed.
352/// let user_result = request.local_cache_async(async {
353/// let db = request.guard::<Database>().await.succeeded()?;
354/// request.cookies()
355/// .get_private("user_id")
356/// .and_then(|cookie| cookie.value().parse().ok())
357/// .and_then(|id| db.get_user(id).ok())
358/// }).await;
359///
360/// user_result.as_ref().or_forward(Status::Unauthorized)
361/// }
362/// }
363///
364/// #[rocket::async_trait]
365/// impl<'r> FromRequest<'r> for Admin<'r> {
366/// type Error = std::convert::Infallible;
367///
368/// async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
369/// let user = try_outcome!(request.guard::<&User>().await);
370/// if user.is_admin {
371/// Outcome::Success(Admin { user })
372/// } else {
373/// Outcome::Forward(Status::Unauthorized)
374/// }
375/// }
376/// }
377/// # } // end of cfg wrapper
378/// ```
379///
380/// Notice that these request guards provide access to *borrowed* data (`&'a
381/// User` and `Admin<'a>`) as the data is now owned by the request's cache.
382///
383/// [request-local state]: https://rocket.rs/v0.6-rc/guide/state/#request-local-state
384#[crate::async_trait]
385pub trait FromRequest<'r>: Sized {
386 /// The associated error to be returned if derivation fails.
387 type Error: Debug;
388
389 /// Derives an instance of `Self` from the incoming request metadata.
390 ///
391 /// If the derivation is successful, an outcome of `Success` is returned. If
392 /// the derivation fails in an unrecoverable fashion, `Error` is returned.
393 /// `Forward` is returned to indicate that the request should be forwarded
394 /// to other matching routes, if any.
395 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error>;
396}
397
398#[crate::async_trait]
399impl<'r> FromRequest<'r> for Method {
400 type Error = Infallible;
401
402 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
403 Success(request.method())
404 }
405}
406
407#[crate::async_trait]
408impl<'r> FromRequest<'r> for &'r Origin<'r> {
409 type Error = Infallible;
410
411 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
412 Success(request.uri())
413 }
414}
415
416#[crate::async_trait]
417impl<'r> FromRequest<'r> for &'r Host<'r> {
418 type Error = Infallible;
419
420 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
421 match request.host() {
422 Some(host) => Success(host),
423 None => Forward(Status::InternalServerError)
424 }
425 }
426}
427
428#[crate::async_trait]
429impl<'r> FromRequest<'r> for &'r Route {
430 type Error = Infallible;
431
432 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
433 match request.route() {
434 Some(route) => Success(route),
435 None => Forward(Status::InternalServerError)
436 }
437 }
438}
439
440#[crate::async_trait]
441impl<'r> FromRequest<'r> for &'r CookieJar<'r> {
442 type Error = Infallible;
443
444 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
445 Success(request.cookies())
446 }
447}
448
449#[crate::async_trait]
450impl<'r> FromRequest<'r> for &'r Accept {
451 type Error = Infallible;
452
453 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
454 match request.accept() {
455 Some(accept) => Success(accept),
456 None => Forward(Status::InternalServerError)
457 }
458 }
459}
460
461#[crate::async_trait]
462impl<'r> FromRequest<'r> for &'r ContentType {
463 type Error = Infallible;
464
465 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
466 match request.content_type() {
467 Some(content_type) => Success(content_type),
468 None => Forward(Status::InternalServerError)
469 }
470 }
471}
472
473#[crate::async_trait]
474impl<'r> FromRequest<'r> for IpAddr {
475 type Error = Infallible;
476
477 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
478 match request.client_ip() {
479 Some(addr) => Success(addr),
480 None => Forward(Status::InternalServerError)
481 }
482 }
483}
484
485#[crate::async_trait]
486impl<'r> FromRequest<'r> for ProxyProto<'r> {
487 type Error = std::convert::Infallible;
488
489 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
490 request.proxy_proto().or_forward(Status::InternalServerError)
491 }
492}
493
494#[crate::async_trait]
495impl<'r> FromRequest<'r> for &'r Endpoint {
496 type Error = Infallible;
497
498 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
499 request.remote().or_forward(Status::InternalServerError)
500 }
501}
502
503#[crate::async_trait]
504impl<'r> FromRequest<'r> for SocketAddr {
505 type Error = Infallible;
506
507 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
508 request.remote()
509 .and_then(|r| r.socket_addr())
510 .or_forward(Status::InternalServerError)
511 }
512}
513
514#[crate::async_trait]
515impl<'r, T: FromRequest<'r>> FromRequest<'r> for Result<T, T::Error> {
516 type Error = Infallible;
517
518 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
519 match T::from_request(request).await {
520 Success(val) => Success(Ok(val)),
521 Error((_, e)) => Success(Err(e)),
522 Forward(status) => Forward(status),
523 }
524 }
525}
526
527#[crate::async_trait]
528impl<'r, T: FromRequest<'r>> FromRequest<'r> for Option<T> {
529 type Error = Infallible;
530
531 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
532 match T::from_request(request).await {
533 Success(val) => Success(Some(val)),
534 Error(_) | Forward(_) => Success(None),
535 }
536 }
537}
538
539#[crate::async_trait]
540impl<'r, T: FromRequest<'r>> FromRequest<'r> for Outcome<T, T::Error> {
541 type Error = Infallible;
542
543 async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Infallible> {
544 Success(T::from_request(request).await)
545 }
546}