e2e_flow.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. //! `test(e2e_flow)` full-browser authorization-code flow over the live router.
  2. //!
  3. //! The existing e2e suites stop at `303 /login?request_id=` (or mint codes
  4. //! directly through [`d_oauth::protocol::code::CodeIssuer`]); no test drives
  5. //! the complete browser flow. These tests do: `GET /authorize` (RFC 6749
  6. //! §4.1.1 + OAuth 2.1 draft §4.1.3) → `GET /login` → `POST /login` (password +
  7. //! TOTP) → `GET /consent` → `POST /consent` → code on the registered redirect
  8. //! (RFC 9700 §4.5.3, `code` + `state` + RFC 9207 `iss`) → `POST /token` with
  9. //! the PKCE verifier (RFC 7636 §4.5) → tokens.
  10. //!
  11. //! A public client is used so the flow needs no PAR/JAR (a confidential
  12. //! client with only plain query params is rejected with `invalid_request`).
  13. //! Public clients are DPoP-bound end to end: the SAME [`browser::DpopKey`]
  14. //! proves `GET /authorize` (its `jkt` is stashed in the pending-auth record)
  15. //! and `POST /token` (the redemption checks the proof `jkt` against the code's
  16. //! `cnf` binding), so one key spans the whole flow.
  17. //!
  18. //! The driver itself lives in [`browser`] so the CIMD, device, logout, and
  19. //! disabled-user suites reuse one implementation instead of copying it.
  20. #[allow(dead_code)]
  21. #[path = "e2e/harness.rs"]
  22. mod harness;
  23. #[path = "e2e/dpop.rs"]
  24. mod dpop;
  25. #[allow(dead_code)]
  26. #[path = "e2e/browser.rs"]
  27. mod browser;
  28. use browser::{
  29. CLIENT_ID, INVALID_CREDENTIALS, REDIRECT_URI, SCOPE, SESSION_COOKIE, STATE, begin_browser,
  30. cookie_value, get_consent, has_query_key, hidden_input, location_of, post_consent, post_login,
  31. query_value, totp_now,
  32. };
  33. use harness::{TestError, World, ensure, json_body, open_rate_limit};
  34. /// Happy path: the full browser flow issues a code and redeems it for
  35. /// DPoP-bound tokens; the code is single-use (RFC 6749 §4.1.2: a second
  36. /// redemption is `invalid_grant`).
  37. #[tokio::test]
  38. async fn e2e_flow_browser_authorize_login_consent_token() -> Result<(), TestError> {
  39. let world = World::start(open_rate_limit()).await?;
  40. let browser = begin_browser(
  41. world,
  42. "flow-happy@example.test",
  43. "correct-horse-28-happy-path",
  44. )
  45. .await?;
  46. let code_2fa = totp_now(&browser.totp_secret).await?;
  47. let (status, headers, _) = post_login(&browser, &browser.password.clone(), &code_2fa).await?;
  48. ensure(
  49. status == reqwest::StatusCode::SEE_OTHER,
  50. format!("login must 303 to consent: {status}"),
  51. )?;
  52. let location = location_of(&headers)?;
  53. ensure(
  54. location == "/consent",
  55. format!("login must land on consent, got {location}"),
  56. )?;
  57. let session = cookie_value(&headers, SESSION_COOKIE)?;
  58. ensure(
  59. session != browser.presession,
  60. "login must rotate the session id",
  61. )?;
  62. let (status, _, body) = get_consent(&browser, &session).await?;
  63. ensure(
  64. status == reqwest::StatusCode::OK,
  65. format!("consent must render: {status} {body}"),
  66. )?;
  67. let bound = hidden_input(&body, "request_id")?;
  68. ensure(
  69. bound == browser.request_id,
  70. "consent must serve the bound authorization request",
  71. )?;
  72. let consent_csrf = hidden_input(&body, "csrf")?;
  73. let (status, headers, _) =
  74. post_consent(&browser, &session, &bound, &consent_csrf, "approve").await?;
  75. ensure(
  76. status == reqwest::StatusCode::SEE_OTHER,
  77. format!("consent approval must 303 to the redirect: {status}"),
  78. )?;
  79. let location = location_of(&headers)?;
  80. ensure(
  81. location.starts_with(REDIRECT_URI),
  82. format!("code must return to the registered redirect, got {location}"),
  83. )?;
  84. let code = query_value(&location, "code")?;
  85. ensure(
  86. query_value(&location, "state")? == STATE,
  87. "code redirect must echo state",
  88. )?;
  89. ensure(
  90. has_query_key(&location, "iss"),
  91. "code redirect must carry iss (RFC 9207)",
  92. )?;
  93. // Authorization-code redemption (RFC 7636 §4.5): the same DPoP key that
  94. // proved `/authorize` proves `/token`, binding the minted token.
  95. let proof = browser.dpop.proof(
  96. "POST",
  97. &format!("{}/token", browser.world.state.config.issuer),
  98. )?;
  99. let (status, _, body) = browser
  100. .world
  101. .post_form(
  102. "/token",
  103. &[
  104. ("grant_type", "authorization_code"),
  105. ("code", code.as_str()),
  106. ("redirect_uri", REDIRECT_URI),
  107. ("client_id", CLIENT_ID),
  108. ("code_verifier", browser.verifier.as_str()),
  109. ],
  110. None,
  111. &[("dpop", proof.as_str())],
  112. )
  113. .await?;
  114. ensure(
  115. status == reqwest::StatusCode::OK,
  116. format!("code redemption must mint: {status} {body}"),
  117. )?;
  118. let tokens = json_body(&body)?;
  119. ensure(
  120. tokens["token_type"] == "DPoP",
  121. format!("public issuance must be DPoP-bound, got {tokens}"),
  122. )?;
  123. ensure(
  124. tokens["access_token"]
  125. .as_str()
  126. .is_some_and(|token| !token.is_empty()),
  127. "redemption must return an access token",
  128. )?;
  129. ensure(
  130. tokens["refresh_token"]
  131. .as_str()
  132. .is_some_and(|token| !token.is_empty()),
  133. "a registered refresh_token grant must return a refresh token",
  134. )?;
  135. ensure(
  136. tokens["scope"] == SCOPE,
  137. format!("tokens must carry the scope, got {tokens}"),
  138. )?;
  139. // The code is single-use: a second redemption fails closed.
  140. let replay = browser.dpop.proof(
  141. "POST",
  142. &format!("{}/token", browser.world.state.config.issuer),
  143. )?;
  144. let (status, _, body) = browser
  145. .world
  146. .post_form(
  147. "/token",
  148. &[
  149. ("grant_type", "authorization_code"),
  150. ("code", code.as_str()),
  151. ("redirect_uri", REDIRECT_URI),
  152. ("client_id", CLIENT_ID),
  153. ("code_verifier", browser.verifier.as_str()),
  154. ],
  155. None,
  156. &[("dpop", replay.as_str())],
  157. )
  158. .await?;
  159. ensure(
  160. status == reqwest::StatusCode::BAD_REQUEST,
  161. format!("code replay must be 400, got {status}: {body}"),
  162. )?;
  163. ensure(
  164. json_body(&body)?["error"] == "invalid_grant",
  165. "code replay must be invalid_grant",
  166. )?;
  167. Ok(())
  168. }
  169. /// A wrong password is rejected uniformly (401, no session upgrade): the
  170. /// presession never becomes an authenticated session, so `/consent` bounces
  171. /// back to `/login` and no code can ever issue for the flow.
  172. #[tokio::test]
  173. async fn e2e_flow_login_wrong_password_rejected() -> Result<(), TestError> {
  174. let world = World::start(open_rate_limit()).await?;
  175. let browser = begin_browser(
  176. world,
  177. "flow-badpw@example.test",
  178. "correct-horse-28-right-one",
  179. )
  180. .await?;
  181. let code_2fa = totp_now(&browser.totp_secret).await?;
  182. let (status, headers, body) = post_login(&browser, "wrong-password-00000000", &code_2fa).await?;
  183. ensure(
  184. status == reqwest::StatusCode::UNAUTHORIZED,
  185. format!("wrong password must be 401, got {status}: {body}"),
  186. )?;
  187. ensure(
  188. body.contains(INVALID_CREDENTIALS),
  189. "rejection must render the uniform message",
  190. )?;
  191. ensure(
  192. cookie_value(&headers, SESSION_COOKIE).is_err(),
  193. "rejection must not upgrade the session",
  194. )?;
  195. let (status, headers, _) = get_consent(&browser, &browser.presession).await?;
  196. ensure(
  197. status == reqwest::StatusCode::SEE_OTHER,
  198. format!("without a session consent must bounce to login: {status}"),
  199. )?;
  200. ensure(
  201. location_of(&headers)? == "/login",
  202. "the bounce target must be the login page",
  203. )?;
  204. Ok(())
  205. }
  206. /// A correct password with a wrong TOTP code is rejected uniformly (401, no
  207. /// session upgrade): the presession never becomes an authenticated session,
  208. /// so `/consent` bounces back to `/login`. A follow-up attempt with the live
  209. /// code still succeeds, proving the rejection was code-specific.
  210. #[tokio::test]
  211. async fn e2e_flow_login_wrong_totp_rejected() -> Result<(), TestError> {
  212. let world = World::start(open_rate_limit()).await?;
  213. let browser = begin_browser(
  214. world,
  215. "flow-badcode@example.test",
  216. "correct-horse-28-right-one",
  217. )
  218. .await?;
  219. // A valid-format but incorrect 6-digit code: flip the first digit of the
  220. // live code (the unit-suite `wrong_code` idiom).
  221. let live = totp_now(&browser.totp_secret).await?;
  222. let mut digits: Vec<u8> = live.bytes().collect();
  223. digits[0] = if digits[0] == b'0' { b'1' } else { b'0' };
  224. let wrong: String = digits.into_iter().map(|byte| byte as char).collect();
  225. let (status, headers, body) = post_login(&browser, &browser.password.clone(), &wrong).await?;
  226. ensure(
  227. status == reqwest::StatusCode::UNAUTHORIZED,
  228. format!("wrong TOTP must be 401, got {status}: {body}"),
  229. )?;
  230. ensure(
  231. body.contains(INVALID_CREDENTIALS),
  232. "rejection must render the uniform message",
  233. )?;
  234. ensure(
  235. cookie_value(&headers, SESSION_COOKIE).is_err(),
  236. "rejection must not upgrade the session",
  237. )?;
  238. let (status, headers, _) = get_consent(&browser, &browser.presession).await?;
  239. ensure(
  240. status == reqwest::StatusCode::SEE_OTHER,
  241. format!("without a session consent must bounce to login: {status}"),
  242. )?;
  243. ensure(
  244. location_of(&headers)? == "/login",
  245. "the bounce target must be the login page",
  246. )?;
  247. // The live code still authenticates afterwards: the rejection was
  248. // code-specific, not an account or session defect.
  249. let live = totp_now(&browser.totp_secret).await?;
  250. let (status, headers, body) = post_login(&browser, &browser.password.clone(), &live).await?;
  251. ensure(
  252. status == reqwest::StatusCode::SEE_OTHER,
  253. format!("live code must 303 to consent: {status} {body}"),
  254. )?;
  255. ensure(
  256. location_of(&headers)? == "/consent",
  257. "live code must land on consent",
  258. )?;
  259. Ok(())
  260. }
  261. /// A mismatched login CSRF is rejected fail-closed (400 `invalid_request`,
  262. /// no session upgrade): the presession never becomes an authenticated
  263. /// session, so `/consent` bounces back to `/login`.
  264. #[tokio::test]
  265. async fn e2e_flow_login_csrf_mismatch_rejected() -> Result<(), TestError> {
  266. let world = World::start(open_rate_limit()).await?;
  267. let browser = begin_browser(
  268. world,
  269. "flow-badcsrf@example.test",
  270. "correct-horse-28-right-one",
  271. )
  272. .await?;
  273. let code_2fa = totp_now(&browser.totp_secret).await?;
  274. let cookie = format!("{SESSION_COOKIE}={}", browser.presession);
  275. let (status, headers, body) = browser
  276. .world
  277. .post_form(
  278. "/login",
  279. &[
  280. ("email", browser.email.as_str()),
  281. ("password", browser.password.as_str()),
  282. ("code", code_2fa.as_str()),
  283. ("csrf", "tampered-token"),
  284. ],
  285. None,
  286. &[("cookie", cookie.as_str())],
  287. )
  288. .await?;
  289. ensure(
  290. status == reqwest::StatusCode::BAD_REQUEST,
  291. format!("CSRF mismatch must be 400, got {status}: {body}"),
  292. )?;
  293. ensure(
  294. body.contains("invalid_request"),
  295. "CSRF mismatch must be invalid_request",
  296. )?;
  297. ensure(
  298. cookie_value(&headers, SESSION_COOKIE).is_err(),
  299. "rejection must not upgrade the session",
  300. )?;
  301. let (status, headers, _) = get_consent(&browser, &browser.presession).await?;
  302. ensure(
  303. status == reqwest::StatusCode::SEE_OTHER,
  304. format!("without a session consent must bounce to login: {status}"),
  305. )?;
  306. ensure(
  307. location_of(&headers)? == "/login",
  308. "the bounce target must be the login page",
  309. )?;
  310. Ok(())
  311. }
  312. /// Denying consent redirects to the registered redirect with
  313. /// `error=access_denied` + echoed `state` (RFC 6749 §4.1.2.1) and issues no
  314. /// code.
  315. #[tokio::test]
  316. async fn e2e_flow_consent_deny_redirects_access_denied() -> Result<(), TestError> {
  317. let world = World::start(open_rate_limit()).await?;
  318. let browser = begin_browser(
  319. world,
  320. "flow-deny@example.test",
  321. "correct-horse-28-deny-case",
  322. )
  323. .await?;
  324. let code_2fa = totp_now(&browser.totp_secret).await?;
  325. let (status, headers, body) = post_login(&browser, &browser.password.clone(), &code_2fa).await?;
  326. ensure(
  327. status == reqwest::StatusCode::SEE_OTHER,
  328. format!("login must 303 to consent: {status} {body}"),
  329. )?;
  330. let session = cookie_value(&headers, SESSION_COOKIE)?;
  331. let (status, _, body) = get_consent(&browser, &session).await?;
  332. ensure(
  333. status == reqwest::StatusCode::OK,
  334. format!("consent must render: {status}"),
  335. )?;
  336. let bound = hidden_input(&body, "request_id")?;
  337. let consent_csrf = hidden_input(&body, "csrf")?;
  338. let (status, headers, _) =
  339. post_consent(&browser, &session, &bound, &consent_csrf, "deny").await?;
  340. ensure(
  341. status == reqwest::StatusCode::SEE_OTHER,
  342. format!("consent denial must 303 to the redirect: {status}"),
  343. )?;
  344. let location = location_of(&headers)?;
  345. ensure(
  346. location.starts_with(REDIRECT_URI),
  347. format!("denial must return to the registered redirect, got {location}"),
  348. )?;
  349. ensure(
  350. query_value(&location, "error")? == "access_denied",
  351. "denial must carry error=access_denied",
  352. )?;
  353. ensure(
  354. query_value(&location, "state")? == STATE,
  355. "denial must echo state",
  356. )?;
  357. ensure(
  358. !has_query_key(&location, "code"),
  359. "denial must issue zero codes",
  360. )?;
  361. Ok(())
  362. }