mas_handlers/admin/v1/oauth2_sessions/
list.rs

1// Copyright 2024 New Vector Ltd.
2// Copyright 2024 The Matrix.org Foundation C.I.C.
3//
4// SPDX-License-Identifier: AGPL-3.0-only
5// Please see LICENSE 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::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.into(),
196                has_next_page: true,
197                has_previous_page: false,
198            };
199
200            t.description("Paginated response of OAuth 2.0 sessions")
201                .example(PaginatedResponse::new(
202                    page,
203                    pagination,
204                    42,
205                    OAuth2Session::PATH,
206                ))
207        })
208        .response_with::<404, RouteError, _>(|t| {
209            let response = ErrorResponse::from_error(&RouteError::UserNotFound(Ulid::nil()));
210            t.description("User was not found").example(response)
211        })
212        .response_with::<400, RouteError, _>(|t| {
213            let response = ErrorResponse::from_error(&RouteError::InvalidScope("not a valid scope".to_owned()));
214            t.description("Invalid scope").example(response)
215        })
216}
217
218#[tracing::instrument(name = "handler.admin.v1.oauth2_sessions.list", skip_all)]
219pub async fn handler(
220    CallContext { mut repo, .. }: CallContext,
221    Pagination(pagination): Pagination,
222    params: FilterParams,
223) -> Result<Json<PaginatedResponse<OAuth2Session>>, RouteError> {
224    let base = format!("{path}{params}", path = OAuth2Session::PATH);
225    let filter = OAuth2SessionFilter::default();
226
227    // Load the user from the filter
228    let user = if let Some(user_id) = params.user {
229        let user = repo
230            .user()
231            .lookup(user_id)
232            .await?
233            .ok_or(RouteError::UserNotFound(user_id))?;
234
235        Some(user)
236    } else {
237        None
238    };
239
240    let filter = match &user {
241        Some(user) => filter.for_user(user),
242        None => filter,
243    };
244
245    let client = if let Some(client_id) = params.client {
246        let client = repo
247            .oauth2_client()
248            .lookup(client_id)
249            .await?
250            .ok_or(RouteError::ClientNotFound(client_id))?;
251
252        Some(client)
253    } else {
254        None
255    };
256
257    let filter = match &client {
258        Some(client) => filter.for_client(client),
259        None => filter,
260    };
261
262    let filter = match params.client_kind {
263        Some(OAuth2ClientKind::Dynamic) => filter.only_dynamic_clients(),
264        Some(OAuth2ClientKind::Static) => filter.only_static_clients(),
265        None => filter,
266    };
267
268    let user_session = if let Some(user_session_id) = params.user_session {
269        let user_session = repo
270            .browser_session()
271            .lookup(user_session_id)
272            .await?
273            .ok_or(RouteError::UserSessionNotFound(user_session_id))?;
274
275        Some(user_session)
276    } else {
277        None
278    };
279
280    let filter = match &user_session {
281        Some(user_session) => filter.for_browser_session(user_session),
282        None => filter,
283    };
284
285    let scope: Scope = params
286        .scope
287        .into_iter()
288        .map(|s| ScopeToken::from_str(&s).map_err(|_| RouteError::InvalidScope(s)))
289        .collect::<Result<_, _>>()?;
290
291    let filter = if scope.is_empty() {
292        filter
293    } else {
294        filter.with_scope(&scope)
295    };
296
297    let filter = match params.status {
298        Some(OAuth2SessionStatus::Active) => filter.active_only(),
299        Some(OAuth2SessionStatus::Finished) => filter.finished_only(),
300        None => filter,
301    };
302
303    let page = repo.oauth2_session().list(filter, pagination).await?;
304    let count = repo.oauth2_session().count(filter).await?;
305
306    Ok(Json(PaginatedResponse::new(
307        page.map(OAuth2Session::from),
308        pagination,
309        count,
310        &base,
311    )))
312}
313
314#[cfg(test)]
315mod tests {
316    use hyper::{Request, StatusCode};
317    use sqlx::PgPool;
318
319    use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup};
320
321    #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
322    async fn test_oauth2_simple_session_list(pool: PgPool) {
323        setup();
324        let mut state = TestState::from_pool(pool).await.unwrap();
325        let token = state.token_with_scope("urn:mas:admin").await;
326
327        // We already have a session because of the token above
328        let request = Request::get("/api/admin/v1/oauth2-sessions")
329            .bearer(&token)
330            .empty();
331        let response = state.request(request).await;
332        response.assert_status(StatusCode::OK);
333        let body: serde_json::Value = response.json();
334        insta::assert_json_snapshot!(body, @r###"
335        {
336          "meta": {
337            "count": 1
338          },
339          "data": [
340            {
341              "type": "oauth2-session",
342              "id": "01FSHN9AG0MKGTBNZ16RDR3PVY",
343              "attributes": {
344                "created_at": "2022-01-16T14:40:00Z",
345                "finished_at": null,
346                "user_id": null,
347                "user_session_id": null,
348                "client_id": "01FSHN9AG0FAQ50MT1E9FFRPZR",
349                "scope": "urn:mas:admin",
350                "user_agent": null,
351                "last_active_at": null,
352                "last_active_ip": null
353              },
354              "links": {
355                "self": "/api/admin/v1/oauth2-sessions/01FSHN9AG0MKGTBNZ16RDR3PVY"
356              }
357            }
358          ],
359          "links": {
360            "self": "/api/admin/v1/oauth2-sessions?page[first]=10",
361            "first": "/api/admin/v1/oauth2-sessions?page[first]=10",
362            "last": "/api/admin/v1/oauth2-sessions?page[last]=10"
363          }
364        }
365        "###);
366    }
367}