zaun_community_protocol/
ids.rs1use std::fmt;
8
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
10use zeroize::{Zeroize, ZeroizeOnDrop};
11
12use crate::b64;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
16#[error("the system random number generator failed")]
17pub struct RngError;
18
19pub fn fill_random(buf: &mut [u8]) -> Result<(), RngError> {
24 getrandom::fill(buf).map_err(|_| RngError)
25}
26
27macro_rules! byte_id {
28 ($(#[$doc:meta])* $name:ident, $len:literal) => {
29 $(#[$doc])*
30 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
31 pub struct $name([u8; $len]);
32
33 impl $name {
34 pub const LEN: usize = $len;
36
37 #[must_use]
39 pub const fn from_bytes(bytes: [u8; $len]) -> Self {
40 Self(bytes)
41 }
42
43 #[must_use]
45 pub const fn as_bytes(&self) -> &[u8; $len] {
46 &self.0
47 }
48
49 #[must_use]
51 pub fn from_slice(bytes: &[u8]) -> Option<Self> {
52 bytes.try_into().ok().map(Self)
53 }
54
55 pub fn from_b64(text: &str) -> Result<Self, b64::B64Error> {
60 b64::decode_array(text).map(Self)
61 }
62
63 #[must_use]
65 pub fn to_b64(&self) -> String {
66 b64::encode(&self.0)
67 }
68 }
69
70 impl fmt::Debug for $name {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 write!(f, "{}({})", stringify!($name), self.to_b64())
73 }
74 }
75
76 impl fmt::Display for $name {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 f.write_str(&self.to_b64())
79 }
80 }
81
82 impl Serialize for $name {
83 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
84 s.serialize_str(&self.to_b64())
85 }
86 }
87
88 impl<'de> Deserialize<'de> for $name {
89 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
90 let text = <std::borrow::Cow<'de, str>>::deserialize(d)?;
91 Self::from_b64(&text).map_err(|_| {
92 D::Error::custom(concat!("invalid ", stringify!($name)))
93 })
94 }
95 }
96 };
97}
98
99macro_rules! random_id {
100 ($(#[$doc:meta])* $name:ident, $len:literal) => {
101 byte_id!($(#[$doc])* $name, $len);
102
103 impl $name {
104 pub fn random() -> Result<Self, RngError> {
109 loop {
110 let mut bytes = [0u8; $len];
111 fill_random(&mut bytes)?;
112 if bytes != [0u8; $len] {
113 return Ok(Self(bytes));
114 }
115 }
116 }
117 }
118 };
119}
120
121byte_id!(
122 CommunityId, 32
124);
125byte_id!(
126 HostId, 32
128);
129byte_id!(
130 DescriptorHash, 32
133);
134random_id!(
135 MemberId, 16
137);
138random_id!(
139 ChannelId, 16
141);
142random_id!(
143 RoleId, 16
145);
146random_id!(
147 MessageId, 16
149);
150random_id!(
151 InviteId, 16
153);
154random_id!(
155 BanId, 16
157);
158random_id!(
159 AuditId, 16
161);
162random_id!(
163 AttachmentId, 16
165);
166random_id!(
167 ReportId, 16
169);
170random_id!(
171 LockdownId, 16
173);
174random_id!(
175 BotId, 16
177);
178random_id!(
179 CommandId, 16
181);
182random_id!(
183 InteractionId, 16
185);
186byte_id!(
187 PublisherId, 32
189);
190random_id!(
191 RequestId, 16
193);
194random_id!(
195 VoiceSessionId, 16
197);
198random_id!(
199 Nonce, 32
201);
202random_id!(
203 Challenge, 32
205);
206
207impl RoleId {
208 pub const EVERYONE: Self = Self([0u8; 16]);
210
211 #[must_use]
213 pub fn is_everyone(&self) -> bool {
214 *self == Self::EVERYONE
215 }
216}
217
218#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
221pub struct InviteSecret([u8; 32]);
222
223impl InviteSecret {
224 #[must_use]
226 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
227 Self(bytes)
228 }
229
230 pub fn random() -> Result<Self, RngError> {
235 let mut bytes = [0u8; 32];
236 fill_random(&mut bytes)?;
237 Ok(Self(bytes))
238 }
239
240 #[must_use]
242 pub const fn expose(&self) -> &[u8; 32] {
243 &self.0
244 }
245
246 #[must_use]
248 pub fn expose_b64(&self) -> String {
249 b64::encode(&self.0)
250 }
251
252 pub fn from_b64(text: &str) -> Result<Self, b64::B64Error> {
257 b64::decode_array(text).map(Self)
258 }
259}
260
261impl fmt::Debug for InviteSecret {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 f.write_str("InviteSecret(<redacted>)")
264 }
265}
266
267impl Serialize for InviteSecret {
268 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
269 s.serialize_str(&self.expose_b64())
270 }
271}
272
273impl<'de> Deserialize<'de> for InviteSecret {
274 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
275 let text = <std::borrow::Cow<'de, str>>::deserialize(d)?;
276 Self::from_b64(&text).map_err(|_| D::Error::custom("invalid InviteSecret"))
277 }
278}
279
280#[cfg(test)]
281mod tests {
282 use super::*;
283
284 #[test]
285 fn json_round_trip_and_strictness() {
286 let id = MemberId::random().unwrap();
287 let json = serde_json::to_string(&id).unwrap();
288 assert_eq!(json.len(), 22 + 2);
289 assert_eq!(serde_json::from_str::<MemberId>(&json).unwrap(), id);
290 assert!(serde_json::from_str::<MemberId>("\"AAAAAAAAAAAAAAAAAAAAAA==\"").is_err());
291 assert!(serde_json::from_str::<CommunityId>("\"AAAAAAAAAAAAAAAAAAAAAA\"").is_err());
292 assert!(serde_json::from_str::<MemberId>("12").is_err());
293 }
294
295 #[test]
296 fn everyone_role_is_reserved_zero() {
297 assert_eq!(RoleId::EVERYONE.to_b64(), "AAAAAAAAAAAAAAAAAAAAAA");
298 assert!(!RoleId::random().unwrap().is_everyone());
299 }
300
301 #[test]
302 fn invite_secret_is_redacted() {
303 let secret = InviteSecret::random().unwrap();
304 let shown = format!("{secret:?}");
305 assert_eq!(shown, "InviteSecret(<redacted>)");
306 assert!(!shown.contains(&secret.expose_b64()));
307 }
308}