Lines
98.99 %
Functions
96.92 %
Branches
100 %
use super::*;
use axum::{
Form, Router,
body::to_bytes,
http::StatusCode,
middleware::{self, Next},
routing::{get, post},
};
use serde::Deserialize;
use tower::ServiceExt;
const HOSTILE: &str = "<script>alert(1)</script>";
async fn failing() -> Result<&'static str, WebError> {
Err(WebError::unprocessable(HOSTILE))
}
async fn logged_out() -> Result<&'static str, WebError> {
Err(WebError::unauthorized("Not logged in"))
async fn forbidden() -> Result<&'static str, WebError> {
Err(WebError::forbidden("No admin"))
async fn down() -> Result<&'static str, WebError> {
Err(WebError::unavailable("Temporarily unavailable"))
async fn fine() -> &'static str {
"OK"
#[derive(Deserialize)]
struct Flag {
enabled: bool,
async fn takes_form(Form(flag): Form<Flag>) -> String {
flag.enabled.to_string()
/// Stands in for `auth`, which appends rotated cookies to whatever the handler answered.
async fn rotating_cookies(req: Request<Body>, next: Next) -> Response {
let mut response = next.run(req).await;
for cookie in ["access_token=a; HttpOnly", "refresh_token=r; HttpOnly"] {
response
.headers_mut()
.append(header::SET_COOKIE, HeaderValue::from_static(cookie));
fn app() -> Router {
Router::new()
.route("/fail", get(failing))
.route("/fine", get(fine))
.route("/logged-out", get(logged_out))
.route("/forbidden", get(forbidden))
.route("/down", get(down))
.route("/form", post(takes_form))
.merge(
.route("/page", get(failing))
.route("/page-logged-out", get(logged_out))
.route_layer(middleware::from_fn(full_page)),
)
.layer(middleware::from_fn(rotating_cookies))
.layer(middleware::from_fn(render_web_error))
async fn fetch(uri: &str, headers: &[(&str, &str)]) -> (StatusCode, String, String) {
let mut builder = Request::builder().uri(uri);
for (name, value) in headers {
builder = builder.header(*name, *value);
let response = app()
.oneshot(builder.body(Body::empty()).unwrap())
.await
.unwrap();
let status = response.status();
let content_type = header_str(response.headers(), "content-type")
.unwrap_or_default()
.to_string();
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
(
status,
content_type,
String::from_utf8(body.to_vec()).unwrap(),
#[tokio::test]
async fn htmx_gets_an_escaped_fragment_with_the_status_kept() {
let (status, content_type, body) =
fetch("/fail", &[("hx-request", "true"), ("accept", "text/html")]).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(content_type.starts_with("text/html"));
assert_eq!(
body,
r#"<div class="error-alert"><script>alert(1)</script></div>"#
);
async fn html_navigation_gets_the_error_page() {
let (status, content_type, body) = fetch("/fail", &[("accept", "text/html")]).await;
assert!(body.contains("<title>Error</title>"));
assert!(body.contains("Error 422"));
assert!(!body.contains(HOSTILE));
assert!(body.contains("<script>"));
assert!(body.contains(r#"href="/""#));
async fn page_links_back_to_a_same_origin_referer() {
let (_, _, body) = fetch(
"/fail",
&[
("accept", "text/html"),
("host", "app.example"),
("referer", "https://app.example/transaction/new?x=1"),
],
.await;
assert!(body.contains(r#"href="/transaction/new?x=1""#));
async fn page_ignores_a_foreign_referer() {
("referer", "https://evil.example/phish"),
assert!(!body.contains("evil.example"));
async fn back_link_never_becomes_protocol_relative() {
("referer", "https://app.example//evil.example/x"),
assert!(body.contains(r#"href="/evil.example/x""#));
async fn referer_without_a_path_links_to_the_root() {
("referer", "https://app.example"),
async fn other_clients_keep_the_json() {
let (status, content_type, body) = fetch("/fail", &[("accept", "application/json")]).await;
assert!(content_type.starts_with("application/json"));
let json: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(json["status"], "error");
assert_eq!(json["message"], HOSTILE);
async fn responses_without_a_web_error_pass_untouched() {
let (status, _, body) = fetch("/fine", &[("hx-request", "true")]).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "OK");
async fn raw(uri: &str, headers: &[(&str, &str)]) -> Response {
app()
.unwrap()
async fn a_page_that_is_not_logged_in_is_sent_to_login() {
let response = raw("/logged-out", &[("accept", "text/html")]).await;
assert_eq!(response.status(), StatusCode::SEE_OTHER);
assert_eq!(response.headers().get(header::LOCATION).unwrap(), "/login");
async fn htmx_that_is_not_logged_in_is_told_to_redirect() {
let response = raw(
"/logged-out",
&[("hx-request", "true"), ("accept", "text/html")],
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
assert_eq!(response.headers().get("hx-redirect").unwrap(), "/login");
assert!(response.headers().get(header::LOCATION).is_none());
async fn json_clients_that_are_not_logged_in_keep_the_401() {
fetch("/logged-out", &[("accept", "application/json")]).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(json["message"], "Not logged in");
async fn forbidden_is_shown_not_redirected() {
let (status, _, page) = fetch("/forbidden", &[("accept", "text/html")]).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert!(page.contains("Error 403") && page.contains("No admin"));
let (status, _, fragment) = fetch(
"/forbidden",
assert_eq!(fragment, r#"<div class="error-alert">No admin</div>"#);
async fn unavailable_gets_the_error_page_or_fragment() {
let (status, _, page) = fetch("/down", &[("accept", "text/html")]).await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
assert!(page.contains("Error 503") && page.contains("Temporarily unavailable"));
let (status, _, fragment) =
fetch("/down", &[("hx-request", "true"), ("accept", "text/html")]).await;
assert!(fragment.contains("Temporarily unavailable"));
fn cookies(response: &Response) -> Vec<&str> {
.headers()
.get_all(header::SET_COOKIE)
.iter()
.filter_map(|value| value.to_str().ok())
.collect()
async fn rendered_errors_keep_the_rotated_session_cookies() {
let expected = vec!["access_token=a; HttpOnly", "refresh_token=r; HttpOnly"];
for headers in [
&[("accept", "text/html")][..],
&[("hx-request", "true"), ("accept", "text/html")][..],
&[("accept", "application/json")][..],
] {
let response = raw("/fail", headers).await;
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(cookies(&response), expected);
async fn the_login_redirect_keeps_the_cookies_too() {
assert_eq!(cookies(&response).len(), 2);
async fn bad_form(headers: &[(&str, &str)]) -> Response {
let mut builder = Request::builder()
.method("POST")
.uri("/form")
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
.oneshot(
builder
.body(Body::from("enabled=%3Cscript%3Ealert(1)%3C/script%3E"))
.unwrap(),
async fn an_extractor_rejection_is_rendered_as_an_escaped_fragment() {
let response = bad_form(&[("hx-request", "true")]).await;
let body = String::from_utf8(body.to_vec()).unwrap();
assert!(body.starts_with(r#"<div class="error-alert">"#));
assert!(!body.contains("<script>"));
async fn an_extractor_rejection_gets_the_error_page_or_json() {
let page = bad_form(&[("accept", "text/html")]).await;
assert!(
header_str(page.headers(), "content-type")
.starts_with("text/html")
let json = bad_form(&[("accept", "application/json")]).await;
let body = to_bytes(json.into_body(), usize::MAX).await.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
async fn adopting_leaves_html_json_and_success_alone() {
let html = (StatusCode::BAD_REQUEST, Html("<p>x</p>")).into_response();
let adopted = adopt_rejection(html).await;
assert!(adopted.extensions().get::<WebError>().is_none());
let ok = adopt_rejection("fine".into_response()).await;
assert_eq!(ok.status(), StatusCode::OK);
let own = adopt_rejection(WebError::forbidden("No").into_response()).await;
own.extensions().get::<WebError>(),
Some(&WebError::forbidden("No"))
async fn a_long_rejection_text_is_bounded() {
let long = (StatusCode::BAD_REQUEST, "x".repeat(5000)).into_response();
let adopted = adopt_rejection(long).await;
let error = adopted.extensions().get::<WebError>().cloned().unwrap();
assert_eq!(error.status, StatusCode::BAD_REQUEST);
assert!(error.message.chars().count() <= REJECTION_MESSAGE_CHARS);
async fn a_page_route_failure_is_a_page_whatever_the_request_accepts() {
for headers in [&[][..], &[("accept", "application/json")][..]] {
let (status, content_type, body) = fetch("/page", headers).await;
assert!(content_type.starts_with("text/html"), "{content_type}");
assert!(body.contains("Error 422"), "{body}");
assert!(body.contains(r#"href="/""#), "{body}");
let (_, _, fragment) = fetch("/page", &[("hx-request", "true")]).await;
fragment.starts_with(r#"<div class="error-alert">"#),
"{fragment}"
let (_, content_type, _) = fetch("/fail", &[]).await;
content_type.starts_with("application/json"),
"{content_type}"
async fn a_page_route_without_a_session_goes_to_login() {
Request::builder()
.uri("/page-logged-out")
.body(Body::empty())
assert!(response.status().is_redirection());
assert_eq!(header_str(response.headers(), "location"), Some(LOGIN));