Skip to main content

zaun_community_protocol/
ids.rs

1//! Identifiers (specification §2).
2//!
3//! Ids are opaque byte strings, base64url in JSON. `CommunityId` and `HostId` are derived from
4//! public keys by the `crypto` module; the 16-byte ids are random and host-assigned (except
5//! `RequestId`, which the client assigns).
6
7use std::fmt;
8
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
10use zeroize::{Zeroize, ZeroizeOnDrop};
11
12use crate::b64;
13
14/// The operating system's CSPRNG failed.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
16#[error("the system random number generator failed")]
17pub struct RngError;
18
19/// Fills `buf` from the operating system CSPRNG.
20///
21/// # Errors
22/// [`RngError`] when `getrandom` fails.
23pub 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            /// Length in bytes.
35            pub const LEN: usize = $len;
36
37            /// Wraps raw bytes.
38            #[must_use]
39            pub const fn from_bytes(bytes: [u8; $len]) -> Self {
40                Self(bytes)
41            }
42
43            /// The raw bytes.
44            #[must_use]
45            pub const fn as_bytes(&self) -> &[u8; $len] {
46                &self.0
47            }
48
49            /// Parses a byte slice of exactly [`Self::LEN`] bytes.
50            #[must_use]
51            pub fn from_slice(bytes: &[u8]) -> Option<Self> {
52                bytes.try_into().ok().map(Self)
53            }
54
55            /// Strict base64url (specification §2).
56            ///
57            /// # Errors
58            /// A non-canonical encoding or a wrong length.
59            pub fn from_b64(text: &str) -> Result<Self, b64::B64Error> {
60                b64::decode_array(text).map(Self)
61            }
62
63            /// Base64url without padding.
64            #[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            /// A fresh id from the OS CSPRNG; never all-zero (all-zero is reserved, §2).
105            ///
106            /// # Errors
107            /// [`RngError`] when the CSPRNG fails.
108            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    /// `SHA3-256("zaun/community-id/v1" ‖ 0x00 ‖ genesis root public key)`.
123    CommunityId, 32
124);
125byte_id!(
126    /// `SHA3-256("zaun/host-id/v1" ‖ 0x00 ‖ host public key)`.
127    HostId, 32
128);
129byte_id!(
130    /// `SHA3-256` of a signed descriptor's bytes (§3.2). The descriptor names its delegation's
131    /// hash, so this identifies the descriptor/delegation pair.
132    DescriptorHash, 32
133);
134random_id!(
135    /// A community-scoped member identity, host-assigned.
136    MemberId, 16
137);
138random_id!(
139    /// A channel or category.
140    ChannelId, 16
141);
142random_id!(
143    /// A role. [`RoleId::EVERYONE`] is the reserved all-zero id.
144    RoleId, 16
145);
146random_id!(
147    /// A message.
148    MessageId, 16
149);
150random_id!(
151    /// An invitation (public handle; the secret is [`InviteSecret`]).
152    InviteId, 16
153);
154random_id!(
155    /// A ban record.
156    BanId, 16
157);
158random_id!(
159    /// An audit-log entry.
160    AuditId, 16
161);
162random_id!(
163    /// An attachment.
164    AttachmentId, 16
165);
166random_id!(
167    /// A member report.
168    ReportId, 16
169);
170random_id!(
171    /// An emergency lockdown.
172    LockdownId, 16
173);
174random_id!(
175    /// An installed bot (specification §8.13).
176    BotId, 16
177);
178random_id!(
179    /// An application command of a bot (specification §8.14).
180    CommandId, 16
181);
182random_id!(
183    /// An interaction: one use of a command, component or modal (specification §8.14).
184    InteractionId, 16
185);
186byte_id!(
187    /// `SHA3-256("zaun/publisher-id/v1" ‖ 0x00 ‖ publisher public key)` (specification §4.9).
188    PublisherId, 32
189);
190random_id!(
191    /// Correlates a command with its response; client-assigned.
192    RequestId, 16
193);
194random_id!(
195    /// One stay of a member in a voice channel, host-assigned at `voice.join`.
196    VoiceSessionId, 16
197);
198random_id!(
199    /// A single-use value in signed objects.
200    Nonce, 32
201);
202random_id!(
203    /// A host-issued challenge that a signed proof must echo.
204    Challenge, 32
205);
206
207impl RoleId {
208    /// The `@everyone` role of every community (specification §2, permissions §2.1).
209    pub const EVERYONE: Self = Self([0u8; 16]);
210
211    /// Whether this is the `@everyone` role.
212    #[must_use]
213    pub fn is_everyone(&self) -> bool {
214        *self == Self::EVERYONE
215    }
216}
217
218/// An invitation secret: 32 random bytes, shown once. Never logged: `Debug` is redacted and
219/// it has no `Display`. Zeroized on drop.
220#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
221pub struct InviteSecret([u8; 32]);
222
223impl InviteSecret {
224    /// Wraps raw bytes.
225    #[must_use]
226    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
227        Self(bytes)
228    }
229
230    /// A fresh secret.
231    ///
232    /// # Errors
233    /// [`RngError`] when the CSPRNG fails.
234    pub fn random() -> Result<Self, RngError> {
235        let mut bytes = [0u8; 32];
236        fill_random(&mut bytes)?;
237        Ok(Self(bytes))
238    }
239
240    /// The raw bytes (for hashing before storage; hosts store only a hash).
241    #[must_use]
242    pub const fn expose(&self) -> &[u8; 32] {
243        &self.0
244    }
245
246    /// Base64url, for the one place it is shown: the invitation link.
247    #[must_use]
248    pub fn expose_b64(&self) -> String {
249        b64::encode(&self.0)
250    }
251
252    /// Strict base64url.
253    ///
254    /// # Errors
255    /// A non-canonical encoding or a wrong length.
256    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}