Skip to main content

alibi_plugins/oauth_provider/
userinfo.rs

1//! Scoped user claims resolved from the real issued access-token authority.
2use super::OAuthProviderPlugin;
3use alibi_core::endpoint::{EndpointResponse, ServerEndpoint};
4use alibi_core::session::SessionRequest;
5use alibi_core::store::{OAuthToken, OAuthTokenKind};
6use alibi_core::utils::json::JsValue;
7use alibi_core::{AuthContext, AuthError, AuthResult, AuthSchema, AuthSession, HttpMethod};
8use serde_json::{Value, json};
9/// The shared access-token liveness gate used by public protocol consumers.
10pub(super) async fn live_access<S: AuthSchema>(
11    token: &str,
12    ctx: &AuthContext<S>,
13    provider: &OAuthProviderPlugin,
14) -> AuthResult<Option<OAuthToken>> {
15    let hash = provider.hash_token(token, "access_token").await?;
16    let Some(row) = ctx
17        .database
18        .get_oauth_token(OAuthTokenKind::Access, &hash)
19        .await?
20    else {
21        return Ok(None);
22    };
23    live_access_row(row, ctx, provider).await
24}
25pub(super) async fn live_access_row<S: AuthSchema>(
26    row: OAuthToken,
27    ctx: &AuthContext<S>,
28    provider: &OAuthProviderPlugin,
29) -> AuthResult<Option<OAuthToken>> {
30    if row.expires_at < chrono::Utc::now()
31        || row.metadata.get("revoked").is_some_and(|v| !v.is_null())
32    {
33        return Ok(None);
34    }
35    let Some(client) = provider.get_client(ctx, &row.client_id).await? else {
36        return Ok(None);
37    };
38    if client.metadata.get("disabled") == Some(&Value::Bool(true)) {
39        return Ok(None);
40    }
41    if let Some(session) = row.session_id.as_deref() {
42        let sessions = if let Some(user) = row.user_id.as_deref() {
43            ctx.database.get_user_sessions(user).await?
44        } else {
45            Vec::new()
46        };
47        if !sessions
48            .iter()
49            .any(|value| value.id().as_ref() == session && value.expires_at() >= chrono::Utc::now())
50        {
51            return Ok(None);
52        }
53    }
54    Ok(Some(row))
55}
56impl OAuthProviderPlugin {
57    /// Read the current user claims authorized by an OAuth access token.
58    #[must_use]
59    pub fn oauth2_user_info_endpoint() -> ServerEndpoint<Value> {
60        ServerEndpoint::new("oauth-provider", "oauth2UserInfo")
61    }
62    pub(super) async fn user_info<S: AuthSchema>(
63        &self,
64        input: Option<&JsValue>,
65        req: &impl SessionRequest,
66        ctx: &AuthContext<S>,
67    ) -> AuthResult<EndpointResponse> {
68        let headers = req.session_headers();
69        let header = headers
70            .iter()
71            .find(|(name, _)| name.eq_ignore_ascii_case("authorization"))
72            .map(|(_, value)| value.as_str());
73        let authorization = crate::oauth2::parse_access_token_authorization(header);
74        let body_token = if req
75            .physical_request()
76            .is_some_and(|request| *request.method() == HttpMethod::Post)
77        {
78            input
79                .and_then(|value| value.get("access_token"))
80                .and_then(JsValue::as_str)
81                .filter(|value| !value.is_empty())
82        } else {
83            None
84        };
85        if authorization.is_some() && body_token.is_some() {
86            return error(
87                400,
88                "invalid_request",
89                "Multiple access token transport methods are not allowed",
90            );
91        }
92        let Some(authorization) = authorization.or_else(|| {
93            body_token.map(|token| crate::oauth2::AccessTokenAuthorization {
94                scheme: "Bearer".into(),
95                token: token.into(),
96            })
97        }) else {
98            return error(401, "invalid_request", "access token not found");
99        };
100        let payload = match self
101            .require_active_access_token(ctx, &authorization.token, None)
102            .await
103        {
104            Ok(payload) => payload,
105            Err(error) => {
106                let mut response = EndpointResponse::error(error.error);
107                if let Some(body) = error.body {
108                    response = response.with_error_body(*body);
109                }
110                if let Some(headers) = error.headers {
111                    response.merge_headers(headers);
112                }
113                return Ok(no_store(response));
114            }
115        };
116        if payload
117            .get("cnf")
118            .and_then(crate::oauth2::get_confirmation_jkt)
119            .is_some()
120            && req.physical_request().is_none()
121        {
122            return error(
123                401,
124                "invalid_token",
125                "DPoP-bound access token requires an HTTP request context",
126            );
127        }
128        let method = match req.physical_request().map(alibi_core::AuthRequest::method) {
129            Some(HttpMethod::Post) => "POST",
130            Some(HttpMethod::Put) => "PUT",
131            Some(HttpMethod::Patch) => "PATCH",
132            Some(HttpMethod::Delete) => "DELETE",
133            Some(HttpMethod::Options) => "OPTIONS",
134            Some(HttpMethod::Head) => "HEAD",
135            Some(HttpMethod::Get) | None => "GET",
136        };
137        let url = super::dpop::endpoint_url(ctx, req, "/oauth2/userinfo");
138        let replay = crate::oauth2::create_dpop_replay_store(ctx);
139        let mut binding =
140            crate::oauth2::EnforceDpopBindingParams::new(&payload, &authorization, method, &url);
141        binding.proof_jwt = super::dpop::proof_header(req);
142        binding.replay_store = Some(&replay);
143        binding.proof_max_age_seconds = self.config.dpop_proof_max_age_seconds;
144        binding.signing_algorithms = self.config.dpop_signing_algorithms.clone();
145        if let Err(failure) = crate::oauth2::enforce_dpop_binding(&binding).await {
146            if crate::oauth2::is_dpop_binding_error(&failure) {
147                return error(
148                    401,
149                    failure.code.as_deref().unwrap_or_default(),
150                    &failure.message,
151                );
152            }
153            return Err(AuthError::internal(failure.message));
154        }
155        let scopes = payload
156            .get("scope")
157            .and_then(Value::as_str)
158            .map(|scope| scope.split(' ').collect::<Vec<_>>())
159            .unwrap_or_default();
160        if !scopes.contains(&"openid") {
161            return error(400, "invalid_scope", "Missing required scope");
162        }
163        let Some(id) = payload
164            .get("sub")
165            .and_then(Value::as_str)
166            .filter(|value| !value.is_empty())
167        else {
168            return error(400, "invalid_request", "user not found");
169        };
170        let Some(user) = ctx.database.get_user_by_id(id).await? else {
171            return error(400, "invalid_request", "user not found");
172        };
173        let user = ctx.user_view(&user);
174        let mut claims = serde_json::Map::from_iter([("sub".into(), json!(user.id))]);
175        if scopes.contains(&"profile") {
176            if let Some(name) = user.name {
177                _ = claims.insert("name".into(), json!(name));
178                let parts = name
179                    .split(' ')
180                    .filter(|value| !value.is_empty())
181                    .collect::<Vec<_>>();
182                if let Some((family, given)) = parts.split_last()
183                    && !given.is_empty()
184                {
185                    _ = claims.insert("given_name".into(), json!(given.join(" ")));
186                    _ = claims.insert("family_name".into(), json!(family));
187                }
188            }
189            if let Some(image) = user.image {
190                _ = claims.insert("picture".into(), json!(image));
191            }
192        }
193        if scopes.contains(&"email") {
194            if let Some(email) = user.email {
195                _ = claims.insert("email".into(), json!(email));
196            }
197            _ = claims.insert("email_verified".into(), json!(user.email_verified));
198        }
199        Ok(no_store(EndpointResponse::json(&claims)?))
200    }
201}
202fn no_store(response: EndpointResponse) -> EndpointResponse {
203    response
204        .with_header("Cache-Control", "no-store")
205        .with_header("Pragma", "no-cache")
206}
207fn error(status: u16, code: &str, description: &str) -> AuthResult<EndpointResponse> {
208    super::clients::status_protocol_error(status, code, description).map(no_store)
209}