forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

tests.rs531 lines, 19.2 KiBHistoryRawDownload
1//! End-to-end tests of the provider through the router: the redirect rules, PKCE, code and refresh
2//! reuse, client binding, and the ID token checked against the published key set.
3
4use std::time::Duration;
5
6use base64::prelude::{BASE64_STANDARD, BASE64_URL_SAFE_NO_PAD, Engine as _};
7use http::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE, LOCATION};
8use im_core::jwt::{self, PublishedKey};
9use im_core::model::Client;
10use im_core::oauth::pkce_s256;
11use im_core::password::hash_password;
12use im_core::store::clients::NewClient;
13use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState};
14use im_core::token::{generate_token, hash_token};
15use serde_json::Value;
16use topcoat::router::response::Response;
17use topcoat::router::{Body, StatusCode, to_bytes};
18
19use super::{encode_value, one, parse_pairs};
20use crate::boot::{router, test_state};
21use crate::state::AppState;
22
23/// The registered redirect URI of the test client.
24const REDIRECT: &str = "http://127.0.0.1:17651/auth/callback";
25
26/// The registered post-logout URI of the test client.
27const POST_LOGOUT: &str = "http://127.0.0.1:17651/signed-out";
28
29/// The cookie name the browser sends: the `__Host-` prefix is added by the jar.
30const SESSION_COOKIE: &str = "__Host-im_session";
31
32/// A client with a secret, a person, and a live browser session of that person.
33struct Fixture {
34 _dir: tempfile::TempDir,
35 state: AppState,
36 client: Client,
37 secret: String,
38 user_id: String,
39 cookie: String,
40}
41
42async fn fixture() -> Fixture {
43 let (dir, state) = test_state().await;
44 crate::oidc::signing::maintain(&state.store, &state.key)
45 .await
46 .expect("signing key");
47 let secret = generate_token();
48 let uris = vec![REDIRECT.to_owned()];
49 let post_logout = vec![POST_LOGOUT.to_owned()];
50 let client = state
51 .store
52 .create_client(&NewClient {
53 name: "Files",
54 secret_hash: &hash_token(&secret),
55 redirect_uris: &uris,
56 post_logout_redirect_uris: &post_logout,
57 backchannel_logout_uri: None,
58 allowed_scopes: "openid profile email",
59 service_key: Some("in"),
60 })
61 .await
62 .expect("client");
63 let hash = hash_password("the current password").expect("hash");
64 let user = state
65 .store
66 .create_user("ada@example.com", "Ada", &hash, false)
67 .await
68 .expect("user");
69 let cookie = generate_token();
70 state
71 .store
72 .create_session(
73 &NewSession {
74 user_id: &user.id,
75 decided_on: SignInState::of(&user),
76 token_hash: &hash_token(&cookie),
77 csrf_token: &generate_token(),
78 amr: "pwd",
79 ip: None,
80 user_agent: None,
81 idle: SESSION_IDLE,
82 max_age: Duration::from_secs(3600),
83 },
84 10,
85 )
86 .await
87 .expect("session")
88 .expect("not refused");
89 Fixture {
90 _dir: dir,
91 state,
92 client,
93 secret,
94 user_id: user.id,
95 cookie,
96 }
97}
98
99/// Sends a request through the whole router and returns the status, headers and body text.
100async fn send(
101 state: &AppState,
102 request: http::Request<Body>,
103) -> (StatusCode, http::HeaderMap, String) {
104 let response: Response = router(state.clone()).handle(request).await;
105 let status = response.status();
106 let headers = response.headers().clone();
107 let bytes = to_bytes(response.into_body(), 1024 * 1024)
108 .await
109 .expect("body");
110 (
111 status,
112 headers,
113 String::from_utf8_lossy(&bytes).into_owned(),
114 )
115}
116
117/// The `/authorize` path for a request, with the given method and challenge.
118fn authorize_path(client_id: &str, redirect: &str, challenge: &str, method: &str) -> String {
119 format!(
120 "/authorize?response_type=code&client_id={client_id}&redirect_uri={}\
121 &scope=openid%20profile%20email&state=s1&nonce=n1&code_challenge={challenge}\
122 &code_challenge_method={method}",
123 encode_value(redirect)
124 )
125}
126
127/// Runs `/authorize` as the signed-in person and returns the code from the redirect.
128async fn code_for(f: &Fixture, client: &Client, verifier: &str) -> String {
129 let path = authorize_path(&client.id, REDIRECT, &pkce_s256(verifier), "S256");
130 let request = http::Request::get(path)
131 .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie))
132 .body(Body::empty())
133 .expect("request");
134 let (status, headers, _) = send(&f.state, request).await;
135 assert_eq!(status, StatusCode::SEE_OTHER);
136 let location = headers[LOCATION].to_str().expect("location").to_owned();
137 assert!(location.starts_with(&format!("{REDIRECT}?")), "{location}");
138 let query = location.split_once('?').expect("query").1;
139 let pairs = parse_pairs(query.as_bytes()).expect("pairs");
140 assert_eq!(one(&pairs, "state"), Some("s1"));
141 assert_eq!(one(&pairs, "iss"), Some(f.state.config.base_url.as_str()));
142 one(&pairs, "code").expect("code").to_owned()
143}
144
145/// Posts a form to `/token` with `client_secret_basic` for `client`.
146async fn token_with(f: &Fixture, client: &Client, secret: &str, body: &str) -> (StatusCode, Value) {
147 let basic = BASE64_STANDARD.encode(format!("{}:{}", client.id, secret));
148 let request = http::Request::post("/token")
149 .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
150 .header(AUTHORIZATION, format!("Basic {basic}"))
151 .body(Body::from(body.to_owned()))
152 .expect("request");
153 let (status, _, text) = send(&f.state, request).await;
154 (status, serde_json::from_str(&text).unwrap_or(Value::Null))
155}
156
157/// The form body of an authorization-code exchange.
158fn code_body(code: &str, verifier: &str) -> String {
159 format!(
160 "grant_type=authorization_code&code={code}&redirect_uri={}&code_verifier={verifier}",
161 encode_value(REDIRECT)
162 )
163}
164
165#[tokio::test]
166async fn an_unregistered_redirect_uri_is_never_redirected_to() {
167 let f = fixture().await;
168 let challenge = pkce_s256(&generate_token());
169 for bad in [
170 "http://127.0.0.1:17651/auth/callback/evil",
171 "http://127.0.0.1:17651/auth/callback/",
172 "http://127.0.0.1:17651/Auth/callback",
173 "http://127.0.0.1:17651@evil.example/auth/callback",
174 "http://127.0.0.1:17651/auth/callback?x=1",
175 "https://127.0.0.1:17651/auth/callback",
176 "http://127.0.0.1:17651/auth/callback#x",
177 ] {
178 let request = http::Request::get(authorize_path(&f.client.id, bad, &challenge, "S256"))
179 .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie))
180 .body(Body::empty())
181 .expect("request");
182 let (status, headers, _) = send(&f.state, request).await;
183 assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}");
184 assert!(headers.get(LOCATION).is_none(), "redirected for {bad}");
185 }
186}
187
188#[tokio::test]
189async fn plain_pkce_is_refused_through_the_registered_redirect() {
190 let f = fixture().await;
191 let verifier = generate_token();
192 let request = http::Request::get(authorize_path(&f.client.id, REDIRECT, &verifier, "plain"))
193 .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie))
194 .body(Body::empty())
195 .expect("request");
196 let (status, headers, _) = send(&f.state, request).await;
197 assert_eq!(status, StatusCode::SEE_OTHER);
198 let location = headers[LOCATION].to_str().expect("location");
199 assert!(location.starts_with(REDIRECT), "{location}");
200 assert!(location.contains("error=invalid_request"), "{location}");
201 assert!(!location.contains("code="), "{location}");
202}
203
204#[tokio::test]
205async fn a_code_is_single_use_and_its_reuse_revokes_the_refresh_token() {
206 let f = fixture().await;
207 let verifier = generate_token();
208 let code = code_for(&f, &f.client, &verifier).await;
209 let body = code_body(&code, &verifier);
210
211 let (status, first) = token_with(&f, &f.client, &f.secret, &body).await;
212 assert_eq!(status, StatusCode::OK, "{first}");
213 let refresh = first["refresh_token"].as_str().expect("refresh").to_owned();
214
215 let (status, second) = token_with(&f, &f.client, &f.secret, &body).await;
216 assert_eq!(status, StatusCode::BAD_REQUEST);
217 assert_eq!(second["error"], "invalid_grant");
218
219 let refresh_body = format!("grant_type=refresh_token&refresh_token={refresh}");
220 let (status, third) = token_with(&f, &f.client, &f.secret, &refresh_body).await;
221 assert_eq!(status, StatusCode::BAD_REQUEST, "{third}");
222 assert_eq!(third["error"], "invalid_grant");
223}
224
225#[tokio::test]
226async fn a_code_for_another_client_is_refused_and_still_usable_by_its_own() {
227 let f = fixture().await;
228 let other_secret = generate_token();
229 let uris = vec![REDIRECT.to_owned()];
230 let other = f
231 .state
232 .store
233 .create_client(&NewClient {
234 name: "Board",
235 secret_hash: &hash_token(&other_secret),
236 redirect_uris: &uris,
237 post_logout_redirect_uris: &[],
238 backchannel_logout_uri: None,
239 allowed_scopes: "openid profile email",
240 service_key: Some("iz"),
241 })
242 .await
243 .expect("client");
244 let verifier = generate_token();
245 let code = code_for(&f, &f.client, &verifier).await;
246 let body = code_body(&code, &verifier);
247
248 let (status, wrong) = token_with(&f, &other, &other_secret, &body).await;
249 assert_eq!(status, StatusCode::BAD_REQUEST);
250 assert_eq!(wrong["error"], "invalid_grant");
251
252 let (status, right) = token_with(&f, &f.client, &f.secret, &body).await;
253 assert_eq!(status, StatusCode::OK, "{right}");
254}
255
256#[tokio::test]
257async fn a_reused_refresh_token_revokes_the_whole_family() {
258 let f = fixture().await;
259 let verifier = generate_token();
260 let code = code_for(&f, &f.client, &verifier).await;
261 let (_, first) = token_with(&f, &f.client, &f.secret, &code_body(&code, &verifier)).await;
262 let r1 = first["refresh_token"].as_str().expect("r1").to_owned();
263
264 let (status, rotated) = token_with(
265 &f,
266 &f.client,
267 &f.secret,
268 &format!("grant_type=refresh_token&refresh_token={r1}"),
269 )
270 .await;
271 assert_eq!(status, StatusCode::OK, "{rotated}");
272 let r2 = rotated["refresh_token"].as_str().expect("r2").to_owned();
273
274 // Presenting the rotated token again is reuse: the successor dies too.
275 let (status, reused) = token_with(
276 &f,
277 &f.client,
278 &f.secret,
279 &format!("grant_type=refresh_token&refresh_token={r1}"),
280 )
281 .await;
282 assert_eq!(status, StatusCode::BAD_REQUEST);
283 assert_eq!(reused["error"], "invalid_grant");
284 let (status, successor) = token_with(
285 &f,
286 &f.client,
287 &f.secret,
288 &format!("grant_type=refresh_token&refresh_token={r2}"),
289 )
290 .await;
291 assert_eq!(status, StatusCode::BAD_REQUEST, "{successor}");
292}
293
294#[tokio::test]
295async fn the_id_token_verifies_against_the_published_key_and_carries_the_nonce() {
296 let f = fixture().await;
297 let verifier = generate_token();
298 let code = code_for(&f, &f.client, &verifier).await;
299 let (status, tokens) = token_with(&f, &f.client, &f.secret, &code_body(&code, &verifier)).await;
300 assert_eq!(status, StatusCode::OK, "{tokens}");
301 let id_token = tokens["id_token"].as_str().expect("id_token");
302
303 let request = http::Request::get("/jwks.json")
304 .body(Body::empty())
305 .expect("request");
306 let (status, _, jwks) = send(&f.state, request).await;
307 assert_eq!(status, StatusCode::OK);
308 let keys: Vec<PublishedKey> = serde_json::from_str::<Value>(&jwks).expect("jwks")["keys"]
309 .as_array()
310 .expect("keys")
311 .iter()
312 .filter_map(|jwk| {
313 let raw = BASE64_URL_SAFE_NO_PAD.decode(jwk["x"].as_str()?).ok()?;
314 PublishedKey::new(jwk["kid"].as_str()?.to_owned(), &raw)
315 })
316 .collect();
317 let claims = jwt::verify(&keys, id_token).expect("signature verifies");
318 let now = im_core::time::unix_now();
319 jwt::check_claims(&claims, &f.state.config.base_url, &f.client.id, now).expect("claims");
320 assert_eq!(claims["nonce"], "n1");
321 assert_eq!(claims["sub"], f.user_id.as_str());
322 assert_eq!(claims["amr"], serde_json::json!(["pwd"]));
323}
324
325/// Posts a form to `path` with `client_secret_basic` for `client`.
326async fn post_as(
327 f: &Fixture,
328 path: &str,
329 client: &Client,
330 secret: &str,
331 body: &str,
332) -> (StatusCode, Value) {
333 let basic = BASE64_STANDARD.encode(format!("{}:{}", client.id, secret));
334 let request = http::Request::post(path)
335 .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
336 .header(AUTHORIZATION, format!("Basic {basic}"))
337 .body(Body::from(body.to_owned()))
338 .expect("request");
339 let (status, _, text) = send(&f.state, request).await;
340 (status, serde_json::from_str(&text).unwrap_or(Value::Null))
341}
342
343/// A client that is a family service with the given key and allowed scopes. Returns it with its secret.
344async fn service(f: &Fixture, key: &str, scopes: &str) -> (Client, String) {
345 let secret = generate_token();
346 let client = f
347 .state
348 .store
349 .create_client(&NewClient {
350 name: key,
351 secret_hash: &hash_token(&secret),
352 redirect_uris: &[],
353 post_logout_redirect_uris: &[],
354 backchannel_logout_uri: None,
355 allowed_scopes: scopes,
356 service_key: Some(key),
357 })
358 .await
359 .expect("service client");
360 (client, secret)
361}
362
363#[tokio::test]
364async fn client_credentials_refuses_a_scope_beyond_the_allowed_ones() {
365 let f = fixture().await;
366 let (caller, secret) = service(&f, "iz", "directory.read").await;
367 let (status, body) = post_as(
368 &f,
369 "/token",
370 &caller,
371 &secret,
372 "grant_type=client_credentials&scope=files.service&audience=im",
373 )
374 .await;
375 assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
376 assert_eq!(body["error"], "invalid_scope");
377}
378
379#[tokio::test]
380async fn client_credentials_refuses_an_unknown_audience() {
381 let f = fixture().await;
382 let (caller, secret) = service(&f, "iz", "directory.read").await;
383 let (status, body) = post_as(
384 &f,
385 "/token",
386 &caller,
387 &secret,
388 "grant_type=client_credentials&scope=directory.read&audience=nowhere",
389 )
390 .await;
391 assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
392 assert_eq!(body["error"], "invalid_target");
393}
394
395#[tokio::test]
396async fn introspection_reports_a_token_inactive_for_any_client_but_its_own() {
397 let f = fixture().await;
398 let (caller, caller_secret) = service(&f, "iz", "directory.read").await;
399 let (other, other_secret) = service(&f, "board", "directory.read").await;
400 let (status, issued) = post_as(
401 &f,
402 "/token",
403 &caller,
404 &caller_secret,
405 "grant_type=client_credentials&scope=directory.read&audience=im",
406 )
407 .await;
408 assert_eq!(status, StatusCode::OK, "{issued}");
409 let token = issued["access_token"].as_str().expect("token");
410 let body = format!("token={token}");
411
412 let (status, own) = post_as(&f, "/introspect", &caller, &caller_secret, &body).await;
413 assert_eq!(status, StatusCode::OK);
414 assert_eq!(own["active"], true, "{own}");
415
416 let (status, foreign) = post_as(&f, "/introspect", &other, &other_secret, &body).await;
417 assert_eq!(status, StatusCode::OK);
418 assert_eq!(foreign, serde_json::json!({ "active": false }));
419}
420
421#[tokio::test]
422async fn a_revoked_access_token_is_refused_by_userinfo_and_introspection() {
423 let f = fixture().await;
424 let verifier = generate_token();
425 let code = code_for(&f, &f.client, &verifier).await;
426 let (status, issued) = token_with(&f, &f.client, &f.secret, &code_body(&code, &verifier)).await;
427 assert_eq!(status, StatusCode::OK, "{issued}");
428 let access = issued["access_token"]
429 .as_str()
430 .expect("access token")
431 .to_owned();
432 let userinfo = || {
433 let request = http::Request::get("/userinfo")
434 .header(AUTHORIZATION, format!("Bearer {access}"))
435 .body(Body::empty())
436 .expect("request");
437 send(&f.state, request)
438 };
439 assert_eq!(userinfo().await.0, StatusCode::OK);
440
441 let (status, _) = post_as(
442 &f,
443 "/revoke",
444 &f.client,
445 &f.secret,
446 &format!("token={access}"),
447 )
448 .await;
449 assert_eq!(status, StatusCode::OK);
450 assert_eq!(userinfo().await.0, StatusCode::UNAUTHORIZED);
451 let (status, answer) = post_as(
452 &f,
453 "/introspect",
454 &f.client,
455 &f.secret,
456 &format!("token={access}"),
457 )
458 .await;
459 assert_eq!(status, StatusCode::OK);
460 assert_eq!(answer, serde_json::json!({ "active": false }));
461}
462
463/// The ID token of a fresh sign-in of the fixture's person, and the code exchange's session id.
464async fn id_token_of(f: &Fixture) -> String {
465 let verifier = generate_token();
466 let code = code_for(f, &f.client, &verifier).await;
467 let (status, tokens) = token_with(f, &f.client, &f.secret, &code_body(&code, &verifier)).await;
468 assert_eq!(status, StatusCode::OK, "{tokens}");
469 tokens["id_token"].as_str().expect("id_token").to_owned()
470}
471
472/// The CSRF token of the fixture's browser session.
473async fn csrf_of(f: &Fixture) -> String {
474 f.state
475 .store
476 .session_by_token_hash(&hash_token(&f.cookie))
477 .await
478 .expect("lookup")
479 .expect("session")
480 .csrf_token
481}
482
483#[tokio::test]
484async fn logout_redirects_only_to_the_registered_post_logout_uri() {
485 let f = fixture().await;
486 let hint = encode_value(&id_token_of(&f).await);
487 let unregistered = encode_value("http://127.0.0.1:17651/elsewhere");
488 let body = format!(
489 "csrf={}&id_token_hint={hint}&post_logout_redirect_uri={unregistered}&state=abc",
490 csrf_of(&f).await
491 );
492 let request = http::Request::post("/logout")
493 .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie))
494 .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
495 .body(Body::from(body))
496 .expect("request");
497 let (status, headers, body) = send(&f.state, request).await;
498 assert_eq!(status, StatusCode::OK, "{body}");
499 assert!(
500 headers.get(LOCATION).is_none(),
501 "redirected to an unregistered URI"
502 );
503 // The hint names the browser's own session, so it ends even though nothing is redirected.
504 let live = f
505 .state
506 .store
507 .session_by_token_hash(&hash_token(&f.cookie))
508 .await
509 .expect("lookup");
510 assert!(live.is_none(), "the session did not end");
511}
512
513#[tokio::test]
514async fn logout_with_the_registered_uri_redirects_and_carries_the_state() {
515 let f = fixture().await;
516 let hint = encode_value(&id_token_of(&f).await);
517 let registered = encode_value(POST_LOGOUT);
518 let body = format!(
519 "csrf={}&id_token_hint={hint}&post_logout_redirect_uri={registered}&state=abc",
520 csrf_of(&f).await
521 );
522 let request = http::Request::post("/logout")
523 .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie))
524 .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
525 .body(Body::from(body))
526 .expect("request");
527 let (status, headers, _) = send(&f.state, request).await;
528 assert_eq!(status, StatusCode::SEE_OTHER);
529 let location = headers[LOCATION].to_str().expect("location");
530 assert_eq!(location, format!("{POST_LOGOUT}?state=abc"));
531}