mas_handlers/admin/v1/oauth2_sessions/
list.rs

1// Copyright 2024, 2025 New Vector Ltd.
2// Copyright 2024 The Matrix.org Foundation C.I.C.
3//
4// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
5// Please see LICENSE files in the repository root for full details.
6
7use std::str::FromStr;
8
9use aide::{OperationIo, transform::TransformOperation};
10use axum::{
11    Json,
12    extract::{Query, rejection::QueryRejection},
13    response::IntoResponse,
14};
15use axum_macros::FromRequestParts;
16use hyper::StatusCode;
17use mas_axum_utils::record_error;
18use mas_storage::{Page, oauth2::OAuth2SessionFilter};
19use oauth2_types::scope::{Scope, ScopeToken};
20use schemars::JsonSchema;
21use serde::Deserialize;
22use ulid::Ulid;
23
24use crate::{
25    admin::{
26        call_context::CallContext,
27        model::{OAuth2Session, Resource},
28        params::{IncludeCount, Pagination},
29        response::{ErrorResponse, PaginatedResponse},
30    },
31    impl_from_error_for_route,
32};
33
34#[derive(Deserialize, JsonSchema, Clone, Copy)]
35#[serde(rename_all = "snake_case")]
36enum OAuth2SessionStatus {
37    Active,
38    Finished,
39}
40
41impl std::fmt::Display for OAuth2SessionStatus {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        match self {
44            Self::Active => write!(f, "active"),
45            Self::Finished => write!(f, "finished"),
46        }
47    }
48}
49
50#[derive(Deserialize, JsonSchema, Clone, Copy)]
51#[serde(rename_all = "snake_case")]
52enum OAuth2ClientKind {
53    Dynamic,
54    Static,
55}
56
57impl std::fmt::Display for OAuth2ClientKind {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        match self {
60            Self::Dynamic => write!(f, "dynamic"),
61            Self::Static => write!(f, "static"),
62        }
63    }
64}
65
66#[derive(FromRequestParts, Deserialize, JsonSchema, OperationIo)]
67#[serde(rename = "OAuth2SessionFilter")]
68#[aide(input_with = "Query<FilterParams>")]
69#[from_request(via(Query), rejection(RouteError))]
70pub struct FilterParams {
71    /// Retrieve the items for the given user
72    #[serde(rename = "filter[user]")]
73    #[schemars(with = "Option<crate::admin::schema::Ulid>")]
74    user: Option<Ulid>,
75
76    /// Retrieve the items for the given client
77    #[serde(rename = "filter[client]")]
78    #[schemars(with = "Option<crate::admin::schema::Ulid>")]
79    client: Option<Ulid>,
80
81    /// Retrieve the items only for a specific client kind
82    #[serde(rename = "filter[client-kind]")]
83    client_kind: Option<OAuth2ClientKind>,
84
85    /// Retrieve the items started from the given browser session
86    #[serde(rename = "filter[user-session]")]
87    #[schemars(with = "Option<crate::admin::schema::Ulid>")]
88    user_session: Option<Ulid>,
89
90    /// Retrieve the items with the given scope
91    #[serde(default, rename = "filter[scope]")]
92    scope: Vec<String>,
93
94    /// Retrieve the items with the given status
95    ///
96    /// Defaults to retrieve all sessions, including finished ones.
97    ///
98    /// * `active`: Only retrieve active sessions
99    ///
100    /// * `finished`: Only retrieve finished sessions
101    #[serde(rename = "filter[status]")]
102    status: Option<OAuth2SessionStatus>,
103}
104
105impl std::fmt::Display for FilterParams {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        let mut sep = '?';
108
109        if let Some(user) = self.user {
110            write!(f, "{sep}filter[user]={user}")?;
111            sep = '&';
112        }
113
114        if let Some(client) = self.client {
115            write!(f, "{sep}filter[client]={client}")?;
116            sep = '&';
117        }
118
119        if let Some(client_kind) = self.client_kind {
120            write!(f, "{sep}filter[client-kind]={client_kind}")?;
121            sep = '&';
122        }
123
124        if let Some(user_session) = self.user_session {
125            write!(f, "{sep}filter[user-session]={user_session}")?;
126            sep = '&';
127        }
128
129        for scope in &self.scope {
130            write!(f, "{sep}filter[scope]={scope}")?;
131            sep = '&';
132        }
133
134        if let Some(status) = self.status {
135            write!(f, "{sep}filter[status]={status}")?;
136            sep = '&';
137        }
138
139        let _ = sep;
140        Ok(())
141    }
142}
143
144#[derive(Debug, thiserror::Error, OperationIo)]
145#[aide(output_with = "Json<ErrorResponse>")]
146pub enum RouteError {
147    #[error(transparent)]
148    Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
149
150    #[error("User ID {0} not found")]
151    UserNotFound(Ulid),
152
153    #[error("Client ID {0} not found")]
154    ClientNotFound(Ulid),
155
156    #[error("User session ID {0} not found")]
157    UserSessionNotFound(Ulid),
158
159    #[error("Invalid filter parameters")]
160    InvalidFilter(#[from] QueryRejection),
161
162    #[error("Invalid scope {0:?} in filter parameters")]
163    InvalidScope(String),
164}
165
166impl_from_error_for_route!(mas_storage::RepositoryError);
167
168impl IntoResponse for RouteError {
169    fn into_response(self) -> axum::response::Response {
170        let error = ErrorResponse::from_error(&self);
171        let sentry_event_id = record_error!(self, RouteError::Internal(_));
172        let status = match self {
173            Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
174            Self::UserNotFound(_) | Self::ClientNotFound(_) | Self::UserSessionNotFound(_) => {
175                StatusCode::NOT_FOUND
176            }
177            Self::InvalidScope(_) | Self::InvalidFilter(_) => StatusCode::BAD_REQUEST,
178        };
179        (status, sentry_event_id, Json(error)).into_response()
180    }
181}
182
183pub fn doc(operation: TransformOperation) -> TransformOperation {
184    operation
185        .id("listOAuth2Sessions")
186        .summary("List OAuth 2.0 sessions")
187        .description("Retrieve a list of OAuth 2.0 sessions.
188Note that by default, all sessions, including finished ones are returned, with the oldest first.
189Use the `filter[status]` parameter to filter the sessions by their status and `page[last]` parameter to retrieve the last N sessions.")
190        .tag("oauth2-session")
191        .response_with::<200, Json<PaginatedResponse<OAuth2Session>>, _>(|t| {
192            let sessions = OAuth2Session::samples();
193            let pagination = mas_storage::Pagination::first(sessions.len());
194            let page = Page {
195                edges: sessions
196                    .into_iter()
197                    .map(|node| mas_storage::pagination::Edge {
198                        cursor: node.id(),
199                        node,
200                    })
201                    .collect(),
202                has_next_page: true,
203                has_previous_page: false,
204            };
205
206            t.description("Paginated response of OAuth 2.0 sessions")
207                .example(PaginatedResponse::for_page(
208                    page,
209                    pagination,
210                    Some(42),
211                    OAuth2Session::PATH,
212                ))
213        })
214        .response_with::<404, RouteError, _>(|t| {
215            let response = ErrorResponse::from_error(&RouteError::UserNotFound(Ulid::nil()));
216            t.description("User was not found").example(response)
217        })
218        .response_with::<400, RouteError, _>(|t| {
219            let response = ErrorResponse::from_error(&RouteError::InvalidScope("not a valid scope".to_owned()));
220            t.description("Invalid scope").example(response)
221        })
222}
223
224#[tracing::instrument(name = "handler.admin.v1.oauth2_sessions.list", skip_all)]
225pub async fn handler(
226    CallContext { mut repo, .. }: CallContext,
227    Pagination(pagination, include_count): Pagination,
228    params: FilterParams,
229) -> Result<Json<PaginatedResponse<OAuth2Session>>, RouteError> {
230    let base = format!("{path}{params}", path = OAuth2Session::PATH);
231    let base = include_count.add_to_base(&base);
232    let filter = OAuth2SessionFilter::default();
233
234    // Load the user from the filter
235    let user = if let Some(user_id) = params.user {
236        let user = repo
237            .user()
238            .lookup(user_id)
239            .await?
240            .ok_or(RouteError::UserNotFound(user_id))?;
241
242        Some(user)
243    } else {
244        None
245    };
246
247    let filter = match &user {
248        Some(user) => filter.for_user(user),
249        None => filter,
250    };
251
252    let client = if let Some(client_id) = params.client {
253        let client = repo
254            .oauth2_client()
255            .lookup(client_id)
256            .await?
257            .ok_or(RouteError::ClientNotFound(client_id))?;
258
259        Some(client)
260    } else {
261        None
262    };
263
264    let filter = match &client {
265        Some(client) => filter.for_client(client),
266        None => filter,
267    };
268
269    let filter = match params.client_kind {
270        Some(OAuth2ClientKind::Dynamic) => filter.only_dynamic_clients(),
271        Some(OAuth2ClientKind::Static) => filter.only_static_clients(),
272        None => filter,
273    };
274
275    let user_session = if let Some(user_session_id) = params.user_session {
276        let user_session = repo
277            .browser_session()
278            .lookup(user_session_id)
279            .await?
280            .ok_or(RouteError::UserSessionNotFound(user_session_id))?;
281
282        Some(user_session)
283    } else {
284        None
285    };
286
287    let filter = match &user_session {
288        Some(user_session) => filter.for_browser_session(user_session),
289        None => filter,
290    };
291
292    let scope: Scope = params
293        .scope
294        .into_iter()
295        .map(|s| ScopeToken::from_str(&s).map_err(|_| RouteError::InvalidScope(s)))
296        .collect::<Result<_, _>>()?;
297
298    let filter = if scope.is_empty() {
299        filter
300    } else {
301        filter.with_scope(&scope)
302    };
303
304    let filter = match params.status {
305        Some(OAuth2SessionStatus::Active) => filter.active_only(),
306        Some(OAuth2SessionStatus::Finished) => filter.finished_only(),
307        None => filter,
308    };
309
310    let response = match include_count {
311        IncludeCount::True => {
312            let page = repo
313                .oauth2_session()
314                .list(filter, pagination)
315                .await?
316                .map(OAuth2Session::from);
317            let count = repo.oauth2_session().count(filter).await?;
318            PaginatedResponse::for_page(page, pagination, Some(count), &base)
319        }
320        IncludeCount::False => {
321            let page = repo
322                .oauth2_session()
323                .list(filter, pagination)
324                .await?
325                .map(OAuth2Session::from);
326            PaginatedResponse::for_page(page, pagination, None, &base)
327        }
328        IncludeCount::Only => {
329            let count = repo.oauth2_session().count(filter).await?;
330            PaginatedResponse::for_count_only(count, &base)
331        }
332    };
333
334    Ok(Json(response))
335}
336
337#[cfg(test)]
338mod tests {
339    use hyper::{Request, StatusCode};
340    use sqlx::PgPool;
341
342    use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup};
343
344    #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
345    async fn test_oauth2_simple_session_list(pool: PgPool) {
346        setup();
347        let mut state = TestState::from_pool(pool).await.unwrap();
348        let token = state.token_with_scope("urn:mas:admin").await;
349
350        // We already have a session because of the token above
351        let request = Request::get("/api/admin/v1/oauth2-sessions")
352            .bearer(&token)
353            .empty();
354        let response = state.request(request).await;
355        response.assert_status(StatusCode::OK);
356        let body: serde_json::Value = response.json();
357        insta::assert_json_snapshot!(body, @r#"
358        {
359          "meta": {
360            "count": 1
361          },
362          "data": [
363            {
364              "type": "oauth2-session",
365              "id": "01FSHN9AG0MKGTBNZ16RDR3PVY",
366              "attributes": {
367                "created_at": "2022-01-16T14:40:00Z",
368                "finished_at": null,
369                "user_id": null,
370                "user_session_id": null,
371                "client_id": "01FSHN9AG0FAQ50MT1E9FFRPZR",
372                "scope": "urn:mas:admin",
373                "user_agent": null,
374                "last_active_at": null,
375                "last_active_ip": null,
376                "human_name": null
377              },
378              "links": {
379                "self": "/api/admin/v1/oauth2-sessions/01FSHN9AG0MKGTBNZ16RDR3PVY"
380              },
381              "meta": {
382                "page": {
383                  "cursor": "01FSHN9AG0MKGTBNZ16RDR3PVY"
384                }
385              }
386            }
387          ],
388          "links": {
389            "self": "/api/admin/v1/oauth2-sessions?page[first]=10",
390            "first": "/api/admin/v1/oauth2-sessions?page[first]=10",
391            "last": "/api/admin/v1/oauth2-sessions?page[last]=10"
392          }
393        }
394        "#);
395
396        // Test count=false
397        let request = Request::get("/api/admin/v1/oauth2-sessions?count=false")
398            .bearer(&token)
399            .empty();
400        let response = state.request(request).await;
401        response.assert_status(StatusCode::OK);
402        let body: serde_json::Value = response.json();
403        insta::assert_json_snapshot!(body, @r#"
404        {
405          "data": [
406            {
407              "type": "oauth2-session",
408              "id": "01FSHN9AG0MKGTBNZ16RDR3PVY",
409              "attributes": {
410                "created_at": "2022-01-16T14:40:00Z",
411                "finished_at": null,
412                "user_id": null,
413                "user_session_id": null,
414                "client_id": "01FSHN9AG0FAQ50MT1E9FFRPZR",
415                "scope": "urn:mas:admin",
416                "user_agent": null,
417                "last_active_at": null,
418                "last_active_ip": null,
419                "human_name": null
420              },
421              "links": {
422                "self": "/api/admin/v1/oauth2-sessions/01FSHN9AG0MKGTBNZ16RDR3PVY"
423              },
424              "meta": {
425                "page": {
426                  "cursor": "01FSHN9AG0MKGTBNZ16RDR3PVY"
427                }
428              }
429            }
430          ],
431          "links": {
432            "self": "/api/admin/v1/oauth2-sessions?count=false&page[first]=10",
433            "first": "/api/admin/v1/oauth2-sessions?count=false&page[first]=10",
434            "last": "/api/admin/v1/oauth2-sessions?count=false&page[last]=10"
435          }
436        }
437        "#);
438
439        // Test count=only
440        let request = Request::get("/api/admin/v1/oauth2-sessions?count=only")
441            .bearer(&token)
442            .empty();
443        let response = state.request(request).await;
444        response.assert_status(StatusCode::OK);
445        let body: serde_json::Value = response.json();
446        insta::assert_json_snapshot!(body, @r#"
447        {
448          "meta": {
449            "count": 1
450          },
451          "links": {
452            "self": "/api/admin/v1/oauth2-sessions?count=only"
453          }
454        }
455        "#);
456    }
457}