Skip to main content

libid_identity/
handle.rs

1//! Turns a typed handle into the form the identity circuits hash into a node.
2//!
3//! A-Z fold to a-z. The handle must be one JSON string as a platform sends
4//! it: printable ASCII without `"` or `\\`, and no longer than the circuit's
5//! buffer. Its format is the platform's. It mirrors the circuits'
6//! `lib/identity`; both run the `handles.json` vector table.
7
8use crate::platforms::{
9    self as v,
10    HandleError,
11};
12
13/// What one platform's circuit takes, generated from the circuits' `platforms.json`.
14#[derive(Debug, Clone, Copy)]
15pub struct Rules {
16    /// Bytes the circuit's buffer holds.
17    pub max_length: usize,
18}
19
20impl Rules {
21    /// X.
22    pub const X: Self = v::PLATFORM_X.rules;
23
24    /// GitHub.
25    pub const GITHUB: Self = v::PLATFORM_GITHUB.rules;
26
27    /// Google: an email address.
28    pub const GOOGLE: Self = v::PLATFORM_GOOGLE.rules;
29
30    /// Telegram: the username.
31    pub const TELEGRAM: Self = v::PLATFORM_TELEGRAM.rules;
32}
33
34/// The rules for a platform key (`"x"`, `"github"`, ...) from the generated
35/// table.
36pub fn rules_for(platform_key: &str) -> Option<Rules> {
37    v::platform(platform_key).map(|p| p.rules)
38}
39
40/// A byte of a JSON string as sent: printable ASCII, not `"` or `\\`.
41pub(crate) fn is_string_byte(b: u8) -> bool {
42    (0x20..=0x7e).contains(&b) && b != b'"' && b != b'\\'
43}
44
45/// The handle folded, or the reason it was refused.
46pub fn normalize(raw: &str, rules: Rules) -> Result<String, HandleError> {
47    let slice = raw.as_bytes();
48    if slice.is_empty() {
49        return Err(HandleError::Empty);
50    }
51    if slice.len() > rules.max_length {
52        return Err(HandleError::TooLong);
53    }
54    if !slice.iter().all(|&b| is_string_byte(b)) {
55        return Err(HandleError::BadCharacter);
56    }
57    // ASCII alone, so lowercasing folds A-Z and nothing else.
58    Ok(raw.to_ascii_lowercase())
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64    use crate::vectors::VECTORS;
65
66    /// The shared table, which TypeScript and the circuits also run.
67    #[test]
68    fn every_vector_matches_the_shared_table() {
69        for (i, v) in VECTORS.iter().enumerate() {
70            let rules = rules_for(v.platform).expect("known platform");
71            assert_eq!(
72                normalize(v.input, rules),
73                v.expected.map(|folded| folded.handle.to_owned()),
74                "vector {i}: {:?}",
75                v.input
76            );
77        }
78    }
79
80    /// The table holds accepted and refused cases, or the vector test proves
81    /// nothing.
82    #[test]
83    fn the_table_covers_both_outcomes() {
84        let accepted = VECTORS.iter().filter(|v| v.expected.is_ok()).count();
85        let refused = VECTORS.len() - accepted;
86        assert!(accepted > 0, "the table accepts nothing");
87        assert!(refused > 0, "the table refuses nothing");
88    }
89
90    /// Case folding is the only change to an accepted handle. Anything else
91    /// could map the handles of two identities onto one node.
92    #[test]
93    fn folding_is_the_only_change() {
94        assert_eq!(
95            normalize("A.B+tag@Example.COM", Rules::GOOGLE).unwrap(),
96            "a.b+tag@example.com"
97        );
98        assert_eq!(normalize("Alice_1", Rules::X).unwrap(), "alice_1");
99        assert_eq!(
100            normalize(" @Octo--Cat- ", Rules::GITHUB).unwrap(),
101            " @octo--cat- "
102        );
103    }
104}