Skip to main content

nibkeep_sync/
invite.rs

1//! Inviting a user to a space, between a replica of an admin of the space and the joiner's,
2//! over a transport ([Sync](../../../docs/spec/sync.md#7-invitations)).
3
4use nibkeep_base::cbor::{ToCbor, Value};
5use nibkeep_crypto::rand_core::CryptoRng;
6use nibkeep_governance::{
7	InvitationGrant, InvitationRequest, Offer, Pairing, PairingCode, PairingKey, Side,
8};
9
10use crate::message::InviteMessage;
11use crate::{SyncError, Transport};
12
13/// The admin's side of an invitation: what it offers the one who asks, once the person
14/// confirms, what it grants once the joiner signed its listing, and how it records the new
15/// member.
16pub trait Inviting {
17	/// Why offering, granting or recording failed.
18	type Error: std::error::Error + Send + Sync + 'static;
19
20	/// What to offer the joiner that `request` names, connected from `endpoint`, once the
21	/// person confirms who asks; `None` if they decline. Nothing is recorded yet.
22	///
23	/// # Errors
24	///
25	/// Returns an error if the library cannot be read.
26	fn offer<R: CryptoRng>(
27		&mut self,
28		request: &InvitationRequest,
29		endpoint: &[u8; 32],
30		rng: &mut R,
31	) -> Result<Option<Offer>, Self::Error>;
32
33	/// What to grant the joiner whose key signed `listing`, its listing in the space as the
34	/// offer said, as text.
35	///
36	/// # Errors
37	///
38	/// Returns an error if the listing is not the joiner's as the request and the offer
39	/// say, or the library cannot be read.
40	fn grant<R: CryptoRng>(
41		&mut self,
42		listing: &str,
43		rng: &mut R,
44	) -> Result<InvitationGrant, Self::Error>;
45
46	/// Records the new member and its replica, now that the joiner holds the space.
47	///
48	/// # Errors
49	///
50	/// Returns an error if they cannot be recorded.
51	fn record<R: CryptoRng>(&mut self, rng: &mut R) -> Result<(), Self::Error>;
52}
53
54/// The joiner's side of an invitation: its listing for what the admin offers, and how it
55/// takes the space.
56pub trait Accepting {
57	/// Why signing the listing or taking the space failed.
58	type Error: std::error::Error + Send + Sync + 'static;
59
60	/// The joiner's listing in the space that `offer` names, signed by its key, as text;
61	/// `None` if its library holds the space already.
62	///
63	/// # Errors
64	///
65	/// Returns an error if the library cannot be read.
66	fn listing(&mut self, offer: &Offer) -> Result<Option<String>, Self::Error>;
67
68	/// Takes the space that `grant` gives, as `offer` named it.
69	///
70	/// # Errors
71	///
72	/// Returns an error if the first key does not open, or the space cannot be made.
73	fn take<R: CryptoRng>(
74		&mut self,
75		offer: &Offer,
76		grant: &InvitationGrant,
77		rng: &mut R,
78	) -> Result<(), Self::Error>;
79}
80
81/// What an invitation did, on either side: who asked, what was offered and what granted.
82#[derive(Clone, Debug)]
83pub struct Invitation {
84	/// The joiner's request.
85	pub request: InvitationRequest,
86	/// What the admin offered.
87	pub offer: Offer,
88	/// What it granted.
89	pub grant: InvitationGrant,
90}
91
92/// Invites the joiner at the other end of `transport` to a space, as the admin's replica,
93/// with the code it showed. The code is spent whatever happens.
94///
95/// # Errors
96///
97/// Returns [`SyncError::WrongCode`] if the joiner typed another code, on either side,
98/// [`SyncError::Declined`] if the person declined who asks, [`SyncError::Ended`] with
99/// [`Reason::HoldsSpace`] if the joiner holds the space already, and other errors if the
100/// connection fails, the joiner breaks the protocol or does not join, or the member cannot
101/// be recorded; in all of these, nothing is recorded.
102///
103/// [`Reason::HoldsSpace`]: crate::Reason::HoldsSpace
104pub fn invite<T: Transport, I: Inviting>(
105	transport: &mut T,
106	inviting: &mut I,
107	code: &PairingCode,
108	rng: &mut impl CryptoRng,
109) -> Result<Invitation, SyncError> {
110	let result = invite_with(transport, inviting, code, rng);
111	end(transport, result.as_ref().err());
112	result.map_err(SyncError::either_side)
113}
114
115fn invite_with<T: Transport, I: Inviting>(
116	transport: &mut T,
117	inviting: &mut I,
118	code: &PairingCode,
119	rng: &mut impl CryptoRng,
120) -> Result<Invitation, SyncError> {
121	let InviteMessage::Pake(theirs, None) = InviteMessage::receive(transport)? else {
122		return Err(SyncError::protocol(
123			"expected the joiner's message of SPAKE2",
124		));
125	};
126	let (pairing, ours) = Pairing::start(Side::Sponsor, code, rng);
127	let key = agree(pairing, &theirs, transport)?;
128	// The admin's replica proves the code first, so that the joiner says who it is only to
129	// a device that has it.
130	let proof = key.tag(Side::Sponsor, &Value::Bytes(ours.clone()));
131	InviteMessage::Pake(ours, Some(proof)).send(transport)?;
132	let InviteMessage::Request(request, tag) = InviteMessage::receive(transport)? else {
133		return Err(SyncError::protocol("expected a request"));
134	};
135	if !key.checks(Side::Joiner, &request.to_cbor(), &tag) {
136		return Err(SyncError::WrongCode);
137	}
138	let offer = inviting
139		.offer(&request, &transport.peer_endpoint(), rng)
140		.map_err(SyncError::holder)?
141		.ok_or(SyncError::Declined)?;
142	let tag = key.tag(Side::Sponsor, &offer.to_cbor());
143	InviteMessage::Offer(Box::new(offer.clone()), tag).send(transport)?;
144	let InviteMessage::Listing(listing, tag) = InviteMessage::receive(transport)? else {
145		return Err(SyncError::protocol("expected a listing"));
146	};
147	if !key.checks(Side::Joiner, &listing.to_cbor(), &tag) {
148		return Err(SyncError::protocol("a listing that is not the joiner's"));
149	}
150	let grant = inviting.grant(&listing, rng).map_err(SyncError::holder)?;
151	let tag = key.tag(Side::Sponsor, &grant.to_cbor());
152	InviteMessage::Grant(Box::new(grant.clone()), tag).send(transport)?;
153	// A joiner that could not take the space is not recorded.
154	let InviteMessage::Joined = InviteMessage::receive(transport)? else {
155		return Err(SyncError::protocol("expected the joiner to say it joined"));
156	};
157	inviting.record(rng).map_err(SyncError::holder)?;
158	Ok(Invitation {
159		request: *request,
160		offer,
161		grant,
162	})
163}
164
165/// Joins a space by the invitation of the admin's replica at the other end of `transport`,
166/// with the code that the person typed and `request`, which says who asks, and takes the
167/// space as `accepting` does.
168///
169/// # Errors
170///
171/// Returns [`SyncError::WrongCode`] if the code did not match, on either side,
172/// [`SyncError::HoldsSpace`] if the library holds the space already, [`SyncError::Ended`]
173/// with [`Reason::Declined`] if the person who invites declined, and other errors if the
174/// connection fails, the admin breaks the protocol, or the space cannot be taken.
175///
176/// [`Reason::Declined`]: crate::Reason::Declined
177pub fn accept<T: Transport, A: Accepting>(
178	transport: &mut T,
179	request: &InvitationRequest,
180	accepting: &mut A,
181	code: &PairingCode,
182	rng: &mut impl CryptoRng,
183) -> Result<Invitation, SyncError> {
184	let result = accept_with(transport, request, accepting, code, rng);
185	end(transport, result.as_ref().err());
186	result.map_err(SyncError::either_side)
187}
188
189fn accept_with<T: Transport, A: Accepting>(
190	transport: &mut T,
191	request: &InvitationRequest,
192	accepting: &mut A,
193	code: &PairingCode,
194	rng: &mut impl CryptoRng,
195) -> Result<Invitation, SyncError> {
196	let (pairing, ours) = Pairing::start(Side::Joiner, code, rng);
197	InviteMessage::Pake(ours, None).send(transport)?;
198	let InviteMessage::Pake(theirs, Some(proof)) = InviteMessage::receive(transport)? else {
199		return Err(SyncError::protocol(
200			"expected the admin's message of SPAKE2, with its tag",
201		));
202	};
203	let key = agree(pairing, &theirs, transport)?;
204	// Nothing of the joiner goes to a device that has not proved the code.
205	if !key.checks(Side::Sponsor, &Value::Bytes(theirs), &proof) {
206		return Err(SyncError::WrongCode);
207	}
208	let tag = key.tag(Side::Joiner, &request.to_cbor());
209	InviteMessage::Request(Box::new(request.clone()), tag).send(transport)?;
210	let InviteMessage::Offer(offer, tag) = InviteMessage::receive(transport)? else {
211		return Err(SyncError::protocol("expected an offer"));
212	};
213	// The code matched, as the admin's replica proved: a wrong tag now breaks the protocol.
214	if !key.checks(Side::Sponsor, &offer.to_cbor(), &tag) {
215		return Err(SyncError::protocol("an offer that is not the admin's"));
216	}
217	let listing = accepting
218		.listing(&offer)
219		.map_err(SyncError::holder)?
220		.ok_or(SyncError::HoldsSpace)?;
221	let tag = key.tag(Side::Joiner, &listing.to_cbor());
222	InviteMessage::Listing(listing, tag).send(transport)?;
223	let InviteMessage::Grant(grant, tag) = InviteMessage::receive(transport)? else {
224		return Err(SyncError::protocol("expected a grant"));
225	};
226	if !key.checks(Side::Sponsor, &grant.to_cbor(), &tag) {
227		return Err(SyncError::protocol("a grant that is not the admin's"));
228	}
229	accepting
230		.take(&offer, &grant, rng)
231		.map_err(SyncError::holder)?;
232	InviteMessage::Joined.send(transport)?;
233	Ok(Invitation {
234		request: request.clone(),
235		offer: *offer,
236		grant: *grant,
237	})
238}
239
240/// Finishes SPAKE2 with the other side's message, with the context of invitations.
241fn agree(
242	pairing: Pairing,
243	theirs: &[u8],
244	transport: &impl Transport,
245) -> Result<PairingKey, SyncError> {
246	pairing
247		.finish_invitation(theirs, &transport.binding())
248		.map_err(|_| SyncError::protocol("a message of SPAKE2 that is not the other side's"))
249}
250
251/// Tells the other side why the invitation ended, unless it ended it or the connection
252/// failed.
253fn end(transport: &mut impl Transport, error: Option<&SyncError>) {
254	if let Some(reason) = error.and_then(SyncError::reason) {
255		let _ = InviteMessage::End(reason).send(transport);
256	}
257}