Skip to main content

zaun_community_protocol/signed/
session.rs

1//! `HostSessionProof` (specification §4.5, ctx `zaun/v1/host-session`).
2
3use super::error::SessionProofError;
4use super::object::{FORMAT_V1, Signed, SignedObject, read_format};
5use super::validity::ValidPair;
6use crate::crypto::{self, Context};
7use crate::encoding::{Decode, DecodeError, Encode, EncodeError, Reader, Writer};
8use crate::ids::{Challenge, CommunityId, HostId, Nonce};
9use crate::json::SignedJson;
10use crate::keys::PublicKey;
11
12/// The host's proof of key possession in `session.welcome`. Signed by the host key.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct HostSessionProof {
15    /// 2: the host.
16    pub host_id: HostId,
17    /// 3: from `session.hello`.
18    pub client_nonce: Nonce,
19    /// 4: the challenge sent in this welcome.
20    pub host_challenge: Challenge,
21    /// 5: the bound or requested community.
22    pub community_id: Option<CommunityId>,
23    /// 6: the epoch the host operates under for field 5.
24    pub delegation_epoch: Option<u64>,
25    /// 7: ms since the epoch.
26    pub issued_at: u64,
27}
28
29impl Encode for HostSessionProof {
30    fn encode(&self, w: &mut Writer) -> Result<(), EncodeError> {
31        w.u8(FORMAT_V1);
32        w.put(&self.host_id)?;
33        w.put(&self.client_nonce)?;
34        w.put(&self.host_challenge)?;
35        w.option(self.community_id.as_ref(), Writer::put)?;
36        w.option(self.delegation_epoch.as_ref(), Writer::put)?;
37        w.u64(self.issued_at);
38        Ok(())
39    }
40}
41
42impl Decode for HostSessionProof {
43    fn decode(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
44        read_format(r)?;
45        Ok(Self {
46            host_id: r.get()?,
47            client_nonce: r.get()?,
48            host_challenge: r.get()?,
49            community_id: r.option(Reader::get)?,
50            delegation_epoch: r.option(Reader::get)?,
51            issued_at: r.u64()?,
52        })
53    }
54}
55
56impl SignedObject for HostSessionProof {
57    const CONTEXT: Context = Context::HostSession;
58}
59
60impl HostSessionProof {
61    /// The client's check (§4.5): verifies under `host_public_key`, requires `host_id` to
62    /// derive from it and `client_nonce` to be the client's fresh nonce. When a community is
63    /// named, `pair` must be a (descriptor, delegation) pair already validated by
64    /// [`super::validate_pair`] for that community, delegating to this `host_id` under this
65    /// epoch; its `min_suite` then applies to the proof's signature.
66    ///
67    /// # Errors
68    /// [`SessionProofError`] for a bad signature, encoding or mismatch.
69    pub fn verify_for_client(
70        signed: &SignedJson,
71        host_public_key: &PublicKey,
72        client_nonce: &Nonce,
73        pair: Option<&ValidPair>,
74    ) -> Result<Signed<Self>, SessionProofError> {
75        let min_suite = pair.map_or(1, |pair| pair.state().min_suite);
76        let signed = Signed::<Self>::from_json(signed, host_public_key, min_suite)?;
77        let proof = signed.object();
78        if proof.host_id != crypto::host_id(host_public_key) {
79            return Err(SessionProofError::HostId);
80        }
81        if proof.client_nonce != *client_nonce {
82            return Err(SessionProofError::Nonce);
83        }
84        // SPEC: §4.5 does not say whether fields 5 and 6 must be present together. Field 6 is
85        // "the epoch ... for field 5" and the client must check "this epoch" whenever field 5
86        // is some, so we require both or neither.
87        match (proof.community_id, proof.delegation_epoch) {
88            (None, None) => Ok(signed),
89            (Some(community), Some(epoch)) => {
90                let pair = pair.ok_or(SessionProofError::MissingPair)?;
91                let delegation = pair.delegation().object();
92                let matches = pair.descriptor().object().community_id == community
93                    && delegation.host_id == proof.host_id
94                    && delegation.host_public_key == *host_public_key
95                    && delegation.epoch == epoch;
96                if matches {
97                    Ok(signed)
98                } else {
99                    Err(SessionProofError::PairMismatch)
100                }
101            }
102            _ => Err(SessionProofError::EpochPresence),
103        }
104    }
105}