Skip to main content

libid_identity/
id.rs

1//! What a platform's user id must be before it is hashed into a node: one
2//! JSON token as sent, digits for a number, otherwise a string's bytes.
3//!
4//! Ids are never normalized; these checks mirror the circuits' `check_id`
5//! and run the same `idVectors` table.
6
7use crate::platforms::{
8    self as v,
9    IdError,
10};
11
12/// What a platform allows in an id.
13#[derive(Debug, Clone, Copy)]
14pub struct IdRules {
15    /// Bytes the circuit's buffer holds.
16    pub max_length: usize,
17    /// ASCII digits; otherwise printable ASCII without `"` or `\`.
18    pub decimal: bool,
19}
20
21impl IdRules {
22    /// X: decimal strings.
23    pub const X: Self = v::PLATFORM_X.id_rules;
24    /// GitHub: JSON integers.
25    pub const GITHUB: Self = v::PLATFORM_GITHUB.id_rules;
26    /// Google: the OIDC `sub`.
27    pub const GOOGLE: Self = v::PLATFORM_GOOGLE.id_rules;
28    /// Telegram: decimal user ids.
29    pub const TELEGRAM: Self = v::PLATFORM_TELEGRAM.id_rules;
30}
31
32/// Accept an id exactly as given, or say why no circuit would hash it.
33pub fn check_id(id: &str, rules: IdRules) -> Result<(), IdError> {
34    let bytes = id.as_bytes();
35    if bytes.is_empty() {
36        return Err(IdError::Empty);
37    }
38    if bytes.len() > rules.max_length {
39        return Err(IdError::TooLong);
40    }
41    let allowed = |b: u8| {
42        if rules.decimal {
43            b.is_ascii_digit()
44        } else {
45            crate::handle::is_string_byte(b)
46        }
47    };
48    if !bytes.iter().all(|&b| allowed(b)) {
49        return Err(IdError::BadCharacter);
50    }
51    Ok(())
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57    use crate::vectors::ID_VECTORS;
58
59    /// TypeScript's `checkId` words its refusals the same way.
60    #[test]
61    fn an_id_refusal_names_the_id() {
62        let refused = |id| check_id(id, IdRules::GITHUB).unwrap_err().to_string();
63        assert_eq!(refused(""), "the id is empty");
64        assert_eq!(
65            refused("12a"),
66            "the id has a byte this platform does not allow"
67        );
68    }
69
70    #[test]
71    fn every_id_vector_matches_the_shared_table() {
72        for (i, v) in ID_VECTORS.iter().enumerate() {
73            let rules = v::platform(v.platform).expect("known platform").id_rules;
74            assert_eq!(
75                check_id(v.input, rules),
76                v.expected.map(|_| ()),
77                "id vector {i}: {:?}",
78                v.input
79            );
80        }
81    }
82}