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
// Copyright 2023 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 oauth2_types::scope::ScopeToken;
use rand::{
    distributions::{Alphanumeric, DistString},
    RngCore,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;

static GENERATED_DEVICE_ID_LENGTH: usize = 10;
static DEVICE_SCOPE_PREFIX: &str = "urn:matrix:org.matrix.msc2967.client:device:";

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Device {
    id: String,
}

#[derive(Debug, Error)]
pub enum InvalidDeviceID {
    #[error("Device ID contains invalid characters")]
    InvalidCharacters,
}

impl Device {
    /// Get the corresponding [`ScopeToken`] for that device
    #[must_use]
    pub fn to_scope_token(&self) -> ScopeToken {
        // SAFETY: the inner id should only have valid scope characters
        let Ok(scope_token) = format!("{DEVICE_SCOPE_PREFIX}{}", self.id).parse() else {
            unreachable!()
        };

        scope_token
    }

    /// Get the corresponding [`Device`] from a [`ScopeToken`]
    ///
    /// Returns `None` if the [`ScopeToken`] is not a device scope
    #[must_use]
    pub fn from_scope_token(token: &ScopeToken) -> Option<Self> {
        let id = token.as_str().strip_prefix(DEVICE_SCOPE_PREFIX)?;
        // XXX: we might be silently ignoring errors here, but it's probably fine?
        Device::try_from(id.to_owned()).ok()
    }

    /// Generate a random device ID
    pub fn generate<R: RngCore + ?Sized>(rng: &mut R) -> Self {
        let id: String = Alphanumeric.sample_string(rng, GENERATED_DEVICE_ID_LENGTH);
        Self { id }
    }

    /// Get the inner device ID as [`&str`]
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.id
    }
}

const fn valid_device_chars(c: char) -> bool {
    // This matches the regex in the policy
    c.is_ascii_alphanumeric()
        || c == '.'
        || c == '_'
        || c == '~'
        || c == '!'
        || c == '$'
        || c == '&'
        || c == '\''
        || c == '('
        || c == ')'
        || c == '*'
        || c == '+'
        || c == ','
        || c == ';'
        || c == '='
        || c == ':'
        || c == '@'
        || c == '/'
        || c == '-'
}

impl TryFrom<String> for Device {
    type Error = InvalidDeviceID;

    /// Create a [`Device`] out of an ID, validating the ID has the right shape
    fn try_from(id: String) -> Result<Self, Self::Error> {
        if !id.chars().all(valid_device_chars) {
            return Err(InvalidDeviceID::InvalidCharacters);
        }

        Ok(Self { id })
    }
}

impl std::fmt::Display for Device {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.id)
    }
}

#[cfg(test)]
mod test {
    use oauth2_types::scope::OPENID;

    use crate::Device;

    #[test]
    fn test_device_id_to_from_scope_token() {
        let device = Device::try_from("AABBCCDDEE".to_owned()).unwrap();
        let scope_token = device.to_scope_token();
        assert_eq!(
            scope_token.as_str(),
            "urn:matrix:org.matrix.msc2967.client:device:AABBCCDDEE"
        );
        assert_eq!(Device::from_scope_token(&scope_token), Some(device));
        assert_eq!(Device::from_scope_token(&OPENID), None);
    }
}