Skip to main content

mas_handlers/compat/
logout.rs

1// Copyright 2025, 2026 Element Creations Ltd.
2// Copyright 2024, 2025 New Vector Ltd.
3// Copyright 2022-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 std::sync::LazyLock;
9
10use axum::{Json, response::IntoResponse};
11use axum_extra::typed_header::TypedHeader;
12use headers::{Authorization, authorization::Bearer};
13use hyper::StatusCode;
14use mas_axum_utils::{RecordAsRequester, record_error};
15use mas_data_model::{BoxClock, BoxRng, Clock, TokenType};
16use mas_storage::{
17    BoxRepository, RepositoryAccess,
18    compat::{CompatAccessTokenRepository, CompatSessionRepository},
19    queue::{QueueJobRepositoryExt as _, SyncDevicesJob},
20};
21use opentelemetry::{Key, KeyValue, metrics::Counter};
22use thiserror::Error;
23
24use super::MatrixError;
25use crate::{BoundActivityTracker, METER, impl_from_error_for_route};
26
27static LOGOUT_COUNTER: LazyLock<Counter<u64>> = LazyLock::new(|| {
28    METER
29        .u64_counter("mas.compat.logout_request")
30        .with_description("How many compatibility logout request have happened")
31        .with_unit("{request}")
32        .build()
33});
34const RESULT: Key = Key::from_static_str("result");
35
36#[derive(Error, Debug)]
37pub enum RouteError {
38    #[error(transparent)]
39    Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
40
41    #[error("Missing access token")]
42    MissingAuthorization,
43
44    #[error("Invalid token format")]
45    TokenFormat(#[from] mas_data_model::TokenFormatError),
46
47    #[error("Invalid access token")]
48    InvalidAuthorization,
49}
50
51impl_from_error_for_route!(mas_storage::RepositoryError);
52
53impl IntoResponse for RouteError {
54    fn into_response(self) -> axum::response::Response {
55        let sentry_event_id = record_error!(self, Self::Internal(_));
56        LOGOUT_COUNTER.add(1, &[KeyValue::new(RESULT, "error")]);
57        let response = match self {
58            Self::Internal(_) => MatrixError {
59                errcode: "M_UNKNOWN",
60                error: "Internal error",
61                status: StatusCode::INTERNAL_SERVER_ERROR,
62            },
63            Self::MissingAuthorization => MatrixError {
64                errcode: "M_MISSING_TOKEN",
65                error: "Missing access token",
66                status: StatusCode::UNAUTHORIZED,
67            },
68            Self::InvalidAuthorization | Self::TokenFormat(_) => MatrixError {
69                errcode: "M_UNKNOWN_TOKEN",
70                error: "Invalid access token",
71                status: StatusCode::UNAUTHORIZED,
72            },
73        };
74
75        (sentry_event_id, response).into_response()
76    }
77}
78
79#[tracing::instrument(name = "handlers.compat.logout.post", skip_all)]
80pub(crate) async fn post(
81    clock: BoxClock,
82    mut rng: BoxRng,
83    mut repo: BoxRepository,
84    activity_tracker: BoundActivityTracker,
85    maybe_authorization: Option<TypedHeader<Authorization<Bearer>>>,
86) -> Result<impl IntoResponse, RouteError> {
87    let TypedHeader(authorization) = maybe_authorization.ok_or(RouteError::MissingAuthorization)?;
88
89    let token = authorization.token();
90    let token_type = TokenType::check(token)?;
91
92    if token_type != TokenType::CompatAccessToken {
93        return Err(RouteError::InvalidAuthorization);
94    }
95
96    let token = repo
97        .compat_access_token()
98        .find_by_token(token)
99        .await?
100        .filter(|t| t.is_valid(clock.now()))
101        .ok_or(RouteError::InvalidAuthorization)?;
102
103    let session = repo
104        .compat_session()
105        .lookup(token.session_id)
106        .await?
107        .filter(|s| s.is_valid())
108        .ok_or(RouteError::InvalidAuthorization)?;
109
110    activity_tracker
111        .record_compat_session(&clock, &session)
112        .await;
113
114    let user = repo
115        .user()
116        .lookup(session.user_id)
117        .await?
118        // XXX: this is probably not the right error
119        .ok_or(RouteError::InvalidAuthorization)?;
120
121    user.maybe_record_as_requester();
122
123    // This will make the access token invalid
124    repo.compat_session().finish(&clock, session).await?;
125
126    // Schedule a job to sync the devices of the user with the homeserver
127    //
128    // Doing this in a background job is ok as the access token will be invalid
129    // right away (from the session being finished above) and we do actually
130    // want to do a full device list sync (as opposed to
131    // `homeserver.delete_device(...)`), because we're not sure whether we want
132    // to delete the device (if there is for example a concurrent logout and
133    // login with the same device ID).
134    repo.queue_job()
135        .schedule_job(&mut rng, &clock, SyncDevicesJob::new(&user))
136        .await?;
137
138    repo.save().await?;
139
140    LOGOUT_COUNTER.add(1, &[KeyValue::new(RESULT, "success")]);
141
142    Ok(Json(serde_json::json!({})))
143}