forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

userinfo.rs96 lines, 3.4 KiBHistoryRawDownload
1//! `GET` and `POST /userinfo` (OpenID Connect Core section 5.3): the claims of the person a user access
2//! token was issued for.
3//!
4//! The token is verified against this provider's own published keys: signature, `iss`, `aud` (this
5//! provider), `exp` and `iat`, and the `openid` scope. The token is then checked against the session it
6//! names: a session that ended, or a disabled account, refuses the token at once, even before it expires.
7
8use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE};
9use im_core::jwt;
10use im_core::time::unix_now;
11use serde_json::{Value, json};
12use topcoat::Result;
13use topcoat::context::{Cx, app_context};
14use topcoat::router::request::headers;
15use topcoat::router::response::Response;
16use topcoat::router::{StatusCode, route};
17
18use super::signing;
19use super::token::person_claims;
20use super::{USERINFO_AUDIENCE, issuer, json_response};
21use crate::state::AppState;
22
23/// `GET /userinfo` and `POST /userinfo`, both with a Bearer token.
24#[route([GET, POST] "/userinfo")]
25async fn userinfo(cx: &Cx) -> Result<Response> {
26 let app = app_context::<AppState>(cx);
27 let Some(token) = bearer(headers(cx).get(AUTHORIZATION)) else {
28 return Ok(unauthorized());
29 };
30 let Some(claims) = signing::verify_access(&app.store, token).await? else {
31 return Ok(unauthorized());
32 };
33 let now = unix_now();
34 if jwt::check_claims(&claims, issuer(app), USERINFO_AUDIENCE, now).is_err() {
35 return Ok(unauthorized());
36 }
37 let scope = claims
38 .get("scope")
39 .and_then(Value::as_str)
40 .unwrap_or_default();
41 if !scope.split_whitespace().any(|word| word == "openid") {
42 return Ok(unauthorized());
43 }
44 let (Some(sub), Some(sid)) = (
45 claims.get("sub").and_then(Value::as_str),
46 claims.get("sid").and_then(Value::as_str),
47 ) else {
48 return Ok(unauthorized());
49 };
50 let Some(session) = app.store.live_session(sid).await? else {
51 return Ok(unauthorized());
52 };
53 let Some(user) = app
54 .store
55 .user_by_id(sub)
56 .await?
57 .filter(|u| !u.is_disabled())
58 else {
59 return Ok(unauthorized());
60 };
61 if session.user_id != user.id {
62 return Ok(unauthorized());
63 }
64 // A token outlives nothing that its client loses: a disabled client's tokens are refused at once.
65 let Some(client_id) = claims.get("azp").and_then(Value::as_str) else {
66 return Ok(unauthorized());
67 };
68 if !app
69 .store
70 .client_by_id(client_id)
71 .await?
72 .is_some_and(|client| !client.is_disabled())
73 {
74 return Ok(unauthorized());
75 }
76
77 let mut body = person_claims(&user, scope);
78 body.insert("sub".into(), json!(user.id));
79 Ok(json_response(StatusCode::OK, &Value::Object(body)))
80}
81
82/// The token of a `Bearer` authorization header, or `None`.
83pub(crate) fn bearer(value: Option<&HeaderValue>) -> Option<&str> {
84 let (scheme, token) = value?.to_str().ok()?.split_once(' ')?;
85 (scheme.eq_ignore_ascii_case("bearer") && !token.is_empty()).then_some(token)
86}
87
88/// `401 invalid_token` with the RFC 6750 challenge. One answer for every reason.
89fn unauthorized() -> Response {
90 let mut response = json_response(StatusCode::UNAUTHORIZED, &json!({"error": "invalid_token"}));
91 response.headers_mut().insert(
92 WWW_AUTHENTICATE,
93 HeaderValue::from_static("Bearer error=\"invalid_token\""),
94 );
95 response
96}