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