Skip to main content

mas_storage_pg/user/
password.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 async_trait::async_trait;
9use chrono::{DateTime, Utc};
10use mas_data_model::{Clock, Password, UlidExt as _, User};
11use mas_storage::user::UserPasswordRepository;
12use rand::Rng;
13use sqlx::PgConnection;
14use ulid::Ulid;
15use uuid::Uuid;
16
17use crate::{DatabaseError, DatabaseInconsistencyError, tracing::ExecuteExt};
18
19/// An implementation of [`UserPasswordRepository`] for a PostgreSQL connection
20pub struct PgUserPasswordRepository<'c> {
21    conn: &'c mut PgConnection,
22}
23
24impl<'c> PgUserPasswordRepository<'c> {
25    /// Create a new [`PgUserPasswordRepository`] from an active PostgreSQL
26    /// connection
27    pub fn new(conn: &'c mut PgConnection) -> Self {
28        Self { conn }
29    }
30}
31
32struct UserPasswordLookup {
33    user_password_id: Uuid,
34    hashed_password: String,
35    version: i32,
36    upgraded_from_id: Option<Uuid>,
37    created_at: DateTime<Utc>,
38}
39
40#[async_trait]
41impl UserPasswordRepository for PgUserPasswordRepository<'_> {
42    type Error = DatabaseError;
43
44    #[tracing::instrument(
45        name = "db.user_password.active",
46        skip_all,
47        fields(
48            db.query.text,
49            %user.id,
50            %user.username,
51        ),
52    )]
53    async fn active(&mut self, user: &User) -> Result<Option<Password>, Self::Error> {
54        let res = sqlx::query_as!(
55            UserPasswordLookup,
56            r#"
57                SELECT up.user_password_id
58                     , up.hashed_password
59                     , up.version
60                     , up.upgraded_from_id
61                     , up.created_at
62                FROM user_passwords up
63                WHERE up.user_id = $1
64                ORDER BY up.created_at DESC
65                LIMIT 1
66            "#,
67            Uuid::from(user.id),
68        )
69        .traced()
70        .fetch_optional(&mut *self.conn)
71        .await?;
72
73        let Some(res) = res else { return Ok(None) };
74
75        let id = Ulid::from(res.user_password_id);
76
77        let version = res.version.try_into().map_err(|e| {
78            DatabaseInconsistencyError::on("user_passwords")
79                .column("version")
80                .row(id)
81                .source(e)
82        })?;
83
84        let upgraded_from_id = res.upgraded_from_id.map(Ulid::from);
85        let created_at = res.created_at;
86        let hashed_password = res.hashed_password;
87
88        Ok(Some(Password {
89            id,
90            hashed_password,
91            version,
92            upgraded_from_id,
93            created_at,
94        }))
95    }
96
97    #[tracing::instrument(
98        name = "db.user_password.add",
99        skip_all,
100        fields(
101            db.query.text,
102            %user.id,
103            %user.username,
104            user_password.id,
105            user_password.version = version,
106        ),
107    )]
108    async fn add(
109        &mut self,
110        rng: &mut (dyn Rng + Send),
111        clock: &dyn Clock,
112        user: &User,
113        version: u16,
114        hashed_password: String,
115        upgraded_from: Option<&Password>,
116    ) -> Result<Password, Self::Error> {
117        let created_at = clock.now();
118        let id = Ulid::from_datetime_with_rng(created_at, rng);
119        tracing::Span::current().record("user_password.id", tracing::field::display(id));
120
121        let upgraded_from_id = upgraded_from.map(|p| p.id);
122
123        sqlx::query!(
124            r#"
125                INSERT INTO user_passwords
126                    (user_password_id, user_id, hashed_password, version, upgraded_from_id, created_at)
127                VALUES ($1, $2, $3, $4, $5, $6)
128            "#,
129            Uuid::from(id),
130            Uuid::from(user.id),
131            hashed_password,
132            i32::from(version),
133            upgraded_from_id.map(Uuid::from),
134            created_at,
135        )
136        .traced()
137        .execute(&mut *self.conn)
138        .await?;
139
140        Ok(Password {
141            id,
142            hashed_password,
143            version,
144            upgraded_from_id,
145            created_at,
146        })
147    }
148}