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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// Copyright 2024 New Vector Ltd.
// Copyright 2023, 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, Utc};
use mas_data_model::{BrowserSession, DeviceCodeGrant, DeviceCodeGrantState, Session, UserAgent};
use mas_storage::{
    oauth2::{OAuth2DeviceCodeGrantParams, OAuth2DeviceCodeGrantRepository},
    Clock,
};
use oauth2_types::scope::Scope;
use rand::RngCore;
use sqlx::PgConnection;
use ulid::Ulid;
use uuid::Uuid;

use crate::{errors::DatabaseInconsistencyError, DatabaseError, ExecuteExt};

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

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

struct OAuth2DeviceGrantLookup {
    oauth2_device_code_grant_id: Uuid,
    oauth2_client_id: Uuid,
    scope: String,
    device_code: String,
    user_code: String,
    created_at: DateTime<Utc>,
    expires_at: DateTime<Utc>,
    fulfilled_at: Option<DateTime<Utc>>,
    rejected_at: Option<DateTime<Utc>>,
    exchanged_at: Option<DateTime<Utc>>,
    user_session_id: Option<Uuid>,
    oauth2_session_id: Option<Uuid>,
    ip_address: Option<IpAddr>,
    user_agent: Option<String>,
}

impl TryFrom<OAuth2DeviceGrantLookup> for DeviceCodeGrant {
    type Error = DatabaseInconsistencyError;

