forge
Explore
Log in

Don't you dare go Hollow

im_old

Clone
★ 0

0 watching0 forksRustGPL-3.0755.6 KiB84318dcTahinli2 months ago77 commits

oidc.rs688 lines, 25.6 KiBHistoryRawDownload
1//! The OIDC surface: discovery, JWKS, authorize, token, userinfo. The pages
2//! are for people; these are for apps — im-client first, any OIDC-speaking
3//! client after.
4
5use im_core::model::{ClientId, UserId};
6use im_core::oidc;
7use serde::Deserialize;
8use topcoat::Result;
9use topcoat::context::Cx;
10use topcoat::router::content::{Form, Json};
11use topcoat::router::request::{headers, uri};
12use topcoat::router::response::{IntoResponse, Response};
13use topcoat::router::{HeaderValue, StatusCode, header, route};
14
15use crate::server::{self, App};
16
17fn app(cx: &Cx) -> &App {
18 server::app(cx)
19}
20
21/// A JSON OIDC error: `{"error": code}` with the matching status.
22fn oidc_error(cx: &Cx, status: StatusCode, code: &str) -> Result<Response> {
23 (status, Json(serde_json::json!({ "error": code }))).into_response(cx)
24}
25
26#[route(GET "/.well-known/openid-configuration")]
27async fn discovery(cx: &Cx) -> Result<Json<serde_json::Value>> {
28 let issuer = &app(cx).config.issuer;
29 Ok(Json(serde_json::json!({
30 "issuer": issuer,
31 "authorization_endpoint": format!("{issuer}/authorize"),
32 "token_endpoint": format!("{issuer}/token"),
33 "userinfo_endpoint": format!("{issuer}/userinfo"),
34 "jwks_uri": format!("{issuer}/jwks.json"),
35 "response_types_supported": ["code"],
36 "grant_types_supported": ["authorization_code", "refresh_token"],
37 "subject_types_supported": ["public"],
38 "id_token_signing_alg_values_supported": ["RS256"],
39 "scopes_supported": ["openid", "profile", "email"],
40 "claims_supported": ["iss", "sub", "aud", "exp", "iat", "nonce", "email", "name"],
41 "code_challenge_methods_supported": ["S256"],
42 })))
43}
44
45#[route(GET "/jwks.json")]
46async fn jwks(cx: &Cx) -> Result<Json<serde_json::Value>> {
47 Ok(Json(im_core::keys::jwks(&app(cx).store).await?))
48}
49
50// ---------------------------------------------------------------------------
51// /authorize
52// ---------------------------------------------------------------------------
53
54/// The OIDC error redirect: only ever sent after the client AND the exact
55/// redirect_uri have checked out — otherwise the answer is a bare 400, never
56// a redirect to an address a stranger supplied.
57fn authorize_error(
58 cx: &Cx,
59 redirect_uri: &str,
60 state: Option<&str>,
61 error: &str,
62) -> Result<Response> {
63 let sep = if redirect_uri.contains('?') { '&' } else { '?' };
64 let mut location = format!("{redirect_uri}{sep}error={error}");
65 if let Some(state) = state {
66 // The state is the caller's bytes: encoded as a query pair or it
67 // could carry `&`, `=`, or a whole second parameter of its own.
68 location.push_str(&format!("&state={}", urlencode(state)));
69 }
70 (
71 StatusCode::SEE_OTHER,
72 [(
73 header::LOCATION,
74 HeaderValue::from_str(&location).unwrap_or_else(|_| HeaderValue::from_static("/")),
75 )],
76 )
77 .into_response(cx)
78}
79
80fn bad_request(cx: &Cx) -> Result<Response> {
81 (StatusCode::BAD_REQUEST, "invalid request").into_response(cx)
82}
83
84/// Percent-encodes a value for a query pair — the `back` a login carries is
85/// a local `/authorize?...` URL, full of `?&=` of its own.
86pub(crate) fn urlencode(raw: &str) -> String {
87 let mut out = String::with_capacity(raw.len());
88 for byte in raw.bytes() {
89 match byte {
90 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
91 out.push(byte as char)
92 }
93 _ => out.push_str(&format!("%{byte:02X}")),
94 }
95 }
96 out
97}
98
99#[route(GET "/authorize")]
100async fn authorize(cx: &Cx) -> Result<Response> {
101 let query = uri(cx).query().unwrap_or("").to_string();
102 let get = |key: &str| crate::pages::query_value(&query, key);
103
104 // Client identity first: nothing redirects anywhere until both the client
105 // and the exact redirect_uri are known-good.
106 let Some(client_id) = get("client_id") else {
107 return bad_request(cx);
108 };
109 let Some(client) = oidc::client_by_id(&app(cx).store, &client_id).await? else {
110 return bad_request(cx);
111 };
112 let Some(redirect_uri) = get("redirect_uri") else {
113 return bad_request(cx);
114 };
115 if !client.redirect_uris.contains(&redirect_uri) {
116 return bad_request(cx);
117 }
118 let state = get("state");
119
120 if get("response_type").as_deref() != Some("code") {
121 return authorize_error(
122 cx,
123 &redirect_uri,
124 state.as_deref(),
125 "unsupported_response_type",
126 );
127 }
128 let scope = get("scope").unwrap_or_default();
129 let scopes: Vec<&str> = scope.split(' ').collect();
130 if !scopes.contains(&"openid")
131 || !scopes
132 .iter()
133 .all(|s| ["openid", "profile", "email"].contains(s))
134 {
135 return authorize_error(cx, &redirect_uri, state.as_deref(), "invalid_scope");
136 }
137 let Some(challenge) = get("code_challenge") else {
138 return authorize_error(cx, &redirect_uri, state.as_deref(), "invalid_request");
139 };
140 if get("code_challenge_method").as_deref() != Some("S256") {
141 return authorize_error(cx, &redirect_uri, state.as_deref(), "invalid_request");
142 }
143
144 // The central session is the whole point: a browser that already signed
145 // in (password and second factor both behind it) gets its code without
146 // seeing a form at all.
147 let presented = server::presented_session(cx);
148 let user = match &presented {
149 Some(token) => im_core::sessions::resolve_session(&app(cx).store, token).await?,
150 None => None,
151 };
152 let Some(user) = user else {
153 let back = format!("/authorize?{query}");
154 let location = format!("/login?back={}", urlencode(&back));
155 let location = HeaderValue::from_str(&location)?;
156 return (
157 StatusCode::SEE_OTHER,
158 [(header::LOCATION, location)],
159 )
160 .into_response(cx);
161 };
162 let session_hash = im_core::accounts::hash_token(presented.as_deref().unwrap_or_default());
163 let code = oidc::create_auth_code(
164 &app(cx).store,
165 &client.client_id,
166 &user.id,
167 &redirect_uri,
168 get("nonce"),
169 &challenge,
170 &session_hash,
171 )
172 .await?;
173 let sep = if redirect_uri.contains('?') { '&' } else { '?' };
174 let mut location = format!("{redirect_uri}{sep}code={}", code.expose());
175 if let Some(state) = state {
176 // Same pair discipline as [`authorize_error`]: the caller's state
177 // is a value, never raw query syntax.
178 location.push_str(&format!("&state={}", urlencode(&state)));
179 }
180 let location = HeaderValue::from_str(&location)?;
181 (
182 StatusCode::SEE_OTHER,
183 [(header::LOCATION, location)],
184 )
185 .into_response(cx)
186}
187
188// ---------------------------------------------------------------------------
189// /token
190// ---------------------------------------------------------------------------
191
192#[derive(Deserialize)]
193struct TokenForm {
194 grant_type: String,
195 code: Option<String>,
196 redirect_uri: Option<String>,
197 client_id: Option<String>,
198 client_secret: Option<String>,
199 code_verifier: Option<String>,
200 refresh_token: Option<String>,
201}
202
203/// Signs the pair of tokens for `user` toward `client`.
204async fn mint_tokens(
205 cx: &Cx,
206 user: &im_core::model::User,
207 client_id: &ClientId,
208 nonce: Option<String>,
209) -> Result<(String, String)> {
210 let now = time::OffsetDateTime::now_utc().unix_timestamp();
211 let issuer = &app(cx).config.issuer;
212 let (kid, key) = im_core::keys::active_signing_key(&app(cx).store).await?;
213 let id_claims = serde_json::json!({
214 "iss": issuer,
215 "sub": user.id.as_str(),
216 "aud": client_id.as_str(),
217 "exp": now + oidc::TOKEN_SECONDS,
218 "iat": now,
219 "email": user.email,
220 "name": user.name,
221 "nonce": nonce,
222 });
223 let access_claims = serde_json::json!({
224 "iss": issuer,
225 "sub": user.id.as_str(),
226 "aud": client_id.as_str(),
227 "exp": now + oidc::TOKEN_SECONDS,
228 "iat": now,
229 "scope": "openid profile email",
230 });
231 Ok((
232 oidc::sign_jwt(&access_claims, &kid, &key),
233 oidc::sign_jwt(&id_claims, &kid, &key),
234 ))
235}
236
237fn token_answer(
238 cx: &Cx,
239 access: String,
240 id: String,
241 refresh: String,
242 app_session: Option<String>,
243) -> Result<Response> {
244 Json(serde_json::json!({
245 "access_token": access,
246 "token_type": "Bearer",
247 "expires_in": oidc::TOKEN_SECONDS,
248 "refresh_token": refresh,
249 "id_token": id,
250 // Not OIDC — ours: the opaque, introspected session im-client holds.
251 // Standard clients ignore it; ours never leaves its ghost window.
252 "app_session": app_session,
253 }))
254 .into_response(cx)
255}
256
257#[route(POST "/token")]
258async fn exchange(cx: &Cx, Form(input): Form<TokenForm>) -> Result<Response> {
259 let Some(client_id) = input.client_id else {
260 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_request");
261 };
262 let Some(client) = oidc::client_by_id(&app(cx).store, &client_id).await? else {
263 return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client");
264 };
265 let Some(secret) = input.client_secret else {
266 return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client");
267 };
268 if !oidc::verify_client_secret(&client, &secret) {
269 return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client");
270 }
271
272 match input.grant_type.as_str() {
273 "authorization_code" => {
274 let (Some(code), Some(redirect_uri), Some(verifier)) =
275 (input.code, input.redirect_uri, input.code_verifier)
276 else {
277 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_request");
278 };
279 // Judge before spending: the peek says what the code is, and a
280 // presentation that fails its client, redirect, or PKCE check
281 // leaves the code alive for its rightful holder. `consume` is
282 // still the atomic exactly-once act that settles a race.
283 let Some(staged) = oidc::peek_auth_code(&app(cx).store, &code).await? else {
284 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
285 };
286 if staged.client_id != client.client_id
287 || staged.redirect_uri != redirect_uri
288 || !oidc::pkce_matches(&staged.code_challenge, &verifier)
289 {
290 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
291 }
292 let Some(consumed) = oidc::consume_auth_code(&app(cx).store, &code).await? else {
293 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
294 };
295 let Some(user) =
296 im_core::accounts::user_by_id(&app(cx).store, &consumed.user_id).await?
297 else {
298 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
299 };
300 if user.disabled {
301 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
302 }
303 let (access, id) = mint_tokens(cx, &user, &client.client_id, consumed.nonce).await?;
304 let refresh = oidc::issue_refresh(
305 &app(cx).store,
306 &user.id,
307 &client.client_id,
308 &consumed.session_hash,
309 )
310 .await?;
311 let app_session = oidc::issue_app_session(
312 &app(cx).store,
313 &user.id,
314 &client.client_id,
315 &consumed.session_hash,
316 )
317 .await?;
318 server::log_event(
319 cx,
320 "code_exchanged",
321 Some(&user.email),
322 Some(&format!("via {}", client.name)),
323 )
324 .await;
325 token_answer(
326 cx,
327 access,
328 id,
329 refresh.expose().to_string(),
330 Some(app_session.expose().to_string()),
331 )
332 }
333 "refresh_token" => {
334 let Some(presented) = input.refresh_token else {
335 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_request");
336 };
337 // Ownership before rotation: a token presented by a client it
338 // was never issued to is judged by the peek, so a wrong-client
339 // presentation cannot burn the rightful holder's chain. The
340 // rotate that follows re-checks everything atomically and
341 // settles a race between two refreshes of the same client.
342 let Some(record) = oidc::peek_refresh(&app(cx).store, &presented).await? else {
343 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
344 };
345 if record.client_id != client.client_id {
346 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
347 }
348 let Some(user) = im_core::accounts::user_by_id(&app(cx).store, &record.user_id).await?
349 else {
350 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
351 };
352 if user.disabled {
353 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
354 }
355 let Some((fresh, _)) = oidc::rotate_refresh(&app(cx).store, &presented).await? else {
356 return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
357 };
358 let (access, id) = mint_tokens(cx, &user, &client.client_id, None).await?;
359 token_answer(cx, access, id, fresh.expose().to_string(), None)
360 }
361 _ => oidc_error(cx, StatusCode::BAD_REQUEST, "unsupported_grant_type"),
362 }
363}
364
365// ---------------------------------------------------------------------------
366// /introspect (RFC 7662): the per-request liveness check im-client makes
367// ---------------------------------------------------------------------------
368
369#[derive(Deserialize)]
370struct IntrospectForm {
371 token: String,
372 client_id: Option<String>,
373 client_secret: Option<String>,
374}
375
376/// The app asks, per request: is this session alive, and whose is it? The
377/// answer is never cached server-side, so a revoked user is inactive on the
378/// very next call.
379#[route(POST "/introspect")]
380async fn introspect(cx: &Cx, Form(input): Form<IntrospectForm>) -> Result<Response> {
381 let (Some(client_id), Some(secret)) = (input.client_id, input.client_secret) else {
382 return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client");
383 };
384 let Some(client) = oidc::client_by_id(&app(cx).store, &client_id).await? else {
385 return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client");
386 };
387 if !oidc::verify_client_secret(&client, &secret) {
388 return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client");
389 }
390 let answer = oidc::introspect_app_session(&app(cx).store, &input.token, &client_id)
391 .await?
392 .unwrap_or_else(|| serde_json::json!({ "active": false }));
393 Json(answer).into_response(cx)
394}
395
396// ---------------------------------------------------------------------------
397// /userinfo
398// ---------------------------------------------------------------------------
399
400#[route(GET "/userinfo")]
401async fn userinfo(cx: &Cx) -> Result<Response> {
402 let presented = headers(cx)
403 .get(header::AUTHORIZATION)
404 .and_then(|value| value.to_str().ok())
405 .and_then(|value| value.strip_prefix("Bearer "))
406 .map(str::to_string);
407 let Some(presented) = presented else {
408 return (
409 StatusCode::UNAUTHORIZED,
410 [(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer"))],
411 )
412 .into_response(cx);
413 };
414 // Signature and expiry first; the audience is checked against the client
415 // registry, not a fixed value — any registered app may ask.
416 let Some(claims) = oidc::verify_jwt(&app(cx).store, &presented, None).await? else {
417 return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_token");
418 };
419 let Some(aud) = claims["aud"].as_str() else {
420 return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_token");
421 };
422 if oidc::client_by_id(&app(cx).store, aud).await?.is_none() {
423 return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_token");
424 }
425 let Some(sub) = claims["sub"].as_str() else {
426 return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_token");
427 };
428 let Some(user) =
429 im_core::accounts::user_by_id(&app(cx).store, &UserId::from(sub.to_string())).await?
430 else {
431 return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_token");
432 };
433 if user.disabled {
434 return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_token");
435 }
436 Json(serde_json::json!({
437 "sub": user.id.as_str(),
438 "email": user.email,
439 "name": user.name,
440 }))
441 .into_response(cx)
442}
443
444#[cfg(test)]
445mod tests {
446 use std::path::Path;
447 use std::sync::Arc;
448
449 use topcoat::cookie::RouterBuilderCookieExt as _;
450 use topcoat::router::{Body, Router, RouterBuilderDiscoverExt as _, StatusCode, header, to_bytes};
451 use im_core::accounts::{create_invite, create_user_from_invite};
452 use im_core::oidc::{create_auth_code, create_client, issue_refresh};
453 use im_core::sessions::{SessionMeta, create_session};
454 use im_core::store::Store;
455
456 use crate::config::Config;
457 use crate::server::{self, SESSION_COOKIE};
458
459 /// The RFC 7636 Appendix B pair: `challenge` is `S256(verifier)`.
460 const VERIFIER: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
461 const CHALLENGE: &str = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
462
463 struct Setup {
464 router: Router,
465 store: Arc<Store>,
466 // The rightful client, its credential, and what it holds.
467 client_id: String,
468 secret: String,
469 // A second registered client — the attacker's seat.
470 other_id: String,
471 other_secret: String,
472 session_cookie: String,
473 }
474
475 async fn setup() -> Setup {
476 let store = Store::open(Path::new(":memory:")).await.unwrap();
477 let (client_id, secret) =
478 create_client(&store, "drive", vec!["http://app/callback".into()])
479 .await
480 .unwrap();
481 let (other_id, other_secret) =
482 create_client(&store, "stranger", vec!["http://stranger/cb".into()])
483 .await
484 .unwrap();
485 let invite = create_invite(&store, "ann@example.com", None, false)
486 .await
487 .unwrap();
488 let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv")
489 .await
490 .unwrap();
491 let session = create_session(&store, &user.id, &SessionMeta::default())
492 .await
493 .unwrap();
494 let (live, _) = tokio::sync::broadcast::channel(64);
495 let store = Arc::new(store);
496 let app = server::App {
497 store: store.clone(),
498 config: Config {
499 database: ":memory:".into(),
500 listen: "127.0.0.1:7650".parse().unwrap(),
501 issuer: "http://127.0.0.1:7650".into(),
502 services: Vec::new(),
503 },
504 live,
505 };
506 let router = Router::builder()
507 .discover()
508 .cookies()
509 .app_context(app)
510 .build();
511 Setup {
512 router,
513 store,
514 client_id: client_id.to_string(),
515 secret: secret.expose().to_string(),
516 other_id: other_id.to_string(),
517 other_secret: other_secret.expose().to_string(),
518 session_cookie: format!("{SESSION_COOKIE}={}", session.expose()),
519 }
520 }
521
522 /// POSTs a token form, answered as (status, body).
523 async fn post_token(router: &Router, form: &str) -> (StatusCode, String) {
524 let response = router
525 .handle(
526 http::Request::builder()
527 .method(http::Method::POST)
528 .uri("/token")
529 .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
530 .body(Body::from(form.to_string()))
531 .unwrap(),
532 )
533 .await;
534 let (parts, body) = response.into_parts();
535 let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec();
536 (parts.status, String::from_utf8(bytes).unwrap())
537 }
538
539 /// A `/authorize` GET carrying the central session, answered as
540 /// (status, Location) — the code handout for the signed-in browser.
541 async fn get_authorize(setup: &Setup) -> (StatusCode, Option<String>) {
542 let query = format!(
543 "response_type=code&client_id={}&redirect_uri=http%3A%2F%2Fapp%2Fcallback\
544 &scope=openid&state=st%26ate&code_challenge={}&code_challenge_method=S256",
545 setup.client_id, CHALLENGE
546 );
547 let response = setup
548 .router
549 .handle(
550 http::Request::builder()
551 .uri(format!("/authorize?{query}"))
552 .header(header::COOKIE, &setup.session_cookie)
553 .body(Body::empty())
554 .unwrap(),
555 )
556 .await;
557 let (parts, _) = response.into_parts();
558 let location = parts
559 .headers
560 .get(header::LOCATION)
561 .and_then(|v| v.to_str().ok())
562 .map(str::to_string);
563 (parts.status, location)
564 }
565
566 #[tokio::test]
567 async fn wrong_client_presentation_leaves_the_refresh_chain_alive() {
568 let setup = setup().await;
569 let token = issue_refresh(
570 &setup.store,
571 &announce_user(&setup).await,
572 &im_core::model::ClientId::from(setup.client_id.clone()),
573 &session_hash(&setup).await,
574 )
575 .await
576 .unwrap();
577
578 // The stranger presents the victim's token: refused — and, the
579 // point, nothing burns.
580 let form = format!(
581 "grant_type=refresh_token&client_id={}&client_secret={}\
582 &refresh_token={}",
583 setup.other_id,
584 setup.other_secret,
585 token.expose()
586 );
587 let (status, body) = post_token(&setup.router, &form).await;
588 assert_eq!(status, StatusCode::BAD_REQUEST);
589 assert_eq!(
590 serde_json::from_str::<serde_json::Value>(&body).unwrap()["error"],
591 "invalid_grant"
592 );
593
594 // The rightful client refreshes with the very same token: the
595 // chain stands. (Before the peek-first ordering this burned.)
596 let form = format!(
597 "grant_type=refresh_token&client_id={}&client_secret={}\
598 &refresh_token={}",
599 setup.client_id,
600 setup.secret,
601 token.expose()
602 );
603 let (status, body) = post_token(&setup.router, &form).await;
604 assert_eq!(status, StatusCode::OK);
605 let answer: serde_json::Value = serde_json::from_str(&body).unwrap();
606 assert!(answer["refresh_token"].as_str().is_some());
607 }
608
609 #[tokio::test]
610 async fn wrong_client_presentation_leaves_the_code_redeemable() {
611 let setup = setup().await;
612 let user = announce_user(&setup).await;
613 let code = create_auth_code(
614 &setup.store,
615 &im_core::model::ClientId::from(setup.client_id.clone()),
616 &user,
617 "http://app/callback",
618 None,
619 CHALLENGE,
620 &session_hash(&setup).await,
621 )
622 .await
623 .unwrap();
624
625 // The stranger presents the victim's code with its redirect and
626 // PKCE pair complete: refused without spending it.
627 let form = format!(
628 "grant_type=authorization_code&client_id={}&client_secret={}\
629 &code={}&redirect_uri=http%3A%2F%2Fapp%2Fcallback&code_verifier={}",
630 setup.other_id,
631 setup.other_secret,
632 code.expose(),
633 VERIFIER
634 );
635 let (status, body) = post_token(&setup.router, &form).await;
636 assert_eq!(status, StatusCode::BAD_REQUEST);
637 assert_eq!(
638 serde_json::from_str::<serde_json::Value>(&body).unwrap()["error"],
639 "invalid_grant"
640 );
641
642 // The rightful client exchanges the very same code.
643 let form = format!(
644 "grant_type=authorization_code&client_id={}&client_secret={}\
645 &code={}&redirect_uri=http%3A%2F%2Fapp%2Fcallback&code_verifier={}",
646 setup.client_id,
647 setup.secret,
648 code.expose(),
649 VERIFIER
650 );
651 let (status, body) = post_token(&setup.router, &form).await;
652 assert_eq!(status, StatusCode::OK);
653 let answer: serde_json::Value = serde_json::from_str(&body).unwrap();
654 assert!(answer["access_token"].as_str().is_some());
655 }
656
657 #[tokio::test]
658 async fn authorize_encodes_the_state_it_hands_back() {
659 let setup = setup().await;
660 let (status, location) = get_authorize(&setup).await;
661 assert_eq!(status, StatusCode::SEE_OTHER);
662 let location = location.unwrap();
663 assert!(location.starts_with("http://app/callback?code="));
664 // The decoded `st&ate` rides back as one pair's value, not two.
665 assert!(location.ends_with("&state=st%26ate"), "{location}");
666 assert!(!location.contains("&ate="), "{location}");
667 }
668
669 /// The signed-in person behind the fixture session.
670 async fn announce_user(setup: &Setup) -> im_core::model::UserId {
671 im_core::accounts::user_by_email(&setup.store, "ann@example.com")
672 .await
673 .unwrap()
674 .unwrap()
675 .id
676 }
677
678 /// The fixture session's hash — the binding refresh tokens and codes
679 /// carry toward the central session.
680 async fn session_hash(setup: &Setup) -> String {
681 im_core::accounts::hash_token(
682 setup
683 .session_cookie
684 .strip_prefix(&format!("{SESSION_COOKIE}="))
685 .unwrap(),
686 )
687 }
688}