Skip to main content

vcon_server/
ids.rs

1//! Identifiers, written in lowercase hex: a tenant or a version is 128
2//! random bits, a key 64 bits.
3
4use std::fmt;
5
6/// Names a key without revealing it: an encryption key by the start of
7/// its SHA-256 (`Key::id`), an access key by 64 random bits.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub struct KeyId(pub [u8; 8]);
10
11impl KeyId {
12    /// A new random key id.
13    #[must_use]
14    pub fn generate() -> KeyId {
15        KeyId(random())
16    }
17
18    /// Reads a key id written by `Display`: exactly 16 lowercase hex
19    /// digits.
20    pub fn parse(text: &str) -> Option<KeyId> {
21        unhex(text).map(KeyId)
22    }
23
24    /// The id's 8 bytes, as catalogs store them.
25    pub(crate) fn bytes(self) -> [u8; 8] {
26        self.0
27    }
28}
29
30/// A tenant.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32pub struct TenantId(pub [u8; 16]);
33
34impl TenantId {
35    /// A new random tenant id.
36    #[must_use]
37    pub fn generate() -> TenantId {
38        TenantId(random())
39    }
40
41    /// Reads a tenant id written by `Display`: exactly 32 lowercase hex
42    /// digits.
43    pub fn parse(text: &str) -> Option<TenantId> {
44        unhex(text).map(TenantId)
45    }
46}
47
48/// A user: a person who signs in.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
50pub struct UserId(pub [u8; 16]);
51
52impl UserId {
53    /// A new random user id.
54    #[must_use]
55    pub fn generate() -> UserId {
56        UserId(random())
57    }
58
59    /// Reads a user id written by `Display`: exactly 32 lowercase hex
60    /// digits.
61    pub fn parse(text: &str) -> Option<UserId> {
62        unhex(text).map(UserId)
63    }
64}
65
66impl fmt::Display for UserId {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        hex(&self.0, f)
69    }
70}
71
72/// One stored version of a vCon.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub struct VersionId(pub [u8; 16]);
75
76impl VersionId {
77    /// A new random version id.
78    #[must_use]
79    pub fn generate() -> VersionId {
80        VersionId(random())
81    }
82}
83
84impl VersionId {
85    /// Reads a version id written by `Display`: exactly 32 lowercase hex
86    /// digits.
87    pub fn parse(text: &str) -> Option<VersionId> {
88        unhex(text).map(VersionId)
89    }
90}
91
92/// A Parquet file of packed versions.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94pub struct FileId(pub [u8; 16]);
95
96impl FileId {
97    /// A new random file id.
98    #[must_use]
99    pub fn generate() -> FileId {
100        FileId(random())
101    }
102
103    /// Reads a file id written by `Display`: exactly 32 lowercase hex
104    /// digits.
105    pub fn parse(text: &str) -> Option<FileId> {
106        unhex(text).map(FileId)
107    }
108}
109
110fn random<const N: usize>() -> [u8; N] {
111    let mut bytes = [0; N];
112    // AWS-LC's RAND_bytes aborts the process when it cannot get enough
113    // randomness, so `fill` never returns its error.
114    aws_lc_rs::rand::fill(&mut bytes).expect("AWS-LC aborts instead of failing");
115    bytes
116}
117
118/// Reads exactly 2N lowercase hex digits.
119fn unhex<const N: usize>(text: &str) -> Option<[u8; N]> {
120    let digits = text.as_bytes();
121    if digits.len() != 2 * N {
122        return None;
123    }
124    let digit = |d: u8| match d {
125        b'0'..=b'9' => Some(d - b'0'),
126        b'a'..=b'f' => Some(d - b'a' + 10),
127        _ => None,
128    };
129    let mut bytes = [0; N];
130    let (pairs, _) = digits.as_chunks::<2>();
131    for (byte, [high, low]) in bytes.iter_mut().zip(pairs) {
132        *byte = digit(*high)? << 4 | digit(*low)?;
133    }
134    Some(bytes)
135}
136
137fn hex(bytes: &[u8], f: &mut fmt::Formatter<'_>) -> fmt::Result {
138    bytes.iter().try_for_each(|b| write!(f, "{b:02x}"))
139}
140
141impl fmt::Display for KeyId {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        hex(&self.0, f)
144    }
145}
146
147impl fmt::Display for TenantId {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        hex(&self.0, f)
150    }
151}
152
153impl fmt::Display for VersionId {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        hex(&self.0, f)
156    }
157}
158
159impl fmt::Display for FileId {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        hex(&self.0, f)
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn ids_are_written_as_32_lowercase_hex_digits() {
171        let mut bytes = [0; 16];
172        bytes[0] = 0x0a;
173        bytes[15] = 0xff;
174        let expected = format!("0a{}ff", "00".repeat(14));
175        assert_eq!(
176            TenantId(bytes).to_string(),
177            expected,
178            "two lower-case hex digits per byte, in order, zeros kept"
179        );
180        assert_eq!(
181            VersionId(bytes).to_string(),
182            expected,
183            "two lower-case hex digits per byte, in order, zeros kept"
184        );
185    }
186
187    /// Every byte of `ids` varies across them.
188    fn varies(ids: &[[u8; 16]]) {
189        for i in 0..16 {
190            assert!(
191                ids.iter().any(|id| id[i] != ids[0][i]),
192                "byte {i} never varies"
193            );
194        }
195    }
196
197    #[test]
198    fn a_key_id_is_64_random_bits_written_as_16_hex_digits() {
199        let ids: Vec<[u8; 8]> = (0..8).map(|_| KeyId::generate().0).collect();
200        for i in 0..8 {
201            assert!(
202                ids.iter().any(|id| id[i] != ids[0][i]),
203                "byte {i} never varies"
204            );
205        }
206        let id = KeyId([0x0a, 0, 0, 0, 0, 0, 0, 0xff]);
207        assert_eq!(
208            id.to_string(),
209            "0a000000000000ff",
210            "two lower-case hex digits per byte, in order, zeros kept"
211        );
212        assert_eq!(
213            KeyId::parse("0a000000000000ff"),
214            Some(id),
215            "parse reads the spelling Display writes"
216        );
217        for bad in [
218            "0A000000000000FF",
219            "0a000000000000f",
220            "0a000000000000ff0",
221            "",
222        ] {
223            assert_eq!(KeyId::parse(bad), None, "{bad:?}");
224        }
225    }
226
227    #[test]
228    fn ids_are_random() {
229        varies(&(0..8).map(|_| VersionId::generate().0).collect::<Vec<_>>());
230        varies(&(0..8).map(|_| TenantId::generate().0).collect::<Vec<_>>());
231        varies(&(0..8).map(|_| FileId::generate().0).collect::<Vec<_>>());
232    }
233
234    /// A file id is written and read as a version id is, and only from its
235    /// own spelling.
236    #[test]
237    fn a_file_id_parses_only_from_its_own_spelling() {
238        let mut bytes = [0; 16];
239        bytes[0] = 0x0a;
240        bytes[15] = 0xff;
241        assert_eq!(
242            FileId(bytes).to_string(),
243            format!("0a{}ff", "00".repeat(14)),
244            "two lower-case hex digits per byte, in order, zeros kept"
245        );
246        let file = FileId::generate();
247        assert_eq!(
248            FileId::parse(&file.to_string()),
249            Some(file),
250            "parse reads the spelling Display writes"
251        );
252        let text = file.to_string();
253        for bad in misspelled(&text) {
254            if bad != text {
255                assert_eq!(
256                    FileId::parse(&bad),
257                    None,
258                    "not a file id's spelling: {bad:?}"
259                );
260            }
261        }
262    }
263
264    /// The spellings parse refuses, given one id's own spelling `text`.
265    fn misspelled(text: &str) -> [String; 7] {
266        [
267            String::new(),
268            text[..31].to_owned(),
269            format!("{text}0"),
270            text.to_uppercase(),
271            format!("g{}", &text[1..]),
272            format!("{text}.tmp"),
273            format!("+{}", &text[1..]),
274        ]
275    }
276
277    #[test]
278    fn tenant_and_version_ids_parse_only_from_their_own_spelling() {
279        let tenant = TenantId::generate();
280        let version = VersionId::generate();
281        assert_eq!(
282            TenantId::parse(&tenant.to_string()),
283            Some(tenant),
284            "parse reads the spelling Display writes"
285        );
286        assert_eq!(
287            VersionId::parse(&version.to_string()),
288            Some(version),
289            "parse reads the spelling Display writes"
290        );
291        for (text, parsed) in [
292            (
293                tenant.to_string(),
294                (|t: &str| TenantId::parse(t).is_some()) as fn(&str) -> bool,
295            ),
296            (version.to_string(), |t: &str| VersionId::parse(t).is_some()),
297        ] {
298            for bad in misspelled(&text) {
299                // An id with no letter is its own upper-case spelling.
300                if bad != text {
301                    assert!(!parsed(&bad), "not an id's own spelling: {bad:?}");
302                }
303            }
304        }
305    }
306}