use crate::support;
use laravel::Application;
use laravel::config::Env;
use laravel::crypt::{Cipher, Encrypter};
use laravel::http::sse::{Event, EventStream};
use laravel::http::{Download, File, IntoResponse, Json, JsonStream, Redirect, Response, StatusCode, Streamed, header};
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use laravel::view::{data, view};
use serde_json::json;
use support::{TempDir, WithDir, received_cookie};
fn app() -> WithDir {
let root = TempDir::with_files(
"headers",
&[
("resources/views/hello.html", "Hello, {{ name }}"),
("public/notes.txt", "Notes"),
],
);
let app = Application::configure()
.replace_env(Env::from_iter([("APP_BASE_PATH", root.to_str().unwrap())]))
.with_config(|config, _| {
config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc));
})
.with_routing(|routing, _| {
routing.web(|route: &mut Router| {
route.get("/view", || async {
view("hello", data! { name => "Taylor" })
.with_header("cache-control", "no-store")
.with_cookie(("theme", "dark"))
});
route.get("/redirect", || async {
Redirect::to("/view")
.with("status", "Saved!")
.with_header("x-saved", "1")
});
route.get("/redirect-headers-first", || async {
Redirect::to("/view")
.with_header("x-saved", "1")
.with("status", "Saved!")
.status(303)
});
route.get("/response", || async {
Response::new("Gone")
.with_header("x-reason", "moved")
.with("status", "It moved.")
.with_status(StatusCode::GONE)
});
route.get("/json", || async {
Json(json!({ "ok": true })).with_headers([("x-one", "1"), ("x-two", "2")])
});
route.get("/text", || async {
"plain".with_header(header::CONTENT_LANGUAGE, "en")
});
route.get("/chained", || async {
"plain"
.with_header("x-version", "1")
.with_header("x-version", "2")
.with_header("content-type", "text/csv")
});
route.get("/file", || async {
File::new("public/notes.txt")
.with_header("x-notes", "yes")
.with_cookie(("theme", "dark"))
});
route.get("/file-type", || async {
File::new("public/notes.txt").with_header("content-type", "text/markdown")
});
route.get("/download", || async {
Download::new("a.csv", "a,b")
.with_header("x-export", "1")
.with_cookie(("theme", "dark"))
});
route.get("/streamed", || async {
Streamed::new(laravel::stream::iter(["a", "b"]))
.with_header("x-stream", "1")
.with_cookie(("theme", "dark"))
});
route.get("/json-stream", || async {
JsonStream::new(laravel::stream::iter([1, 2]))
.with_header("x-stream", "json")
.with_cookie(("theme", "dark"))
});
route.get("/events", || async {
EventStream::new(laravel::stream::iter([Event::new("ping", "")]))
.without_end_event()
.with_header("x-stream", "events")
.with_cookie(("theme", "dark"))
});
route.get("/redirect-cookie", || async {
Redirect::to("/view")
.with_header("x-saved", "1")
.with_cookie(("theme", "dark"))
});
});
})
.create();
WithDir::new(app, root)
}
#[cfg(feature = "minijinja")]
#[tokio::test]
async fn views_keep_their_headers_and_what_tests_know_of_them() {
app()
.get("/view")
.await
.assert_ok()
.assert_see("Hello, Taylor")
.assert_header("cache-control", "no-store")
.assert_view_is("hello")
.assert_view_has("name", "Taylor");
}
#[tokio::test]
async fn redirects_take_headers_and_flash_data_in_either_order() {
let app = app();
app.get("/redirect")
.await
.assert_redirect_to("/view")
.assert_header("x-saved", "1")
.assert_session_has("status", "Saved!");
app.get("/redirect-headers-first")
.await
.assert_status(303)
.assert_header("x-saved", "1")
.assert_session_has("status", "Saved!");
}
#[tokio::test]
async fn responses_take_headers_flash_data_and_a_status() {
app()
.get("/response")
.await
.assert_status(410)
.assert_see("Gone")
.assert_header("x-reason", "moved")
.assert_session_has("status", "It moved.");
}
#[tokio::test]
async fn any_response_takes_headers() {
let app = app();
app.get("/json")
.await
.assert_json(json!({ "ok": true }))
.assert_header("x-one", "1")
.assert_header("x-two", "2");
app.get("/text")
.await
.assert_see("plain")
.assert_header("content-language", "en");
app.get("/file")
.await
.assert_see("Notes")
.assert_header("x-notes", "yes");
app.get("/download")
.await
.assert_header("x-export", "1")
.assert_header("content-disposition", "attachment; filename=\"a.csv\"");
app.get("/streamed")
.await
.assert_see("ab")
.assert_header("x-stream", "1");
app.get("/json-stream")
.await
.assert_see("[1,2]")
.assert_header("x-stream", "json");
app.get("/events").await.assert_header("x-stream", "events");
}
#[tokio::test]
async fn headers_replace_earlier_ones_and_the_responses_own() {
let app = app();
let response = app.get("/chained").await;
response
.assert_header("x-version", "2")
.assert_header("content-type", "text/csv");
assert_eq!(response.headers().get_all("x-version").iter().count(), 1);
app.get("/file-type")
.await
.assert_header("content-type", "text/markdown");
}
#[tokio::test]
async fn response_types_carry_cookies_through_finishing_and_encryption() {
let app = app();
let mut paths = vec![
"/file",
"/download",
"/streamed",
"/json-stream",
"/events",
"/redirect-cookie",
];
if cfg!(feature = "minijinja") {
paths.push("/view");
}
for path in paths {
let response = app.get(path).await;
let theme = received_cookie(&response, "theme").expect("the response carries its cookie");
assert_ne!(theme, "dark", "{path} must encrypt cookies");
}
}
#[tokio::test]
async fn invalid_headers_are_located_where_they_were_given() {
let app = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| config.app.debug = true)
.with_routing(|routing, _| {
routing.api(|route: &mut Router| {
route.get("/name", || async { "plain".with_header("bad header", "1") });
route.get("/value", || async {
Redirect::to("/").with_header("x-bad", "line\nbreak")
});
route.get("/content-type", || async {
Streamed::new(futures_util::stream::empty::<&str>()).content_type("text/\n")
});
});
})
.create();
for path in ["/api/name", "/api/value", "/api/content-type"] {
let json = app.get(path).await.assert_internal_server_error().json();
assert_eq!(json["file"], "tests/headers.rs", "{path}: {json}");
}
}