Skip to main content

capy_testing/
session.rs

1use crate::{TestApp, TestResponse};
2use axum::{
3    body::{to_bytes, Body},
4    http::{header, HeaderMap, HeaderName, HeaderValue, Method, Request},
5};
6use capy_core::{AppError, Result};
7use serde::Serialize;
8use std::{
9    net::SocketAddr,
10    time::{SystemTime, UNIX_EPOCH},
11};
12use tower::ServiceExt;
13
14struct StoredCookie {
15    cookie: cookie::Cookie<'static>,
16    host: String,
17    expires: Option<i64>,
18}
19
20/// An independent single-origin HTTP session using real auth and CSRF routes.
21/// Cookies honor origin, path, expiry and Secure; this is not a full browser or CORS emulator.
22/// Secrets are never included in this type's Debug output.
23pub struct TestSession {
24    app: TestApp,
25    cookies: Vec<StoredCookie>,
26    headers: HeaderMap,
27    peer: SocketAddr,
28    origin: url::Url,
29}
30
31impl std::fmt::Debug for TestSession {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.debug_struct("TestSession")
34            .field("peer", &self.peer)
35            .finish_non_exhaustive()
36    }
37}
38
39impl TestSession {
40    pub(crate) fn new(app: TestApp) -> Self {
41        let peer = app.peer;
42        Self {
43            app,
44            cookies: Vec::new(),
45            headers: HeaderMap::new(),
46            peer,
47            origin: url::Url::parse("http://localhost").expect("static origin"),
48        }
49    }
50
51    /// Set the browser origin before making requests; HTTPS enables Secure cookies.
52    /// Only same-origin relative paths are accepted by requests.
53    pub fn origin(mut self, origin: &str) -> Result<Self> {
54        let url = url::Url::parse(origin)
55            .map_err(|_| AppError::Configuration("Invalid test session origin.".into()))?;
56        if !matches!(url.scheme(), "http" | "https")
57            || url.host_str().is_none()
58            || !url.username().is_empty()
59            || url.password().is_some()
60            || url.path() != "/"
61            || url.query().is_some()
62            || url.fragment().is_some()
63        {
64            return Err(AppError::Configuration("Test session origin must be an HTTP(S) origin without credentials, path, query or fragment.".into()));
65        }
66        self.origin = url;
67        Ok(self)
68    }
69
70    /// Set deterministic peer identity for both CSRF bootstrap and application requests.
71    pub fn peer_addr(mut self, peer: SocketAddr) -> Self {
72        self.peer = peer;
73        self
74    }
75
76    /// Add a default request header, including sanitized proxy identity for proxy tests.
77    pub fn header(mut self, name: &str, value: &str) -> Self {
78        self.headers.insert(
79            name.parse::<HeaderName>().expect("valid test header name"),
80            value.parse().expect("valid test header value"),
81        );
82        self
83    }
84
85    /// Build a request; unsafe methods automatically obtain a fresh CSRF token.
86    pub fn request(&mut self, method: Method, path: &str) -> SessionRequest<'_> {
87        SessionRequest {
88            session: self,
89            method,
90            path: path.into(),
91            headers: HeaderMap::new(),
92            body: Vec::new(),
93            csrf: true,
94        }
95    }
96    /// GET with session cookies.
97    pub fn get(&mut self, path: &str) -> SessionRequest<'_> {
98        self.request(Method::GET, path)
99    }
100    /// POST with automatic CSRF.
101    pub fn post(&mut self, path: &str) -> SessionRequest<'_> {
102        self.request(Method::POST, path)
103    }
104    /// PUT with automatic CSRF.
105    pub fn put(&mut self, path: &str) -> SessionRequest<'_> {
106        self.request(Method::PUT, path)
107    }
108    /// PATCH with automatic CSRF.
109    pub fn patch(&mut self, path: &str) -> SessionRequest<'_> {
110        self.request(Method::PATCH, path)
111    }
112    /// DELETE with automatic CSRF.
113    pub fn delete(&mut self, path: &str) -> SessionRequest<'_> {
114        self.request(Method::DELETE, path)
115    }
116
117    /// Authenticate through the real endpoint; returns errors as ordinary HTTP responses.
118    pub async fn login(&mut self, email: &str, password: &str) -> Result<TestResponse> {
119        self.post("/api/auth/login")
120            .json(serde_json::json!({"email": email, "password": password}))
121            .send()
122            .await
123    }
124
125    /// Revoke the current server-side session through the real logout endpoint.
126    pub async fn logout(&mut self) -> Result<TestResponse> {
127        self.post("/api/auth/logout").send().await
128    }
129
130    async fn send_raw(
131        &mut self,
132        method: Method,
133        path: &str,
134        mut headers: HeaderMap,
135        body: Vec<u8>,
136    ) -> Result<TestResponse> {
137        if !path.starts_with('/')
138            || path.starts_with("//")
139            || path.contains('\\')
140            || path.contains('#')
141        {
142            return Err(AppError::Configuration(
143                "Test session requests require a same-origin absolute path without a fragment."
144                    .into(),
145            ));
146        }
147        let uri: axum::http::Uri = path
148            .parse()
149            .map_err(|_| AppError::Configuration("Invalid test request path.".into()))?;
150        if uri.scheme().is_some() || uri.authority().is_some() {
151            return Err(AppError::Configuration(
152                "Test session requests must stay on the configured origin.".into(),
153            ));
154        }
155        for (name, value) in &self.headers {
156            headers.entry(name).or_insert(value.clone());
157        }
158        headers
159            .entry("sec-fetch-site")
160            .or_insert(HeaderValue::from_static("same-origin"));
161        let host = self.origin.host_str().expect("validated origin");
162        let now = now();
163        self.cookies
164            .retain(|c| c.expires.is_none_or(|expires| expires > now));
165        let cookie_header = self
166            .cookies
167            .iter()
168            .filter(|stored| {
169                let cookie_path = stored.cookie.path().unwrap_or("/");
170                let matches_path = uri.path() == cookie_path
171                    || (uri.path().starts_with(cookie_path)
172                        && (cookie_path.ends_with('/')
173                            || uri.path().as_bytes().get(cookie_path.len()) == Some(&b'/')));
174                stored.host == host
175                    && matches_path
176                    && (!stored.cookie.secure().unwrap_or(false) || self.origin.scheme() == "https")
177            })
178            .map(|c| format!("{}={}", c.cookie.name(), c.cookie.value()))
179            .collect::<Vec<_>>()
180            .join("; ");
181        if !cookie_header.is_empty() && !headers.contains_key(header::COOKIE) {
182            let mut value = HeaderValue::from_str(&cookie_header).map_err(|_| {
183                AppError::Configuration("Invalid server-issued test cookie.".into())
184            })?;
185            value.set_sensitive(true);
186            headers.insert(header::COOKIE, value);
187        }
188        let mut request = Request::builder()
189            .method(method)
190            .uri(uri)
191            .extension(axum::extract::ConnectInfo(self.peer))
192            .body(Body::from(body))
193            .map_err(|_| AppError::Configuration("Invalid test request.".into()))?;
194        *request.headers_mut() = headers;
195        let response = self
196            .app
197            .router
198            .clone()
199            .oneshot(request)
200            .await
201            .expect("Axum router is infallible");
202        let (parts, body) = response.into_parts();
203        for value in parts.headers.get_all(header::SET_COOKIE) {
204            let Some(mut cookie) = value
205                .to_str()
206                .ok()
207                .and_then(|v| cookie::Cookie::parse(v.to_owned()).ok())
208            else {
209                continue;
210            };
211            if cookie
212                .domain()
213                .is_some_and(|domain| !domain.eq_ignore_ascii_case(host))
214            {
215                continue;
216            }
217            if cookie.secure().unwrap_or(false) && self.origin.scheme() != "https" {
218                continue;
219            }
220            if cookie.path().is_none() {
221                let path = path.split('?').next().unwrap_or("/");
222                let default_path = path
223                    .rsplit_once('/')
224                    .map(|(parent, _)| parent)
225                    .filter(|p| !p.is_empty())
226                    .unwrap_or("/");
227                cookie.set_path(default_path.to_owned());
228            }
229            self.cookies.retain(|stored| {
230                !(stored.host == host
231                    && stored.cookie.name() == cookie.name()
232                    && stored.cookie.path() == cookie.path())
233            });
234            let expires = cookie
235                .max_age()
236                .map(|age| now.saturating_add(age.whole_seconds()))
237                .or_else(|| cookie.expires_datetime().map(|date| date.unix_timestamp()));
238            if expires.is_none_or(|expires| expires > now) {
239                self.cookies.push(StoredCookie {
240                    cookie: cookie.into_owned(),
241                    host: host.into(),
242                    expires,
243                });
244            }
245        }
246        Ok(TestResponse {
247            status: parts.status,
248            headers: parts.headers,
249            body: to_bytes(body, 16 * 1024 * 1024).await.map_err(|_| {
250                AppError::Configuration("Test response exceeds 16 MiB or cannot be read.".into())
251            })?,
252        })
253    }
254}
255
256fn now() -> i64 {
257    SystemTime::now()
258        .duration_since(UNIX_EPOCH)
259        .unwrap_or_default()
260        .as_secs() as i64
261}
262
263/// A session request borrowing the cookie jar until its response is received.
264pub struct SessionRequest<'a> {
265    session: &'a mut TestSession,
266    method: Method,
267    path: String,
268    headers: HeaderMap,
269    body: Vec<u8>,
270    csrf: bool,
271}
272
273impl SessionRequest<'_> {
274    /// Serialize the request and set JSON content type.
275    pub fn json(mut self, value: impl Serialize) -> Self {
276        self.body = serde_json::to_vec(&value).expect("test JSON must serialize");
277        self.headers.insert(
278            header::CONTENT_TYPE,
279            HeaderValue::from_static("application/json"),
280        );
281        self
282    }
283    /// Add a request-specific header, overriding a session default.
284    pub fn header(mut self, name: &str, value: &str) -> Self {
285        self.headers.insert(
286            name.parse::<HeaderName>().expect("valid test header name"),
287            value.parse().expect("valid test header value"),
288        );
289        self
290    }
291    /// Deliberately omit automatic CSRF for rejection tests. Server checks remain enabled.
292    pub fn without_csrf(mut self) -> Self {
293        self.csrf = false;
294        self
295    }
296    /// Supply raw body bytes, including malformed JSON for rejection tests.
297    pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
298        self.body = body.into();
299        self
300    }
301
302    /// Send through the actual router, collecting cookies and refreshing CSRF after rotation.
303    /// Bootstrap failures return their original HTTP response and do not submit the mutation.
304    pub async fn send(mut self) -> Result<TestResponse> {
305        if self.csrf
306            && self.session.app.csrf
307            && !matches!(self.method, Method::GET | Method::HEAD | Method::OPTIONS)
308        {
309            let mut headers = self.headers.clone();
310            headers.insert("x-capy-csrf", HeaderValue::from_static("1"));
311            let bootstrap = self
312                .session
313                .send_raw(Method::GET, "/api/auth/csrf", headers, Vec::new())
314                .await?;
315            if !bootstrap.status.is_success() {
316                return Ok(bootstrap);
317            }
318            let data: serde_json::Value =
319                serde_json::from_slice(&bootstrap.body).map_err(|_| {
320                    AppError::Configuration("CSRF bootstrap did not return JSON.".into())
321                })?;
322            let token = data["csrf_token"].as_str().ok_or_else(|| {
323                AppError::Configuration("CSRF bootstrap did not return a token.".into())
324            })?;
325            let mut value = HeaderValue::from_str(token).map_err(|_| {
326                AppError::Configuration("CSRF bootstrap returned an invalid token.".into())
327            })?;
328            value.set_sensitive(true);
329            self.headers.entry("x-csrf-token").or_insert(value);
330        }
331        self.session
332            .send_raw(self.method, &self.path, self.headers, self.body)
333            .await
334    }
335}