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 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
use std::fmt::Debug;
use std::net::{IpAddr, SocketAddr};
use crate::{Request, Route};
use crate::outcome::{self, IntoOutcome};
use crate::outcome::Outcome::*;
use crate::http::{Status, ContentType, Accept, Method, CookieJar};
use crate::http::uri::{Host, Origin};
/// Type alias for the `Outcome` of a `FromRequest` conversion.
pub type Outcome<S, E> = outcome::Outcome<S, (Status, E), Status>;
impl<S, E> IntoOutcome<S, (Status, E), Status> for Result<S, E> {
type Failure = Status;
type Forward = Status;
#[inline]
fn into_outcome(self, status: Status) -> Outcome<S, E> {
match self {
Ok(val) => Success(val),
Err(err) => Failure((status, err))
}
}
#[inline]
fn or_forward(self, status: Status) -> Outcome<S, E> {
match self {
Ok(val) => Success(val),
Err(_) => Forward(status)
}
}
}
/// Trait implemented by request guards to derive a value from incoming
/// requests.
///
/// # Request Guards
///
/// A request guard is a type that represents an arbitrary validation policy.
/// The validation policy is implemented through `FromRequest`. In other words,
/// every type that implements `FromRequest` is a request guard.
///
/// Request guards appear as inputs to handlers. An arbitrary number of request
/// guards can appear as arguments in a route handler. Rocket will automatically
/// invoke the `FromRequest` implementation for request guards before calling
/// the handler. Rocket only dispatches requests to a handler when all of its
/// guards pass.
///
/// ## Async Trait
///
/// [`FromRequest`] is an _async_ trait. Implementations of `FromRequest` must
/// be decorated with an attribute of `#[rocket::async_trait]`:
///
/// ```rust
/// use rocket::request::{self, Request, FromRequest};
/// # struct MyType;
/// # type MyError = String;
///
/// #[rocket::async_trait]
/// impl<'r> FromRequest<'r> for MyType {
/// type Error = MyError;
///
/// async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
/// /* .. */
/// # unimplemented!()
/// }
/// }
/// ```
///
/// ## Example
///
/// The following dummy handler makes use of three request guards, `A`, `B`, and
/// `C`. An input type can be identified as a request guard if it is not named
/// in the route attribute. This is why, for instance, `param` is not a request
/// guard.
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// # use rocket::http::Method;
/// # type A = Method; type B = Method; type C = Method; type T = ();
/// #[get("/<param>")]
/// fn index(param: isize, a: A, b: B, c: C) -> T { /* ... */ }
/// # fn main() {}
/// ```
///
/// Request guards always fire in left-to-right declaration order. In the
/// example above, the order is `a` followed by `b` followed by `c`. Failure is
/// short-circuiting; if one guard fails, the remaining are not attempted.
///
/// # Outcomes
///
/// The returned [`Outcome`] of a `from_request` call determines how the
/// incoming request will be processed.
///
/// * **Success**(S)
///
/// If the `Outcome` is [`Success`], then the `Success` value will be used as
/// the value for the corresponding parameter. As long as all other guards
/// succeed, the request will be handled.
///
/// * **Failure**(Status, E)
///
/// If the `Outcome` is [`Failure`], the request will fail with the given
/// status code and error. The designated error [`Catcher`](crate::Catcher)
/// will be used to respond to the request. Note that users can request types
/// of `Result<S, E>` and `Option<S>` to catch `Failure`s and retrieve the
/// error value.
///
/// * **Forward**(Status)
///
/// If the `Outcome` is [`Forward`], the request will be forwarded to the next
/// matching route until either one succeds or there are no further matching
/// routes to attempt. In the latter case, the request will be sent to the
/// [`Catcher`](crate::Catcher) for the designated `Status`. Note that users
/// can request an `Option<S>` to catch `Forward`s.
///
/// # Provided Implementations
///
/// Rocket implements `FromRequest` for several built-in types. Their behavior
/// is documented here.
///
/// * **Method**
///
/// Extracts the [`Method`] from the incoming request.
///
/// _This implementation always returns successfully._
///
/// * **&Origin**
///
/// Extracts the [`Origin`] URI from the incoming request.
///
/// _This implementation always returns successfully._
///
/// * **&Host**
///
/// Extracts the [`Host`] from the incoming request, if it exists. See
/// [`Request::host()`] for details.
///
/// * **&Route**
///
/// Extracts the [`Route`] from the request if one is available. When used
/// as a request guard in a route handler, this will always succeed. Outside
/// of a route handler, a route may not be available, and the request is
/// forwarded with a 500 Internal Server Error status.
///
/// For more information on when an `&Route` is available, see
/// [`Request::route()`].
///
/// * **&CookieJar**
///
/// Returns a borrow to the [`CookieJar`] in the incoming request. Note that
/// `CookieJar` implements internal mutability, so a handle to a `CookieJar`
/// allows you to get _and_ set cookies in the request.
///
/// _This implementation always returns successfully._
///
/// * **&[`Config`]**
///
/// Extracts the application [`Config`].
///
/// _This implementation always returns successfully._
///
/// * **ContentType**
///
/// Extracts the [`ContentType`] from the incoming request via
/// [`Request::content_type()`]. If the request didn't specify a
/// Content-Type, the request is forwarded with a 404 Not Found status.
///
/// * **IpAddr**
///
/// Extracts the client ip address of the incoming request as an [`IpAddr`]
/// via [`Request::client_ip()`]. If the client's IP address is not known,
/// the request is forwarded with a 404 Not Found status.
///
/// * **SocketAddr**
///
/// Extracts the remote address of the incoming request as a [`SocketAddr`]
/// via [`Request::remote()`]. If the remote address is not known, the
/// request is forwarded with a 404 Not Found status.
///
/// * **Option<T>** _where_ **T: FromRequest**
///
/// The type `T` is derived from the incoming request using `T`'s
/// `FromRequest` implementation. If the derivation is a `Success`, the
/// derived value is returned in `Some`. Otherwise, a `None` is returned.
///
/// _This implementation always returns successfully._
///
/// * **Result<T, T::Error>** _where_ **T: FromRequest**
///
/// The type `T` is derived from the incoming request using `T`'s
/// `FromRequest` implementation. If derivation is a `Success`, the value is
/// returned in `Ok`. If the derivation is a `Failure`, the error value is
/// returned in `Err`. If the derivation is a `Forward`, the request is
/// forwarded with the same status code as the original forward.
///
/// [`Config`]: crate::config::Config
///
/// # Example
///
/// Imagine you're running an authenticated API service that requires that some
/// requests be sent along with a valid API key in a header field. You want to
/// ensure that the handlers corresponding to these requests don't get called
/// unless there is an API key in the request and the key is valid. The
/// following example implements this using an `ApiKey` type and a `FromRequest`
/// implementation for that type. The `ApiKey` type is then used in the
/// `sensitive` handler.
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// #
/// use rocket::http::Status;
/// use rocket::request::{self, Outcome, Request, FromRequest};
///
/// struct ApiKey<'r>(&'r str);
///
/// #[derive(Debug)]
/// enum ApiKeyError {
/// Missing,
/// Invalid,
/// }
///
/// #[rocket::async_trait]
/// impl<'r> FromRequest<'r> for ApiKey<'r> {
/// type Error = ApiKeyError;
///
/// async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
/// /// Returns true if `key` is a valid API key string.
/// fn is_valid(key: &str) -> bool {
/// key == "valid_api_key"
/// }
///
/// match req.headers().get_one("x-api-key") {
/// None => Outcome::Failure((Status::BadRequest, ApiKeyError::Missing)),
/// Some(key) if is_valid(key) => Outcome::Success(ApiKey(key)),
/// Some(_) => Outcome::Failure((Status::BadRequest, ApiKeyError::Invalid)),
/// }
/// }
/// }
///
/// #[get("/sensitive")]
/// fn sensitive(key: ApiKey<'_>) -> &'static str {
/// "Sensitive data."
/// }
/// ```
///
/// # Request-Local State
///
/// Request guards that perform expensive operations, such as those that query a
/// database or an external service, should use the [request-local state] cache
/// to store results if they might be invoked multiple times during the routing
/// of a single request.
///
/// For example, consider a pair of `User` and `Admin` guards and a pair of
/// routes (`admin_dashboard` and `user_dashboard`):
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// # #[cfg(feature = "secrets")] mod wrapper {
/// # use rocket::outcome::{IntoOutcome, try_outcome};
/// # use rocket::request::{self, Outcome, FromRequest, Request};
/// # use rocket::http::Status;
/// # struct User { id: String, is_admin: bool }
/// # struct Database;
/// # impl Database {
/// # fn get_user(&self, id: String) -> Result<User, ()> {
/// # Ok(User { id, is_admin: false })
/// # }
/// # }
/// # #[rocket::async_trait]
/// # impl<'r> FromRequest<'r> for Database {
/// # type Error = ();
/// # async fn from_request(request: &'r Request<'_>) -> Outcome<Database, ()> {
/// # Outcome::Success(Database)
/// # }
/// # }
/// #
/// # struct Admin { user: User }
/// #
/// #[rocket::async_trait]
/// impl<'r> FromRequest<'r> for User {
/// type Error = ();
///
/// async fn from_request(request: &'r Request<'_>) -> Outcome<User, ()> {
/// let db = try_outcome!(request.guard::<Database>().await);
/// request.cookies()
/// .get_private("user_id")
/// .and_then(|cookie| cookie.value().parse().ok())
/// .and_then(|id| db.get_user(id).ok())
/// .or_forward(Status::Unauthorized)
/// }
/// }
///
/// #[rocket::async_trait]
/// impl<'r> FromRequest<'r> for Admin {
/// type Error = ();
///
/// async fn from_request(request: &'r Request<'_>) -> Outcome<Admin, ()> {
/// // This will unconditionally query the database!
/// let user = try_outcome!(request.guard::<User>().await);
/// if user.is_admin {
/// Outcome::Success(Admin { user })
/// } else {
/// Outcome::Forward(Status::Unauthorized)
/// }
/// }
/// }
///
/// #[get("/dashboard")]
/// fn admin_dashboard(admin: Admin) { }
///
/// #[get("/dashboard", rank = 2)]
/// fn user_dashboard(user: User) { }
/// # } // end of cfg wrapper
/// ```
///
/// When a non-admin user is logged in, the database will be queried twice: once
/// via the `Admin` guard invoking the `User` guard, and a second time via the
/// `User` guard directly. For cases like these, request-local state should be
/// used, as illustrated below:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// # #[cfg(feature = "secrets")] mod wrapper {
/// # use rocket::outcome::{IntoOutcome, try_outcome};
/// # use rocket::request::{self, Outcome, FromRequest, Request};
/// # use rocket::http::Status;
/// # struct User { id: String, is_admin: bool }
/// # struct Database;
/// # impl Database {
/// # fn get_user(&self, id: String) -> Result<User, ()> {
/// # Ok(User { id, is_admin: false })
/// # }
/// # }
/// # #[rocket::async_trait]
/// # impl<'r> FromRequest<'r> for Database {
/// # type Error = ();
/// # async fn from_request(request: &'r Request<'_>) -> Outcome<Database, ()> {
/// # Outcome::Success(Database)
/// # }
/// # }
/// #
/// # struct Admin<'a> { user: &'a User }
/// #
/// #[rocket::async_trait]
/// impl<'r> FromRequest<'r> for &'r User {
/// type Error = std::convert::Infallible;
///
/// async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
/// // This closure will execute at most once per request, regardless of
/// // the number of times the `User` guard is executed.
/// let user_result = request.local_cache_async(async {
/// let db = request.guard::<Database>().await.succeeded()?;
/// request.cookies()
/// .get_private("user_id")
/// .and_then(|cookie| cookie.value().parse().ok())
/// .and_then(|id| db.get_user(id).ok())
/// }).await;
///
/// user_result.as_ref().or_forward(Status::Unauthorized)
/// }
/// }
///
/// #[rocket::async_trait]
/// impl<'r> FromRequest<'r> for Admin<'r> {
/// type Error = std::convert::Infallible;
///
/// async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
/// let user = try_outcome!(request.guard::<&User>().await);
/// if user.is_admin {
/// Outcome::Success(Admin { user })
/// } else {
/// Outcome::Forward(Status::Unauthorized)
/// }
/// }
/// }
/// # } // end of cfg wrapper
/// ```
///
/// Notice that these request guards provide access to *borrowed* data (`&'a
/// User` and `Admin<'a>`) as the data is now owned by the request's cache.
///
/// [request-local state]: https://rocket.rs/v0.5-rc/guide/state/#request-local-state
#[crate::async_trait]
pub trait FromRequest<'r>: Sized {
/// The associated error to be returned if derivation fails.
type Error: Debug;
/// Derives an instance of `Self` from the incoming request metadata.
///
/// If the derivation is successful, an outcome of `Success` is returned. If
/// the derivation fails in an unrecoverable fashion, `Failure` is returned.
/// `Forward` is returned to indicate that the request should be forwarded
/// to other matching routes, if any.
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error>;
}
#[crate::async_trait]
impl<'r> FromRequest<'r> for Method {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
Success(request.method())
}
}
#[crate::async_trait]
impl<'r> FromRequest<'r> for &'r Origin<'r> {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
Success(request.uri())
}
}
#[crate::async_trait]
impl<'r> FromRequest<'r> for &'r Host<'r> {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
match request.host() {
Some(host) => Success(host),
None => Forward(Status::NotFound)
}
}
}
#[crate::async_trait]
impl<'r> FromRequest<'r> for &'r Route {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
match request.route() {
Some(route) => Success(route),
None => Forward(Status::InternalServerError)
}
}
}
#[crate::async_trait]
impl<'r> FromRequest<'r> for &'r CookieJar<'r> {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
Success(request.cookies())
}
}
#[crate::async_trait]
impl<'r> FromRequest<'r> for &'r Accept {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
match request.accept() {
Some(accept) => Success(accept),
None => Forward(Status::NotFound)
}
}
}
#[crate::async_trait]
impl<'r> FromRequest<'r> for &'r ContentType {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
match request.content_type() {
Some(content_type) => Success(content_type),
None => Forward(Status::NotFound)
}
}
}
#[crate::async_trait]
impl<'r> FromRequest<'r> for IpAddr {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
match request.client_ip() {
Some(addr) => Success(addr),
None => Forward(Status::NotFound)
}
}
}
#[crate::async_trait]
impl<'r> FromRequest<'r> for SocketAddr {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
match request.remote() {
Some(addr) => Success(addr),
None => Forward(Status::NotFound)
}
}
}
#[crate::async_trait]
impl<'r, T: FromRequest<'r>> FromRequest<'r> for Result<T, T::Error> {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
match T::from_request(request).await {
Success(val) => Success(Ok(val)),
Failure((_, e)) => Success(Err(e)),
Forward(status) => Forward(status),
}
}
}
#[crate::async_trait]
impl<'r, T: FromRequest<'r>> FromRequest<'r> for Option<T> {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
match T::from_request(request).await {
Success(val) => Success(Some(val)),
Failure(_) | Forward(_) => Success(None),
}
}
}
#[crate::async_trait]
impl<'r, T: FromRequest<'r>> FromRequest<'r> for Outcome<T, T::Error> {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
Success(T::from_request(request).await)
}
}