mas_handlers/graphql/model/
compat_sessions.rs

1// Copyright 2024 New Vector Ltd.
2// Copyright 2022-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 anyhow::Context as _;
8use async_graphql::{Context, Description, Enum, ID, Object};
9use chrono::{DateTime, Utc};
10use mas_data_model::Device;
11use mas_storage::{compat::CompatSessionRepository, user::UserRepository};
12use url::Url;
13
14use super::{BrowserSession, NodeType, SessionState, User, UserAgent};
15use crate::graphql::state::ContextExt;
16
17/// Lazy-loaded reverse reference.
18///
19/// XXX: maybe we want to stick that in a utility module
20#[derive(Clone, Debug, Default)]
21enum ReverseReference<T> {
22    Loaded(T),
23    #[default]
24    Lazy,
25}
26
27/// A compat session represents a client session which used the legacy Matrix
28/// login API.
29#[derive(Description)]
30pub struct CompatSession {
31    session: mas_data_model::CompatSession,
32    sso_login: ReverseReference<Option<mas_data_model::CompatSsoLogin>>,
33}
34
35impl CompatSession {
36    pub fn new(session: mas_data_model::CompatSession) -> Self {
37        Self {
38            session,
39            sso_login: ReverseReference::Lazy,
40        }
41    }
42
43    /// Save an eagerly loaded SSO login.
44    pub fn with_loaded_sso_login(
45        mut self,
46        sso_login: Option<mas_data_model::CompatSsoLogin>,
47    ) -> Self {
48        self.sso_login = ReverseReference::Loaded(sso_login);
49        self
50    }
51}
52
53/// The type of a compatibility session.
54#[derive(Enum, Copy, Clone, Eq, PartialEq)]
55pub enum CompatSessionType {
56    /// The session was created by a SSO login.
57    SsoLogin,
58
59    /// The session was created by an unknown method.
60    Unknown,
61}
62
63#[Object(use_type_description)]
64impl CompatSession {
65    /// ID of the object.
66    pub async fn id(&self) -> ID {
67        NodeType::CompatSession.id(self.session.id)
68    }
69
70    /// The user authorized for this session.
71    async fn user(&self, ctx: &Context<'_>) -> Result<User, async_graphql::Error> {
72        let state = ctx.state();
73        let mut repo = state.repository().await?;
74        let user = repo
75            .user()
76            .lookup(self.session.user_id)
77            .await?
78            .context("Could not load user")?;
79        repo.cancel().await?;
80
81        Ok(User(user))
82    }
83
84    /// The Matrix Device ID of this session.
85    async fn device_id(&self) -> Option<&str> {
86        self.session.device.as_ref().map(Device::as_str)
87    }
88
89    /// When the object was created.
90    pub async fn created_at(&self) -> DateTime<Utc> {
91        self.session.created_at
92    }
93
94    /// When the session ended.
95    pub async fn finished_at(&self) -> Option<DateTime<Utc>> {
96        self.session.finished_at()
97    }
98
99    /// The user-agent with which the session was created.
100    pub async fn user_agent(&self) -> Option<UserAgent> {
101        self.session.user_agent.clone().map(UserAgent::from)
102    }
103
104    /// The associated SSO login, if any.
105    pub async fn sso_login(
106        &self,
107        ctx: &Context<'_>,
108    ) -> Result<Option<CompatSsoLogin>, async_graphql::Error> {
109        if let ReverseReference::Loaded(sso_login) = &self.sso_login {
110            return Ok(sso_login.clone().map(CompatSsoLogin));
111        }
112
113        // We need to load it on the fly
114        let state = ctx.state();
115        let mut repo = state.repository().await?;
116        let sso_login = repo
117            .compat_sso_login()
118            .find_for_session(&self.session)
119            .await
120            .context("Could not load SSO login")?;
121        repo.cancel().await?;
122
123        Ok(sso_login.map(CompatSsoLogin))
124    }
125
126    /// The browser session which started this session, if any.
127    pub async fn browser_session(
128        &self,
129        ctx: &Context<'_>,
130    ) -> Result<Option<BrowserSession>, async_graphql::Error> {
131        let Some(user_session_id) = self.session.user_session_id else {
132            return Ok(None);
133        };
134
135        let state = ctx.state();
136        let mut repo = state.repository().await?;
137        let browser_session = repo
138            .browser_session()
139            .lookup(user_session_id)
140            .await?
141            .context("Could not load browser session")?;
142        repo.cancel().await?;
143
144        Ok(Some(BrowserSession(browser_session)))
145    }
146
147    /// The state of the session.
148    pub async fn state(&self) -> SessionState {
149        match &self.session.state {
150            mas_data_model::CompatSessionState::Valid => SessionState::Active,
151            mas_data_model::CompatSessionState::Finished { .. } => SessionState::Finished,
152        }
153    }
154
155    /// The last IP address used by the session.
156    pub async fn last_active_ip(&self) -> Option<String> {
157        self.session.last_active_ip.map(|ip| ip.to_string())
158    }
159
160    /// The last time the session was active.
161    pub async fn last_active_at(&self) -> Option<DateTime<Utc>> {
162        self.session.last_active_at
163    }
164}
165
166/// A compat SSO login represents a login done through the legacy Matrix login
167/// API, via the `m.login.sso` login method.
168#[derive(Description)]
169pub struct CompatSsoLogin(pub mas_data_model::CompatSsoLogin);
170
171#[Object(use_type_description)]
172impl CompatSsoLogin {
173    /// ID of the object.
174    pub async fn id(&self) -> ID {
175        NodeType::CompatSsoLogin.id(self.0.id)
176    }
177
178    /// When the object was created.
179    pub async fn created_at(&self) -> DateTime<Utc> {
180        self.0.created_at
181    }
182
183    /// The redirect URI used during the login.
184    async fn redirect_uri(&self) -> &Url {
185        &self.0.redirect_uri
186    }
187
188    /// When the login was fulfilled, and the user was redirected back to the
189    /// client.
190    async fn fulfilled_at(&self) -> Option<DateTime<Utc>> {
191        self.0.fulfilled_at()
192    }
193
194    /// When the client exchanged the login token sent during the redirection.
195    async fn exchanged_at(&self) -> Option<DateTime<Utc>> {
196        self.0.exchanged_at()
197    }
198
199    /// The compat session which was started by this login.
200    async fn session(
201        &self,
202        ctx: &Context<'_>,
203    ) -> Result<Option<CompatSession>, async_graphql::Error> {
204        let Some(session_id) = self.0.session_id() else {
205            return Ok(None);
206        };
207
208        let state = ctx.state();
209        let mut repo = state.repository().await?;
210        let session = repo
211            .compat_session()
212            .lookup(session_id)
213            .await?
214            .context("Could not load compat session")?;
215        repo.cancel().await?;
216
217        Ok(Some(
218            CompatSession::new(session).with_loaded_sso_login(Some(self.0.clone())),
219        ))
220    }
221}