    fn try_from(
        OAuth2DeviceGrantLookup {
            oauth2_device_code_grant_id,
            oauth2_client_id,
            scope,
            device_code,
            user_code,
            created_at,
            expires_at,
            fulfilled_at,
            rejected_at,
            exchanged_at,
            user_session_id,
            oauth2_session_id,
            ip_address,
            user_agent,
        }: OAuth2DeviceGrantLookup,
    ) -> Result<Self, Self::Error> {
        let id = Ulid::from(oauth2_device_code_grant_id);
        let client_id = Ulid::from(oauth2_client_id);

        let scope: Scope = scope.parse().map_err(|e| {
            DatabaseInconsistencyError::on("oauth2_authorization_grants")
                .column("scope")
                .row(id)
                .source(e)
        })?;

        let state = match (
            fulfilled_at,
            rejected_at,
            exchanged_at,
            user_session_id,
            oauth2_session_id,
        ) {
            (None, None, None, None, None) => DeviceCodeGrantState::Pending,

            (Some(fulfilled_at), None, None, Some(user_session_id), None) => {
                DeviceCodeGrantState::Fulfilled {
                    browser_session_id: Ulid::from(user_session_id),
                    fulfilled_at,
                }
            }

            (None, Some(rejected_at), None, Some(user_session_id), None) => {
                DeviceCodeGrantState::Rejected {
                    browser_session_id: Ulid::from(user_session_id),
                    rejected_at,
                }
            }

            (
                Some(fulfilled_at),
                None,
                Some(exchanged_at),
                Some(user_session_id),
                Some(oauth2_session_id),
            ) => DeviceCodeGrantState::Exchanged {
                browser_session_id: Ulid::from(user_session_id),
                session_id: Ulid::from(oauth2_session_id),
                fulfilled_at,
                exchanged_at,
            },

            _ => return Err(DatabaseInconsistencyError::on("oauth2_device_code_grant").row(id)),
        };

        Ok(DeviceCodeGrant {
            id,
            state,
            client_id,
            scope,
            user_code,
            device_code,
            created_at,
            expires_at,
            ip_address,
            user_agent: user_agent.map(UserAgent::parse),
        })
    }
}

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

    #[tracing::instrument(
        name = "db.oauth2_device_code_grant.add",
        skip_all,
        fields(
            db.query.text,
            oauth2_device_code.id,
            oauth2_device_code.scope = %params.scope,
            oauth2_client.id = %params.client.id,
        ),
        err,
    )]
    async fn add(
        &mut self,
        rng: &mut (dyn RngCore + Send),
        clock: &dyn Clock,
        params: OAuth2DeviceCodeGrantParams<'_>,
    ) -> Result<DeviceCodeGrant, Self::Error> {
        let now = clock.now();
        let id = Ulid::from_datetime_with_source(now.into(), rng);
        tracing::Span::current().record("oauth2_device_code.id", tracing::field::display(id));

        let created_at = now;
        let expires_at = now + params.expires_in;
        let client_id = params.client.id;

        sqlx::query!(
            r#"
                INSERT INTO "oauth2_device_code_grant"
                    ( oauth2_device_code_grant_id
                    , oauth2_client_id
                    , scope
                    , device_code
                    , user_code
                    , created_at
                    , expires_at
                    , ip_address
                    , user_agent
                    )
                VALUES
                    ($1, $2, $3, $4, $5, $6, $7, $8, $9)
            "#,
            Uuid::from(id),
            Uuid::from(client_id),
            params.scope.to_string(),
            &params.device_code,
            &params.user_code,
            created_at,
            expires_at,
            params.ip_address as Option<IpAddr>,
            params.user_agent.as_deref(),
        )
        .traced()
        .execute(&mut *self.conn)
        .await?;

        Ok(DeviceCodeGrant {
            id,
            state: DeviceCodeGrantState::Pending,
            client_id,
            scope: params.scope,
            user_code: params.user_code,
            device_code: params.device_code,
            created_at,
            expires_at,
            ip_address: params.ip_address,
            user_agent: params.user_agent,
        })
    }

    #[tracing::instrument(
        name = "db.oauth2_device_code_grant.lookup",
        skip_all,
        fields(
            db.query.text,
            oauth2_device_code.id = %id,
        ),
        err,
    )]
    async fn lookup(&mut self, id: Ulid) -> Result<Option<DeviceCodeGrant>, Self::Error> {
        let res = sqlx::query_as!(
            OAuth2DeviceGrantLookup,
            r#"
                SELECT oauth2_device_code_grant_id
                     , oauth2_client_id
                     , scope
                     , device_code
                     , user_code
                     , created_at
                     , expires_at
                     , fulfilled_at
                     , rejected_at
                     , exchanged_at
                     , user_session_id
                     , oauth2_session_id
                     , ip_address as "ip_address: IpAddr"
                     , user_agent
                FROM
                    oauth2_device_code_grant

                WHERE oauth2_device_code_grant_id = $1
            "#,
            Uuid::from(id),
        )
        .traced()
        .fetch_optional(&mut *self.conn)
        .await?;

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

        Ok(Some(res.try_into()?))
    }

    #[tracing::instrument(
        name = "db.oauth2_device_code_grant.find_by_user_code",
        skip_all,
        fields(
            db.query.text,
            oauth2_device_code.user_code = %user_code,
        ),
        err,
    )]
    async fn find_by_user_code(
        &mut self,
        user_code: &str,
    ) -> Result<Option<DeviceCodeGrant>, Self::Error> {
        let res = sqlx::query_as!(
            OAuth2DeviceGrantLookup,
            r#"
                SELECT oauth2_device_code_grant_id
                     , oauth2_client_id
                     , scope
                     , device_code
                     , user_code
                     , created_at
                     , expires_at
                     , fulfilled_at
                     , rejected_at
                     , exchanged_at
                     , user_session_id
                     , oauth2_session_id
                     , ip_address as "ip_address: IpAddr"
                     , user_agent
                FROM
                    oauth2_device_code_grant

                WHERE user_code = $1
            "#,
            user_code,
        )
        .traced()
        .fetch_optional(&mut *self.conn)
        .await?;

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

        Ok(Some(res.try_into()?))
    }

    #[tracing::instrument(
        name = "db.oauth2_device_code_grant.find_by_device_code",
        skip_all,
        fields(
            db.query.text,
            oauth2_device_code.device_code = %device_code,
        ),
        err,
    )]
    async fn find_by_device_code(
        &mut self,
        device_code: &str,
    ) -> Result<Option<DeviceCodeGrant>, Self::Error> {
        let res = sqlx::query_as!(
            OAuth2DeviceGrantLookup,
            r#"
                SELECT oauth2_device_code_grant_id
                     , oauth2_client_id
                     , scope
                     , device_code
                     , user_code
                     , created_at
                     , expires_at
                     , fulfilled_at
                     , rejected_at
                     , exchanged_at
                     , user_session_id
                     , oauth2_session_id
                     , ip_address as "ip_address: IpAddr"
                     , user_agent
                FROM
                    oauth2_device_code_grant

                WHERE device_code = $1
            "#,
            device_code,
        )
        .traced()
        .fetch_optional(&mut *self.conn)
        .await?;

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

        Ok(Some(res.try_into()?))
    }

    #[tracing::instrument(
        name = "db.oauth2_device_code_grant.fulfill",
        skip_all,
        fields(
            db.query.text,
            oauth2_device_code.id = %device_code_grant.id,
            oauth2_client.id = %device_code_grant.client_id,
            browser_session.id = %browser_session.id,
            user.id = %browser_session.user.id,
        ),
        err,
    )]
    async fn fulfill(
        &mut self,
        clock: &dyn Clock,
        device_code_grant: DeviceCodeGrant,
        browser_session: &BrowserSession,
    ) -> Result<DeviceCodeGrant, Self::Error> {
        let fulfilled_at = clock.now();
        let device_code_grant = device_code_grant
            .fulfill(browser_session, fulfilled_at)
            .map_err(DatabaseError::to_invalid_operation)?;

        let res = sqlx::query!(
            r#"
                UPDATE oauth2_device_code_grant
                SET fulfilled_at = $1
                  , user_session_id = $2
                WHERE oauth2_device_code_grant_id = $3
            "#,
            fulfilled_at,
            Uuid::from(browser_session.id),
            Uuid::from(device_code_grant.id),
        )
        .traced()
        .execute(&mut *self.conn)
        .await?;

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

        Ok(device_code_grant)
    }

    #[tracing::instrument(
        name = "db.oauth2_device_code_grant.reject",
        skip_all,
        fields(
            db.query.text,
            oauth2_device_code.id = %device_code_grant.id,
            oauth2_client.id = %device_code_grant.client_id,
            browser_session.id = %browser_session.id,
            user.id = %browser_session.user.id,
        ),
        err,
    )]
    async fn reject(
        &mut self,
        clock: &dyn Clock,
        device_code_grant: DeviceCodeGrant,
        browser_session: &BrowserSession,
    ) -> Result<DeviceCodeGrant, Self::Error> {
        let fulfilled_at = clock.now();
        let device_code_grant = device_code_grant
            .reject(browser_session, fulfilled_at)
            .map_err(DatabaseError::to_invalid_operation)?;

        let res = sqlx::query!(
            r#"
                UPDATE oauth2_device_code_grant
                SET rejected_at = $1
                  , user_session_id = $2
                WHERE oauth2_device_code_grant_id = $3
            "#,
            fulfilled_at,
            Uuid::from(browser_session.id),
            Uuid::from(device_code_grant.id),
        )
        .traced()
        .execute(&mut *self.conn)
        .await?;

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

        Ok(device_code_grant)
    }

    #[tracing::instrument(
        name = "db.oauth2_device_code_grant.exchange",
        skip_all,
        fields(
            db.query.text,
            oauth2_device_code.id = %device_code_grant.id,
            oauth2_client.id = %device_code_grant.client_id,
            oauth2_session.id = %session.id,
        ),
        err,
    )]
    async fn exchange(
        &mut self,
        clock: &dyn Clock,
        device_code_grant: DeviceCodeGrant,
        session: &Session,
    ) -> Result<DeviceCodeGrant, Self::Error> {
        let exchanged_at = clock.now();
        let device_code_grant = device_code_grant
            .exchange(session, exchanged_at)
            .map_err(DatabaseError::to_invalid_operation)?;

        let res = sqlx::query!(
            r#"
                UPDATE oauth2_device_code_grant
                SET exchanged_at = $1
                  , oauth2_session_id = $2
                WHERE oauth2_device_code_grant_id = $3
            "#,
            exchanged_at,
            Uuid::from(session.id),
            Uuid::from(device_code_grant.id),
        )
        .traced()
        .execute(&mut *self.conn)
        .await?;

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

        Ok(device_code_grant)
    }
}