engineioxide/
sid.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
//! [`Socket`](crate::Socket) id type and generator
//!
//! It it stored as a 128 bit id and it represent a base64 16 char string
use std::{
    fmt::{Debug, Display, Formatter},
    str::FromStr,
};

use base64::Engine;
use rand::Rng;

/// A 128 bit session id type representing a base64 16 char string
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Sid([u8; 16]);

impl Sid {
    /// A zeroed session id
    pub const ZERO: Self = Self([0u8; 16]);
    /// Generate a new random session id (base64 10 chars)
    pub fn new() -> Self {
        Self::default()
    }

    /// Get the session id as a base64 10 chars string
    pub fn as_str(&self) -> &str {
        // SAFETY: SID is always a base64 chars string
        unsafe { std::str::from_utf8_unchecked(&self.0) }
    }
}

/// Error type for [`Sid::from_str`]
#[derive(Debug, thiserror::Error)]
pub enum SidDecodeError {
    /// Invalid base64 string
    #[error("Invalid url base64 string")]
    InvalidBase64String,

    /// Invalid length
    #[error("Invalid sid length")]
    InvalidLength,
}

impl FromStr for Sid {
    type Err = SidDecodeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use SidDecodeError::*;

        let mut id = [0u8; 16];

        // Verify the length of the string
        if s.len() != 16 {
            return Err(InvalidLength);
        }

        // Verify that the string is a valid base64 url safe string without padding
        for (idx, byte) in s.as_bytes()[0..16].iter().enumerate() {
            if byte.is_ascii_alphanumeric() || byte == &b'_' || byte == &b'-' {
                id[idx] = *byte;
            } else {
                return Err(InvalidBase64String);
            }
        }
        Ok(Sid(id))
    }
}

impl Default for Sid {
    fn default() -> Self {
        let mut random = [0u8; 12]; // 12 bytes = 16 chars base64
        let mut id = [0u8; 16];

        rand::thread_rng().fill(&mut random);

        base64::prelude::BASE64_URL_SAFE_NO_PAD
            .encode_slice(random, &mut id)
            .unwrap();

        Sid(id)
    }
}

impl Display for Sid {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}
impl serde::Serialize for Sid {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

struct SidVisitor;
impl<'de> serde::de::Visitor<'de> for SidVisitor {
    type Value = Sid;

    fn expecting(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("a valid sid")
    }

    fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
        Sid::from_str(v).map_err(serde::de::Error::custom)
    }
}
impl<'de> serde::Deserialize<'de> for Sid {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_str(SidVisitor)
    }
}

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

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use crate::sid::Sid;

    #[test]
    fn test_sid_from_str() {
        let id = Sid::new();
        let id2 = Sid::from_str(&id.to_string()).unwrap();
        assert_eq!(id, id2);
        let id = Sid::from_str("AA9AAA0AAzAAAAHs").unwrap();
        assert_eq!(id.to_string(), "AA9AAA0AAzAAAAHs");
    }

    #[test]
    fn test_sid_from_str_invalid() {
        let id = Sid::from_str("*$^รนรน!").unwrap_err();
        assert_eq!(id.to_string(), "Invalid sid length");
        let id = Sid::from_str("aoassaAZDoin#zd{").unwrap_err();
        assert_eq!(id.to_string(), "Invalid url base64 string");
        let id = Sid::from_str("aoassaAZDoinazd<").unwrap_err();
        assert_eq!(id.to_string(), "Invalid url base64 string");
    }
}