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.clone())
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            method,
248            path: path.into(),
249            contracts: self.app.contracts.clone(),
250            status: parts.status,
251            headers: parts.headers,
252            body: to_bytes(body, 16 * 1024 * 1024).await.map_err(|_| {
253                AppError::Configuration("Test response exceeds 16 MiB or cannot be read.".into())
254            })?,
255        })
256    }
257}
258
259fn now() -> i64 {
260    SystemTime::now()
261        .duration_since(UNIX_EPOCH)
262        .unwrap_or_default()
263        .as_secs() as i64
264}
265
266/// A session request borrowing the cookie jar until its response is received.
267pub struct SessionRequest<'a> {
268    session: &'a mut TestSession,
269    method: Method,
270    path: String,
271    headers: HeaderMap,
272    body: Vec<u8>,
273    csrf: bool,
274}
275
276impl SessionRequest<'_> {
277    /// Serialize the request and set JSON content type.
278    pub fn json(mut self, value: impl Serialize) -> Self {
279        self.body = serde_json::to_vec(&value).expect("test JSON must serialize");
280        self.headers.insert(
281            header::CONTENT_TYPE,
282            HeaderValue::from_static("application/json"),
283        );
284        self
285    }
286    /// Add a request-specific header, overriding a session default.
287    pub fn header(mut self, name: &str, value: &str) -> Self {
288        self.headers.insert(
289            name.parse::<HeaderName>().expect("valid test header name"),
290            value.parse().expect("valid test header value"),
291        );
292        self
293    }
294    /// Deliberately omit automatic CSRF for rejection tests. Server checks remain enabled.
295    pub fn without_csrf(mut self) -> Self {
296        self.csrf = false;
297        self
298    }
299    /// Supply raw body bytes, including malformed JSON for rejection tests.
300    pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
301        self.body = body.into();
302        self
303    }
304
305    /// Send through the actual router, collecting cookies and refreshing CSRF after rotation.
306    /// Bootstrap failures return their original HTTP response and do not submit the mutation.
307    pub async fn send(mut self) -> Result<TestResponse> {
308        if self.csrf
309            && self.session.app.csrf
310            && !matches!(self.method, Method::GET | Method::HEAD | Method::OPTIONS)
311        {
312            let mut headers = self.headers.clone();
313            headers.insert("x-capy-csrf", HeaderValue::from_static("1"));
314            let bootstrap = self
315                .session
316                .send_raw(Method::GET, "/api/auth/csrf", headers, Vec::new())
317                .await?;
318            if !bootstrap.status.is_success() {
319                return Ok(bootstrap);
320            }
321            let data: serde_json::Value =
322                serde_json::from_slice(&bootstrap.body).map_err(|_| {
323                    AppError::Configuration("CSRF bootstrap did not return JSON.".into())
324                })?;
325            let token = data["csrf_token"].as_str().ok_or_else(|| {
326                AppError::Configuration("CSRF bootstrap did not return a token.".into())
327            })?;
328            let mut value = HeaderValue::from_str(token).map_err(|_| {
329                AppError::Configuration("CSRF bootstrap returned an invalid token.".into())
330            })?;
331            value.set_sensitive(true);
332            self.headers.entry("x-csrf-token").or_insert(value);
333        }
334        self.session
335            .send_raw(self.method, &self.path, self.headers, self.body)
336            .await
337    }
338}