Skip to main content

url_from

Function url_from 

Source
pub fn url_from(uri: &Uri, candidate: &str) -> Option<String>
Expand description

The URL to redirect to when candidate points inside this app, else None (Rails’ url_from).

Use it for every redirect target that comes from the request (a return_to parameter, a Referer), so the app cannot be used to send users to another site (open redirect). Accepted:

  • a path: /account?tab=keys (but not //evil.example, which browsers read as another host, nor /\evil.example);
  • an absolute http(s) URL whose host (and port) is the request’s own host: it is returned as its path and query.

Anything with control characters (CR, LF, tab: header injection) or backslashes is refused. uri is the request’s URI (the Uri extractor); on Workers it includes the host. No binding call.

§Examples

use axum::http::Uri;
use ocre::security::url_from;

let request: Uri = "https://app.example.com/login".parse().unwrap();
assert_eq!(url_from(&request, "/account?tab=keys").as_deref(), Some("/account?tab=keys"));
assert_eq!(url_from(&request, "https://app.example.com/posts/1").as_deref(), Some("/posts/1"));
assert_eq!(url_from(&request, "https://evil.example/"), None);
assert_eq!(url_from(&request, "//evil.example"), None);
assert_eq!(url_from(&request, "/\r\nSet-Cookie: x=1"), None);

// In a handler: `Redirect::to(&url_from(&uri, &form.return_to).unwrap_or_else(|| "/".to_owned()))`.