1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// Copyright 2024 New Vector Ltd.
// Copyright 2024 The Matrix.org Foundation C.I.C.
//
// SPDX-License-Identifier: AGPL-3.0-only
// Please see LICENSE in the repository root for full details.

use std::net::IpAddr;

use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use mas_data_model::{UserAgent, UserEmail, UserRecoverySession, UserRecoveryTicket};
use mas_storage::{user::UserRecoveryRepository, Clock};
use rand::RngCore;
use sqlx::PgConnection;
use ulid::Ulid;
use uuid::Uuid;

use crate::{DatabaseError, ExecuteExt};

/// An implementation of [`UserRecoveryRepository`] for a PostgreSQL connection
pub struct PgUserRecoveryRepository<'c> {
    conn: &'c mut PgConnection,
}

impl<'c> PgUserRecoveryRepository<'c> {
    /// Create a new [`PgUserRecoveryRepository`] from an active PostgreSQL
    /// connection
    pub fn new(conn: &'c mut PgConnection) -> Self {
        Self { conn }
    }
}

struct UserRecoverySessionRow {
    user_recovery_session_id: Uuid,
    email: String,
    user_agent: String,
    ip_address: Option<IpAddr>,
    locale: String,
    created_at: DateTime<Utc>,
    consumed_at: Option<DateTime<Utc>>,
}

impl From<UserRecoverySessionRow> for UserRecoverySession {
    fn from(row: UserRecoverySessionRow) -> Self {
        UserRecoverySession {
            id: row.user_recovery_session_id.into(),
            email: row.email,
            user_agent: UserAgent::parse(row.user_agent),
            ip_address: row.ip_address,
            locale: row.locale,
            created_at: row.created_at,
            consumed_at: row.consumed_at,
        }
    }
}

struct UserRecoveryTicketRow {
    user_recovery_ticket_id: Uuid,
    user_recovery_session_id: Uuid,
    user_email_id: Uuid,
    ticket: String,
    created_at: DateTime<Utc>,
    expires_at: DateTime<Utc>,
}

impl From<UserRecoveryTicketRow> for UserRecoveryTicket {
    fn from(row: UserRecoveryTicketRow) -> Self {
        Self {
            id: row.user_recovery_ticket_id.into(),
            user_recovery_session_id: row.user_recovery_session_id.into(),
            user_email_id: row.user_email_id.into(),
            ticket: row.ticket,
            created_at: row.created_at,
            expires_at: row.expires_at,
        }
    }
}

#[async_trait]
impl<'c> UserRecoveryRepository for PgUserRecoveryRepository<'c> {
    type Error = DatabaseError;

