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
// Copyright 2023, 2024 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::{HashMap, HashSet};

use anyhow::Context;
use async_trait::async_trait;
use tokio::sync::RwLock;

use crate::{MatrixUser, ProvisionRequest};

struct MockUser {
    sub: String,
    avatar_url: Option<String>,
    displayname: Option<String>,
    devices: HashSet<String>,
    emails: Option<Vec<String>>,
    cross_signing_reset_allowed: bool,
    deactivated: bool,
}

/// A mock implementation of a [`HomeserverConnection`], which never fails and
/// doesn't do anything.
pub struct HomeserverConnection {
    homeserver: String,
    users: RwLock<HashMap<String, MockUser>>,
    reserved_localparts: RwLock<HashSet<&'static str>>,
}

impl HomeserverConnection {
    /// Create a new mock connection.
    pub fn new<H>(homeserver: H) -> Self
    where
        H: Into<String>,
    {
        Self {
            homeserver: homeserver.into(),
            users: RwLock::new(HashMap::new()),
            reserved_localparts: RwLock::new(HashSet::new()),
        }
    }

    pub async fn reserve_localpart(&self, localpart: &'static str) {
        self.reserved_localparts.write().await.insert(localpart);
    }
}

#[async_trait]
impl crate::HomeserverConnection for HomeserverConnection {
    type Error = anyhow::Error;

    fn homeserver(&self) -> &str {
        &self.homeserver
    }

    async fn query_user(&self, mxid: &str) -> Result<MatrixUser, Self::Error> {
        let users = self.users.read().await;
        let user = users.get(mxid).context("User not found")?;
        Ok(MatrixUser {
            displayname: user.displayname.clone(),
            avatar_url: user.avatar_url.clone(),
            deactivated: user.deactivated,
        })
    }

    async fn provision_user(&self, request: &ProvisionRequest) -> Result<bool, Self::Error> {
        let mut users = self.users.write().await;
        let inserted = !users.contains_key(request.mxid());
        let user = users.entry(request.mxid().to_owned()).or_insert(MockUser {
            sub: request.sub().to_owned(),
            avatar_url: None,
            displayname: None,
            devices: HashSet::new(),
            emails: None,
            cross_signing_reset_allowed: false,
            deactivated: false,
        });

        anyhow::ensure!(
            user.sub == request.sub(),
            "User already provisioned with different sub"
        );

        request.on_emails(|emails| {
            user.emails = emails.map(ToOwned::to_owned);
        });

        request.on_displayname(|displayname| {
            user.displayname = displayname.map(ToOwned::to_owned);
        });

        request.on_avatar_url(|avatar_url| {
            user.avatar_url = avatar_url.map(ToOwned::to_owned);
        });

        Ok(inserted)
    }

    async fn is_localpart_available(&self, localpart: &str) -> Result<bool, Self::Error> {
        if self.reserved_localparts.read().await.contains(localpart) {
            return Ok(false);
        }

        let mxid = self.mxid(localpart);
        let users = self.users.read().await;
        Ok(!users.contains_key(&mxid))
    }

    async fn create_device(&self, mxid: &str, device_id: &str) -> Result<(), Self::Error> {
        let mut users = self.users.write().await;
        let user = users.get_mut(mxid).context("User not found")?;
        user.devices.insert(device_id.to_owned());
        Ok(())
    }

    async fn delete_device(&self, mxid: &str, device_id: &str) -> Result<(), Self::Error> {
        let mut users = self.users.write().await;
        let user = users.get_mut(mxid).context("User not found")?;
        user.devices.remove(device_id);
        Ok(())
    }

    async fn sync_devices(&self, mxid: &str, devices: HashSet<String>) -> Result<(), Self::Error> {
        let mut users = self.users.write().await;
        let user = users.get_mut(mxid).context("User not found")?;
        user.devices = devices;
        Ok(())
    }

    async fn delete_user(&self, mxid: &str, erase: bool) -> Result<(), Self::Error> {
        let mut users = self.users.write().await;
        let user = users.get_mut(mxid).context("User not found")?;
        user.devices.clear();
        user.emails = None;
        user.deactivated = true;
        if erase {
            user.avatar_url = None;
            user.displayname = None;
        }

        Ok(())
    }

    async fn reactivate_user(&self, mxid: &str) -> Result<(), Self::Error> {
        let mut users = self.users.write().await;
        let user = users.get_mut(mxid).context("User not found")?;
        user.deactivated = false;

        Ok(())
    }

    async fn set_displayname(&self, mxid: &str, displayname: &str) -> Result<(), Self::Error> {
        let mut users = self.users.write().await;
        let user = users.get_mut(mxid).context("User not found")?;
        user.displayname = Some(displayname.to_owned());
        Ok(())
    }

    async fn unset_displayname(&self, mxid: &str) -> Result<(), Self::Error> {
        let mut users = self.users.write().await;
        let user = users.get_mut(mxid).context("User not found")?;
        user.displayname = None;
        Ok(())
    }

    async fn allow_cross_signing_reset(&self, mxid: &str) -> Result<(), Self::Error> {
        let mut users = self.users.write().await;
        let user = users.get_mut(mxid).context("User not found")?;
        user.cross_signing_reset_allowed = true;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::HomeserverConnection as _;

    #[tokio::test]
    async fn test_mock_connection() {
        let conn = HomeserverConnection::new("example.org");

        let mxid = "@test:example.org";
        let device = "test";
        assert_eq!(conn.homeserver(), "example.org");
        assert_eq!(conn.mxid("test"), mxid);

        assert!(conn.query_user(mxid).await.is_err());
        assert!(conn.create_device(mxid, device).await.is_err());
        assert!(conn.delete_device(mxid, device).await.is_err());

        let request = ProvisionRequest::new("@test:example.org", "test")
            .set_displayname("Test User".into())
            .set_avatar_url("mxc://example.org/1234567890".into())
            .set_emails(vec!["test@example.org".to_owned()]);

        let inserted = conn.provision_user(&request).await.unwrap();
        assert!(inserted);

        let user = conn.query_user(mxid).await.unwrap();
        assert_eq!(user.displayname, Some("Test User".into()));
        assert_eq!(user.avatar_url, Some("mxc://example.org/1234567890".into()));

        // Set the displayname again
        assert!(conn.set_displayname(mxid, "John").await.is_ok());

        let user = conn.query_user(mxid).await.unwrap();
        assert_eq!(user.displayname, Some("John".into()));

        // Unset the displayname
        assert!(conn.unset_displayname(mxid).await.is_ok());

        let user = conn.query_user(mxid).await.unwrap();
        assert_eq!(user.displayname, None);

        // Deleting a non-existent device should not fail
        assert!(conn.delete_device(mxid, device).await.is_ok());

        // Create the device
        assert!(conn.create_device(mxid, device).await.is_ok());
        // Create the same device again
        assert!(conn.create_device(mxid, device).await.is_ok());

        // XXX: there is no API to query devices yet in the trait
        // Delete the device
        assert!(conn.delete_device(mxid, device).await.is_ok());

        // The user we just created should be not available
        assert!(!conn.is_localpart_available("test").await.unwrap());
        // But another user should be
        assert!(conn.is_localpart_available("alice").await.unwrap());

        // Reserve the localpart, it should not be available anymore
        conn.reserve_localpart("alice").await;
        assert!(!conn.is_localpart_available("alice").await.unwrap());
    }
}