Skip to main content

zaun_community_protocol/signed/
member_key.rs

1//! `MemberKeyRegistration` (specification §4.4, ctx `zaun/v1/member-key`).
2
3use super::error::{RegistrationError, SignedError};
4use super::object::{FORMAT_V1, Signed, SignedObject, read_format};
5use crate::crypto::Context;
6use crate::encoding::{Decode, DecodeError, Encode, EncodeError, Reader, Writer};
7use crate::ids::{Challenge, CommunityId, HostId};
8use crate::json::SignedJson;
9use crate::keys::PublicKey;
10
11/// Why a member key is registered (field 2). Other values are reserved and rejected.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[repr(u8)]
14pub enum Purpose {
15    /// `0x01`: `community.create`.
16    CreateCommunity = 1,
17    /// `0x02`: `invite.redeem`.
18    JoinByInvitation = 2,
19    /// `0x03`: `membership.request` (§8.9).
20    MembershipRequest = 3,
21}
22
23impl Purpose {
24    /// Parses the purpose byte.
25    #[must_use]
26    pub const fn from_byte(byte: u8) -> Option<Self> {
27        match byte {
28            1 => Some(Self::CreateCommunity),
29            2 => Some(Self::JoinByInvitation),
30            3 => Some(Self::MembershipRequest),
31            _ => None,
32        }
33    }
34}
35
36/// Proves that the client holds the private key of the member key it registers. Signed by
37/// that key.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct MemberKeyRegistration {
40    /// 2: why the key is registered.
41    pub purpose: Purpose,
42    /// 3: the community.
43    pub community_id: CommunityId,
44    /// 4: the host this registration is made to.
45    pub host_id: HostId,
46    /// 5: from this connection's latest `session.welcome`.
47    pub host_challenge: Challenge,
48    /// 6: the key being registered; the signer.
49    pub member_public_key: PublicKey,
50    /// 7: ms since the epoch.
51    pub issued_at: u64,
52}
53
54impl Encode for MemberKeyRegistration {
55    fn encode(&self, w: &mut Writer) -> Result<(), EncodeError> {
56        w.u8(FORMAT_V1);
57        w.u8(self.purpose as u8);
58        w.put(&self.community_id)?;
59        w.put(&self.host_id)?;
60        w.put(&self.host_challenge)?;
61        w.put(&self.member_public_key)?;
62        w.u64(self.issued_at);
63        Ok(())
64    }
65}
66
67impl Decode for MemberKeyRegistration {
68    fn decode(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
69        read_format(r)?;
70        let purpose = Purpose::from_byte(r.u8()?).ok_or(DecodeError::Invalid("purpose"))?;
71        Ok(Self {
72            purpose,
73            community_id: r.get()?,
74            host_id: r.get()?,
75            host_challenge: r.get()?,
76            member_public_key: r.get()?,
77            issued_at: r.u64()?,
78        })
79    }
80}
81
82impl SignedObject for MemberKeyRegistration {
83    const CONTEXT: Context = Context::MemberKey;
84}
85
86/// What the host expects of a registration: the command's fields and the connection's
87/// current challenge (§4.4).
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct RegistrationExpectation {
90    /// The command's purpose.
91    pub purpose: Purpose,
92    /// The command's community.
93    pub community_id: CommunityId,
94    /// This host.
95    pub host_id: HostId,
96    /// The connection's current, unused challenge.
97    pub host_challenge: Challenge,
98}
99
100impl MemberKeyRegistration {
101    /// The host's check (§4.4): verifies under the command's `member_public_key` (the signer,
102    /// supplied by the caller rather than read from the unverified bytes), then requires field
103    /// 6 to be that key and fields 2–5 to match. Consuming the challenge is the caller's job.
104    ///
105    /// # Errors
106    /// [`RegistrationError`] for a bad signature, encoding or mismatch.
107    pub fn verify_for_host(
108        signed: &SignedJson,
109        member_public_key: &PublicKey,
110        expected: &RegistrationExpectation,
111        min_suite: u8,
112    ) -> Result<Signed<Self>, RegistrationError> {
113        let signed = Signed::<Self>::from_json(signed, member_public_key, min_suite)
114            .map_err(|e: SignedError| RegistrationError::Signed(e))?;
115        let reg = signed.object();
116        let checks = [
117            (
118                reg.member_public_key == *member_public_key,
119                RegistrationError::MemberKey,
120            ),
121            (reg.purpose == expected.purpose, RegistrationError::Purpose),
122            (
123                reg.community_id == expected.community_id,
124                RegistrationError::Community,
125            ),
126            (reg.host_id == expected.host_id, RegistrationError::Host),
127            (
128                reg.host_challenge == expected.host_challenge,
129                RegistrationError::Challenge,
130            ),
131        ];
132        match checks.into_iter().find(|(ok, _)| !ok) {
133            Some((_, error)) => Err(error),
134            None => Ok(signed),
135        }
136    }
137}