Skip to main content

nibkeep_sync/
pair.rs

1//! Pairing a new replica with one that holds the library, over a transport
2//! ([Sync](../../../docs/spec/sync.md#2-pairing)).
3
4use nibkeep_base::cbor::{ToCbor, Value};
5use nibkeep_crypto::rand_core::CryptoRng;
6use nibkeep_governance::{Grant, JoinRequest, Pairing, PairingCode, Side};
7
8use crate::message::PairMessage;
9use crate::{Reason, SyncError, Transport};
10
11/// The library's side of pairing: what grants a new replica the space keys, and records it
12/// once it has joined.
13pub trait Sponsoring {
14	/// Why granting or recording the replica failed.
15	type Error: std::error::Error + Send + Sync + 'static;
16
17	/// What to grant the replica that `request` asks for, connected from `endpoint`, with
18	/// the space keys sealed to it. Nothing is recorded yet.
19	///
20	/// # Errors
21	///
22	/// Returns an error if the library cannot be read or written.
23	fn grant<R: CryptoRng>(
24		&mut self,
25		request: &JoinRequest,
26		endpoint: &[u8; 32],
27		rng: &mut R,
28	) -> Result<Grant, Self::Error>;
29
30	/// Records the replica that the last grant named, now that it has made its library, with
31	/// the listings that its key signed: in the personal space first, then, for an AI agent's
32	/// replica, in each space that the grant chose for it.
33	///
34	/// # Errors
35	///
36	/// Returns an error if the replica cannot be recorded, or a listing is not the one the
37	/// grant asked for.
38	fn record<R: CryptoRng>(&mut self, listings: &[String], rng: &mut R)
39	-> Result<(), Self::Error>;
40}
41
42/// What a sponsor did: whom it added, and what it granted.
43#[derive(Clone, Debug)]
44pub struct Sponsored {
45	/// The joiner's request.
46	pub request: JoinRequest,
47	/// What the joiner was granted.
48	pub grant: Grant,
49}
50
51/// What a joiner was granted, once it has made its library.
52#[derive(Clone, Debug)]
53pub struct Joined {
54	/// The grant.
55	pub grant: Grant,
56}
57
58/// Pairs with the joiner at the other end of `transport`, as the sponsor, with the code it
59/// showed. The code is spent whatever happens.
60///
61/// # Errors
62///
63/// Returns [`SyncError::WrongCode`] if the joiner typed another code, on either side, and
64/// other errors if the connection fails, the joiner breaks the protocol or does not join,
65/// or the replica cannot be recorded; in all of these, nothing is recorded.
66pub fn sponsor<T: Transport, S: Sponsoring>(
67	transport: &mut T,
68	sponsoring: &mut S,
69	code: &PairingCode,
70	rng: &mut impl CryptoRng,
71) -> Result<Sponsored, SyncError> {
72	let result = sponsor_with(transport, sponsoring, code, rng);
73	end(transport, result.as_ref().err());
74	result.map_err(SyncError::either_side)
75}
76
77fn sponsor_with<T: Transport, S: Sponsoring>(
78	transport: &mut T,
79	sponsoring: &mut S,
80	code: &PairingCode,
81	rng: &mut impl CryptoRng,
82) -> Result<Sponsored, SyncError> {
83	let PairMessage::Pake(theirs, None) = PairMessage::receive(transport)? else {
84		return Err(SyncError::protocol(
85			"expected the joiner's message of SPAKE2",
86		));
87	};
88	let (pairing, ours) = Pairing::start(Side::Sponsor, code, rng);
89	let key = pairing
90		.finish(&theirs, &transport.binding())
91		.map_err(|_| SyncError::protocol("a message of SPAKE2 that is not the joiner's"))?;
92	// The sponsor proves the code first, so that the joiner tells nothing of itself to a
93	// device that does not have it.
94	let proof = key.tag(Side::Sponsor, &Value::Bytes(ours.clone()));
95	PairMessage::Pake(ours, Some(proof)).send(transport)?;
96	let PairMessage::Request(request, tag) = PairMessage::receive(transport)? else {
97		return Err(SyncError::protocol("expected a request"));
98	};
99	if !key.checks(Side::Joiner, &request.to_cbor(), &tag) {
100		return Err(SyncError::WrongCode);
101	}
102	let grant = sponsoring
103		.grant(&request, &transport.peer_endpoint(), rng)
104		.map_err(SyncError::holder)?;
105	let tag = key.tag(Side::Sponsor, &grant.to_cbor());
106	PairMessage::Grant(Box::new(grant.clone()), tag).send(transport)?;
107	// A joiner that could not make its library is not recorded.
108	let PairMessage::Joined(listings) = PairMessage::receive(transport)? else {
109		return Err(SyncError::protocol("expected the joiner to say it joined"));
110	};
111	if listings.len() != grant.chosen.len() + 1 {
112		return Err(SyncError::protocol(
113			"a listing in the personal space, then one for each space chosen, and no other",
114		));
115	}
116	sponsoring
117		.record(&listings, rng)
118		.map_err(SyncError::holder)?;
119	Ok(Sponsored {
120		request: *request,
121		grant,
122	})
123}
124
125/// Pairs with the sponsor at the other end of `transport`, as the joiner, with the code the
126/// person typed, and returns what the sponsor granted. The joiner then makes its library
127/// and says so with [`joined`].
128///
129/// # Errors
130///
131/// Returns [`SyncError::WrongCode`] if the code did not match, on either side, and other
132/// errors if the connection fails or the sponsor breaks the protocol.
133pub fn join<T: Transport>(
134	transport: &mut T,
135	request: &JoinRequest,
136	code: &PairingCode,
137	rng: &mut impl CryptoRng,
138) -> Result<Grant, SyncError> {
139	let result = join_with(transport, request, code, rng);
140	end(transport, result.as_ref().err());
141	result.map_err(SyncError::either_side)
142}
143
144fn join_with<T: Transport>(
145	transport: &mut T,
146	request: &JoinRequest,
147	code: &PairingCode,
148	rng: &mut impl CryptoRng,
149) -> Result<Grant, SyncError> {
150	let (pairing, ours) = Pairing::start(Side::Joiner, code, rng);
151	PairMessage::Pake(ours, None).send(transport)?;
152	let PairMessage::Pake(theirs, Some(proof)) = PairMessage::receive(transport)? else {
153		return Err(SyncError::protocol(
154			"expected the sponsor's message of SPAKE2, with its tag",
155		));
156	};
157	let key = pairing
158		.finish(&theirs, &transport.binding())
159		.map_err(|_| SyncError::protocol("a message of SPAKE2 that is not the sponsor's"))?;
160	// Nothing of the joiner goes to a sponsor that has not proved the code.
161	if !key.checks(Side::Sponsor, &Value::Bytes(theirs), &proof) {
162		return Err(SyncError::WrongCode);
163	}
164	let tag = key.tag(Side::Joiner, &request.to_cbor());
165	PairMessage::Request(Box::new(request.clone()), tag).send(transport)?;
166	let PairMessage::Grant(grant, tag) = PairMessage::receive(transport)? else {
167		return Err(SyncError::protocol("expected a grant"));
168	};
169	// The code matched, as the sponsor proved: a wrong tag now breaks the protocol.
170	if !key.checks(Side::Sponsor, &grant.to_cbor(), &tag) {
171		return Err(SyncError::protocol("a grant that is not the sponsor's"));
172	}
173	Ok(*grant)
174}
175
176/// Tells the sponsor that the joiner made its library: the end of pairing, with the listings
177/// that its key signed, in the personal space first, then, for an AI agent's replica, in
178/// the spaces that the grant chose for it, in their order.
179///
180/// # Errors
181///
182/// Returns an error if the connection fails.
183pub fn joined<T: Transport>(
184	transport: &mut T,
185	grant: Grant,
186	listings: Vec<String>,
187) -> Result<Joined, SyncError> {
188	PairMessage::Joined(listings).send(transport)?;
189	Ok(Joined { grant })
190}
191
192/// Ends a pairing or a sync before it starts, telling the other side why, as a replica that
193/// cannot take it now does.
194///
195/// # Errors
196///
197/// Returns an error if the connection fails.
198pub fn refuse<T: Transport>(transport: &mut T, reason: Reason) -> Result<(), SyncError> {
199	Ok(transport.send(&crate::message::end_message(reason))?)
200}
201
202/// Tells the other side why pairing ended, unless it ended it or the connection failed.
203fn end(transport: &mut impl Transport, error: Option<&SyncError>) {
204	if let Some(reason) = error.and_then(SyncError::reason) {
205		let _ = PairMessage::End(reason).send(transport);
206	}
207}