use crate::{TestApp, TestResponse};
use axum::{
body::{to_bytes, Body},
http::{header, HeaderMap, HeaderName, HeaderValue, Method, Request},
};
use capy_core::{AppError, Result};
use serde::Serialize;
use std::{
net::SocketAddr,
time::{SystemTime, UNIX_EPOCH},
};
use tower::ServiceExt;
struct StoredCookie {
cookie: cookie::Cookie<'static>,
host: String,
expires: Option<i64>,
}
pub struct TestSession {
app: TestApp,
cookies: Vec<StoredCookie>,
headers: HeaderMap,
peer: SocketAddr,
origin: url::Url,
}
impl std::fmt::Debug for TestSession {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TestSession")
.field("peer", &self.peer)
.finish_non_exhaustive()
}
}
impl TestSession {
pub(crate) fn new(app: TestApp) -> Self {
let peer = app.peer;
Self {
app,
cookies: Vec::new(),
headers: HeaderMap::new(),
peer,
origin: url::Url::parse("http://localhost").expect("static origin"),
}
}
pub fn origin(mut self, origin: &str) -> Result<Self> {
let url = url::Url::parse(origin)
.map_err(|_| AppError::Configuration("Invalid test session origin.".into()))?;
if !matches!(url.scheme(), "http" | "https")
|| url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| url.path() != "/"
|| url.query().is_some()
|| url.fragment().is_some()
{
return Err(AppError::Configuration("Test session origin must be an HTTP(S) origin without credentials, path, query or fragment.".into()));
}
self.origin = url;
Ok(self)
}
pub fn peer_addr(mut self, peer: SocketAddr) -> Self {
self.peer = peer;
self
}
pub fn header(mut self, name: &str, value: &str) -> Self {
self.headers.insert(
name.parse::<HeaderName>().expect("valid test header name"),
value.parse().expect("valid test header value"),
);
self
}
pub fn request(&mut self, method: Method, path: &str) -> SessionRequest<'_> {
SessionRequest {
session: self,
method,
path: path.into(),
headers: HeaderMap::new(),
body: Vec::new(),
csrf: true,
}
}
pub fn get(&mut self, path: &str) -> SessionRequest<'_> {
self.request(Method::GET, path)
}
pub fn post(&mut self, path: &str) -> SessionRequest<'_> {
self.request(Method::POST, path)
}
pub fn put(&mut self, path: &str) -> SessionRequest<'_> {
self.request(Method::PUT, path)
}
pub fn patch(&mut self, path: &str) -> SessionRequest<'_> {
self.request(Method::PATCH, path)
}
pub fn delete(&mut self, path: &str) -> SessionRequest<'_> {
self.request(Method::DELETE, path)
}
pub async fn login(&mut self, email: &str, password: &str) -> Result<TestResponse> {
self.post("/api/auth/login")
.json(serde_json::json!({"email": email, "password": password}))
.send()
.await
}
pub async fn logout(&mut self) -> Result<TestResponse> {
self.post("/api/auth/logout").send().await
}
async fn send_raw(
&mut self,
method: Method,
path: &str,
mut headers: HeaderMap,
body: Vec<u8>,
) -> Result<TestResponse> {
if !path.starts_with('/')
|| path.starts_with("//")
|| path.contains('\\')
|| path.contains('#')
{
return Err(AppError::Configuration(
"Test session requests require a same-origin absolute path without a fragment."
.into(),
));
}
let uri: axum::http::Uri = path
.parse()
.map_err(|_| AppError::Configuration("Invalid test request path.".into()))?;
if uri.scheme().is_some() || uri.authority().is_some() {
return Err(AppError::Configuration(
"Test session requests must stay on the configured origin.".into(),
));
}
for (name, value) in &self.headers {
headers.entry(name).or_insert(value.clone());
}
headers
.entry("sec-fetch-site")
.or_insert(HeaderValue::from_static("same-origin"));
let host = self.origin.host_str().expect("validated origin");
let now = now();
self.cookies
.retain(|c| c.expires.is_none_or(|expires| expires > now));
let cookie_header = self
.cookies
.iter()
.filter(|stored| {
let cookie_path = stored.cookie.path().unwrap_or("/");
let matches_path = uri.path() == cookie_path
|| (uri.path().starts_with(cookie_path)
&& (cookie_path.ends_with('/')
|| uri.path().as_bytes().get(cookie_path.len()) == Some(&b'/')));
stored.host == host
&& matches_path
&& (!stored.cookie.secure().unwrap_or(false) || self.origin.scheme() == "https")
})
.map(|c| format!("{}={}", c.cookie.name(), c.cookie.value()))
.collect::<Vec<_>>()
.join("; ");
if !cookie_header.is_empty() && !headers.contains_key(header::COOKIE) {
let mut value = HeaderValue::from_str(&cookie_header).map_err(|_| {
AppError::Configuration("Invalid server-issued test cookie.".into())
})?;
value.set_sensitive(true);
headers.insert(header::COOKIE, value);
}
let mut request = Request::builder()
.method(method.clone())
.uri(uri)
.extension(axum::extract::ConnectInfo(self.peer))
.body(Body::from(body))
.map_err(|_| AppError::Configuration("Invalid test request.".into()))?;
*request.headers_mut() = headers;
let response = self
.app
.router
.clone()
.oneshot(request)
.await
.expect("Axum router is infallible");
let (parts, body) = response.into_parts();
for value in parts.headers.get_all(header::SET_COOKIE) {
let Some(mut cookie) = value
.to_str()
.ok()
.and_then(|v| cookie::Cookie::parse(v.to_owned()).ok())
else {
continue;
};
if cookie
.domain()
.is_some_and(|domain| !domain.eq_ignore_ascii_case(host))
{
continue;
}
if cookie.secure().unwrap_or(false) && self.origin.scheme() != "https" {
continue;
}
if cookie.path().is_none() {
let path = path.split('?').next().unwrap_or("/");
let default_path = path
.rsplit_once('/')
.map(|(parent, _)| parent)
.filter(|p| !p.is_empty())
.unwrap_or("/");
cookie.set_path(default_path.to_owned());
}
self.cookies.retain(|stored| {
!(stored.host == host
&& stored.cookie.name() == cookie.name()
&& stored.cookie.path() == cookie.path())
});
let expires = cookie
.max_age()
.map(|age| now.saturating_add(age.whole_seconds()))
.or_else(|| cookie.expires_datetime().map(|date| date.unix_timestamp()));
if expires.is_none_or(|expires| expires > now) {
self.cookies.push(StoredCookie {
cookie: cookie.into_owned(),
host: host.into(),
expires,
});
}
}
Ok(TestResponse {
method,
path: path.into(),
contracts: self.app.contracts.clone(),
status: parts.status,
headers: parts.headers,
body: to_bytes(body, 16 * 1024 * 1024).await.map_err(|_| {
AppError::Configuration("Test response exceeds 16 MiB or cannot be read.".into())
})?,
})
}
}
fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
}
pub struct SessionRequest<'a> {
session: &'a mut TestSession,
method: Method,
path: String,
headers: HeaderMap,
body: Vec<u8>,
csrf: bool,
}
impl SessionRequest<'_> {
pub fn json(mut self, value: impl Serialize) -> Self {
self.body = serde_json::to_vec(&value).expect("test JSON must serialize");
self.headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
self
}
pub fn header(mut self, name: &str, value: &str) -> Self {
self.headers.insert(
name.parse::<HeaderName>().expect("valid test header name"),
value.parse().expect("valid test header value"),
);
self
}
pub fn without_csrf(mut self) -> Self {
self.csrf = false;
self
}
pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
self.body = body.into();
self
}
pub async fn send(mut self) -> Result<TestResponse> {
if self.csrf
&& self.session.app.csrf
&& !matches!(self.method, Method::GET | Method::HEAD | Method::OPTIONS)
{
let mut headers = self.headers.clone();
headers.insert("x-capy-csrf", HeaderValue::from_static("1"));
let bootstrap = self
.session
.send_raw(Method::GET, "/api/auth/csrf", headers, Vec::new())
.await?;
if !bootstrap.status.is_success() {
return Ok(bootstrap);
}
let data: serde_json::Value =
serde_json::from_slice(&bootstrap.body).map_err(|_| {
AppError::Configuration("CSRF bootstrap did not return JSON.".into())
})?;
let token = data["csrf_token"].as_str().ok_or_else(|| {
AppError::Configuration("CSRF bootstrap did not return a token.".into())
})?;
let mut value = HeaderValue::from_str(token).map_err(|_| {
AppError::Configuration("CSRF bootstrap returned an invalid token.".into())
})?;
value.set_sensitive(true);
self.headers.entry("x-csrf-token").or_insert(value);
}
self.session
.send_raw(self.method, &self.path, self.headers, self.body)
.await
}
}