Skip to main content

zaun_community_protocol/client/
welcome.rs

1//! Verification of `session.welcome` (§4.3, §4.5, §6.2).
2
3mod chain;
4
5use serde_json::{Map, Value};
6
7use super::{ExpectedHost, WelcomeError};
8use crate::command::object::Binding;
9use crate::command::session::{HostAttachments, Welcome};
10use crate::crypto;
11use crate::envelope::VersionRange;
12use crate::ids::{Challenge, CommunityId, HostId, Nonce};
13use crate::json::SignedJson;
14use crate::keys::PublicKey;
15use crate::signed::{
16    AcceptedState, HostSessionProof, Scopes, SignedRootRotation, ValidPair, validate_pair,
17};
18
19/// A welcome that passed every check. Everything in it comes from verified signed objects
20/// or was compared with them.
21#[derive(Debug, Clone)]
22pub struct VerifiedWelcome {
23    /// The negotiated version.
24    pub version: u16,
25    /// The host's id (derives from `host_public_key`).
26    pub host_id: HostId,
27    /// The host's key, as pinned by the configuration.
28    pub host_public_key: PublicKey,
29    /// The challenge to sign into a `MemberKeyRegistration` (§4.4), from the decoded proof.
30    pub host_challenge: Challenge,
31    /// Capabilities both sides support.
32    pub capabilities: Vec<String>,
33    /// Effective limits (§12); the keys are not defined by the specification.
34    pub limits: Map<String, Value>,
35    /// The connection's binding, if bound.
36    pub binding: Option<Binding>,
37    /// The verified descriptor and delegation, when a community was named. Persist
38    /// [`ValidPair::state`] for anti-rollback (§4.3 rule 5).
39    pub community: Option<ValidPair>,
40    /// What the host accepts as attachments; `None` when it takes none.
41    pub attachments: Option<HostAttachments>,
42}
43
44/// What the welcome is checked against.
45#[derive(Debug)]
46pub(super) struct Expectation<'a> {
47    /// The pair the hello named as held, used when the welcome leaves it out.
48    pub(super) held: Option<&'a (SignedJson, SignedJson)>,
49    pub(super) nonce: &'a Nonce,
50    pub(super) offered: VersionRange,
51    pub(super) host: &'a ExpectedHost,
52    pub(super) community: Option<CommunityId>,
53    pub(super) accepted: Option<&'a AcceptedState>,
54    pub(super) rotations: &'a [SignedRootRotation],
55    pub(super) now_ms: u64,
56}
57
58/// Checks, in order: version, host identity (pinned by the caller, since the proof only
59/// shows possession of the key in the welcome), the binding, the descriptor/delegation pair
60/// (§4.3) and its authorisation of this host (§4.2), then the session proof (§4.5).
61///
62/// # Errors
63/// The first failing check.
64pub(super) fn verify(
65    welcome: Welcome,
66    exp: &Expectation<'_>,
67) -> Result<VerifiedWelcome, WelcomeError> {
68    if !exp.offered.contains(welcome.version) {
69        return Err(WelcomeError::Version {
70            version: welcome.version,
71            offered: exp.offered,
72        });
73    }
74    let key = &welcome.host_public_key;
75    if crypto::host_id(key) != welcome.host_id {
76        return Err(WelcomeError::HostId);
77    }
78    if !exp.host.matches(key) {
79        return Err(WelcomeError::Host);
80    }
81    let bound = welcome.binding.map(|b| b.community_id);
82    if let (Some(expected), Some(bound)) = (exp.community, bound)
83        && expected != bound
84    {
85        return Err(WelcomeError::Binding);
86    }
87    let target = exp.community.or(bound);
88    let pair = match target {
89        Some(community) => Some(verify_pair(&welcome, community, exp)?),
90        None => None,
91    };
92    let proof = HostSessionProof::verify_for_client(&welcome.proof, key, exp.nonce, pair.as_ref())?;
93    let proof = proof.object();
94    if target.is_some() && proof.community_id != target {
95        return Err(WelcomeError::MissingCommunity);
96    }
97    if proof.host_challenge != welcome.host_challenge {
98        return Err(WelcomeError::Challenge);
99    }
100    Ok(VerifiedWelcome {
101        version: welcome.version,
102        host_id: welcome.host_id,
103        host_challenge: proof.host_challenge,
104        host_public_key: welcome.host_public_key,
105        capabilities: welcome.capabilities,
106        limits: welcome.limits,
107        binding: welcome.binding,
108        community: pair,
109        attachments: welcome.attachments,
110    })
111}
112
113fn verify_pair(
114    welcome: &Welcome,
115    community: CommunityId,
116    exp: &Expectation<'_>,
117) -> Result<ValidPair, WelcomeError> {
118    // §6.2: a welcome without the pair the hello named means that pair, which is then checked
119    // exactly as if the host had sent it; the proof below still has to name this community
120    // and the pair's delegation epoch.
121    let (descriptor, delegation) = match (&welcome.descriptor, &welcome.delegation, exp.held) {
122        (Some(d), Some(g), _) => (d, g),
123        (None, None, Some((d, g))) => (d, g),
124        _ => return Err(WelcomeError::MissingCommunity),
125    };
126    let rotations = chain::complete(&descriptor.bytes, exp.rotations)?;
127    let pair = validate_pair(
128        &community,
129        descriptor,
130        delegation,
131        &rotations,
132        exp.accepted,
133        exp.now_ms,
134    )?;
135    let d = pair.delegation().object();
136    let authorised = d.host_id == welcome.host_id
137        && d.host_public_key == welcome.host_public_key
138        && d.grants(Scopes::OPERATE);
139    if authorised {
140        Ok(pair)
141    } else {
142        Err(WelcomeError::Delegation)
143    }
144}