1use alloc::collections::BTreeMap;
35use alloc::string::String;
36use alloc::vec::Vec;
37
38use serde::{Deserialize, Serialize};
39use zeroize::{Zeroize, ZeroizeOnDrop};
40
41use crate::types::{Duration, ProtocolVersion, Timestamp};
42
43use super::{
44 AccessToken, ChallengeResponse, CommunicationProtocol, ConnectError, Deployment,
45 EndpointDescription, HmacBinding, HmacHashingAlgorithm, NodeDescription, NodeId, NodeIdAlias,
46 PairingToken, Role,
47};
48
49pub const PAIRING_BUDGET: Duration = Duration::from_secs(15);
54
55pub const MINIMUM_SERVER_DELAY: Duration = Duration::from_secs(1);
63
64#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
74#[serde(transparent)]
75pub struct PairingAttemptId(String);
76
77impl PairingAttemptId {
78 pub const MIN_LEN: usize = 32;
80
81 #[must_use]
83 pub fn new(value: impl Into<String>) -> Self {
84 Self(value.into())
85 }
86
87 pub fn from_entropy(bytes: &[u8]) -> Result<Self, ConnectError> {
89 if bytes.len() < 24 {
91 return Err(ConnectError::WeakSecret {
92 got: bytes.len(),
93 need: 24,
94 });
95 }
96 Ok(Self(super::base64_encode(bytes)))
97 }
98
99 #[must_use]
101 pub fn as_str(&self) -> &str {
102 &self.0
103 }
104
105 #[must_use]
107 pub fn verify(&self, presented: &str) -> bool {
108 use subtle::ConstantTimeEq as _;
109 self.0.len() == presented.len() && bool::from(self.0.as_bytes().ct_eq(presented.as_bytes()))
110 }
111}
112
113impl core::fmt::Debug for PairingAttemptId {
114 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115 f.write_str("PairingAttemptId(<redacted>)")
116 }
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(rename_all = "camelCase")]
122pub struct PairingRequest {
123 pub client_node_description: NodeDescription,
125 pub client_endpoint_description: EndpointDescription,
127 #[serde(skip_serializing_if = "Option::is_none")]
132 pub node_id: Option<NodeId>,
133 #[serde(skip_serializing_if = "Option::is_none")]
135 pub node_id_alias: Option<NodeIdAlias>,
136 pub supported_communication_protocols: Vec<CommunicationProtocol>,
138 pub supported_s2_message_versions: Vec<ProtocolVersion>,
141 pub supported_hmac_hashing_algorithms: Vec<HmacHashingAlgorithm>,
143 pub client_hmac_challenge: String,
145 #[serde(default, skip_serializing_if = "core::ops::Not::not")]
147 pub force_pairing: bool,
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase")]
153pub struct PairingAccepted {
154 pub pairing_attempt_id: PairingAttemptId,
156 pub server_node_description: NodeDescription,
158 pub server_endpoint_description: EndpointDescription,
160 pub selected_hmac_hashing_algorithm: HmacHashingAlgorithm,
162 pub client_hmac_challenge_response: String,
164 pub server_hmac_challenge: String,
166}
167
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
170#[non_exhaustive]
171pub enum PairingErrorMessage {
172 InvalidCombinationOfRoles,
174 IncompatibleS2MessageVersions,
176 IncompatibleHmacHashingAlgorithms,
178 IncompatibleCommunicationProtocols,
180 NodeNotFound,
182 NoNodeIdProvided,
184 NoValidPairingTokenOnPairingServer,
186 ParsingError,
188 Other,
190}
191
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
194#[serde(rename_all = "camelCase")]
195pub struct PairingRefused {
196 pub error_message: PairingErrorMessage,
198 #[serde(skip_serializing_if = "Option::is_none")]
200 pub additional_info: Option<String>,
201}
202
203#[derive(Debug, Clone, Serialize, Deserialize)]
207#[serde(rename_all = "camelCase")]
208pub struct ConnectionDetails {
209 pub initiate_session_url: String,
211 pub access_token: AccessToken,
213 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
223 pub certificate_fingerprint: BTreeMap<String, String>,
224}
225
226impl ConnectionDetails {
227 pub const SHA256: &'static str = "SHA256";
232
233 #[must_use]
236 pub fn new(initiate_session_url: impl Into<String>, access_token: AccessToken) -> Self {
237 Self {
238 initiate_session_url: initiate_session_url.into(),
239 access_token,
240 certificate_fingerprint: BTreeMap::new(),
241 }
242 }
243
244 #[must_use]
250 pub fn with_ca_fingerprint(mut self, sha256: &[u8; 32]) -> Self {
251 use core::fmt::Write as _;
252 let mut hex = String::with_capacity(64);
253 for b in sha256 {
254 let _ = write!(hex, "{b:02x}");
255 }
256 self.certificate_fingerprint
257 .insert(String::from(Self::SHA256), hex);
258 self
259 }
260
261 #[must_use]
264 pub fn ca_fingerprint(&self) -> Option<[u8; 32]> {
265 let hex = self.certificate_fingerprint.get(Self::SHA256)?;
266 match super::HmacBinding::from_hex_fingerprint(hex).ok()? {
267 super::HmacBinding::LeafFingerprint(bytes) => bytes.try_into().ok(),
268 super::HmacBinding::DomainName(_) => None,
269 }
270 }
271}
272
273#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
275#[serde(rename_all = "camelCase")]
276pub struct ConnectionDetailsRequest {
277 pub server_hmac_challenge_response: String,
279}
280
281#[derive(Debug, Clone, Serialize, Deserialize)]
283#[serde(rename_all = "camelCase")]
284pub struct ConnectionDetailsPost {
285 pub server_hmac_challenge_response: String,
287 pub connection_details: ConnectionDetails,
289}
290
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
293pub struct FinalizePairing {
294 pub success: bool,
296}
297
298#[derive(Debug, Clone)]
300pub struct Pairing {
301 pub local: NodeId,
303 pub remote: NodeDescription,
305 pub remote_endpoint: EndpointDescription,
307 pub details: ConnectionDetails,
309 pub communication_server: Role,
311 pub s2_message_versions: Vec<ProtocolVersion>,
314}
315
316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
322pub enum PairingStep {
323 Start,
325 AwaitingAcceptance,
327 Authenticated,
329 DetailsExchanged,
331 Paired,
333 Failed,
335}
336
337impl PairingStep {
338 const fn name(self) -> &'static str {
339 match self {
340 PairingStep::Start => "the start of pairing",
341 PairingStep::AwaitingAcceptance => "the server's acceptance",
342 PairingStep::Authenticated => "connection details",
343 PairingStep::DetailsExchanged => "finalization",
344 PairingStep::Paired => "a completed pairing",
345 PairingStep::Failed => "a failed pairing",
346 }
347 }
348}
349
350#[derive(Debug, Clone, Copy, PartialEq, Eq)]
352pub enum NextStep {
353 RequestConnectionDetails,
355 PostConnectionDetails,
357}
358
359#[derive(Debug)]
380pub struct PairingClient {
381 local: NodeDescription,
382 local_endpoint: EndpointDescription,
383 code: super::PairingCode,
384 binding: Option<HmacBinding>,
387 started: Timestamp,
388 step: PairingStep,
389 challenge: Option<Vec<u8>>,
391 s2_message_versions: Vec<ProtocolVersion>,
392 protocols: Vec<CommunicationProtocol>,
393 force: bool,
394 accepted: Option<PairingAccepted>,
395 attempt_id: Option<PairingAttemptId>,
404 details: Option<ConnectionDetails>,
405 communication_server: Option<Role>,
406}
407
408impl PairingClient {
409 #[must_use]
411 pub fn start(
412 local: NodeDescription,
413 local_endpoint: EndpointDescription,
414 code: super::PairingCode,
415 now: Timestamp,
416 ) -> Self {
417 Self {
418 local,
419 local_endpoint,
420 code,
421 binding: None,
422 started: now,
423 step: PairingStep::Start,
424 challenge: None,
425 s2_message_versions: alloc::vec![
427 crate::types::WireProfile::V1_0_0.connect_version(),
428 crate::types::WireProfile::V0_0_2Beta.connect_version(),
429 ],
430 protocols: alloc::vec![CommunicationProtocol::WebSocket],
431 force: false,
432 accepted: None,
433 attempt_id: None,
434 details: None,
435 communication_server: None,
436 }
437 }
438
439 #[must_use]
441 pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
442 self.s2_message_versions = versions;
443 self
444 }
445
446 #[must_use]
452 pub fn forcing(mut self) -> Self {
453 self.force = true;
454 self
455 }
456
457 #[must_use]
459 pub const fn step(&self) -> PairingStep {
460 self.step
461 }
462
463 #[must_use]
465 pub fn attempt_id(&self) -> Option<&PairingAttemptId> {
466 self.attempt_id.as_ref()
467 }
468
469 pub fn request_pairing(&mut self, challenge: &[u8]) -> Result<PairingRequest, ConnectError> {
475 self.expect(PairingStep::Start)?;
476 if challenge.len() < 32 {
477 self.step = PairingStep::Failed;
478 return Err(ConnectError::WeakSecret {
479 got: challenge.len(),
480 need: 32,
481 });
482 }
483 self.challenge = Some(challenge.to_vec());
484 self.step = PairingStep::AwaitingAcceptance;
485 Ok(PairingRequest {
486 client_node_description: self.local.clone(),
487 client_endpoint_description: self.local_endpoint.clone(),
488 node_id: None,
491 node_id_alias: self.code.alias.clone(),
492 supported_communication_protocols: self.protocols.clone(),
493 supported_s2_message_versions: self.s2_message_versions.clone(),
494 supported_hmac_hashing_algorithms: alloc::vec![HmacHashingAlgorithm::Sha256],
495 client_hmac_challenge: super::base64_encode(challenge),
496 force_pairing: self.force,
497 })
498 }
499
500 pub fn accept(
518 &mut self,
519 accepted: PairingAccepted,
520 binding: HmacBinding,
521 server_deployment: Deployment,
522 now: Timestamp,
523 ) -> Result<NextStep, ConnectError> {
524 self.expect(PairingStep::AwaitingAcceptance)?;
525 self.attempt_id = Some(accepted.pairing_attempt_id.clone());
528 self.within_budget(now)?;
529 self.binding = Some(binding);
530
531 if !self
532 .local
533 .role
534 .can_pair_with(accepted.server_node_description.role)
535 {
536 self.step = PairingStep::Failed;
537 return Err(ConnectError::SameRole(self.local.role));
538 }
539
540 let challenge = self.challenge.as_ref().ok_or(ConnectError::OutOfOrder {
541 got: "the server's acceptance",
542 expected: "the start of pairing",
543 })?;
544 let binding = self.binding.as_ref().ok_or(ConnectError::ChallengeFailed)?;
545 let expected = ChallengeResponse::compute(challenge, &self.code.token, binding)?;
546 if !expected.verify(&accepted.client_hmac_challenge_response) {
547 self.step = PairingStep::Failed;
548 return Err(ConnectError::ChallengeFailed);
549 }
550
551 let server_deployment = accepted
554 .server_endpoint_description
555 .deployment
556 .unwrap_or(server_deployment);
557 let local_deployment = self.local_endpoint.deployment.unwrap_or(Deployment::Lan);
558 let (cem, rm) = if self.local.role == Role::Cem {
559 (local_deployment, server_deployment)
560 } else {
561 (server_deployment, local_deployment)
562 };
563 let communication_server = Deployment::communication_server(cem, rm);
564 self.communication_server = Some(communication_server);
565
566 self.accepted = Some(accepted);
567 self.step = PairingStep::Authenticated;
568 Ok(if communication_server == self.local.role {
569 NextStep::PostConnectionDetails
570 } else {
571 NextStep::RequestConnectionDetails
572 })
573 }
574
575 pub fn server_challenge_response(&self) -> Result<String, ConnectError> {
579 let accepted = self.accepted.as_ref().ok_or(ConnectError::OutOfOrder {
580 got: "a challenge response",
581 expected: "the server's acceptance",
582 })?;
583 let binding = self.binding.as_ref().ok_or(ConnectError::OutOfOrder {
584 got: "a challenge response",
585 expected: "the server's acceptance",
586 })?;
587 let challenge = super::base64_decode(&accepted.server_hmac_challenge)
588 .ok_or(ConnectError::ChallengeFailed)?;
589 Ok(ChallengeResponse::compute(&challenge, &self.code.token, binding)?.as_base64())
590 }
591
592 pub fn request_connection_details(&self) -> Result<ConnectionDetailsRequest, ConnectError> {
594 Ok(ConnectionDetailsRequest {
595 server_hmac_challenge_response: self.server_challenge_response()?,
596 })
597 }
598
599 pub fn post_connection_details(
601 &mut self,
602 details: ConnectionDetails,
603 now: Timestamp,
604 ) -> Result<ConnectionDetailsPost, ConnectError> {
605 if details.ca_fingerprint().is_none() {
608 return Err(ConnectError::OutOfOrder {
609 got: "connection details without a SHA256 CA fingerprint",
610 expected: "certificateFingerprint.SHA256",
611 });
612 }
613 let response = self.server_challenge_response()?;
614 self.connection_details(details.clone(), now)?;
615 Ok(ConnectionDetailsPost {
616 server_hmac_challenge_response: response,
617 connection_details: details,
618 })
619 }
620
621 pub fn connection_details(
623 &mut self,
624 details: ConnectionDetails,
625 now: Timestamp,
626 ) -> Result<(), ConnectError> {
627 self.expect(PairingStep::Authenticated)?;
628 self.within_budget(now)?;
629 self.details = Some(details);
630 self.step = PairingStep::DetailsExchanged;
631 Ok(())
632 }
633
634 pub fn finalize(&mut self, now: Timestamp) -> Result<(FinalizePairing, Pairing), ConnectError> {
636 self.expect(PairingStep::DetailsExchanged)?;
637 self.within_budget(now)?;
638 let accepted = self.accepted.take().ok_or(ConnectError::OutOfOrder {
639 got: "finalization",
640 expected: "the server's acceptance",
641 })?;
642 let details = self.details.take().ok_or(ConnectError::OutOfOrder {
643 got: "finalization",
644 expected: "connection details",
645 })?;
646 self.step = PairingStep::Paired;
647 Ok((
648 FinalizePairing { success: true },
649 Pairing {
650 local: self.local.id,
651 remote: accepted.server_node_description,
652 remote_endpoint: accepted.server_endpoint_description,
653 details,
654 communication_server: self.communication_server.unwrap_or(Role::Cem),
655 s2_message_versions: self.s2_message_versions.clone(),
656 },
657 ))
658 }
659
660 pub fn abandon(&mut self) -> FinalizePairing {
663 self.step = PairingStep::Failed;
664 FinalizePairing { success: false }
665 }
666
667 fn expect(&mut self, step: PairingStep) -> Result<(), ConnectError> {
668 if self.step == step {
669 return Ok(());
670 }
671 let got = self.step.name();
672 self.step = PairingStep::Failed;
673 Err(ConnectError::OutOfOrder {
674 got,
675 expected: step.name(),
676 })
677 }
678
679 fn within_budget(&mut self, now: Timestamp) -> Result<(), ConnectError> {
680 if now.saturating_duration_since(self.started) > PAIRING_BUDGET {
681 self.step = PairingStep::Failed;
682 return Err(ConnectError::Expired {
683 what: "pairing",
684 limit: PAIRING_BUDGET,
685 });
686 }
687 Ok(())
688 }
689}
690
691#[derive(Debug)]
701pub struct PairingServer {
702 local: NodeDescription,
703 local_endpoint: EndpointDescription,
704 binding: HmacBinding,
705 s2_message_versions: Vec<ProtocolVersion>,
706 protocols: Vec<CommunicationProtocol>,
707 attempt: Option<Attempt>,
709 last_finished: Option<Timestamp>,
711 pending: Option<(Timestamp, PairingAccepted)>,
713}
714
715#[derive(Debug)]
716struct Attempt {
717 id: PairingAttemptId,
718 started: Timestamp,
719 expected_response: ChallengeResponse,
721 client: NodeDescription,
722 client_endpoint: EndpointDescription,
723 s2_message_versions: Vec<ProtocolVersion>,
724 details: Option<ConnectionDetails>,
725 verified: bool,
726 client_is_communication_server: bool,
730}
731
732impl PairingServer {
733 #[must_use]
735 pub fn new(
736 local: NodeDescription,
737 local_endpoint: EndpointDescription,
738 binding: HmacBinding,
739 ) -> Self {
740 Self {
741 local,
742 local_endpoint,
743 binding,
744 s2_message_versions: alloc::vec![
745 crate::types::WireProfile::V1_0_0.connect_version(),
746 crate::types::WireProfile::V0_0_2Beta.connect_version(),
747 ],
748 protocols: alloc::vec![CommunicationProtocol::WebSocket],
749 attempt: None,
750 last_finished: None,
751 pending: None,
752 }
753 }
754
755 #[must_use]
757 pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
758 self.s2_message_versions = versions;
759 self
760 }
761
762 pub fn request_pairing(
777 &mut self,
778 request: &PairingRequest,
779 token: &PairingToken,
780 server_challenge: &[u8],
781 attempt_id: PairingAttemptId,
782 now: Timestamp,
783 ) -> Result<(Timestamp, PairingAccepted), ConnectError> {
784 if let Some(attempt) = &self.attempt
785 && now.saturating_duration_since(attempt.started) <= PAIRING_BUDGET
786 {
787 return Err(ConnectError::RateLimited);
788 }
789 if let Some(finished) = self.last_finished
790 && now.saturating_duration_since(finished) < MINIMUM_SERVER_DELAY
791 {
792 return Err(ConnectError::RateLimited);
793 }
794
795 let result = self.answer(request, token, server_challenge, attempt_id, now);
796 if result.is_err() {
797 self.last_finished = Some(now);
798 self.attempt = None;
799 }
800 result
801 }
802
803 fn answer(
804 &mut self,
805 request: &PairingRequest,
806 token: &PairingToken,
807 server_challenge: &[u8],
808 attempt_id: PairingAttemptId,
809 now: Timestamp,
810 ) -> Result<(Timestamp, PairingAccepted), ConnectError> {
811 use PairingErrorMessage as E;
812
813 if !self
815 .local
816 .role
817 .can_pair_with(request.client_node_description.role)
818 {
819 return Err(refused(E::InvalidCombinationOfRoles));
820 }
821 if !request
822 .supported_hmac_hashing_algorithms
823 .contains(&HmacHashingAlgorithm::Sha256)
824 {
825 return Err(refused(E::IncompatibleHmacHashingAlgorithms));
826 }
827 if !request
828 .supported_communication_protocols
829 .iter()
830 .any(|p| self.protocols.contains(p))
831 {
832 return Err(refused(E::IncompatibleCommunicationProtocols));
833 }
834 let common = request
837 .supported_s2_message_versions
838 .iter()
839 .filter(|v| self.s2_message_versions.iter().any(|ours| ours.matches(v)))
840 .cloned()
841 .collect::<Vec<_>>();
842 if common.is_empty() && !request.force_pairing {
843 return Err(refused(E::IncompatibleS2MessageVersions));
844 }
845 if request.node_id.is_some() && request.node_id_alias.is_some() {
846 return Err(refused(E::ParsingError));
847 }
848
849 let client_challenge = super::base64_decode(&request.client_hmac_challenge)
850 .ok_or_else(|| refused(E::ParsingError))?;
851 let client_response = ChallengeResponse::compute(&client_challenge, token, &self.binding)?;
854 let expected_response = ChallengeResponse::compute(server_challenge, token, &self.binding)?;
856
857 let accepted = PairingAccepted {
858 pairing_attempt_id: attempt_id.clone(),
859 server_node_description: self.local.clone(),
860 server_endpoint_description: self.local_endpoint.clone(),
861 selected_hmac_hashing_algorithm: HmacHashingAlgorithm::Sha256,
862 client_hmac_challenge_response: client_response.as_base64(),
863 server_hmac_challenge: super::base64_encode(server_challenge),
864 };
865
866 let client_deployment = request
867 .client_endpoint_description
868 .deployment
869 .unwrap_or(Deployment::Lan);
870 let own_deployment = self.local_endpoint.deployment.unwrap_or(Deployment::Lan);
871 let (cem, rm) = if self.local.role == Role::Cem {
872 (own_deployment, client_deployment)
873 } else {
874 (client_deployment, own_deployment)
875 };
876 let client_is_communication_server =
877 Deployment::communication_server(cem, rm) == request.client_node_description.role;
878
879 self.attempt = Some(Attempt {
880 id: attempt_id,
881 started: now,
882 expected_response,
883 client: request.client_node_description.clone(),
884 client_endpoint: request.client_endpoint_description.clone(),
885 s2_message_versions: common,
886 details: None,
887 verified: false,
888 client_is_communication_server,
889 });
890 let send_after = now.checked_add(MINIMUM_SERVER_DELAY).unwrap_or(now);
891 self.pending = Some((send_after, accepted.clone()));
892 Ok((send_after, accepted))
893 }
894
895 #[must_use]
898 pub fn poll_timeout(&self) -> Option<Timestamp> {
899 self.pending.as_ref().map(|(at, _)| *at).or_else(|| {
900 self.attempt
901 .as_ref()
902 .map(|a| a.started.checked_add(PAIRING_BUDGET).unwrap_or(a.started))
903 })
904 }
905
906 pub fn poll_response(&mut self, now: Timestamp) -> Option<PairingAccepted> {
911 let (at, _) = self.pending.as_ref()?;
912 if now < *at {
913 return None;
914 }
915 self.pending.take().map(|(_, accepted)| accepted)
916 }
917
918 #[must_use]
923 pub fn authenticates(&self, bearer: &str) -> bool {
924 self.attempt.as_ref().is_some_and(|a| a.id.verify(bearer))
925 }
926
927 pub fn verify_client(&mut self, response: &str, now: Timestamp) -> Result<(), ConnectError> {
932 let Some(attempt) = self.attempt.as_mut() else {
933 return Err(ConnectError::OutOfOrder {
934 got: "a challenge response",
935 expected: "the start of pairing",
936 });
937 };
938 if now.saturating_duration_since(attempt.started) > PAIRING_BUDGET {
939 self.fail(now);
940 return Err(ConnectError::Expired {
941 what: "pairing",
942 limit: PAIRING_BUDGET,
943 });
944 }
945 if !attempt.expected_response.verify(response) {
946 self.fail(now);
947 return Err(ConnectError::ChallengeFailed);
948 }
949 attempt.verified = true;
950 Ok(())
951 }
952
953 #[must_use]
956 pub fn client_is_communication_server(&self) -> Option<bool> {
957 self.attempt
958 .as_ref()
959 .map(|a| a.client_is_communication_server)
960 }
961
962 pub fn connection_details(
970 &mut self,
971 details: ConnectionDetails,
972 now: Timestamp,
973 ) -> Result<ConnectionDetails, ConnectError> {
974 self.record_details(details, false, now)
975 }
976
977 pub fn accept_connection_details(
982 &mut self,
983 details: ConnectionDetails,
984 now: Timestamp,
985 ) -> Result<(), ConnectError> {
986 if details.ca_fingerprint().is_none() {
987 self.fail(now);
988 return Err(refused(PairingErrorMessage::ParsingError));
989 }
990 self.record_details(details, true, now).map(|_| ())
991 }
992
993 fn record_details(
994 &mut self,
995 details: ConnectionDetails,
996 posted_by_client: bool,
997 now: Timestamp,
998 ) -> Result<ConnectionDetails, ConnectError> {
999 let (verified, client_is_server) = self
1000 .attempt
1001 .as_ref()
1002 .map(|a| (a.verified, a.client_is_communication_server))
1003 .ok_or(ConnectError::OutOfOrder {
1004 got: "connection details",
1005 expected: "the start of pairing",
1006 })?;
1007 if !verified {
1008 return Err(ConnectError::ChallengeFailed);
1009 }
1010 if client_is_server != posted_by_client {
1011 let (got, expected) = if posted_by_client {
1012 ("postConnectionDetails", "requestConnectionDetails")
1013 } else {
1014 ("requestConnectionDetails", "postConnectionDetails")
1015 };
1016 self.fail(now);
1017 return Err(ConnectError::OutOfOrder { got, expected });
1018 }
1019 if let Some(attempt) = self.attempt.as_mut() {
1020 attempt.details = Some(details.clone());
1021 }
1022 Ok(details)
1023 }
1024
1025 pub fn finalize(
1030 &mut self,
1031 body: FinalizePairing,
1032 now: Timestamp,
1033 ) -> Result<Option<Pairing>, ConnectError> {
1034 let Some(attempt) = self.attempt.take() else {
1035 return Err(ConnectError::OutOfOrder {
1036 got: "finalization",
1037 expected: "the start of pairing",
1038 });
1039 };
1040 self.last_finished = Some(now);
1041 self.pending = None;
1042
1043 if now.saturating_duration_since(attempt.started) > PAIRING_BUDGET {
1044 return Err(ConnectError::Expired {
1045 what: "pairing",
1046 limit: PAIRING_BUDGET,
1047 });
1048 }
1049 if !body.success {
1050 return Ok(None);
1051 }
1052 if !attempt.verified {
1053 return Err(ConnectError::ChallengeFailed);
1054 }
1055 let details = attempt.details.ok_or(ConnectError::OutOfOrder {
1056 got: "finalization",
1057 expected: "connection details",
1058 })?;
1059 let client_deployment = attempt
1060 .client_endpoint
1061 .deployment
1062 .unwrap_or(Deployment::Lan);
1063 let own_deployment = self.local_endpoint.deployment.unwrap_or(Deployment::Lan);
1064 let (cem, rm) = if self.local.role == Role::Cem {
1065 (own_deployment, client_deployment)
1066 } else {
1067 (client_deployment, own_deployment)
1068 };
1069 Ok(Some(Pairing {
1070 local: self.local.id,
1071 remote: attempt.client,
1072 remote_endpoint: attempt.client_endpoint,
1073 details,
1074 communication_server: Deployment::communication_server(cem, rm),
1075 s2_message_versions: attempt.s2_message_versions,
1076 }))
1077 }
1078
1079 fn fail(&mut self, now: Timestamp) {
1080 self.attempt = None;
1081 self.pending = None;
1082 self.last_finished = Some(now);
1083 }
1084}
1085
1086fn refused(message: PairingErrorMessage) -> ConnectError {
1087 ConnectError::Refused(PairingRefused {
1088 error_message: message,
1089 additional_info: None,
1090 })
1091}
1092
1093#[cfg(test)]
1094mod tests {
1095 use super::*;
1096 use crate::connect::proto::{PairingCode, TokenKind};
1097 use alloc::string::ToString;
1100
1101 const CLIENT_CHALLENGE: [u8; 32] = [0xA5; 32];
1102 const SERVER_CHALLENGE: [u8; 32] = [0x5A; 32];
1103 const ATTEMPT: [u8; 24] = [0x33; 24];
1104
1105 fn binding() -> HmacBinding {
1106 HmacBinding::DomainName("pairing.example.com".to_string())
1107 }
1108
1109 fn code() -> PairingCode {
1110 PairingCode::parse("evse7-A1b2C3", TokenKind::Static).expect("a legal code")
1111 }
1112
1113 fn node(id: &str, role: Role) -> NodeDescription {
1114 NodeDescription {
1115 id: NodeId::parse(id).expect("a legal id"),
1116 brand: "Acme".to_string(),
1117 logo_url: None,
1118 kind: if role == Role::Cem { "CEM" } else { "EVSE" }.to_string(),
1119 model_name: "Charger 9000".to_string(),
1120 user_defined_name: None,
1121 role,
1122 }
1123 }
1124
1125 fn endpoint(deployment: Deployment) -> EndpointDescription {
1126 EndpointDescription {
1127 name: Some("Test endpoint".to_string()),
1128 logo_url: None,
1129 deployment: Some(deployment),
1130 }
1131 }
1132
1133 fn details() -> ConnectionDetails {
1134 ConnectionDetails::new(
1135 "https://pairing.example.com/",
1136 AccessToken::from_entropy(&[1u8; 32]).expect("32 bytes"),
1137 )
1138 .with_ca_fingerprint(&[0xCA; 32])
1139 }
1140
1141 fn t(secs: i64) -> Timestamp {
1142 Timestamp::from_unix(1_700_000_000 + secs, 0)
1143 }
1144
1145 fn attempt_id() -> PairingAttemptId {
1146 PairingAttemptId::from_entropy(&ATTEMPT).expect("24 bytes")
1147 }
1148
1149 struct Run {
1153 client: PairingClient,
1154 server: PairingServer,
1155 }
1156
1157 fn setup(
1158 client_role: Role,
1159 client_deployment: Deployment,
1160 server_deployment: Deployment,
1161 ) -> Run {
1162 Run {
1163 client: PairingClient::start(
1164 node("cem-1", client_role),
1165 endpoint(client_deployment),
1166 code(),
1167 t(0),
1168 ),
1169 server: PairingServer::new(
1170 node("rm-1", client_role.other()),
1171 endpoint(server_deployment),
1172 binding(),
1173 ),
1174 }
1175 }
1176
1177 #[test]
1178 fn a_pairing_runs_to_completion_and_both_sides_agree() {
1179 let Run {
1180 mut client,
1181 mut server,
1182 } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1183
1184 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1186 let (send_after, accepted) = server
1187 .request_pairing(
1188 &request,
1189 &code().token,
1190 &SERVER_CHALLENGE,
1191 attempt_id(),
1192 t(0),
1193 )
1194 .unwrap();
1195 assert_eq!(send_after, t(1));
1196 let accepted = {
1197 assert!(server.poll_response(t(0)).is_none());
1198 server.poll_response(t(1)).unwrap_or(accepted)
1199 };
1200
1201 let next = client
1203 .accept(accepted, binding(), Deployment::Lan, t(1))
1204 .unwrap();
1205 assert_eq!(next, NextStep::PostConnectionDetails);
1206
1207 let post = client.post_connection_details(details(), t(1)).unwrap();
1209 assert!(server.authenticates(client.attempt_id().unwrap().as_str()));
1210 server
1211 .verify_client(&post.server_hmac_challenge_response, t(1))
1212 .unwrap();
1213 server
1214 .accept_connection_details(post.connection_details, t(1))
1215 .unwrap();
1216
1217 let (body, mine) = client.finalize(t(2)).unwrap();
1219 assert!(body.success);
1220 let theirs = server.finalize(body, t(2)).unwrap().expect("a pairing");
1221
1222 assert_eq!(client.step(), PairingStep::Paired);
1223 assert_eq!(mine.remote.id, theirs.local);
1224 assert_eq!(theirs.remote.id, mine.local);
1225 assert_eq!(mine.communication_server, Role::Cem);
1226 assert_eq!(theirs.communication_server, Role::Cem);
1227 }
1228
1229 #[test]
1230 fn a_wan_pairing_server_supplies_the_details_instead() {
1231 let Run {
1233 mut client,
1234 mut server,
1235 } = setup(Role::Cem, Deployment::Lan, Deployment::Wan);
1236
1237 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1238 let (_, accepted) = server
1239 .request_pairing(
1240 &request,
1241 &code().token,
1242 &SERVER_CHALLENGE,
1243 attempt_id(),
1244 t(0),
1245 )
1246 .unwrap();
1247 let next = client
1248 .accept(accepted, binding(), Deployment::Lan, t(1))
1249 .unwrap();
1250 assert_eq!(next, NextStep::RequestConnectionDetails);
1251
1252 let ask = client.request_connection_details().unwrap();
1253 server
1254 .verify_client(&ask.server_hmac_challenge_response, t(1))
1255 .unwrap();
1256 let given = server.connection_details(details(), t(1)).unwrap();
1257 client.connection_details(given, t(1)).unwrap();
1258 let (body, pairing) = client.finalize(t(2)).unwrap();
1259 assert_eq!(pairing.communication_server, Role::Rm);
1260 assert!(server.finalize(body, t(2)).unwrap().is_some());
1261 }
1262
1263 #[test]
1264 fn a_server_that_omits_its_deployment_is_taken_to_be_where_it_was_reached() {
1265 let outcome = |reached: Deployment| {
1270 let Run {
1271 mut client,
1272 mut server,
1273 } = setup(Role::Cem, Deployment::Lan, Deployment::Wan);
1274 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1275 let (_, mut accepted) = server
1276 .request_pairing(
1277 &request,
1278 &code().token,
1279 &SERVER_CHALLENGE,
1280 attempt_id(),
1281 t(0),
1282 )
1283 .unwrap();
1284 accepted.server_endpoint_description.deployment = None;
1285 client.accept(accepted, binding(), reached, t(1)).unwrap()
1286 };
1287 assert_eq!(outcome(Deployment::Wan), NextStep::RequestConnectionDetails);
1288 assert_eq!(outcome(Deployment::Lan), NextStep::PostConnectionDetails);
1289 }
1290
1291 #[test]
1292 fn the_wrong_branch_of_step_six_fails_the_attempt() {
1293 let Run {
1298 mut client,
1299 mut server,
1300 } = setup(Role::Cem, Deployment::Lan, Deployment::Wan);
1301 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1302 let (_, accepted) = server
1303 .request_pairing(
1304 &request,
1305 &code().token,
1306 &SERVER_CHALLENGE,
1307 attempt_id(),
1308 t(0),
1309 )
1310 .unwrap();
1311 client
1312 .accept(accepted, binding(), Deployment::Lan, t(1))
1313 .unwrap();
1314 let ask = client.request_connection_details().unwrap();
1315 server
1316 .verify_client(&ask.server_hmac_challenge_response, t(1))
1317 .unwrap();
1318 assert_eq!(server.client_is_communication_server(), Some(false));
1319 assert!(matches!(
1320 server.accept_connection_details(details(), t(1)),
1321 Err(ConnectError::OutOfOrder { .. })
1322 ));
1323 assert!(
1324 server.client_is_communication_server().is_none(),
1325 "the attempt is failed, not merely refused"
1326 );
1327 }
1328
1329 #[test]
1330 fn posted_details_without_a_ca_fingerprint_are_refused() {
1331 let bare = ConnectionDetails::new("https://cem.local/", AccessToken::new("x".repeat(43)));
1334 assert!(bare.ca_fingerprint().is_none());
1335 let pinned = bare.clone().with_ca_fingerprint(&[0xAB; 32]);
1336 assert_eq!(pinned.ca_fingerprint(), Some([0xAB; 32]));
1337 assert_eq!(
1338 pinned
1339 .certificate_fingerprint
1340 .get("SHA256")
1341 .map(String::as_str),
1342 Some("ab".repeat(32).as_str()),
1343 "plain lowercase hexadecimal on the wire"
1344 );
1345 let mut colons = bare;
1347 colons
1348 .certificate_fingerprint
1349 .insert("SHA256".to_string(), alloc::vec!["AB"; 32].join(":"));
1350 assert_eq!(colons.ca_fingerprint(), Some([0xAB; 32]));
1351 }
1352
1353 #[test]
1354 fn the_response_may_not_be_sent_before_the_mandatory_second() {
1355 let Run {
1356 mut client,
1357 mut server,
1358 } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1359 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1360 server
1361 .request_pairing(
1362 &request,
1363 &code().token,
1364 &SERVER_CHALLENGE,
1365 attempt_id(),
1366 t(0),
1367 )
1368 .unwrap();
1369
1370 assert_eq!(server.poll_timeout(), Some(t(1)));
1371 assert!(server.poll_response(t(0)).is_none());
1372 assert!(
1373 server
1374 .poll_response(Timestamp::from_unix(1_700_000_000, 999_000_000))
1375 .is_none()
1376 );
1377 assert!(server.poll_response(t(1)).is_some());
1378 assert!(server.poll_response(t(2)).is_none());
1380 }
1381
1382 #[test]
1383 fn a_second_attempt_for_the_same_node_is_refused() {
1384 let Run {
1385 mut client,
1386 mut server,
1387 } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1388 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1389 server
1390 .request_pairing(
1391 &request,
1392 &code().token,
1393 &SERVER_CHALLENGE,
1394 attempt_id(),
1395 t(0),
1396 )
1397 .unwrap();
1398
1399 assert!(matches!(
1400 server.request_pairing(
1401 &request,
1402 &code().token,
1403 &SERVER_CHALLENGE,
1404 attempt_id(),
1405 t(1)
1406 ),
1407 Err(ConnectError::RateLimited)
1408 ));
1409 assert!(
1411 server
1412 .request_pairing(
1413 &request,
1414 &code().token,
1415 &SERVER_CHALLENGE,
1416 attempt_id(),
1417 t(16)
1418 )
1419 .is_ok()
1420 );
1421 }
1422
1423 #[test]
1424 fn a_wrong_token_costs_the_attacker_a_second_too() {
1425 let Run {
1426 mut client,
1427 mut server,
1428 } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1429 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1430
1431 let wrong = PairingToken::parse("Z9y8X7", TokenKind::Static).unwrap();
1434 let (_, accepted) = server
1435 .request_pairing(&request, &wrong, &SERVER_CHALLENGE, attempt_id(), t(0))
1436 .unwrap();
1437 assert!(matches!(
1438 client.accept(accepted, binding(), Deployment::Lan, t(1)),
1439 Err(ConnectError::ChallengeFailed)
1440 ));
1441
1442 let Run {
1444 mut client,
1445 mut server,
1446 } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1447 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1448 let (_, accepted) = server
1449 .request_pairing(
1450 &request,
1451 &code().token,
1452 &SERVER_CHALLENGE,
1453 attempt_id(),
1454 t(0),
1455 )
1456 .unwrap();
1457 client
1458 .accept(accepted, binding(), Deployment::Lan, t(1))
1459 .unwrap();
1460 let forged = ChallengeResponse::compute(&SERVER_CHALLENGE, &wrong, &binding())
1461 .unwrap()
1462 .as_base64();
1463 assert!(matches!(
1464 server.verify_client(&forged, t(1)),
1465 Err(ConnectError::ChallengeFailed)
1466 ));
1467 assert!(!server.authenticates(attempt_id().as_str()));
1469 }
1470
1471 #[test]
1472 fn a_man_in_the_middle_cannot_relay_the_exchange() {
1473 let attacker = HmacBinding::DomainName("pairing.example.com.evil.test".to_string());
1475 let mut client = PairingClient::start(
1476 node("cem-1", Role::Cem),
1477 endpoint(Deployment::Lan),
1478 code(),
1479 t(0),
1480 );
1481 let mut server =
1482 PairingServer::new(node("rm-1", Role::Rm), endpoint(Deployment::Lan), attacker);
1483
1484 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1485 let (_, accepted) = server
1487 .request_pairing(
1488 &request,
1489 &code().token,
1490 &SERVER_CHALLENGE,
1491 attempt_id(),
1492 t(0),
1493 )
1494 .unwrap();
1495 assert!(matches!(
1497 client.accept(accepted, binding(), Deployment::Lan, t(1)),
1498 Err(ConnectError::ChallengeFailed)
1499 ));
1500 assert_eq!(client.step(), PairingStep::Failed);
1501 }
1502
1503 #[test]
1504 fn the_fifteen_second_budget_is_enforced_on_both_sides() {
1505 let Run {
1506 mut client,
1507 mut server,
1508 } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1509 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1510 let (_, accepted) = server
1511 .request_pairing(
1512 &request,
1513 &code().token,
1514 &SERVER_CHALLENGE,
1515 attempt_id(),
1516 t(0),
1517 )
1518 .unwrap();
1519
1520 assert!(matches!(
1521 client.accept(accepted, binding(), Deployment::Lan, t(16)),
1522 Err(ConnectError::Expired { .. })
1523 ));
1524 assert!(matches!(
1525 server.verify_client("anything", t(16)),
1526 Err(ConnectError::Expired { .. })
1527 ));
1528 }
1529
1530 #[test]
1531 fn the_steps_cannot_be_taken_out_of_order() {
1532 let Run { mut client, .. } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1533 assert!(matches!(
1534 client.finalize(t(0)),
1535 Err(ConnectError::OutOfOrder { .. })
1536 ));
1537 assert_eq!(client.step(), PairingStep::Failed);
1539 assert!(client.request_pairing(&CLIENT_CHALLENGE).is_err());
1540 }
1541
1542 #[test]
1543 fn two_nodes_of_the_same_role_are_refused_by_both_sides() {
1544 let mut client = PairingClient::start(
1546 node("cem-1", Role::Cem),
1547 endpoint(Deployment::Lan),
1548 code(),
1549 t(0),
1550 );
1551 let mut server = PairingServer::new(
1552 node("cem-2", Role::Cem),
1553 endpoint(Deployment::Lan),
1554 binding(),
1555 );
1556 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1557 let err = server
1558 .request_pairing(
1559 &request,
1560 &code().token,
1561 &SERVER_CHALLENGE,
1562 attempt_id(),
1563 t(0),
1564 )
1565 .unwrap_err();
1566 assert!(matches!(
1567 err,
1568 ConnectError::Refused(PairingRefused {
1569 error_message: PairingErrorMessage::InvalidCombinationOfRoles,
1570 ..
1571 })
1572 ));
1573 }
1574
1575 #[test]
1576 fn incompatible_versions_are_refused_unless_forced() {
1577 let mut client = PairingClient::start(
1578 node("cem-1", Role::Cem),
1579 endpoint(Deployment::Lan),
1580 code(),
1581 t(0),
1582 )
1583 .with_s2_message_versions(alloc::vec![crate::types::ProtocolVersion::new("9.9.9")]);
1584 let mut server =
1585 PairingServer::new(node("rm-1", Role::Rm), endpoint(Deployment::Lan), binding());
1586 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1587 assert!(matches!(
1588 server.request_pairing(
1589 &request,
1590 &code().token,
1591 &SERVER_CHALLENGE,
1592 attempt_id(),
1593 t(0)
1594 ),
1595 Err(ConnectError::Refused(PairingRefused {
1596 error_message: PairingErrorMessage::IncompatibleS2MessageVersions,
1597 ..
1598 }))
1599 ));
1600
1601 let mut client = PairingClient::start(
1604 node("cem-1", Role::Cem),
1605 endpoint(Deployment::Lan),
1606 code(),
1607 t(0),
1608 )
1609 .with_s2_message_versions(alloc::vec![crate::types::ProtocolVersion::new("9.9.9")])
1610 .forcing();
1611 let mut server =
1612 PairingServer::new(node("rm-1", Role::Rm), endpoint(Deployment::Lan), binding());
1613 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1614 assert!(
1615 server
1616 .request_pairing(
1617 &request,
1618 &code().token,
1619 &SERVER_CHALLENGE,
1620 attempt_id(),
1621 t(16)
1622 )
1623 .is_ok()
1624 );
1625 }
1626
1627 #[test]
1628 fn a_client_without_sha256_is_refused() {
1629 let Run {
1630 mut client,
1631 mut server,
1632 } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1633 let mut request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1634 request.supported_hmac_hashing_algorithms.clear();
1635 assert!(matches!(
1636 server.request_pairing(
1637 &request,
1638 &code().token,
1639 &SERVER_CHALLENGE,
1640 attempt_id(),
1641 t(0)
1642 ),
1643 Err(ConnectError::Refused(PairingRefused {
1644 error_message: PairingErrorMessage::IncompatibleHmacHashingAlgorithms,
1645 ..
1646 }))
1647 ));
1648 }
1649
1650 #[test]
1651 fn a_short_challenge_never_reaches_the_wire() {
1652 let Run { mut client, .. } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1653 assert!(matches!(
1654 client.request_pairing(&[0u8; 16]),
1655 Err(ConnectError::WeakSecret { need: 32, .. })
1656 ));
1657 }
1658
1659 #[test]
1660 fn the_attempt_id_is_a_bearer_and_is_compared_in_constant_time() {
1661 let Run {
1662 mut client,
1663 mut server,
1664 } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1665 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1666 server
1667 .request_pairing(
1668 &request,
1669 &code().token,
1670 &SERVER_CHALLENGE,
1671 attempt_id(),
1672 t(0),
1673 )
1674 .unwrap();
1675
1676 assert!(server.authenticates(attempt_id().as_str()));
1677 assert!(!server.authenticates("something else entirely"));
1678 assert!(!server.authenticates(""));
1679 assert_eq!(attempt_id().as_str().len(), PairingAttemptId::MIN_LEN);
1681 assert!(PairingAttemptId::from_entropy(&[0u8; 23]).is_err());
1682 assert_eq!(
1684 alloc::format!("{:?}", attempt_id()),
1685 "PairingAttemptId(<redacted>)"
1686 );
1687 }
1688
1689 #[test]
1690 fn a_client_that_gives_up_says_so_and_no_pairing_is_stored() {
1691 let Run {
1692 mut client,
1693 mut server,
1694 } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1695 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1696 let (_, accepted) = server
1697 .request_pairing(
1698 &request,
1699 &code().token,
1700 &SERVER_CHALLENGE,
1701 attempt_id(),
1702 t(0),
1703 )
1704 .unwrap();
1705 client
1706 .accept(accepted, binding(), Deployment::Lan, t(1))
1707 .unwrap();
1708
1709 let body = client.abandon();
1710 assert!(!body.success);
1711 assert!(server.finalize(body, t(2)).unwrap().is_none());
1712 }
1713
1714 #[test]
1715 fn the_request_body_is_the_shape_the_openapi_defines() {
1716 let Run { mut client, .. } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1717 let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1718 let json = serde_json::to_value(&request).expect("serializable");
1719 for key in [
1720 "clientNodeDescription",
1721 "clientEndpointDescription",
1722 "supportedCommunicationProtocols",
1723 "supportedS2MessageVersions",
1724 "supportedHmacHashingAlgorithms",
1725 "clientHmacChallenge",
1726 ] {
1727 assert!(json.get(key).is_some(), "missing required property {key}");
1728 }
1729 assert!(json.get("nodeId").is_none());
1731 assert!(json.get("nodeIdAlias").is_some());
1732 assert!(json.get("forcePairing").is_none());
1733 assert_eq!(
1734 json["clientNodeDescription"]["role"].as_str(),
1735 Some("CEM"),
1736 "the role enum is spelled as the schema spells it"
1737 );
1738 }
1739}