1pub mod lan;
9pub mod pairing;
10pub mod session_init;
11
12use alloc::string::{String, ToString};
13use alloc::vec::Vec;
14
15use base64::Engine as _;
16use serde::{Deserialize, Serialize};
17use zeroize::{Zeroize, ZeroizeOnDrop};
18
19use crate::types::Duration;
20
21pub use lan::{
22 CancelPreparePairing, LONG_POLL_HOLD, LONG_POLL_TIMEOUT, NodeListing, PreparePairing,
23 PrepareRefused, WaitAction, WaitErrorMessage, WaitForPairing, WaitInstruction,
24};
25pub use pairing::{
26 ConnectionDetails, ConnectionDetailsPost, ConnectionDetailsRequest, FinalizePairing,
27 MINIMUM_SERVER_DELAY, NextStep, PAIRING_BUDGET, Pairing, PairingAccepted, PairingAttemptId,
28 PairingClient, PairingErrorMessage, PairingRefused, PairingRequest, PairingServer, PairingStep,
29};
30pub use session_init::{
31 COMMUNICATION_TOKEN_LIFETIME, CommunicationDetails, SessionCredentials, SessionErrorMessage,
32 SessionGrant, SessionInitClient, SessionInitServer, SessionRefused, SessionRequest, TokenStore,
33 UnpairRequest,
34};
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
41#[serde(rename_all = "UPPERCASE")]
42pub enum Role {
43 Cem,
45 Rm,
47}
48
49impl Role {
50 #[must_use]
52 pub const fn service_subtype(self) -> &'static str {
53 match self {
54 Role::Cem => "_cem",
55 Role::Rm => "_rm",
56 }
57 }
58
59 #[must_use]
62 pub const fn can_pair_with(self, other: Self) -> bool {
63 !matches!((self, other), (Role::Cem, Role::Cem) | (Role::Rm, Role::Rm))
64 }
65
66 #[must_use]
68 pub const fn other(self) -> Self {
69 match self {
70 Role::Cem => Role::Rm,
71 Role::Rm => Role::Cem,
72 }
73 }
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
78#[serde(rename_all = "UPPERCASE")]
79pub enum Deployment {
80 Wan,
82 Lan,
84}
85
86impl Deployment {
87 #[must_use]
93 pub const fn communication_server(cem: Self, rm: Self) -> Role {
94 match (cem, rm) {
95 (Deployment::Lan, Deployment::Wan) => Role::Rm,
96 _ => Role::Cem,
97 }
98 }
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
111#[serde(transparent)]
112pub struct NodeId(pub crate::types::Id);
113
114impl NodeId {
115 #[cfg(feature = "uuid")]
117 #[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
118 #[must_use]
119 pub fn generate() -> Self {
120 Self(crate::types::Id::generate())
121 }
122
123 pub fn parse(s: &str) -> Result<Self, ConnectError> {
125 crate::types::Id::parse(s)
126 .map(Self)
127 .map_err(|_| ConnectError::MalformedNodeId)
128 }
129}
130
131impl core::fmt::Display for NodeId {
132 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
133 self.0.fmt(f)
134 }
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
147#[serde(transparent)]
148pub struct NodeIdAlias(pub String);
149
150impl NodeIdAlias {
151 pub const MAX_LEN: usize = 64;
158
159 pub fn parse(s: &str) -> Result<Self, ConnectError> {
161 if s.is_empty() || s.len() > Self::MAX_LEN || !s.bytes().all(|b| b.is_ascii_alphanumeric())
162 {
163 return Err(ConnectError::MalformedPairingCode);
164 }
165 Ok(Self(s.to_string()))
166 }
167}
168
169impl<'de> Deserialize<'de> for NodeIdAlias {
170 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
171 let raw = String::deserialize(deserializer)?;
178 Self::parse(&raw).map_err(serde::de::Error::custom)
179 }
180}
181
182#[derive(Clone, Zeroize, ZeroizeOnDrop)]
187pub struct PairingToken(Vec<u8>);
188
189impl PartialEq for PairingToken {
192 fn eq(&self, other: &Self) -> bool {
193 use subtle::ConstantTimeEq as _;
194 self.0.ct_eq(&other.0).into()
195 }
196}
197
198impl Eq for PairingToken {}
199
200impl PairingToken {
201 pub const MIN_DYNAMIC: usize = 4;
203 pub const MIN_STATIC: usize = 6;
205 pub const MAX_LEN: usize = 256;
211
212 pub fn parse(s: &str, kind: TokenKind) -> Result<Self, ConnectError> {
214 let minimum = match kind {
215 TokenKind::Dynamic => Self::MIN_DYNAMIC,
216 TokenKind::Static => Self::MIN_STATIC,
217 };
218 if s.len() < minimum
219 || s.len() > Self::MAX_LEN
220 || !s.bytes().all(|b| b.is_ascii_alphanumeric())
221 {
222 return Err(ConnectError::MalformedPairingCode);
223 }
224 Ok(Self(s.as_bytes().to_vec()))
225 }
226
227 #[must_use]
231 pub fn as_bytes(&self) -> &[u8] {
232 &self.0
233 }
234}
235
236impl core::fmt::Debug for PairingToken {
237 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
238 write!(f, "PairingToken(<{} characters>)", self.0.len())
240 }
241}
242
243#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261pub enum TokenKind {
262 Dynamic,
265 Static,
268}
269
270#[derive(Debug, Clone, PartialEq, Eq)]
275pub struct PairingCode {
276 pub alias: Option<NodeIdAlias>,
278 pub token: PairingToken,
280}
281
282impl PairingCode {
283 pub fn parse(code: &str, kind: TokenKind) -> Result<Self, ConnectError> {
301 match code.split_once('-') {
302 Some((alias, token)) => Ok(Self {
305 alias: Some(NodeIdAlias::parse(alias)?),
306 token: PairingToken::parse(token, kind)?,
307 }),
308 None => Ok(Self {
309 alias: None,
310 token: PairingToken::parse(code, kind)?,
311 }),
312 }
313 }
314}
315
316#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
321#[serde(transparent)]
322pub struct AccessToken(String);
323
324#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
329#[serde(transparent)]
330pub struct CommunicationToken(String);
331
332macro_rules! opaque_token {
333 ($ty:ident, $name:literal, $lifetime:expr) => {
334 impl $ty {
335 pub const MIN_BYTES: usize = 32;
337
338 #[must_use]
340 pub fn new(value: impl Into<String>) -> Self {
341 Self(value.into())
342 }
343
344 pub fn from_entropy(bytes: &[u8]) -> Result<Self, ConnectError> {
349 if bytes.len() < Self::MIN_BYTES {
350 return Err(ConnectError::WeakSecret {
351 got: bytes.len(),
352 need: Self::MIN_BYTES,
353 });
354 }
355 Ok(Self(
356 base64::engine::general_purpose::STANDARD.encode(bytes),
357 ))
358 }
359
360 #[must_use]
362 pub fn as_str(&self) -> &str {
363 &self.0
364 }
365
366 #[must_use]
368 pub const fn lifetime() -> Duration {
369 $lifetime
370 }
371
372 #[must_use]
374 pub fn verify(&self, other: &Self) -> bool {
375 self.verify_str(&other.0)
376 }
377
378 #[must_use]
385 pub fn verify_str(&self, presented: &str) -> bool {
386 use subtle::ConstantTimeEq as _;
387 self.0.len() == presented.len()
390 && bool::from(self.0.as_bytes().ct_eq(presented.as_bytes()))
391 }
392 }
393
394 impl core::fmt::Debug for $ty {
395 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
396 write!(f, concat!($name, "(<redacted>)"))
397 }
398 }
399 };
400}
401
402opaque_token!(AccessToken, "AccessToken", Duration::from_secs(157_680_000));
404opaque_token!(
405 CommunicationToken,
406 "CommunicationToken",
407 Duration::from_secs(30)
408);
409
410#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
412pub struct NodeDescription {
413 pub id: NodeId,
415 pub brand: String,
417 #[serde(rename = "logoUrl", skip_serializing_if = "Option::is_none")]
419 pub logo_url: Option<String>,
420 #[serde(rename = "type")]
422 pub kind: String,
423 #[serde(rename = "modelName")]
425 pub model_name: String,
426 #[serde(rename = "userDefinedName", skip_serializing_if = "Option::is_none")]
428 pub user_defined_name: Option<String>,
429 pub role: Role,
431}
432
433#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
435pub struct EndpointDescription {
436 #[serde(skip_serializing_if = "Option::is_none")]
438 pub name: Option<String>,
439 #[serde(rename = "logoUrl", skip_serializing_if = "Option::is_none")]
441 pub logo_url: Option<String>,
442 #[serde(skip_serializing_if = "Option::is_none")]
444 pub deployment: Option<Deployment>,
445}
446
447#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
449#[non_exhaustive]
450pub enum ConnectError {
451 #[error("the pairing code is malformed")]
454 MalformedPairingCode,
455 #[error("the node identifier is malformed")]
457 MalformedNodeId,
458 #[error("a secret of {got} bytes is weaker than the {need} the specification requires")]
460 WeakSecret {
461 got: usize,
463 need: usize,
465 },
466 #[error("the challenge response does not match")]
469 ChallengeFailed,
470 #[error("a {0:?} cannot pair with another {0:?}")]
472 SameRole(Role),
473 #[error("{got} arrived while waiting for {expected}")]
475 OutOfOrder {
476 got: &'static str,
478 expected: &'static str,
480 },
481 #[error("the {what} budget of {} seconds ran out", limit.as_secs_f64())]
483 Expired {
484 what: &'static str,
486 limit: Duration,
488 },
489 #[error("another pairing attempt for this node is in progress")]
495 RateLimited,
496 #[error("no common {0}")]
498 NoOverlap(&'static str),
499 #[error("not paired")]
501 NotPaired,
502 #[error("pairing refused: {:?}", .0.error_message)]
506 Refused(pairing::PairingRefused),
507 #[error("session refused: {:?}", .0.error_message)]
509 SessionRefused(session_init::SessionRefused),
510}
511
512#[derive(Debug, Clone, PartialEq, Eq)]
519pub enum HmacBinding {
520 LeafFingerprint(Vec<u8>),
526 DomainName(String),
529}
530
531impl HmacBinding {
532 pub fn from_hex_fingerprint(hex: &str) -> Result<Self, ConnectError> {
534 let digits: Vec<u8> = hex.bytes().filter(|b| *b != b':' && *b != b' ').collect();
535 if !digits.len().is_multiple_of(2) || digits.is_empty() {
536 return Err(ConnectError::WeakSecret {
537 got: digits.len() / 2,
538 need: 32,
539 });
540 }
541 let mut bytes = Vec::with_capacity(digits.len() / 2);
542 for pair in digits.chunks(2) {
543 let hi = hex_value(*pair.first().unwrap_or(&0))?;
544 let lo = hex_value(*pair.get(1).unwrap_or(&0))?;
545 bytes.push(hi << 4 | lo);
546 }
547 if bytes.len() < 32 {
548 return Err(ConnectError::WeakSecret {
549 got: bytes.len(),
550 need: 32,
551 });
552 }
553 Ok(Self::LeafFingerprint(bytes))
554 }
555
556 fn as_bytes(&self) -> &[u8] {
557 match self {
558 HmacBinding::LeafFingerprint(bytes) => bytes,
559 HmacBinding::DomainName(name) => name.as_bytes(),
560 }
561 }
562}
563
564fn hex_value(b: u8) -> Result<u8, ConnectError> {
565 match b {
566 b'0'..=b'9' => Ok(b - b'0'),
567 b'a'..=b'f' => Ok(b - b'a' + 10),
568 b'A'..=b'F' => Ok(b - b'A' + 10),
569 _ => Err(ConnectError::MalformedPairingCode),
570 }
571}
572
573#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
578#[non_exhaustive]
579pub enum CommunicationProtocol {
580 WebSocket,
582}
583
584#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
586#[non_exhaustive]
587pub enum HmacHashingAlgorithm {
588 #[serde(rename = "SHA256")]
590 Sha256,
591}
592
593#[derive(Debug, Clone, PartialEq, Eq)]
599pub struct ChallengeResponse {
600 bytes: [u8; 32],
601}
602
603impl ChallengeResponse {
604 pub fn compute(
625 challenge: &[u8],
626 token: &PairingToken,
627 binding: &HmacBinding,
628 ) -> Result<Self, ConnectError> {
629 use hmac::Mac as _;
630 if challenge.len() < 32 {
631 return Err(ConnectError::WeakSecret {
632 got: challenge.len(),
633 need: 32,
634 });
635 }
636 let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::KeyInit>::new_from_slice(challenge)
637 .map_err(|_| ConnectError::ChallengeFailed)?;
638 mac.update(token.as_bytes());
639 mac.update(binding.as_bytes());
640 let out = mac.finalize().into_bytes();
641 let mut bytes = [0u8; 32];
642 bytes.copy_from_slice(&out);
643 Ok(Self { bytes })
644 }
645
646 pub fn from_base64(encoded: &str) -> Result<Self, ConnectError> {
648 let decoded = base64::engine::general_purpose::STANDARD
649 .decode(encoded)
650 .map_err(|_| ConnectError::ChallengeFailed)?;
651 if decoded.len() != 32 {
652 return Err(ConnectError::ChallengeFailed);
653 }
654 let mut bytes = [0u8; 32];
655 bytes.copy_from_slice(&decoded);
656 Ok(Self { bytes })
657 }
658
659 #[must_use]
661 pub fn as_base64(&self) -> String {
662 base64::engine::general_purpose::STANDARD.encode(self.bytes)
663 }
664
665 #[must_use]
667 pub fn verify(&self, theirs: &str) -> bool {
668 use subtle::ConstantTimeEq as _;
669 let Ok(other) = Self::from_base64(theirs) else {
670 return false;
671 };
672 self.bytes.ct_eq(&other.bytes).into()
673 }
674}
675
676pub(crate) fn base64_encode(bytes: &[u8]) -> String {
677 base64::engine::general_purpose::STANDARD.encode(bytes)
678}
679
680pub(crate) fn base64_decode(encoded: &str) -> Option<Vec<u8>> {
681 base64::engine::general_purpose::STANDARD
682 .decode(encoded)
683 .ok()
684}
685
686pub type Backoff = crate::session::Backoff;
691
692pub mod dnssd {
694 use super::{Deployment, Role};
695 use alloc::string::{String, ToString};
696 use alloc::vec::Vec;
697
698 pub const SERVICE_TYPE: &str = "_s2connect";
700 pub const PROTOCOL: &str = "_tcp";
702 pub const TXT_VERSION: &str = "1";
704
705 #[derive(Debug, Clone, Default, PartialEq, Eq)]
707 pub struct ServiceRecord {
708 pub endpoint_name: Option<String>,
710 pub endpoint_logo_url: Option<String>,
712 pub pairing_url: Option<String>,
714 pub longpolling_url: Option<String>,
717 pub roles: Vec<Role>,
719 }
720
721 impl ServiceRecord {
722 #[must_use]
728 pub fn txt_pairs(&self) -> Vec<(&'static str, String)> {
729 let mut out = alloc::vec![("txtver", TXT_VERSION.to_string())];
730 if let Some(name) = &self.endpoint_name {
731 out.push(("e_name", name.clone()));
732 }
733 if let Some(logo) = &self.endpoint_logo_url {
734 out.push(("e_logoUrl", logo.clone()));
735 }
736 if let Some(url) = &self.pairing_url {
737 out.push(("pairingUrl", url.clone()));
738 }
739 if let Some(url) = &self.longpolling_url {
740 out.push(("longpollingUrl", url.clone()));
741 }
742 out
743 }
744
745 #[must_use]
750 pub fn from_txt<'a, I>(pairs: I) -> Option<Self>
751 where
752 I: IntoIterator<Item = (&'a str, &'a str)>,
753 {
754 let mut record = Self::default();
755 let mut version_seen = false;
756 for (key, value) in pairs {
757 match key {
758 "txtver" | "txtvers" => {
759 if value != TXT_VERSION {
760 return None;
761 }
762 version_seen = true;
763 }
764 "e_name" => record.endpoint_name = Some(value.to_string()),
765 "e_logoUrl" => record.endpoint_logo_url = Some(value.to_string()),
766 "pairingUrl" => record.pairing_url = Some(value.to_string()),
767 "longpollingUrl" => record.longpolling_url = Some(value.to_string()),
768 _ => {}
769 }
770 }
771 if !version_seen || (record.pairing_url.is_none() && record.longpolling_url.is_none()) {
774 return None;
775 }
776 Some(record)
777 }
778
779 #[must_use]
782 pub fn has_pairing_server(&self) -> bool {
783 self.pairing_url.is_some()
784 }
785
786 #[must_use]
788 pub fn subtypes(&self) -> Vec<&'static str> {
789 self.roles.iter().map(|r| r.service_subtype()).collect()
790 }
791
792 #[must_use]
794 pub fn is_consistent_with(&self, deployment: Deployment) -> bool {
795 self.longpolling_url.is_none() || deployment == Deployment::Lan
796 }
797 }
798}
799
800#[cfg(test)]
801mod tests {
802 use super::*;
803
804 fn token() -> PairingToken {
805 PairingToken::parse("A1b2C3", TokenKind::Static).expect("a legal token")
806 }
807
808 #[test]
809 fn an_alias_is_validated_however_the_body_was_parsed() {
810 assert!(serde_json::from_str::<NodeIdAlias>(r#""evse7""#).is_ok());
813 assert!(serde_json::from_str::<NodeIdAlias>(r#""evse 7""#).is_err());
814 assert!(serde_json::from_str::<NodeIdAlias>(r#""""#).is_err());
815
816 assert!(serde_json::from_str::<NodeIdAlias>(r#""evse\u0037""#).is_ok());
821 assert_eq!(
822 serde_json::from_value::<NodeIdAlias>(serde_json::json!("evse7")).ok(),
823 Some(NodeIdAlias("evse7".into()))
824 );
825 }
826
827 #[test]
828 fn a_pairing_code_splits_at_the_first_dash() {
829 let code = PairingCode::parse("evse7-A1b2C3", TokenKind::Static).unwrap();
830 assert_eq!(code.alias.unwrap().0, "evse7");
831 assert_eq!(code.token.as_bytes(), b"A1b2C3");
832
833 let code = PairingCode::parse("A1b2C3", TokenKind::Static).unwrap();
834 assert!(code.alias.is_none());
835 }
836
837 #[test]
838 fn a_pairing_code_is_checked_before_the_network_is() {
839 assert!(PairingCode::parse("abc", TokenKind::Dynamic).is_err());
841 assert!(PairingCode::parse("abcd", TokenKind::Dynamic).is_ok());
842 assert!(PairingCode::parse("abcde", TokenKind::Static).is_err());
843 assert!(PairingCode::parse("abcdef", TokenKind::Static).is_ok());
844 assert!(PairingCode::parse("ab cd", TokenKind::Dynamic).is_err());
846 assert!(PairingCode::parse("ab.cd", TokenKind::Dynamic).is_err());
847 assert!(PairingCode::parse("", TokenKind::Dynamic).is_err());
848 assert!(PairingCode::parse("-abcd", TokenKind::Dynamic).is_err());
850 }
851
852 #[test]
853 fn everything_an_unauthenticated_peer_chooses_is_bounded() {
854 use alloc::string::ToString;
855
856 assert!(NodeIdAlias::parse(&"a".repeat(NodeIdAlias::MAX_LEN)).is_ok());
858 assert!(NodeIdAlias::parse(&"a".repeat(NodeIdAlias::MAX_LEN + 1)).is_err());
859
860 let long = alloc::format!("\"{}\"", "a".repeat(NodeIdAlias::MAX_LEN + 1));
864 assert!(serde_json::from_str::<NodeIdAlias>(&long).is_err());
865 assert!(serde_json::from_str::<NodeIdAlias>("\"has space\"").is_err());
866 assert!(serde_json::from_str::<NodeIdAlias>("\"\"").is_err());
867 assert_eq!(
868 serde_json::from_str::<NodeIdAlias>("\"hub7\"").unwrap().0,
869 "hub7".to_string()
870 );
871
872 let longest = "a".repeat(PairingToken::MAX_LEN);
874 assert!(PairingToken::parse(&longest, TokenKind::Static).is_ok());
875 assert!(PairingToken::parse(&alloc::format!("{longest}a"), TokenKind::Static).is_err());
876 assert!(PairingCode::parse(&alloc::format!("hub7-{longest}a"), TokenKind::Static).is_err());
878 }
879
880 #[test]
881 fn a_secret_never_prints_itself() {
882 let code = PairingCode::parse("evse7-SuperSecret", TokenKind::Static).unwrap();
883 let rendered = alloc::format!("{:?}", code.token);
884 assert!(!rendered.contains("SuperSecret"), "{rendered}");
885 let access = AccessToken::new("hunter2");
886 assert_eq!(alloc::format!("{access:?}"), "AccessToken(<redacted>)");
887 }
888
889 #[test]
890 fn a_token_needs_the_entropy_the_specification_demands() {
891 assert!(AccessToken::from_entropy(&[0u8; 31]).is_err());
892 let token = AccessToken::from_entropy(&[0u8; 32]).unwrap();
893 assert_eq!(token.as_str().len(), 44);
895 assert_eq!(CommunicationToken::lifetime(), Duration::from_secs(30));
896 }
897
898 #[test]
899 fn the_challenge_binds_to_the_server_it_was_answered_by() {
900 let challenge = [9u8; 32];
901 let here = HmacBinding::DomainName("pairing.example.com".into());
902 let there = HmacBinding::DomainName("pairing.example.com.evil.test".into());
903
904 let ours = ChallengeResponse::compute(&challenge, &token(), &here).unwrap();
905 let theirs = ChallengeResponse::compute(&challenge, &token(), &here).unwrap();
906 assert!(ours.verify(&theirs.as_base64()));
907
908 let forged = ChallengeResponse::compute(&challenge, &token(), &there).unwrap();
911 assert!(!ours.verify(&forged.as_base64()));
912
913 let wrong = PairingToken::parse("Z9y8X7", TokenKind::Static).unwrap();
915 let forged = ChallengeResponse::compute(&challenge, &wrong, &here).unwrap();
916 assert!(!ours.verify(&forged.as_base64()));
917 }
918
919 #[test]
920 fn a_short_challenge_is_refused_rather_than_padded() {
921 let binding = HmacBinding::DomainName("x.example".into());
922 assert!(matches!(
923 ChallengeResponse::compute(&[0u8; 31], &token(), &binding),
924 Err(ConnectError::WeakSecret { need: 32, .. })
925 ));
926 }
927
928 #[test]
929 fn a_fingerprint_is_read_with_or_without_colons() {
930 let colons = "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:\
931 AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99";
932 let plain = colons.replace(':', "");
933 assert_eq!(
934 HmacBinding::from_hex_fingerprint(colons).unwrap(),
935 HmacBinding::from_hex_fingerprint(&plain).unwrap()
936 );
937 assert!(HmacBinding::from_hex_fingerprint("AABB").is_err());
939 assert!(HmacBinding::from_hex_fingerprint("nonsense").is_err());
940 }
941
942 #[test]
943 fn verification_refuses_anything_that_is_not_a_response() {
944 let ours = ChallengeResponse::compute(
945 &[1u8; 32],
946 &token(),
947 &HmacBinding::DomainName("x.example".into()),
948 )
949 .unwrap();
950 assert!(!ours.verify("not base64 at all !!"));
951 assert!(!ours.verify(""));
952 assert!(!ours.verify(&base64::engine::general_purpose::STANDARD.encode([0u8; 16])));
954 }
955
956 #[test]
957 fn only_a_cem_and_an_rm_may_pair() {
958 assert!(Role::Cem.can_pair_with(Role::Rm));
959 assert!(Role::Rm.can_pair_with(Role::Cem));
960 assert!(!Role::Cem.can_pair_with(Role::Cem));
961 assert!(!Role::Rm.can_pair_with(Role::Rm));
962 }
963
964 #[test]
965 fn the_communication_server_is_the_one_the_standard_names() {
966 use Deployment::{Lan, Wan};
967 assert_eq!(Deployment::communication_server(Wan, Lan), Role::Cem);
970 assert_eq!(Deployment::communication_server(Lan, Wan), Role::Rm);
971 assert_eq!(Deployment::communication_server(Wan, Wan), Role::Cem);
974 assert_eq!(Deployment::communication_server(Lan, Lan), Role::Cem);
975 }
976
977 #[test]
978 fn the_dns_sd_record_round_trips_and_accepts_both_spellings() {
979 use dnssd::ServiceRecord;
980 let record = ServiceRecord {
981 endpoint_name: Some("EVSE1038".into()),
982 endpoint_logo_url: None,
983 pairing_url: Some("https://EVSE1038.local:443/pairing/".into()),
984 longpolling_url: None,
985 roles: alloc::vec![Role::Rm],
986 };
987 let pairs = record.txt_pairs();
988 assert_eq!(pairs[0], ("txtver", "1".to_string()));
989 assert_eq!(record.subtypes(), alloc::vec!["_rm"]);
990
991 let borrowed: alloc::vec::Vec<(&str, &str)> =
992 pairs.iter().map(|(k, v)| (*k, v.as_str())).collect();
993 let back = ServiceRecord::from_txt(borrowed).unwrap();
994 assert_eq!(back.pairing_url, record.pairing_url);
995
996 let back =
998 ServiceRecord::from_txt([("txtvers", "1"), ("pairingUrl", "https://x.local/pairing/")])
999 .unwrap();
1000 assert!(back.has_pairing_server());
1001
1002 assert!(ServiceRecord::from_txt([("txtver", "1")]).is_none());
1004 assert!(ServiceRecord::from_txt([("txtver", "2"), ("pairingUrl", "x")]).is_none());
1006 }
1007
1008 #[test]
1009 fn long_polling_is_a_lan_only_arrangement() {
1010 use dnssd::ServiceRecord;
1011 let record = ServiceRecord {
1012 longpolling_url: Some("https://rm.local/pairing/".into()),
1013 roles: alloc::vec![Role::Rm],
1014 ..ServiceRecord::default()
1015 };
1016 assert!(record.is_consistent_with(Deployment::Lan));
1017 assert!(!record.is_consistent_with(Deployment::Wan));
1018 }
1019}