harness.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. //! Shared E2E harness for the task-43 conformance + abuse suites.
  2. //!
  3. //! Every test boots the REAL production router ([`d_oauth::routes::build_router`],
  4. //! unmodified) over a REAL loopback TCP socket, against the REAL shared
  5. //! Postgres + Redis from `compose.test.yaml`
  6. //! (`docker compose -f compose.test.yaml up -d`) with the shipped migrations
  7. //! applied. Nothing is mocked; every assertion reads an HTTP
  8. //! status/header/body observed through `reqwest`.
  9. //!
  10. //! TLS termination is intentionally NOT re-proven here: the task-41
  11. //! `bootstrap` suite already drives mutual-TLS through the production accept
  12. //! loop. The router under test is byte-identical on either listener.
  13. //!
  14. //! Coverage split (plan requirement): the `oauth2` crate builds PKCE material,
  15. //! authorization URLs, and baseline token-request shapes; every extension
  16. //! (DPoP proofs, PAR pushes, device flow, introspection, revocation) is
  17. //! hand-rolled `reqwest` so the suite never depends on crate support the
  18. //! extensions do not have.
  19. //!
  20. //! Isolation: each `World` migrates a freshly created database on the shared
  21. //! server and uses unique Redis key prefixes, so parallel tests never share
  22. //! state (and never FLUSH shared state).
  23. //!
  24. //! [`Store`]: d_oauth::store::Store
  25. use std::net::SocketAddr;
  26. use d_oauth::{
  27. config::{Config, ConfigError},
  28. crypto::secret::{Argon2Params, hash_secret},
  29. db::{NewClient, TokenEndpointAuthMethod, client_repo, redirect_repo, scope_repo},
  30. protocol::token::{ClientKind, MintRequest, MintedTokens, SenderProof, TokenService},
  31. routes::build_router,
  32. state::{AppState, RedisConn, StateError},
  33. store::Store,
  34. };
  35. // `tests/common/mod.rs` is the single definition of the shared-service
  36. // helpers (`pg_server_url`, `redis_url`, `unique_prefixes`); this `#[path]`
  37. // include (relative to `tests/e2e/`) keeps the e2e harness on the same
  38. // contract without duplicating it.
  39. #[path = "../common/mod.rs"]
  40. mod common;
  41. use common::{pg_server_url, redis_url, unique_prefixes};
  42. use sqlx::{Executor as _, postgres::PgPoolOptions};
  43. /// Placeholder guard kept so [`World`]'s shape is unchanged.
  44. ///
  45. /// With shared external services there is no per-test container to guard;
  46. /// per-World isolation comes from a fresh database plus unique Redis key
  47. /// prefixes instead. The fields exist only so every existing caller keeps
  48. /// compiling unchanged.
  49. pub struct E2EGuard {
  50. /// Unused; present only to preserve the struct shape.
  51. _placeholder: (),
  52. }
  53. /// Argon2id work factor for seeded client secrets (fast: test-only).
  54. const SEED_MEM_KIB: u32 = 8;
  55. /// Hint shown when the shared test services are unreachable.
  56. const COMPOSE_HINT: &str = "run `docker compose -f compose.test.yaml up -d`";
  57. /// Harness failure (no `unwrap`/`expect`/`panic` under the deny lints).
  58. #[derive(Debug, thiserror::Error)]
  59. pub enum TestError {
  60. /// A database operation failed.
  61. #[error("database error: {0}")]
  62. Database(#[from] sqlx::Error),
  63. /// A Redis operation failed.
  64. #[error("redis error: {0}")]
  65. Redis(#[from] redis::RedisError),
  66. /// An I/O operation failed.
  67. #[error("io error: {0}")]
  68. Io(#[from] std::io::Error),
  69. /// An HTTP operation failed.
  70. #[error("http error: {0}")]
  71. Http(#[from] reqwest::Error),
  72. /// Configuration failed to validate.
  73. #[error("config error: {0}")]
  74. Config(#[from] ConfigError),
  75. /// Application state failed to connect.
  76. #[error("state error: {0}")]
  77. State(#[from] StateError),
  78. /// A test step observed an unexpected value.
  79. #[error("failed: {0}")]
  80. Failed(String),
  81. }
  82. /// Fail one test step with a message.
  83. pub fn fail(message: impl Into<String>) -> TestError {
  84. TestError::Failed(message.into())
  85. }
  86. /// Assert `cond`, failing the test with `message` otherwise.
  87. pub fn ensure(cond: bool, message: impl Into<String>) -> Result<(), TestError> {
  88. if cond { Ok(()) } else { Err(fail(message)) }
  89. }
  90. /// Live world for one E2E test: shared-service handles, migrated DB, connected
  91. /// state, the production router on a loopback socket, and a redirect-free
  92. /// `reqwest` client pointed at it.
  93. pub struct World {
  94. /// Placeholder (no per-test container under shared services).
  95. _postgres: E2EGuard,
  96. /// Placeholder (no per-test container under shared services).
  97. _redis: E2EGuard,
  98. /// Migrated Postgres pool (same database the router serves).
  99. pub pool: sqlx::PgPool,
  100. /// Connected application state (same state the router serves).
  101. pub state: AppState,
  102. /// Key layout + durability knobs matching the router's store.
  103. pub store: Store,
  104. /// Token minting primitive (setup only: issues fixture tokens).
  105. pub service: TokenService,
  106. /// Redirect-free HTTP client for observing exact statuses/locations.
  107. pub client: reqwest::Client,
  108. /// Base URL of the live router (e.g. `http://127.0.0.1:43111`).
  109. pub base: String,
  110. /// Serving task (aborted on drop so no test leaks a listener).
  111. _server: tokio::task::JoinHandle<()>,
  112. }
  113. impl Drop for World {
  114. fn drop(&mut self) {
  115. self._server.abort();
  116. }
  117. }
  118. impl World {
  119. /// Start one world: fresh DB + unique Redis prefixes on the shared
  120. /// services, migrations, connected state, live router.
  121. ///
  122. /// `rate_limit` is the `rate_limit` table of the config fixture, so the
  123. /// abuse suite can pin tiny budgets while conformance runs wide open.
  124. pub async fn start(rate_limit: serde_json::Value) -> Result<Self, TestError> {
  125. let pg_url = fresh_db_url().await?;
  126. let redis_url = redis_url();
  127. let (token_prefix, ratelimit_prefix) = unique_prefixes();
  128. let pool = PgPoolOptions::new()
  129. .max_connections(4)
  130. .connect(&pg_url)
  131. .await
  132. .map_err(|error| {
  133. fail(format!(
  134. "cannot reach shared test Postgres at {pg_url}: {error}; {COMPOSE_HINT}"
  135. ))
  136. })?;
  137. d_oauth::state::MIGRATOR
  138. .run(&pool)
  139. .await
  140. .map_err(|error| TestError::Failed(format!("migrations failed to apply: {error}")))?;
  141. let fixture = serde_json::json!({
  142. "issuer": "https://auth.example.test",
  143. "environment": "development",
  144. "bind_addr": "127.0.0.1:0",
  145. "health_addr": "127.0.0.1:0",
  146. "tls": {"cert_path": "/tmp/e2e-cert.pem", "key_path": "/tmp/e2e-key.pem"},
  147. "database": {"url": pg_url},
  148. "redis": {
  149. "url": redis_url,
  150. "durability": "waitaof",
  151. "token_key_prefix": token_prefix,
  152. "ratelimit_key_prefix": ratelimit_prefix,
  153. },
  154. "token_pepper": "e2e-test-pepper-0123456789abcdef",
  155. "totp_encryption_key": "e2e-test-totp-key-0123456789abcdef",
  156. "rate_limit": rate_limit,
  157. "cors_allowed_origins": [],
  158. });
  159. let config =
  160. Config::from_source(::config::Config::try_from(&fixture).map_err(ConfigError::from)?)?;
  161. let state = AppState::connect(std::sync::Arc::new(config))
  162. .await
  163. .map_err(|error| {
  164. fail(format!(
  165. "cannot connect shared test services ({COMPOSE_HINT}): {error}"
  166. ))
  167. })?;
  168. let store = Store::from_config(&state.config.redis);
  169. let service = TokenService::new(&state.config.ttl, &state.keys)
  170. .map_err(|error| fail(format!("token service failed: {error}")))?;
  171. let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
  172. let port = listener.local_addr()?.port();
  173. let router = build_router(state.clone());
  174. let server = tokio::spawn(async move {
  175. let _ = axum::serve(
  176. listener,
  177. router.into_make_service_with_connect_info::<SocketAddr>(),
  178. )
  179. .await;
  180. });
  181. let client = reqwest::Client::builder()
  182. .redirect(reqwest::redirect::Policy::none())
  183. .timeout(std::time::Duration::from_secs(10))
  184. .build()?;
  185. Ok(Self {
  186. _postgres: E2EGuard { _placeholder: () },
  187. _redis: E2EGuard { _placeholder: () },
  188. pool,
  189. state,
  190. store,
  191. service,
  192. client,
  193. base: format!("http://127.0.0.1:{port}"),
  194. _server: server,
  195. })
  196. }
  197. /// `POST {path}` with a form body, optional Basic auth, and extra headers.
  198. pub async fn post_form(
  199. &self,
  200. path: &str,
  201. params: &[(&str, &str)],
  202. basic: Option<(&str, &str)>,
  203. headers: &[(&str, &str)],
  204. ) -> Result<(reqwest::StatusCode, reqwest::header::HeaderMap, String), TestError> {
  205. let mut request = self.client.post(format!("{}{path}", self.base));
  206. if let Some((user, pass)) = basic {
  207. request = request.basic_auth(user, Some(pass));
  208. }
  209. for (name, value) in headers {
  210. request = request.header(*name, *value);
  211. }
  212. let response = request.form(params).send().await?;
  213. let status = response.status();
  214. let response_headers = response.headers().clone();
  215. let body = response.text().await?;
  216. Ok((status, response_headers, body))
  217. }
  218. /// `GET {path}` with extra headers (query string included in `path`).
  219. pub async fn get(
  220. &self,
  221. path: &str,
  222. headers: &[(&str, &str)],
  223. ) -> Result<(reqwest::StatusCode, reqwest::header::HeaderMap, String), TestError> {
  224. let mut request = self.client.get(format!("{}{path}", self.base));
  225. for (name, value) in headers {
  226. request = request.header(*name, *value);
  227. }
  228. let response = request.send().await?;
  229. let status = response.status();
  230. let response_headers = response.headers().clone();
  231. let body = response.text().await?;
  232. Ok((status, response_headers, body))
  233. }
  234. /// Mint a fixture token pair through the REAL [`TokenService`] (setup, not
  235. /// behavior: every assertion still reads an HTTP response).
  236. pub async fn mint(
  237. &self,
  238. client_id: &str,
  239. scope: &str,
  240. kind: ClientKind,
  241. jkt: Option<&str>,
  242. ) -> Result<MintedTokens, TestError> {
  243. let mut conn: RedisConn = self.state.redis.clone();
  244. let minted = self
  245. .service
  246. .mint(
  247. &mut conn,
  248. &self.store,
  249. &MintRequest {
  250. client_id: client_id.to_owned(),
  251. client_kind: kind,
  252. subject: "e2e-subject".to_owned(),
  253. scope: scope.to_owned(),
  254. grant_id: uuid::Uuid::new_v4().to_string(),
  255. proof: SenderProof {
  256. dpop_jkt: jkt.map(str::to_owned),
  257. mtls_x5t_s256: None,
  258. },
  259. },
  260. time::OffsetDateTime::now_utc().unix_timestamp(),
  261. )
  262. .await
  263. .map_err(|error| fail(format!("fixture mint failed: {error}")))?;
  264. Ok(minted)
  265. }
  266. }
  267. /// Create a uniquely named database on the shared Postgres server and return
  268. /// a URL pointing at it (the caller connects and migrates).
  269. async fn fresh_db_url() -> Result<String, TestError> {
  270. let server = pg_server_url();
  271. let admin = PgPoolOptions::new()
  272. .max_connections(1)
  273. .connect(&server)
  274. .await
  275. .map_err(|error| {
  276. fail(format!(
  277. "cannot reach shared test Postgres at {server}: {error}; {COMPOSE_HINT}"
  278. ))
  279. })?;
  280. let name = format!("e2e_{}", uuid::Uuid::new_v4().simple());
  281. // `CREATE DATABASE` cannot take a bind parameter, and `Pool`'s `Executor`
  282. // requires a `'static` query, so leak this one tiny test-only string.
  283. let ddl: &'static str = Box::leak(format!("CREATE DATABASE \"{name}\"").into_boxed_str());
  284. let created = admin
  285. .execute(ddl)
  286. .await
  287. .map_err(|error| fail(format!("failed to create test database {name}: {error}")));
  288. admin.close().await;
  289. created?;
  290. Ok(server.replacen("/postgres?", &format!("/{name}?"), 1))
  291. }
  292. /// Default (wide-open) rate-limit table for conformance worlds.
  293. pub fn open_rate_limit() -> serde_json::Value {
  294. serde_json::json!({
  295. "enabled": true, "window_secs": 60,
  296. "per_ip": 100_000, "per_client": 100_000,
  297. "login_per_ip": 100_000, "token_per_client": 100_000,
  298. })
  299. }
  300. /// Seed one client row (secret hashed with the REAL Argon2id verifier path).
  301. pub async fn seed_client(
  302. pool: &sqlx::PgPool,
  303. client_id: &str,
  304. secret: Option<&str>,
  305. grants: &[&str],
  306. scope: &str,
  307. method: TokenEndpointAuthMethod,
  308. ) -> Result<(), TestError> {
  309. seed_client_bound(pool, client_id, secret, grants, scope, method, false).await
  310. }
  311. /// Seed one client row with an explicit DPoP-bound-access-tokens flag.
  312. pub async fn seed_client_bound(
  313. pool: &sqlx::PgPool,
  314. client_id: &str,
  315. secret: Option<&str>,
  316. grants: &[&str],
  317. scope: &str,
  318. method: TokenEndpointAuthMethod,
  319. dpop_bound: bool,
  320. ) -> Result<(), TestError> {
  321. let params =
  322. Argon2Params::new(SEED_MEM_KIB, 1, 1, 32).map_err(|error| fail(format!("argon2: {error}")))?;
  323. let secret_hash = secret
  324. .map(|value| hash_secret(value, &params))
  325. .transpose()
  326. .map_err(|error| fail(format!("hash: {error}")))?;
  327. let new = NewClient {
  328. id: uuid::Uuid::new_v4(),
  329. client_id: client_id.to_owned(),
  330. client_secret_hash: secret_hash,
  331. client_secret_expires_at: None,
  332. client_name: format!("{client_id} e2e"),
  333. grant_types: grants.iter().map(ToString::to_string).collect(),
  334. response_types: vec!["code".to_owned()],
  335. scope: scope.to_owned(),
  336. token_endpoint_auth_method: method.as_str().to_owned(),
  337. jwks: None,
  338. jwks_uri: None,
  339. tls_client_auth_subject_dn: None,
  340. tls_client_auth_cert_thumbprint: None,
  341. request_uris: None,
  342. contacts: None,
  343. software_id: None,
  344. dpop_bound_access_tokens: dpop_bound,
  345. registration_access_token_hash: None,
  346. };
  347. client_repo::insert(pool, &new).await?;
  348. Ok(())
  349. }
  350. /// Seed one catalog scope (enabled).
  351. pub async fn seed_scope(pool: &sqlx::PgPool, name: &str) -> Result<(), TestError> {
  352. scope_repo::upsert(pool, name, &format!("e2e scope {name}"))
  353. .await
  354. .map_err(|error| fail(format!("scope upsert failed: {error}")))?;
  355. Ok(())
  356. }
  357. /// Register a redirect URI in the catalog and attach it to a client.
  358. pub async fn attach_redirect(
  359. pool: &sqlx::PgPool,
  360. client_id: &str,
  361. uri: &str,
  362. ) -> Result<(), TestError> {
  363. let row = redirect_repo::upsert(
  364. pool,
  365. uuid::Uuid::new_v4(),
  366. uri,
  367. redirect_repo::RedirectKind::Authorize,
  368. "e2e",
  369. None,
  370. )
  371. .await?;
  372. redirect_repo::attach(pool, client_id, row.id, None).await?;
  373. Ok(())
  374. }
  375. /// Decode a JSON body, failing the test on malformed content.
  376. pub fn json_body(body: &str) -> Result<serde_json::Value, TestError> {
  377. serde_json::from_str(body).map_err(|error| fail(format!("body is not JSON ({error}): {body}")))
  378. }