Skip to main content

mas_handlers/oauth2/
userinfo.rs

1// Copyright 2025, 2026 Element Creations Ltd.
2// Copyright 2024, 2025 New Vector Ltd.
3// Copyright 2021-2024 The Matrix.org Foundation C.I.C.
4//
5// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
6// Please see LICENSE files in the repository root for full details.
7
8use axum::{
9    Json,
10    extract::State,
11    response::{IntoResponse, Response},
12};
13use hyper::StatusCode;
14use mas_axum_utils::{
15    jwt::JwtResponse,
16    record_error,
17    user_authorization::{AuthorizationVerificationError, UserAuthorization},
18};
19use mas_data_model::{BoxClock, BoxRng};
20use mas_jose::{
21    constraints::Constrainable,
22    jwt::{JsonWebSignatureHeader, Jwt},
23};
24use mas_keystore::Keystore;
25use mas_router::UrlBuilder;
26use mas_storage::{BoxRepository, oauth2::OAuth2ClientRepository};
27use serde::Serialize;
28use serde_with::skip_serializing_none;
29use thiserror::Error;
30use ulid::Ulid;
31
32use crate::{BoundActivityTracker, impl_from_error_for_route};
33
34#[skip_serializing_none]
35#[derive(Serialize)]
36struct UserInfo {
37    sub: String,
38    username: String,
39}
40
41#[derive(Serialize)]
42struct SignedUserInfo {
43    iss: String,
44    aud: String,
45    #[serde(flatten)]
46    user_info: UserInfo,
47}
48
49#[derive(Debug, Error)]
50pub enum RouteError {
51    #[error(transparent)]
52    Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
53
54    #[error("failed to authenticate")]
55    AuthorizationVerificationError(
56        #[from] AuthorizationVerificationError<mas_storage::RepositoryError>,
57    ),
58
59    #[error("session is not allowed to access the userinfo endpoint")]
60    Unauthorized,
61
62    #[error("no suitable key found for signing")]
63    InvalidSigningKey,
64
65    #[error("failed to load client {0}")]
66    NoSuchClient(Ulid),
67
68    #[error("failed to load user {0}")]
69    NoSuchUser(Ulid),
70}
71
72impl_from_error_for_route!(mas_storage::RepositoryError);
73impl_from_error_for_route!(mas_keystore::WrongAlgorithmError);
74impl_from_error_for_route!(mas_jose::jwt::JwtSignatureError);
75
76impl IntoResponse for RouteError {
77    fn into_response(self) -> axum::response::Response {
78        let sentry_event_id = record_error!(
79            self,
80            Self::Internal(_)
81                | Self::InvalidSigningKey
82                | Self::NoSuchClient(_)
83                | Self::NoSuchUser(_)
84                | Self::AuthorizationVerificationError(AuthorizationVerificationError::Internal(_))
85        );
86        let response = match self {
87            Self::Internal(_)
88            | Self::InvalidSigningKey
89            | Self::NoSuchClient(_)
90            | Self::NoSuchUser(_)
91            | Self::AuthorizationVerificationError(AuthorizationVerificationError::Internal(_)) => {
92                (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()).into_response()
93            }
94            Self::AuthorizationVerificationError(_) | Self::Unauthorized => {
95                StatusCode::UNAUTHORIZED.into_response()
96            }
97        };
98
99        (sentry_event_id, response).into_response()
100    }
101}
102
103#[tracing::instrument(name = "handlers.oauth2.userinfo.get", skip_all)]
104pub async fn get(
105    mut rng: BoxRng,
106    clock: BoxClock,
107    State(url_builder): State<UrlBuilder>,
108    activity_tracker: BoundActivityTracker,
109    mut repo: BoxRepository,
110    State(key_store): State<Keystore>,
111    user_authorization: UserAuthorization,
112) -> Result<Response, RouteError> {
113    let session = user_authorization.protected(&mut repo, &clock).await?;
114
115    // This endpoint requires the `openid` scope.
116    if !session.scope.contains("openid") {
117        return Err(RouteError::Unauthorized);
118    }
119
120    // Fail if the session is not associated with a user.
121    let Some(user_id) = session.user_id else {
122        return Err(RouteError::Unauthorized);
123    };
124
125    activity_tracker
126        .record_oauth2_session(&clock, &session)
127        .await;
128
129    let user = repo
130        .user()
131        .lookup(user_id)
132        .await?
133        .ok_or(RouteError::NoSuchUser(user_id))?;
134
135    let user_info = UserInfo {
136        sub: user.sub.clone(),
137        username: user.username.clone(),
138    };
139
140    let client = repo
141        .oauth2_client()
142        .lookup(session.client_id)
143        .await?
144        .ok_or(RouteError::NoSuchClient(session.client_id))?;
145
146    repo.save().await?;
147
148    if let Some(alg) = client.userinfo_signed_response_alg {
149        let key = key_store
150            .signing_key_for_algorithm(&alg)
151            .ok_or(RouteError::InvalidSigningKey)?;
152
153        let signer = key.params().signing_key_for_alg(&alg)?;
154        let header = JsonWebSignatureHeader::new(alg)
155            .with_kid(key.kid().ok_or(RouteError::InvalidSigningKey)?);
156
157        let user_info = SignedUserInfo {
158            iss: url_builder.oidc_issuer().to_string(),
159            aud: client.client_id,
160            user_info,
161        };
162
163        let token = Jwt::sign_with_rng(&mut rng, header, user_info, &signer)?;
164        Ok(JwtResponse(token).into_response())
165    } else {
166        Ok(Json(user_info).into_response())
167    }
168}