Skip to main content

mas_storage_pg/
app_session.rs

1// Copyright 2025, 2026 Element Creations Ltd.
2// Copyright 2024, 2025 New Vector Ltd.
3// Copyright 2023, 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
8//! A module containing PostgreSQL implementation of repositories for sessions
9
10use async_trait::async_trait;
11use mas_data_model::{
12    Clock, CompatSession, CompatSessionState, Device, Session, SessionState, User,
13};
14use mas_storage::{
15    Page, Pagination,
16    app_session::{AppSession, AppSessionFilter, AppSessionRepository, AppSessionState},
17    compat::CompatSessionFilter,
18    oauth2::OAuth2SessionFilter,
19};
20use oauth2_types::scope::{Scope, ScopeToken};
21use opentelemetry_semantic_conventions::trace::DB_QUERY_TEXT;
22use sea_query::{
23    Alias, ColumnRef, CommonTableExpression, Expr, PostgresQueryBuilder, Query, UnionType,
24};
25use sea_query_sqlx::SqlxBinder;
26use sqlx::PgConnection;
27use tracing::Instrument;
28use ulid::Ulid;
29use uuid::Uuid;
30
31use crate::{
32    DatabaseError, ExecuteExt,
33    errors::DatabaseInconsistencyError,
34    filter::StatementExt,
35    iden::{CompatSessions, OAuth2Sessions},
36    pagination::QueryBuilderExt,
37};
38
39/// An implementation of [`AppSessionRepository`] for a PostgreSQL connection
40pub struct PgAppSessionRepository<'c> {
41    conn: &'c mut PgConnection,
42}
43
44impl<'c> PgAppSessionRepository<'c> {
45    /// Create a new [`PgAppSessionRepository`] from an active PostgreSQL
46    /// connection
47    pub fn new(conn: &'c mut PgConnection) -> Self {
48        Self { conn }
49    }
50}
51
52mod priv_ {
53    // The enum_def macro generates a public enum, which we don't want, because it
54    // triggers the missing docs warning
55
56    use std::net::IpAddr;
57
58    use chrono::{DateTime, Utc};
59    use mas_storage::pagination::Node;
60    use sea_query::enum_def;
61    use ulid::Ulid;
62    use uuid::Uuid;
63
64    #[derive(sqlx::FromRow)]
65    #[enum_def]
66    pub(super) struct AppSessionLookup {
67        pub(super) cursor: Uuid,
68        pub(super) compat_session_id: Option<Uuid>,
69        pub(super) oauth2_session_id: Option<Uuid>,
70        pub(super) oauth2_client_id: Option<Uuid>,
71        pub(super) user_session_id: Option<Uuid>,
72        pub(super) user_id: Option<Uuid>,
73        pub(super) scope_list: Option<Vec<String>>,
74        pub(super) device_id: Option<String>,
75        pub(super) human_name: Option<String>,
76        pub(super) created_at: DateTime<Utc>,
77        pub(super) finished_at: Option<DateTime<Utc>>,
78        pub(super) is_synapse_admin: Option<bool>,
79        pub(super) user_agent: Option<String>,
80        pub(super) last_active_at: Option<DateTime<Utc>>,
81        pub(super) last_active_ip: Option<IpAddr>,
82    }
83
84    impl Node<Ulid> for AppSessionLookup {
85        fn cursor(&self) -> Ulid {
86            self.cursor.into()
87        }
88    }
89}
90
91use priv_::{AppSessionLookup, AppSessionLookupIden};
92
93impl TryFrom<AppSessionLookup> for AppSession {
94    type Error = DatabaseError;
95
96    fn try_from(value: AppSessionLookup) -> Result<Self, Self::Error> {
97        // This is annoying to do, but we have to match on all the fields to determine
98        // whether it's a compat session or an oauth2 session
99        let AppSessionLookup {
100            cursor,
101            compat_session_id,
102            oauth2_session_id,
103            oauth2_client_id,
104            user_session_id,
105            user_id,
106            scope_list,
107            device_id,
108            human_name,
109            created_at,
110            finished_at,
111            is_synapse_admin,
112            user_agent,
113            last_active_at,
114            last_active_ip,
115        } = value;
116
117        let user_session_id = user_session_id.map(Ulid::from);
118
119        match (
120            compat_session_id,
121            oauth2_session_id,
122            oauth2_client_id,
123            user_id,
124            scope_list,
125            device_id,
126            is_synapse_admin,
127        ) {
128            (
129                Some(compat_session_id),
130                None,
131                None,
132                Some(user_id),
133                None,
134                device_id_opt,
135                Some(is_synapse_admin),
136            ) => {
137                let id = compat_session_id.into();
138                let device = device_id_opt.map(Device::from);
139
140                let state = match finished_at {
141                    None => CompatSessionState::Valid,
142                    Some(finished_at) => CompatSessionState::Finished { finished_at },
143                };
144
145                let session = CompatSession {
146                    id,
147                    state,
148                    user_id: user_id.into(),
149                    device,
150                    human_name,
151                    user_session_id,
152                    created_at,
153                    is_synapse_admin,
154                    user_agent,
155                    last_active_at,
156                    last_active_ip,
157                };
158
159                Ok(AppSession::Compat(Box::new(session)))
160            }
161
162            (
163                None,
164                Some(oauth2_session_id),
165                Some(oauth2_client_id),
166                user_id,
167                Some(scope_list),
168                None,
169                None,
170            ) => {
171                let id = oauth2_session_id.into();
172                let scope: Result<Scope, _> =
173                    scope_list.iter().map(|s| s.parse::<ScopeToken>()).collect();
174                let scope = scope.map_err(|e| {
175                    DatabaseInconsistencyError::on("oauth2_sessions")
176                        .column("scope")
177                        .row(id)
178                        .source(e)
179                })?;
180
181                let state = match value.finished_at {
182                    None => SessionState::Valid,
183                    Some(finished_at) => SessionState::Finished { finished_at },
184                };
185
186                let session = Session {
187                    id,
188                    state,
189                    created_at,
190                    client_id: oauth2_client_id.into(),
191                    user_id: user_id.map(Ulid::from),
192                    user_session_id,
193                    scope,
194                    user_agent,
195                    last_active_at,
196                    last_active_ip,
197                    human_name,
198                };
199
200                Ok(AppSession::OAuth2(Box::new(session)))
201            }
202
203            _ => Err(DatabaseInconsistencyError::on("sessions")
204                .row(cursor.into())
205                .into()),
206        }
207    }
208}
209
210/// Split a [`AppSessionFilter`] into two separate filters: a
211/// [`CompatSessionFilter`] and an [`OAuth2SessionFilter`].
212fn split_filter(
213    filter: AppSessionFilter<'_>,
214) -> (CompatSessionFilter<'_>, OAuth2SessionFilter<'_>) {
215    let mut compat_filter = CompatSessionFilter::new();
216    let mut oauth2_filter = OAuth2SessionFilter::new();
217
218    if let Some(user) = filter.user() {
219        compat_filter = compat_filter.for_user(user);
220        oauth2_filter = oauth2_filter.for_user(user);
221    }
222
223    match filter.state() {
224        Some(AppSessionState::Active) => {
225            compat_filter = compat_filter.active_only();
226            oauth2_filter = oauth2_filter.active_only();
227        }
228        Some(AppSessionState::Finished) => {
229            compat_filter = compat_filter.finished_only();
230            oauth2_filter = oauth2_filter.finished_only();
231        }
232        None => {}
233    }
234
235    if let Some(device) = filter.device() {
236        compat_filter = compat_filter.for_device(device);
237        oauth2_filter = oauth2_filter.for_device(device);
238    }
239
240    if let Some(browser_session) = filter.browser_session() {
241        compat_filter = compat_filter.for_browser_session(browser_session);
242        oauth2_filter = oauth2_filter.for_browser_session(browser_session);
243    }
244
245    if let Some(last_active_before) = filter.last_active_before() {
246        compat_filter = compat_filter.with_last_active_before(last_active_before);
247        oauth2_filter = oauth2_filter.with_last_active_before(last_active_before);
248    }
249
250    if let Some(last_active_after) = filter.last_active_after() {
251        compat_filter = compat_filter.with_last_active_after(last_active_after);
252        oauth2_filter = oauth2_filter.with_last_active_after(last_active_after);
253    }
254
255    if let Some(created_before) = filter.created_before() {
256        compat_filter = compat_filter.with_created_before(created_before);
257        oauth2_filter = oauth2_filter.with_created_before(created_before);
258    }
259
260    if let Some(created_after) = filter.created_after() {
261        compat_filter = compat_filter.with_created_after(created_after);
262        oauth2_filter = oauth2_filter.with_created_after(created_after);
263    }
264
265    (compat_filter, oauth2_filter)
266}
267
268#[async_trait]
269impl AppSessionRepository for PgAppSessionRepository<'_> {
270    type Error = DatabaseError;
271
272    #[tracing::instrument(
273        name = "db.app_session.list",
274        fields(
275            db.query.text,
276        ),
277        skip_all,
278    )]
279    async fn list(
280        &mut self,
281        filter: AppSessionFilter<'_>,
282        pagination: Pagination,
283    ) -> Result<Page<AppSession>, Self::Error> {
284        let (compat_filter, oauth2_filter) = split_filter(filter);
285
286        let mut oauth2_session_select = Query::select()
287            .expr_as(
288                Expr::col((OAuth2Sessions::Table, OAuth2Sessions::OAuth2SessionId)),
289                AppSessionLookupIden::Cursor,
290            )
291            .expr_as(Expr::cust("NULL"), AppSessionLookupIden::CompatSessionId)
292            .expr_as(
293                Expr::col((OAuth2Sessions::Table, OAuth2Sessions::OAuth2SessionId)),
294                AppSessionLookupIden::Oauth2SessionId,
295            )
296            .expr_as(
297                Expr::col((OAuth2Sessions::Table, OAuth2Sessions::OAuth2ClientId)),
298                AppSessionLookupIden::Oauth2ClientId,
299            )
300            .expr_as(
301                Expr::col((OAuth2Sessions::Table, OAuth2Sessions::UserSessionId)),
302                AppSessionLookupIden::UserSessionId,
303            )
304            .expr_as(
305                Expr::col((OAuth2Sessions::Table, OAuth2Sessions::UserId)),
306                AppSessionLookupIden::UserId,
307            )
308            .expr_as(
309                Expr::col((OAuth2Sessions::Table, OAuth2Sessions::ScopeList)),
310                AppSessionLookupIden::ScopeList,
311            )
312            .expr_as(Expr::cust("NULL"), AppSessionLookupIden::DeviceId)
313            .expr_as(
314                Expr::col((OAuth2Sessions::Table, OAuth2Sessions::HumanName)),
315                AppSessionLookupIden::HumanName,
316            )
317            .expr_as(
318                Expr::col((OAuth2Sessions::Table, OAuth2Sessions::CreatedAt)),
319                AppSessionLookupIden::CreatedAt,
320            )
321            .expr_as(
322                Expr::col((OAuth2Sessions::Table, OAuth2Sessions::FinishedAt)),
323                AppSessionLookupIden::FinishedAt,
324            )
325            .expr_as(Expr::cust("NULL"), AppSessionLookupIden::IsSynapseAdmin)
326            .expr_as(
327                Expr::col((OAuth2Sessions::Table, OAuth2Sessions::UserAgent)),
328                AppSessionLookupIden::UserAgent,
329            )
330            .expr_as(
331                Expr::col((OAuth2Sessions::Table, OAuth2Sessions::LastActiveAt)),
332                AppSessionLookupIden::LastActiveAt,
333            )
334            .expr_as(
335                Expr::col((OAuth2Sessions::Table, OAuth2Sessions::LastActiveIp)),
336                AppSessionLookupIden::LastActiveIp,
337            )
338            .from(OAuth2Sessions::Table)
339            .apply_filter(oauth2_filter)
340            .clone();
341
342        let compat_session_select = Query::select()
343            .expr_as(
344                Expr::col((CompatSessions::Table, CompatSessions::CompatSessionId)),
345                AppSessionLookupIden::Cursor,
346            )
347            .expr_as(
348                Expr::col((CompatSessions::Table, CompatSessions::CompatSessionId)),
349                AppSessionLookupIden::CompatSessionId,
350            )
351            .expr_as(Expr::cust("NULL"), AppSessionLookupIden::Oauth2SessionId)
352            .expr_as(Expr::cust("NULL"), AppSessionLookupIden::Oauth2ClientId)
353            .expr_as(
354                Expr::col((CompatSessions::Table, CompatSessions::UserSessionId)),
355                AppSessionLookupIden::UserSessionId,
356            )
357            .expr_as(
358                Expr::col((CompatSessions::Table, CompatSessions::UserId)),
359                AppSessionLookupIden::UserId,
360            )
361            .expr_as(Expr::cust("NULL"), AppSessionLookupIden::ScopeList)
362            .expr_as(
363                Expr::col((CompatSessions::Table, CompatSessions::DeviceId)),
364                AppSessionLookupIden::DeviceId,
365            )
366            .expr_as(
367                Expr::col((CompatSessions::Table, CompatSessions::HumanName)),
368                AppSessionLookupIden::HumanName,
369            )
370            .expr_as(
371                Expr::col((CompatSessions::Table, CompatSessions::CreatedAt)),
372                AppSessionLookupIden::CreatedAt,
373            )
374            .expr_as(
375                Expr::col((CompatSessions::Table, CompatSessions::FinishedAt)),
376                AppSessionLookupIden::FinishedAt,
377            )
378            .expr_as(
379                Expr::col((CompatSessions::Table, CompatSessions::IsSynapseAdmin)),
380                AppSessionLookupIden::IsSynapseAdmin,
381            )
382            .expr_as(
383                Expr::col((CompatSessions::Table, CompatSessions::UserAgent)),
384                AppSessionLookupIden::UserAgent,
385            )
386            .expr_as(
387                Expr::col((CompatSessions::Table, CompatSessions::LastActiveAt)),
388                AppSessionLookupIden::LastActiveAt,
389            )
390            .expr_as(
391                Expr::col((CompatSessions::Table, CompatSessions::LastActiveIp)),
392                AppSessionLookupIden::LastActiveIp,
393            )
394            .from(CompatSessions::Table)
395            .apply_filter(compat_filter)
396            .clone();
397
398        let common_table_expression = CommonTableExpression::new()
399            .query(
400                oauth2_session_select
401                    .union(UnionType::All, compat_session_select)
402                    .clone(),
403            )
404            .table_name(Alias::new("sessions"))
405            .clone();
406
407        let with_clause = Query::with().cte(common_table_expression).clone();
408
409        let select = Query::select()
410            .column(ColumnRef::Asterisk(None))
411            .from(Alias::new("sessions"))
412            .generate_pagination(AppSessionLookupIden::Cursor, pagination)
413            .clone();
414
415        let (sql, arguments) = with_clause.query(select).build_sqlx(PostgresQueryBuilder);
416
417        let edges: Vec<AppSessionLookup> = sqlx::query_as_with(&sql, arguments)
418            .traced()
419            .fetch_all(&mut *self.conn)
420            .await?;
421
422        let page = pagination.process(edges).try_map(TryFrom::try_from)?;
423
424        Ok(page)
425    }
426
427    #[tracing::instrument(
428        name = "db.app_session.count",
429        fields(
430            db.query.text,
431        ),
432        skip_all,
433    )]
434    async fn count(&mut self, filter: AppSessionFilter<'_>) -> Result<usize, Self::Error> {
435        let (compat_filter, oauth2_filter) = split_filter(filter);
436        let mut oauth2_session_select = Query::select()
437            .expr(Expr::cust("1"))
438            .from(OAuth2Sessions::Table)
439            .apply_filter(oauth2_filter)
440            .clone();
441
442        let compat_session_select = Query::select()
443            .expr(Expr::cust("1"))
444            .from(CompatSessions::Table)
445            .apply_filter(compat_filter)
446            .clone();
447
448        let common_table_expression = CommonTableExpression::new()
449            .query(
450                oauth2_session_select
451                    .union(UnionType::All, compat_session_select)
452                    .clone(),
453            )
454            .table_name(Alias::new("sessions"))
455            .clone();
456
457        let with_clause = Query::with().cte(common_table_expression).clone();
458
459        let select = Query::select()
460            .expr(Expr::cust("COUNT(*)"))
461            .from(Alias::new("sessions"))
462            .clone();
463
464        let (sql, arguments) = with_clause.query(select).build_sqlx(PostgresQueryBuilder);
465
466        let count: i64 = sqlx::query_scalar_with(&sql, arguments)
467            .traced()
468            .fetch_one(&mut *self.conn)
469            .await?;
470
471        count
472            .try_into()
473            .map_err(DatabaseError::to_invalid_operation)
474    }
475
476    #[tracing::instrument(
477        name = "db.app_session.finish_sessions_to_replace_device",
478        fields(
479            db.query.text,
480            %user.id,
481            %device_id = device.as_str()
482        ),
483        skip_all,
484    )]
485    async fn finish_sessions_to_replace_device(
486        &mut self,
487        clock: &dyn Clock,
488        user: &User,
489        device: &Device,
490    ) -> Result<bool, Self::Error> {
491        let mut affected = false;
492        // TODO need to invoke this from all the oauth2 login sites
493        let span = tracing::info_span!(
494            "db.app_session.finish_sessions_to_replace_device.compat_sessions",
495            { DB_QUERY_TEXT } = tracing::field::Empty,
496        );
497        let finished_at = clock.now();
498        let compat_affected = sqlx::query!(
499            "
500                UPDATE compat_sessions SET finished_at = $3 WHERE user_id = $1 AND device_id = $2 AND finished_at IS NULL
501            ",
502            Uuid::from(user.id),
503            device.as_str(),
504            finished_at
505        )
506        .record(&span)
507        .execute(&mut *self.conn)
508        .instrument(span)
509        .await?
510        .rows_affected();
511        affected |= compat_affected > 0;
512
513        if let Ok([stable_device_as_scope_token, unstable_device_as_scope_token]) =
514            device.to_scope_token()
515        {
516            let span = tracing::info_span!(
517                "db.app_session.finish_sessions_to_replace_device.oauth2_sessions",
518                { DB_QUERY_TEXT } = tracing::field::Empty,
519            );
520            let oauth2_affected = sqlx::query!(
521                "
522                    UPDATE oauth2_sessions
523                    SET finished_at = $4
524                    WHERE user_id = $1
525                      AND ($2 = ANY(scope_list) OR $3 = ANY(scope_list))
526                      AND finished_at IS NULL
527                ",
528                Uuid::from(user.id),
529                stable_device_as_scope_token.as_str(),
530                unstable_device_as_scope_token.as_str(),
531                finished_at
532            )
533            .record(&span)
534            .execute(&mut *self.conn)
535            .instrument(span)
536            .await?
537            .rows_affected();
538            affected |= oauth2_affected > 0;
539        }
540
541        Ok(affected)
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use chrono::Duration;
548    use mas_data_model::{Clock, Device, clock::MockClock};
549    use mas_storage::{
550        Pagination, RepositoryAccess,
551        app_session::{AppSession, AppSessionFilter},
552        oauth2::OAuth2SessionRepository,
553    };
554    use oauth2_types::{
555        requests::GrantType,
556        scope::{OPENID, Scope},
557    };
558    use rand::SeedableRng;
559    use rand_chacha::ChaChaRng;
560    use sqlx::PgPool;
561
562    use crate::PgRepository;
563
564    #[sqlx::test(migrator = "crate::MIGRATOR")]
565    async fn test_app_repo(pool: PgPool) {
566        let mut rng = ChaChaRng::seed_from_u64(42);
567        let clock = MockClock::default();
568        let mut repo = PgRepository::from_pool(&pool).await.unwrap();
569
570        // Create a user
571        let user = repo
572            .user()
573            .add(&mut rng, &clock, "john".to_owned())
574            .await
575            .unwrap();
576
577        let all = AppSessionFilter::new().for_user(&user);
578        let active = all.active_only();
579        let finished = all.finished_only();
580        let pagination = Pagination::first(10);
581
582        assert_eq!(repo.app_session().count(all).await.unwrap(), 0);
583        assert_eq!(repo.app_session().count(active).await.unwrap(), 0);
584        assert_eq!(repo.app_session().count(finished).await.unwrap(), 0);
585
586        let full_list = repo.app_session().list(all, pagination).await.unwrap();
587        assert_eq!(full_list.edges, []);
588        let active_list = repo.app_session().list(active, pagination).await.unwrap();
589        assert_eq!(active_list.edges, []);
590        let finished_list = repo.app_session().list(finished, pagination).await.unwrap();
591        assert_eq!(finished_list.edges, []);
592
593        // Start a compat session for that user
594        let device = Device::generate(&mut rng);
595        let compat_session = repo
596            .compat_session()
597            .add(&mut rng, &clock, &user, device.clone(), None, false, None)
598            .await
599            .unwrap();
600
601        assert_eq!(repo.app_session().count(all).await.unwrap(), 1);
602        assert_eq!(repo.app_session().count(active).await.unwrap(), 1);
603        assert_eq!(repo.app_session().count(finished).await.unwrap(), 0);
604
605        let full_list = repo.app_session().list(all, pagination).await.unwrap();
606        assert_eq!(full_list.edges.len(), 1);
607        assert_eq!(
608            full_list.edges[0].node,
609            AppSession::Compat(Box::new(compat_session.clone()))
610        );
611        let active_list = repo.app_session().list(active, pagination).await.unwrap();
612        assert_eq!(active_list.edges.len(), 1);
613        assert_eq!(
614            active_list.edges[0].node,
615            AppSession::Compat(Box::new(compat_session.clone()))
616        );
617        let finished_list = repo.app_session().list(finished, pagination).await.unwrap();
618        assert_eq!(finished_list.edges, []);
619
620        // Finish the session
621        let compat_session = repo
622            .compat_session()
623            .finish(&clock, compat_session)
624            .await
625            .unwrap();
626
627        assert_eq!(repo.app_session().count(all).await.unwrap(), 1);
628        assert_eq!(repo.app_session().count(active).await.unwrap(), 0);
629        assert_eq!(repo.app_session().count(finished).await.unwrap(), 1);
630
631        let full_list = repo.app_session().list(all, pagination).await.unwrap();
632        assert_eq!(full_list.edges.len(), 1);
633        assert_eq!(
634            full_list.edges[0].node,
635            AppSession::Compat(Box::new(compat_session.clone()))
636        );
637        let active_list = repo.app_session().list(active, pagination).await.unwrap();
638        assert_eq!(active_list.edges, []);
639        let finished_list = repo.app_session().list(finished, pagination).await.unwrap();
640        assert_eq!(finished_list.edges.len(), 1);
641        assert_eq!(
642            finished_list.edges[0].node,
643            AppSession::Compat(Box::new(compat_session.clone()))
644        );
645
646        // Start an OAuth2 session
647        let (client, _) = repo
648            .oauth2_client()
649            .add_or_reuse(
650                &mut rng,
651                &clock,
652                vec!["https://example.com/redirect".parse().unwrap()],
653                None,
654                None,
655                None,
656                vec![GrantType::AuthorizationCode],
657                Some("First client".to_owned()),
658                Some("https://example.com/logo.png".parse().unwrap()),
659                Some("https://example.com/".parse().unwrap()),
660                Some("https://example.com/policy".parse().unwrap()),
661                Some("https://example.com/tos".parse().unwrap()),
662                Some("https://example.com/jwks.json".parse().unwrap()),
663                None,
664                None,
665                None,
666                None,
667                None,
668                Some("https://example.com/login".parse().unwrap()),
669            )
670            .await
671            .unwrap();
672
673        let device2 = Device::generate(&mut rng);
674        let scope: Scope = [OPENID]
675            .into_iter()
676            .chain(device2.to_scope_token().unwrap().into_iter())
677            .collect();
678
679        // We're moving the clock forward by 1 minute between each session to ensure
680        // we're getting consistent ordering in lists.
681        clock.advance(Duration::try_minutes(1).unwrap());
682
683        let oauth_session = repo
684            .oauth2_session()
685            .add(&mut rng, &clock, &client, Some(&user), None, scope)
686            .await
687            .unwrap();
688
689        assert_eq!(repo.app_session().count(all).await.unwrap(), 2);
690        assert_eq!(repo.app_session().count(active).await.unwrap(), 1);
691        assert_eq!(repo.app_session().count(finished).await.unwrap(), 1);
692
693        let full_list = repo.app_session().list(all, pagination).await.unwrap();
694        assert_eq!(full_list.edges.len(), 2);
695        assert_eq!(
696            full_list.edges[0].node,
697            AppSession::Compat(Box::new(compat_session.clone()))
698        );
699        assert_eq!(
700            full_list.edges[1].node,
701            AppSession::OAuth2(Box::new(oauth_session.clone()))
702        );
703
704        let active_list = repo.app_session().list(active, pagination).await.unwrap();
705        assert_eq!(active_list.edges.len(), 1);
706        assert_eq!(
707            active_list.edges[0].node,
708            AppSession::OAuth2(Box::new(oauth_session.clone()))
709        );
710
711        let finished_list = repo.app_session().list(finished, pagination).await.unwrap();
712        assert_eq!(finished_list.edges.len(), 1);
713        assert_eq!(
714            finished_list.edges[0].node,
715            AppSession::Compat(Box::new(compat_session.clone()))
716        );
717
718        // Finish the session
719        let oauth_session = repo
720            .oauth2_session()
721            .finish(&clock, oauth_session)
722            .await
723            .unwrap();
724
725        assert_eq!(repo.app_session().count(all).await.unwrap(), 2);
726        assert_eq!(repo.app_session().count(active).await.unwrap(), 0);
727        assert_eq!(repo.app_session().count(finished).await.unwrap(), 2);
728
729        let full_list = repo.app_session().list(all, pagination).await.unwrap();
730        assert_eq!(full_list.edges.len(), 2);
731        assert_eq!(
732            full_list.edges[0].node,
733            AppSession::Compat(Box::new(compat_session.clone()))
734        );
735        assert_eq!(
736            full_list.edges[1].node,
737            AppSession::OAuth2(Box::new(oauth_session.clone()))
738        );
739
740        let active_list = repo.app_session().list(active, pagination).await.unwrap();
741        assert_eq!(active_list.edges, []);
742
743        let finished_list = repo.app_session().list(finished, pagination).await.unwrap();
744        assert_eq!(finished_list.edges.len(), 2);
745        assert_eq!(
746            finished_list.edges[0].node,
747            AppSession::Compat(Box::new(compat_session.clone()))
748        );
749        assert_eq!(
750            full_list.edges[1].node,
751            AppSession::OAuth2(Box::new(oauth_session.clone()))
752        );
753
754        // Query by device
755        let filter = AppSessionFilter::new().for_device(&device);
756        assert_eq!(repo.app_session().count(filter).await.unwrap(), 1);
757        let list = repo.app_session().list(filter, pagination).await.unwrap();
758        assert_eq!(list.edges.len(), 1);
759        assert_eq!(
760            list.edges[0].node,
761            AppSession::Compat(Box::new(compat_session.clone()))
762        );
763
764        let filter = AppSessionFilter::new().for_device(&device2);
765        assert_eq!(repo.app_session().count(filter).await.unwrap(), 1);
766        let list = repo.app_session().list(filter, pagination).await.unwrap();
767        assert_eq!(list.edges.len(), 1);
768        assert_eq!(
769            list.edges[0].node,
770            AppSession::OAuth2(Box::new(oauth_session.clone()))
771        );
772
773        // Create a second user
774        let user2 = repo
775            .user()
776            .add(&mut rng, &clock, "alice".to_owned())
777            .await
778            .unwrap();
779
780        // If we list/count for this user, we should get nothing
781        let filter = AppSessionFilter::new().for_user(&user2);
782        assert_eq!(repo.app_session().count(filter).await.unwrap(), 0);
783        let list = repo.app_session().list(filter, pagination).await.unwrap();
784        assert_eq!(list.edges, []);
785    }
786
787    /// Test the created-at filters on [`AppSessionFilter`]: they should apply
788    /// to both the compat and the `OAuth2` branches of the union.
789    #[sqlx::test(migrator = "crate::MIGRATOR")]
790    async fn test_list_app_sessions_by_created_at(pool: PgPool) {
791        let mut rng = ChaChaRng::seed_from_u64(42);
792        let clock = MockClock::default();
793        let mut repo = PgRepository::from_pool(&pool).await.unwrap();
794
795        let user = repo
796            .user()
797            .add(&mut rng, &clock, "alice".to_owned())
798            .await
799            .unwrap();
800
801        // Create a compat session
802        let device = Device::generate(&mut rng);
803        let compat_session = repo
804            .compat_session()
805            .add(&mut rng, &clock, &user, device, None, false, None)
806            .await
807            .unwrap();
808        clock.advance(Duration::try_minutes(1).unwrap());
809
810        // Capture a cutoff that sits between the compat session and the
811        // OAuth2 one
812        let cutoff = clock.now();
813        clock.advance(Duration::try_minutes(1).unwrap());
814
815        // Create an OAuth2 session for the same user
816        let (client, _) = repo
817            .oauth2_client()
818            .add_or_reuse(
819                &mut rng,
820                &clock,
821                vec!["https://example.com/redirect".parse().unwrap()],
822                None,
823                None,
824                None,
825                vec![GrantType::AuthorizationCode],
826                Some("Test client".to_owned()),
827                Some("https://example.com/logo.png".parse().unwrap()),
828                Some("https://example.com/".parse().unwrap()),
829                Some("https://example.com/policy".parse().unwrap()),
830                Some("https://example.com/tos".parse().unwrap()),
831                Some("https://example.com/jwks.json".parse().unwrap()),
832                None,
833                None,
834                None,
835                None,
836                None,
837                Some("https://example.com/login".parse().unwrap()),
838            )
839            .await
840            .unwrap();
841        let scope: Scope = [OPENID].into_iter().collect();
842        let oauth_session = repo
843            .oauth2_session()
844            .add(&mut rng, &clock, &client, Some(&user), None, scope)
845            .await
846            .unwrap();
847
848        let pagination = Pagination::first(10);
849
850        // Sessions created before the cutoff: only the compat one
851        let filter = AppSessionFilter::new().with_created_before(cutoff);
852        let list = repo.app_session().list(filter, pagination).await.unwrap();
853        assert_eq!(list.edges.len(), 1);
854        assert_eq!(
855            list.edges[0].node,
856            AppSession::Compat(Box::new(compat_session.clone()))
857        );
858        assert_eq!(repo.app_session().count(filter).await.unwrap(), 1);
859
860        // Sessions created after the cutoff: only the OAuth2 one
861        let filter = AppSessionFilter::new().with_created_after(cutoff);
862        let list = repo.app_session().list(filter, pagination).await.unwrap();
863        assert_eq!(list.edges.len(), 1);
864        assert_eq!(
865            list.edges[0].node,
866            AppSession::OAuth2(Box::new(oauth_session.clone()))
867        );
868        assert_eq!(repo.app_session().count(filter).await.unwrap(), 1);
869    }
870}