server.rs (11658B)
1 /* 2 This file is part of TALER 3 Copyright (C) 2025, 2026 Taler Systems SA 4 5 TALER is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 TALER is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 use std::{fmt::Debug, pin::Pin}; 18 19 use axum::{ 20 Router, 21 body::{Body, Bytes}, 22 extract::{OriginalUri, Query, Request, State}, 23 http::{ 24 HeaderMap, HeaderValue, Method, StatusCode, Uri, 25 header::{self, AUTHORIZATION, AsHeaderName, IntoHeaderName}, 26 uri::PathAndQuery, 27 }, 28 middleware::{self}, 29 }; 30 use http_body_util::BodyExt as _; 31 use serde::{Deserialize, Serialize, de::DeserializeOwned}; 32 use taler_api::error::GanaErrorCode; 33 use taler_common::{api::ErrorDetail, encoding::base64, error_code::ErrorCode}; 34 use tower::ServiceExt as _; 35 use tracing::warn; 36 use url::Url; 37 use zlib_rs::{DeflateConfig, ReturnCode, compress_bound, compress_slice}; 38 39 pub trait TestServer { 40 fn prefix(&self, prefix: &'static str) -> Self; 41 fn suffix(&self, suffix: &'static str) -> Self; 42 43 fn request(&self, method: Method, path: impl AsRef<str>) -> TestRequest; 44 45 fn get(&self, path: impl AsRef<str>) -> TestRequest { 46 self.request(Method::GET, path) 47 } 48 49 fn post(&self, path: impl AsRef<str>) -> TestRequest { 50 self.request(Method::POST, path) 51 } 52 53 fn delete(&self, path: impl AsRef<str>) -> TestRequest { 54 self.request(Method::DELETE, path) 55 } 56 } 57 58 impl TestServer for Router { 59 fn prefix(&self, prefix: &'static str) -> Self { 60 Router::new() 61 .fallback_service(self.clone().into_service()) 62 .layer(middleware::map_request_with_state( 63 prefix, 64 async |State(prefix): State<&'static str>, mut req: Request| { 65 let uri = req.uri().clone(); 66 let mut parts = uri.into_parts(); 67 68 let path_and_query = parts.path_and_query.unwrap(); 69 let current_path = path_and_query.path(); 70 71 let new_path_and_query = match path_and_query.query() { 72 Some(query) => format!("{prefix}{current_path}?{query}"), 73 None => format!("{prefix}{current_path}"), 74 }; 75 76 let new_pq = PathAndQuery::from_maybe_shared(new_path_and_query).unwrap(); 77 parts.path_and_query = Some(new_pq); 78 *req.uri_mut() = Uri::from_parts(parts).unwrap(); 79 req.extensions_mut().remove::<OriginalUri>(); 80 req 81 }, 82 )) 83 } 84 85 fn suffix(&self, suffix: &'static str) -> Self { 86 Router::new() 87 .fallback_service(self.clone().into_service()) 88 .layer(middleware::map_request_with_state( 89 suffix.trim_start_matches('/'), 90 async |State(suffix): State<&'static str>, mut req: Request| { 91 let uri = req.uri().clone(); 92 let mut parts = uri.into_parts(); 93 94 let path_and_query = parts.path_and_query.unwrap(); 95 let current_path = path_and_query.path(); 96 97 let new_path_and_query = match path_and_query.query() { 98 Some(query) => format!("{current_path}{suffix}?{query}"), 99 None => format!("{current_path}{suffix}"), 100 }; 101 let new_pq = PathAndQuery::from_maybe_shared(new_path_and_query).unwrap(); 102 parts.path_and_query = Some(new_pq); 103 *req.uri_mut() = Uri::from_parts(parts).unwrap(); 104 req.extensions_mut().remove::<OriginalUri>(); 105 req 106 }, 107 )) 108 } 109 110 fn request(&self, method: Method, path: impl AsRef<str>) -> TestRequest { 111 let url = format!("https://example{}", path.as_ref()); 112 TestRequest { 113 router: self.clone(), 114 method, 115 url: url.parse().unwrap(), 116 body: None, 117 headers: HeaderMap::new(), 118 } 119 } 120 } 121 122 pub struct TestRequest { 123 router: Router, 124 method: Method, 125 pub url: Url, 126 body: Option<Bytes>, 127 headers: HeaderMap, 128 } 129 130 impl TestRequest { 131 #[track_caller] 132 pub fn query<T: Serialize>(mut self, k: &str, v: T) -> Self { 133 let mut pairs = self.url.query_pairs_mut(); 134 let serializer = serde_urlencoded::Serializer::new(&mut pairs); 135 [(k, v)].serialize(serializer).unwrap(); 136 drop(pairs); 137 self 138 } 139 140 pub fn json<T: Serialize>(mut self, body: T) -> Self { 141 assert!(self.body.is_none()); 142 let bytes = serde_json::to_vec(&body).unwrap(); 143 self.body = Some(bytes.into()); 144 self.headers.insert( 145 header::CONTENT_TYPE, 146 HeaderValue::from_static("application/json"), 147 ); 148 self 149 } 150 151 pub fn raw_json(mut self, raw: Bytes) -> Self { 152 assert!(self.body.is_none()); 153 self.body = Some(raw); 154 self.headers.insert( 155 header::CONTENT_TYPE, 156 HeaderValue::from_static("application/json"), 157 ); 158 self 159 } 160 161 pub fn deflate(mut self) -> Self { 162 let body = self.body.unwrap(); 163 let mut compressed = vec![0; compress_bound(body.len())]; 164 let (output, code) = compress_slice(&mut compressed, &body, DeflateConfig::best_speed()); 165 assert_eq!(code, ReturnCode::Ok); 166 let len = output.len(); 167 compressed.truncate(len); 168 self.body = Some(compressed.into()); 169 self.headers.insert( 170 header::CONTENT_ENCODING, 171 HeaderValue::from_static("deflate"), 172 ); 173 self 174 } 175 176 pub fn remove(mut self, k: impl AsHeaderName) -> Self { 177 self.headers.remove(k); 178 self 179 } 180 181 pub fn header<V>(mut self, k: impl IntoHeaderName, v: V) -> Self 182 where 183 V: TryInto<HeaderValue>, 184 V::Error: Debug, 185 { 186 self.headers.insert(k, v.try_into().unwrap()); 187 self 188 } 189 190 pub fn basic_auth(self, username: &str, password: &str) -> Self { 191 self.header( 192 AUTHORIZATION, 193 format!( 194 "Basic {}", 195 base64::fmt(format!("{username}:{password}").as_bytes()) 196 ), 197 ) 198 } 199 200 async fn send(self) -> TestResponse { 201 let Self { 202 router, 203 method, 204 url, 205 body: req_body, 206 headers: req_headers, 207 } = self; 208 let uri = Uri::try_from(url.as_str()).unwrap(); 209 let mut req = axum::http::request::Builder::new() 210 .method(&method) 211 .uri(&uri) 212 .body(req_body.clone().map(Body::from).unwrap_or_else(Body::empty)) 213 .unwrap(); 214 *req.headers_mut() = req_headers.clone(); 215 let resp = router.clone().oneshot(req).await.unwrap(); 216 let (parts, body) = resp.into_parts(); 217 let bytes = body.collect().await.unwrap(); 218 TestResponse { 219 router, 220 req_body: req_body.unwrap_or_default(), 221 req_headers, 222 res_body: bytes.to_bytes(), 223 method, 224 status: parts.status, 225 uri, 226 } 227 } 228 } 229 230 impl IntoFuture for TestRequest { 231 type Output = TestResponse; 232 type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>; 233 234 fn into_future(self) -> Self::IntoFuture { 235 Box::pin(self.send()) 236 } 237 } 238 239 #[must_use] 240 pub struct TestResponse { 241 pub router: Router, 242 pub req_headers: HeaderMap, 243 pub req_body: Bytes, 244 res_body: Bytes, 245 pub method: Method, 246 pub uri: Uri, 247 pub status: StatusCode, 248 } 249 250 impl TestResponse { 251 #[track_caller] 252 pub fn is_implemented(&self) -> bool { 253 if self.status == StatusCode::NOT_IMPLEMENTED { 254 let err: ErrorDetail = self.json_parse(); 255 warn!( 256 "{} is not implemented: {}", 257 self.uri.path(), 258 err.hint.unwrap_or_default() 259 ); 260 false 261 } else { 262 true 263 } 264 } 265 266 #[track_caller] 267 pub fn json_parse<'de, T: Deserialize<'de>>(&'de self) -> T { 268 let Self { 269 status, 270 res_body: bytes, 271 method, 272 uri, 273 .. 274 } = self; 275 match serde_json::from_slice(bytes) { 276 Ok(body) => body, 277 Err(err) => panic!( 278 "{method} {uri} {status} invalid JSON body: {err}\n{}", 279 String::from_utf8_lossy(bytes) 280 ), 281 } 282 } 283 284 #[track_caller] 285 pub fn assert_status(&self, expected: StatusCode) { 286 let Self { 287 status, 288 res_body: bytes, 289 method, 290 uri, 291 .. 292 } = self; 293 if expected != *status { 294 if status.is_success() || bytes.is_empty() { 295 panic!("{method} {uri} expected {expected} got {status}"); 296 } else { 297 let err: ErrorDetail = self.json_parse(); 298 let description = err.hint.unwrap_or_default(); 299 if let Ok(nb) = u16::try_from(err.code) 300 && let Ok(code) = ErrorCode::try_from(nb) 301 { 302 panic!( 303 "{method} {uri} expected {expected} got {status}: {} {description}", 304 code.name() 305 ); 306 } else { 307 panic!( 308 "{method} {uri} expected {expected} got {status}: {} {description}", 309 err.code 310 ); 311 } 312 } 313 } 314 } 315 316 #[track_caller] 317 pub fn assert_ok_json<'de, T: Deserialize<'de>>(&'de self) -> T { 318 self.assert_ok(); 319 self.json_parse() 320 } 321 322 #[track_caller] 323 pub fn assert_accepted_json<'de, T: Deserialize<'de>>(&'de self) -> T { 324 self.assert_accepted(); 325 self.json_parse() 326 } 327 328 #[track_caller] 329 pub fn assert_ok(&self) { 330 self.assert_status(StatusCode::OK); 331 } 332 333 #[track_caller] 334 pub fn assert_accepted(&self) { 335 self.assert_status(StatusCode::ACCEPTED); 336 } 337 338 #[track_caller] 339 pub fn assert_no_content(&self) { 340 self.assert_status(StatusCode::NO_CONTENT); 341 } 342 343 #[track_caller] 344 pub fn assert_not_implemented(&self) { 345 self.assert_status(StatusCode::NOT_IMPLEMENTED); 346 } 347 348 #[track_caller] 349 pub fn assert_error(&self, error_code: impl GanaErrorCode) { 350 let status = StatusCode::from_u16(error_code.status_code()).unwrap(); 351 self.assert_error_status(error_code, status); 352 } 353 354 #[track_caller] 355 pub fn assert_bad_request(&self) { 356 self.assert_error(ErrorCode::GENERIC_JSON_INVALID); 357 } 358 359 #[track_caller] 360 pub fn assert_error_status(&self, error_code: impl GanaErrorCode, status: StatusCode) { 361 self.assert_status(status); 362 let err: ErrorDetail = self.json_parse(); 363 assert_eq!(error_code.value(), err.code); 364 } 365 366 #[track_caller] 367 pub fn query<T: DeserializeOwned>(&self) -> T { 368 Query::try_from_uri(&self.uri).unwrap().0 369 } 370 }