    #[tracing::instrument(
        name = "db.user_recovery.lookup_session",
        skip_all,
        fields(
            db.query.text,
            user_recovery_session.id = %id,
        ),
        err,
    )]
    async fn lookup_session(
        &mut self,
        id: Ulid,
    ) -> Result<Option<UserRecoverySession>, Self::Error> {
        let row = sqlx::query_as!(
            UserRecoverySessionRow,
            r#"
                SELECT
                      user_recovery_session_id
                    , email
                    , user_agent
                    , ip_address as "ip_address: IpAddr"
                    , locale
                    , created_at
                    , consumed_at
                FROM user_recovery_sessions
                WHERE user_recovery_session_id = $1
            "#,
            Uuid::from(id),
        )
        .traced()
        .fetch_optional(&mut *self.conn)
        .await?;

        let Some(row) = row else {
            return Ok(None);
        };

        Ok(Some(row.into()))
    }

    #[tracing::instrument(
        name = "db.user_recovery.add_session",
        skip_all,
        fields(
            db.query.text,
            user_recovery_session.id,
            user_recovery_session.email = email,
            user_recovery_session.user_agent = &*user_agent,
            user_recovery_session.ip_address = ip_address.map(|ip| ip.to_string()),
        )
    )]
    async fn add_session(
        &mut self,
        rng: &mut (dyn RngCore + Send),
        clock: &dyn Clock,
        email: String,
        user_agent: UserAgent,
        ip_address: Option<IpAddr>,
        locale: String,
    ) -> Result<UserRecoverySession, Self::Error> {
        let created_at = clock.now();
        let id = Ulid::from_datetime_with_source(created_at.into(), rng);
        tracing::Span::current().record("user_recovery_session.id", tracing::field::display(id));
        sqlx::query!(
            r#"
                INSERT INTO user_recovery_sessions (
                      user_recovery_session_id
                    , email
                    , user_agent
                    , ip_address
                    , locale
                    , created_at
                )
                VALUES ($1, $2, $3, $4, $5, $6)
            "#,
            Uuid::from(id),
            &email,
            &*user_agent,
            ip_address as Option<IpAddr>,
            &locale,
            created_at,
        )
        .traced()
        .execute(&mut *self.conn)
        .await?;

        let user_recovery_session = UserRecoverySession {
            id,
            email,
            user_agent,
            ip_address,
            locale,
            created_at,
            consumed_at: None,
        };

        Ok(user_recovery_session)
    }

    #[tracing::instrument(
        name = "db.user_recovery.find_ticket",
        skip_all,
        fields(
            db.query.text,
            user_recovery_ticket.id = ticket,
        ),
        err,
    )]
    async fn find_ticket(
        &mut self,
        ticket: &str,
    ) -> Result<Option<UserRecoveryTicket>, Self::Error> {
        let row = sqlx::query_as!(
            UserRecoveryTicketRow,
            r#"
                SELECT
                      user_recovery_ticket_id
                    , user_recovery_session_id
                    , user_email_id
                    , ticket
                    , created_at
                    , expires_at
                FROM user_recovery_tickets
                WHERE ticket = $1
            "#,
            ticket,
        )
        .traced()
        .fetch_optional(&mut *self.conn)
        .await?;

        let Some(row) = row else {
            return Ok(None);
        };

        Ok(Some(row.into()))
    }

    #[tracing::instrument(
        name = "db.user_recovery.add_ticket",
        skip_all,
        fields(
            db.query.text,
            user_recovery_ticket.id,
            user_recovery_ticket.id = ticket,
            %user_recovery_session.id,
            %user_email.id,
        )
    )]
    async fn add_ticket(
        &mut self,
        rng: &mut (dyn RngCore + Send),
        clock: &dyn Clock,
        user_recovery_session: &UserRecoverySession,
        user_email: &UserEmail,
        ticket: String,
    ) -> Result<UserRecoveryTicket, Self::Error> {
        let created_at = clock.now();
        let id = Ulid::from_datetime_with_source(created_at.into(), rng);
        tracing::Span::current().record("user_recovery_ticket.id", tracing::field::display(id));

        // TODO: move that to a parameter
        let expires_at = created_at + Duration::minutes(10);

        sqlx::query!(
            r#"
                INSERT INTO user_recovery_tickets (
                      user_recovery_ticket_id
                    , user_recovery_session_id
                    , user_email_id
                    , ticket
                    , created_at
                    , expires_at
                )
                VALUES ($1, $2, $3, $4, $5, $6)
            "#,
            Uuid::from(id),
            Uuid::from(user_recovery_session.id),
            Uuid::from(user_email.id),
            &ticket,
            created_at,
            expires_at,
        )
        .traced()
        .execute(&mut *self.conn)
        .await?;

        let ticket = UserRecoveryTicket {
            id,
            user_recovery_session_id: user_recovery_session.id,
            user_email_id: user_email.id,
            ticket,
            created_at,
            expires_at,
        };

        Ok(ticket)
    }

    #[tracing::instrument(
        name = "db.user_recovery.consume_ticket",
        skip_all,
        fields(
            db.query.text,
            %user_recovery_ticket.id,
            user_email.id = %user_recovery_ticket.user_email_id,
            %user_recovery_session.id,
            %user_recovery_session.email,
        ),
        err,
    )]
    async fn consume_ticket(
        &mut self,
        clock: &dyn Clock,
        user_recovery_ticket: UserRecoveryTicket,
        mut user_recovery_session: UserRecoverySession,
    ) -> Result<UserRecoverySession, Self::Error> {
        // We don't really use the ticket, we just want to make sure we drop it
        let _ = user_recovery_ticket;

        // This should have been checked by the caller
        if user_recovery_session.consumed_at.is_some() {
            return Err(DatabaseError::invalid_operation());
        }

        let consumed_at = clock.now();

        let res = sqlx::query!(
            r#"
                UPDATE user_recovery_sessions
                SET consumed_at = $1
                WHERE user_recovery_session_id = $2
            "#,
            consumed_at,
            Uuid::from(user_recovery_session.id),
        )
        .traced()
        .execute(&mut *self.conn)
        .await?;

        user_recovery_session.consumed_at = Some(consumed_at);

        DatabaseError::ensure_affected_rows(&res, 1)?;

        Ok(user_recovery_session)
    }
}