authly_common/
id.rs

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
//! Authly identifier types
use std::{fmt::Debug, hash::Hash, io::Cursor, marker::PhantomData, str::FromStr};

use byteorder::{BigEndian, ReadBytesExt};
use rand::Rng;
use serde::{Deserialize, Serialize};

use crate::FromStrVisitor;

/// Authly generic 128-bit identifier
pub struct Id128<K>(u128, PhantomData<K>);

impl<K> Id128<K> {
    /// Construct a new identifier from a 128-bit unsigned int.
    pub const fn new(val: u128) -> Self {
        Self(val, PhantomData)
    }

    /// The 128-bit unsigned integer value of the ID.
    pub const fn value(&self) -> u128 {
        self.0
    }

    /// Get the byte-wise representation of the ID.
    pub const fn to_bytes(self) -> [u8; 16] {
        self.0.to_be_bytes()
    }

    /// Try to deserialize from a byte representation.
    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
        Some(Self(
            Cursor::new(bytes).read_u128::<BigEndian>().ok()?,
            PhantomData,
        ))
    }

    /// Create a new random identifier.
    pub fn random() -> Self {
        loop {
            let id: u128 = rand::thread_rng().gen();
            // low IDs are reserved for builtin/fixed
            if id > u16::MAX as u128 {
                return Self(id, PhantomData);
            }
        }
    }
}

impl<K> Clone for Id128<K> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<K> Copy for Id128<K> {}

impl<K> PartialEq for Id128<K> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<K> Eq for Id128<K> {}

impl<K> PartialOrd<Id128<K>> for Id128<K> {
    fn partial_cmp(&self, other: &Id128<K>) -> Option<std::cmp::Ordering> {
        Some(self.0.cmp(&other.0))
    }
}

impl<K> Ord for Id128<K> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.cmp(&other.0)
    }
}

impl<K> Hash for Id128<K> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl<K> Debug for Id128<K> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Kinds of typed Ids.
pub mod idkind {
    /// Trait for kinds of Ids.
    pub trait IdKind {
        /// The name of the id kind.
        fn name() -> &'static str;
    }

    /// Entity ID kind.
    pub struct Entity;

    /// Object ID kind.
    pub struct Object;

    impl IdKind for Entity {
        fn name() -> &'static str {
            "entity id"
        }
    }

    impl IdKind for Object {
        fn name() -> &'static str {
            "entity id"
        }
    }
}

/// Authly Entity ID
pub type Eid = Id128<idkind::Entity>;

/// Authly Object ID
pub type ObjId = Id128<idkind::Object>;

/// Builtin Object IDs
#[derive(Clone, Copy)]
#[repr(u32)]
pub enum BuiltinID {
    /// Id representing Authly itself
    Authly = 0,
    /// The entity property
    PropEntity = 1,
    /// The built-in authly:role for authly internal access control
    PropAuthlyRole = 2,
    /// A service role for getting an access token
    AttrAuthlyRoleGetAccessToken = 3,
    /// A service role for authenticating users
    AttrAuthlyRoleAuthenticate = 4,
    /// A user role for applying documents
    AttrAuthlyRoleApplyDocument = 5,
    /// The entity membership relation
    RelEntityMembership = 6,
    /// The username ident property
    PropUsername = 7,
    /// The email ident property
    PropEmail = 8,
    /// The password_hash text property
    PropPasswordHash = 9,
    /// The label text property
    PropLabel = 10,
    /// The kubernetes service account name property.
    /// The value format is `{namespace}/{account_name}`.
    PropK8sServiceAccount = 11,
}

impl BuiltinID {
    /// Convert to an [ObjId].
    pub const fn to_obj_id(self) -> ObjId {
        Id128(self as u128, PhantomData)
    }

    /// Get an optional label for this builtin ID.
    pub const fn label(self) -> Option<&'static str> {
        match self {
            Self::Authly => None,
            Self::PropEntity => Some("entity"),
            Self::PropAuthlyRole => Some("authly:role"),
            Self::AttrAuthlyRoleGetAccessToken => Some("get_access_token"),
            Self::AttrAuthlyRoleAuthenticate => Some("authenticate"),
            Self::AttrAuthlyRoleApplyDocument => Some("apply_document"),
            Self::PropUsername => None,
            Self::PropEmail => None,
            Self::RelEntityMembership => None,
            Self::PropPasswordHash => None,
            Self::PropLabel => None,
            Self::PropK8sServiceAccount => None,
        }
    }

    /// List attributes for an ID, in case it represents a builtin-in property.
    pub const fn attributes(self) -> &'static [BuiltinID] {
        match self {
            Self::PropAuthlyRole => &[
                Self::AttrAuthlyRoleGetAccessToken,
                Self::AttrAuthlyRoleAuthenticate,
                Self::AttrAuthlyRoleApplyDocument,
            ],
            _ => &[],
        }
    }
}

impl<K> FromStr for Id128<K> {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let id = s.parse().map_err(|_| "invalid format")?;

        if id > 0 && id < 32768 {
            return Err("invalid value");
        }

        Ok(Id128(id, PhantomData))
    }
}

impl<'de, K: idkind::IdKind> Deserialize<'de> for Id128<K> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_str(FromStrVisitor::new(K::name()))
    }
}

impl<K> Serialize for Id128<K> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.0.to_string())
    }
}