1use std::fmt;
34
35use anyhow::{anyhow, bail, Context, Result};
36use base64::engine::general_purpose::URL_SAFE_NO_PAD;
37use base64::Engine as _;
38use sha2::{Digest, Sha256};
39use x25519_dalek::{PublicKey, StaticSecret};
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
47pub enum Suite {
48 #[default]
50 ChaChaPoly,
51 AesGcm,
53}
54
55impl Suite {
56 pub const ALL: [Suite; 2] = [Suite::ChaChaPoly, Suite::AesGcm];
58
59 pub const fn wire_name(self) -> &'static str {
62 match self {
63 Suite::ChaChaPoly => "25519_ChaChaPoly_SHA256",
64 Suite::AesGcm => "25519_AESGCM_SHA256",
65 }
66 }
67
68 pub const fn params(self) -> &'static str {
70 match self {
71 Suite::ChaChaPoly => "Noise_KKpsk2_25519_ChaChaPoly_SHA256",
72 Suite::AesGcm => "Noise_KKpsk2_25519_AESGCM_SHA256",
73 }
74 }
75
76 pub fn from_wire_name(name: &str) -> Option<Suite> {
81 Suite::ALL
82 .into_iter()
83 .find(|suite| suite.wire_name() == name)
84 }
85}
86
87impl fmt::Display for Suite {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 f.write_str(self.wire_name())
91 }
92}
93
94pub const NOISE_PARAMS: &str = Suite::ChaChaPoly.params();
96
97pub const SENTINEL_PSK: [u8; 32] = [
102 0x1b, 0x5e, 0x24, 0xdb, 0xc1, 0xae, 0xd9, 0x5f, 0xc2, 0xa5, 0xa3, 0x38, 0xa9, 0x0c, 0x05, 0xdf,
103 0x44, 0xbd, 0x10, 0xf5, 0xec, 0x1f, 0x4c, 0xd6, 0x6c, 0xbf, 0x86, 0x27, 0x27, 0x67, 0xb9, 0xd3,
104];
105
106pub const SENTINEL_PSK_ID: &str = "GFsV9tLaSQm9HcFWpKsgYQOr7wFTvNUtkmFwuVz3zoo";
108
109pub const MAX_MESSAGE_LEN: usize = 65_535;
114
115pub const TAG_LEN: usize = 16;
117
118pub const MAX_PLAINTEXT_LEN: usize = MAX_MESSAGE_LEN - TAG_LEN;
121
122const PSK_ID_LABEL: &[u8] = b"sendspin-psk-id-v1";
124
125const HANDSHAKE_MESSAGE_2: &[u8] = b"{}";
127
128const KEY_CHARS: usize = 43;
130
131pub fn psk_id_for(psk: &[u8]) -> String {
136 let mut hasher = Sha256::new();
137 hasher.update(PSK_ID_LABEL);
138 hasher.update(psk);
139 URL_SAFE_NO_PAD.encode(hasher.finalize())
140}
141
142#[derive(Clone, Copy)]
149pub struct Identity {
150 pub public: [u8; 32],
152 pub secret: [u8; 32],
154}
155
156impl Identity {
157 pub fn generate() -> Identity {
164 let params = NOISE_PARAMS
165 .parse()
166 .expect("NOISE_PARAMS is a valid Noise protocol name");
167 let keypair = snow::Builder::new(params)
168 .generate_keypair()
169 .expect("the operating system CSPRNG is available");
170 let secret: [u8; 32] = keypair
171 .private
172 .as_slice()
173 .try_into()
174 .expect("an X25519 secret key is 32 bytes");
175 Identity::from_secret(secret)
176 }
177
178 pub fn from_secret_base64(s: &str) -> Result<Identity> {
186 let secret = decode_key(s).ok_or_else(|| {
187 anyhow!("identity secret is not a canonical 43-character unpadded base64url X25519 key")
188 })?;
189 Ok(Identity::from_secret(secret))
190 }
191
192 pub fn public_base64(&self) -> String {
196 URL_SAFE_NO_PAD.encode(self.public)
197 }
198
199 pub fn secret_base64(&self) -> String {
204 URL_SAFE_NO_PAD.encode(self.secret)
205 }
206
207 fn from_secret(secret: [u8; 32]) -> Identity {
209 Identity {
210 public: public_key_for(&secret),
211 secret,
212 }
213 }
214
215 fn validate(&self) -> Result<()> {
217 if public_key_for(&self.secret) != self.public {
218 bail!("identity public key does not match its secret key");
219 }
220 Ok(())
221 }
222}
223
224impl fmt::Debug for Identity {
225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227 f.debug_struct("Identity")
228 .field("public", &self.public_base64())
229 .field("secret", &"<redacted>")
230 .finish()
231 }
232}
233
234pub struct Responder {
236 handshake: snow::HandshakeState,
237 suite: Suite,
239}
240
241impl Responder {
242 pub fn new(identity: &Identity, prologue: &[u8]) -> Result<Responder> {
254 let peer_public = initiator_key_from_prologue(prologue)?;
255 let suite = suite_from_prologue(prologue)?;
256 Responder::with_peer_suite(identity, &peer_public, suite, prologue)
257 }
258
259 pub fn with_suite(identity: &Identity, suite: Suite, prologue: &[u8]) -> Result<Responder> {
266 let peer_public = initiator_key_from_prologue(prologue)?;
267 let announced = suite_from_prologue(prologue)?;
268 if announced != suite {
269 bail!(
270 "the `client/init` in the prologue announces the cipher suite `{announced}`, so \
271 this handshake cannot run `{suite}`; a suite the peer did not announce is \
272 refused, never substituted"
273 );
274 }
275 Responder::with_peer_suite(identity, &peer_public, suite, prologue)
276 }
277
278 pub fn with_peer(
287 identity: &Identity,
288 peer_public: &[u8; 32],
289 prologue: &[u8],
290 ) -> Result<Responder> {
291 Responder::with_peer_suite(identity, peer_public, Suite::default(), prologue)
292 }
293
294 pub fn with_peer_suite(
300 identity: &Identity,
301 peer_public: &[u8; 32],
302 suite: Suite,
303 prologue: &[u8],
304 ) -> Result<Responder> {
305 identity.validate()?;
306
307 debug_assert_eq!(psk_id_for(&SENTINEL_PSK), SENTINEL_PSK_ID);
309
310 let params = suite
311 .params()
312 .parse()
313 .context("failed to parse the Noise protocol parameters")?;
314 let handshake = snow::Builder::new(params)
315 .local_private_key(&identity.secret)
316 .context("failed to set the local static key")?
317 .remote_public_key(peer_public)
318 .context("failed to set the peer static key")?
319 .psk(2, &SENTINEL_PSK)
320 .context("failed to set the handshake PSK")?
321 .prologue(prologue)
322 .context("failed to set the Noise prologue")?
323 .build_responder()
324 .context("failed to build the Noise responder")?;
325 Ok(Responder { handshake, suite })
326 }
327
328 pub fn suite(&self) -> Suite {
330 self.suite
331 }
332
333 pub fn set_psk(&mut self, psk: &[u8; 32]) -> Result<()> {
347 self.handshake
348 .set_psk(2, psk)
349 .context("failed to set the Noise handshake PSK")
350 }
351
352 pub fn read_message(&mut self, msg: &[u8]) -> Result<Vec<u8>> {
358 read_handshake_payload(&mut self.handshake, msg)
359 }
360
361 pub fn write_message(&mut self) -> Result<Vec<u8>> {
365 write_handshake_payload(&mut self.handshake, HANDSHAKE_MESSAGE_2)
366 }
367
368 pub fn handshake_finished(&self) -> bool {
370 self.handshake.is_handshake_finished()
371 }
372
373 pub fn into_transport(self) -> Result<TransportState> {
378 transport_from(self.handshake, self.suite)
379 }
380}
381
382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
388pub enum PskOutcome {
389 SelectedKey,
392 SentinelFallback,
395}
396
397pub struct Initiator {
408 handshake: snow::HandshakeState,
409 suite: Suite,
411 selected_non_sentinel: bool,
421}
422
423impl Initiator {
424 pub fn new(
433 identity: &Identity,
434 peer_public: &[u8; 32],
435 suite: Suite,
436 prologue: &[u8],
437 ) -> Result<Initiator> {
438 if let Some(announced) = announced_suite_from_prologue(prologue)? {
439 if announced != suite {
440 bail!(
441 "the `client/init` in the prologue announces the cipher suite `{announced}`, \
442 so this handshake cannot run `{suite}`; the suite a peer announced is \
443 refused when it differs, never substituted"
444 );
445 }
446 }
447 Initiator::build(identity, peer_public, suite, prologue)
448 }
449
450 pub fn with_announced_suite(
458 identity: &Identity,
459 peer_public: &[u8; 32],
460 prologue: &[u8],
461 ) -> Result<Initiator> {
462 let suite = suite_from_prologue(prologue)?;
463 Initiator::build(identity, peer_public, suite, prologue)
464 }
465
466 fn build(
468 identity: &Identity,
469 peer_public: &[u8; 32],
470 suite: Suite,
471 prologue: &[u8],
472 ) -> Result<Initiator> {
473 identity.validate()?;
474
475 debug_assert_eq!(psk_id_for(&SENTINEL_PSK), SENTINEL_PSK_ID);
477
478 let params = suite
479 .params()
480 .parse()
481 .context("failed to parse the Noise protocol parameters")?;
482 let handshake = snow::Builder::new(params)
483 .local_private_key(&identity.secret)
484 .context("failed to set the local static key")?
485 .remote_public_key(peer_public)
486 .context("failed to set the peer static key")?
487 .psk(2, &SENTINEL_PSK)
488 .context("failed to set the handshake PSK")?
489 .prologue(prologue)
490 .context("failed to set the Noise prologue")?
491 .build_initiator()
492 .context("failed to build the Noise initiator")?;
493 Ok(Initiator {
494 handshake,
495 suite,
496 selected_non_sentinel: false,
497 })
498 }
499
500 pub fn suite(&self) -> Suite {
502 self.suite
503 }
504
505 pub fn set_psk(&mut self, psk: &[u8; 32]) -> Result<()> {
516 self.handshake
517 .set_psk(2, psk)
518 .context("failed to set the Noise handshake PSK")?;
519 self.selected_non_sentinel = psk != &SENTINEL_PSK;
520 Ok(())
521 }
522
523 pub fn write_message(&mut self, payload: &[u8]) -> Result<Vec<u8>> {
528 write_handshake_payload(&mut self.handshake, payload)
529 }
530
531 pub fn read_message(&mut self, msg: &[u8]) -> Result<Vec<u8>> {
537 read_handshake_payload(&mut self.handshake, msg)
538 }
539
540 pub fn read_message_with_sentinel(&mut self, msg: &[u8]) -> Result<(PskOutcome, Vec<u8>)> {
560 if !self.selected_non_sentinel {
561 bail!(
562 "the selected PSK is the Sentinel key, so a failed read cannot be retried under \
563 the Sentinel key"
564 );
565 }
566 ensure_message_len(msg.len(), "handshake message")?;
567 let mut payload = vec![0u8; plaintext_capacity(msg.len(), "handshake message")?];
568 match self.handshake.read_message(msg, &mut payload) {
569 Ok(len) => {
570 payload.truncate(len);
571 return Ok((PskOutcome::SelectedKey, payload));
572 }
573 Err(error) if should_retry_under_sentinel(&error) => {}
576 Err(error) => return Err(error).context("failed to read the Noise handshake message"),
577 }
578 self.handshake
579 .set_psk(2, &SENTINEL_PSK)
580 .context("failed to set the Noise handshake PSK")?;
581 let len = self
582 .handshake
583 .read_message(msg, &mut payload)
584 .context("failed to read the Noise handshake message under the Sentinel key")?;
585 payload.truncate(len);
586 Ok((PskOutcome::SentinelFallback, payload))
587 }
588
589 pub fn handshake_finished(&self) -> bool {
591 self.handshake.is_handshake_finished()
592 }
593
594 pub fn into_transport(self) -> Result<TransportState> {
600 transport_from(self.handshake, self.suite)
601 }
602}
603
604fn read_handshake_payload(handshake: &mut snow::HandshakeState, msg: &[u8]) -> Result<Vec<u8>> {
606 ensure_message_len(msg.len(), "handshake message")?;
607 let mut payload = vec![0u8; plaintext_capacity(msg.len(), "handshake message")?];
608 let len = handshake
609 .read_message(msg, &mut payload)
610 .context("failed to read the Noise handshake message")?;
611 payload.truncate(len);
612 Ok(payload)
613}
614
615fn should_retry_under_sentinel(error: &snow::Error) -> bool {
622 matches!(error, snow::Error::Decrypt)
623}
624
625fn write_handshake_payload(
627 handshake: &mut snow::HandshakeState,
628 payload: &[u8],
629) -> Result<Vec<u8>> {
630 let mut message = vec![0u8; MAX_MESSAGE_LEN];
631 let len = handshake
632 .write_message(payload, &mut message)
633 .context("failed to write the Noise handshake message")?;
634 message.truncate(len);
635 Ok(message)
636}
637
638fn transport_from(handshake: snow::HandshakeState, suite: Suite) -> Result<TransportState> {
643 let handshake_hash: [u8; 32] = handshake
644 .get_handshake_hash()
645 .try_into()
646 .context("the Noise handshake hash is not 32 bytes")?;
647 let state = handshake
648 .into_transport_mode()
649 .context("failed to finish the Noise handshake")?;
650 Ok(TransportState {
651 state,
652 handshake_hash,
653 suite,
654 })
655}
656
657pub struct TransportState {
663 state: snow::TransportState,
664 handshake_hash: [u8; 32],
666 suite: Suite,
668}
669
670impl TransportState {
671 pub fn suite(&self) -> Suite {
676 self.suite
677 }
678
679 pub fn handshake_hash(&self) -> &[u8; 32] {
687 &self.handshake_hash
688 }
689
690 pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>> {
695 ensure_plaintext_len(plaintext.len())?;
696 let mut message = vec![0u8; plaintext.len() + TAG_LEN];
697 let len = self
698 .state
699 .write_message(plaintext, &mut message)
700 .context("failed to encrypt the Noise transport message")?;
701 message.truncate(len);
702 Ok(message)
703 }
704
705 pub fn decrypt(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>> {
710 ensure_message_len(ciphertext.len(), "transport message")?;
711 let mut plaintext = vec![0u8; plaintext_capacity(ciphertext.len(), "transport message")?];
712 let len = self
713 .state
714 .read_message(ciphertext, &mut plaintext)
715 .context("failed to decrypt the Noise transport message")?;
716 plaintext.truncate(len);
717 Ok(plaintext)
718 }
719}
720
721fn initiator_key_from_prologue(prologue: &[u8]) -> Result<[u8; 32]> {
729 let mut server_id = None;
730 for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
731 {
732 let document = document.context("the prologue is not a sequence of JSON documents")?;
733 if document.get("type").and_then(serde_json::Value::as_str) != Some("server/init") {
734 continue;
735 }
736 if server_id.is_some() {
737 bail!("the prologue contains more than one `server/init` document");
738 }
739 let id = document
740 .pointer("/payload/server_id")
741 .and_then(serde_json::Value::as_str)
742 .ok_or_else(|| {
743 anyhow!("the `server/init` document carries no string `payload.server_id`")
744 })?;
745 server_id = Some(decode_key(id).ok_or_else(|| {
746 anyhow!("`server_id` is not a canonical 43-character unpadded base64url X25519 key")
747 })?);
748 }
749
750 server_id.ok_or_else(|| {
751 anyhow!(
752 "the prologue contains no `server/init` document with a `server_id`, so the \
753 initiator's static public key is unknown; pass it with `Responder::with_peer`"
754 )
755 })
756}
757
758fn public_key_for(secret: &[u8; 32]) -> [u8; 32] {
760 PublicKey::from(&StaticSecret::from(*secret)).to_bytes()
761}
762
763fn suite_from_prologue(prologue: &[u8]) -> Result<Suite> {
771 let mut announced = None;
772 for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
773 {
774 let document = document.context("the prologue is not a sequence of JSON documents")?;
775 if let Some(suite) = client_init_suite(&document)? {
776 if announced.is_some() {
777 bail!("the prologue contains more than one `client/init` document");
778 }
779 announced = Some(suite);
780 }
781 }
782
783 announced.ok_or_else(|| {
784 anyhow!(
785 "the prologue contains no `client/init` document with a `suite`, so the cipher suite \
786 is unknown; a first handshake needs the init exchange, pass the suite with \
787 `Responder::with_peer_suite` on a re-handshake"
788 )
789 })
790}
791
792fn announced_suite_from_prologue(prologue: &[u8]) -> Result<Option<Suite>> {
798 let mut announced = None;
799 for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
800 {
801 let Ok(document) = document else {
802 return Ok(None);
804 };
805 if let Some(suite) = client_init_suite(&document)? {
806 if announced.is_some() {
807 bail!("the prologue contains more than one `client/init` document");
808 }
809 announced = Some(suite);
810 }
811 }
812 Ok(announced)
813}
814
815fn client_init_suite(document: &serde_json::Value) -> Result<Option<Suite>> {
817 if document.get("type").and_then(serde_json::Value::as_str) != Some("client/init") {
818 return Ok(None);
819 }
820 let name = document
821 .pointer("/payload/suite")
822 .and_then(serde_json::Value::as_str)
823 .ok_or_else(|| {
824 anyhow!(
825 "the `client/init` document carries no string `payload.suite`; the cipher suite \
826 is required and is not assumed to be `{}`",
827 Suite::default()
828 )
829 })?;
830 Ok(Some(Suite::from_wire_name(name).ok_or_else(|| {
831 anyhow!(
832 "the `client/init` document announces the cipher suite `{name}`, which this build \
833 does not have; it supports {}",
834 Suite::ALL
835 .map(Suite::wire_name)
836 .map(|name| format!("`{name}`"))
837 .join(", ")
838 )
839 })?))
840}
841
842fn ensure_message_len(len: usize, what: &str) -> Result<()> {
844 if len > MAX_MESSAGE_LEN {
845 bail!(
846 "Noise {what} is {len} bytes, exceeding the maximum Noise message size of \
847 {MAX_MESSAGE_LEN} bytes"
848 );
849 }
850 Ok(())
851}
852
853fn ensure_plaintext_len(len: usize) -> Result<()> {
855 if len > MAX_PLAINTEXT_LEN {
856 bail!(
857 "plaintext is {len} bytes, exceeding the maximum Noise plaintext size of \
858 {MAX_PLAINTEXT_LEN} bytes (a {MAX_MESSAGE_LEN}-byte message including the \
859 {TAG_LEN}-byte tag); payloads are not fragmented at this layer"
860 );
861 }
862 Ok(())
863}
864
865fn plaintext_capacity(len: usize, what: &str) -> Result<usize> {
867 len.checked_sub(TAG_LEN).ok_or_else(|| {
868 anyhow!("Noise {what} is {len} bytes, shorter than the {TAG_LEN}-byte authentication tag")
869 })
870}
871
872fn decode_key(value: &str) -> Option<[u8; 32]> {
874 if value.len() != KEY_CHARS {
875 return None;
876 }
877 let bytes = URL_SAFE_NO_PAD.decode(value).ok()?;
878 if bytes.len() != 32 || URL_SAFE_NO_PAD.encode(&bytes) != value {
879 return None;
880 }
881 bytes.try_into().ok()
882}
883
884#[cfg(test)]
885mod tests {
886 use super::*;
887
888 const CLIENT_INIT: &[u8] =
889 br#"{"type":"client/init","payload":{"client_id":"test-client","version":1}}"#;
890
891 fn server_init(server_id: &str) -> Vec<u8> {
892 format!(r#"{{"type":"server/init","payload":{{"server_id":"{server_id}","version":1}}}}"#)
893 .into_bytes()
894 }
895
896 fn prologue(server_id: &str) -> Vec<u8> {
897 let mut bytes = CLIENT_INIT.to_vec();
898 bytes.extend_from_slice(&server_init(server_id));
899 bytes
900 }
901
902 const TEST_PROLOGUE: &[u8] = b"client/init{}server/init{}";
905
906 const RECORD_PSK: [u8; 32] = [0x11; 32];
909
910 const MESSAGE_1_PAYLOAD: &[u8] = br#"{"psk_id":"test","psk_category":"sn"}"#;
912
913 fn peer_responder(
916 client: &Identity,
917 server: &Identity,
918 psk: &[u8; 32],
919 ) -> snow::HandshakeState {
920 snow::Builder::new(
921 Suite::ChaChaPoly
922 .params()
923 .parse()
924 .expect("valid Noise parameters"),
925 )
926 .local_private_key(&client.secret)
927 .expect("set the local static key")
928 .remote_public_key(&server.public)
929 .expect("set the peer static key")
930 .psk(2, psk)
931 .expect("set the handshake PSK")
932 .prologue(TEST_PROLOGUE)
933 .expect("set the Noise prologue")
934 .build_responder()
935 .expect("build the Noise responder")
936 }
937
938 fn peer_write(peer: &mut snow::HandshakeState, payload: &[u8]) -> Vec<u8> {
939 let mut message = vec![0u8; MAX_MESSAGE_LEN];
940 let len = peer
941 .write_message(payload, &mut message)
942 .expect("write a Noise handshake message");
943 message.truncate(len);
944 message
945 }
946
947 fn peer_read(peer: &mut snow::HandshakeState, message: &[u8]) -> Vec<u8> {
948 let mut payload = vec![0u8; MAX_MESSAGE_LEN];
949 let len = peer
950 .read_message(message, &mut payload)
951 .expect("read a Noise handshake message");
952 payload.truncate(len);
953 payload
954 }
955
956 fn handshake_after_message_1(
958 initiator_psk: &[u8; 32],
959 peer_psk: &[u8; 32],
960 ) -> (Initiator, snow::HandshakeState) {
961 let server = Identity::generate();
962 let client = Identity::generate();
963 let mut initiator =
964 Initiator::new(&server, &client.public, Suite::ChaChaPoly, TEST_PROLOGUE)
965 .expect("build the initiator");
966 initiator
967 .set_psk(initiator_psk)
968 .expect("select the initiator PSK");
969 let mut peer = peer_responder(&client, &server, peer_psk);
970
971 let message_1 = initiator
972 .write_message(MESSAGE_1_PAYLOAD)
973 .expect("write message 1");
974 assert_eq!(
975 peer_read(&mut peer, &message_1),
976 MESSAGE_1_PAYLOAD,
977 "message 1 must reach the peer whichever key each side selected"
978 );
979 (initiator, peer)
980 }
981
982 #[test]
983 fn the_prologue_carries_the_initiator_static_key() {
984 let identity = Identity::generate();
985 let key = initiator_key_from_prologue(&prologue(&identity.public_base64()))
986 .expect("server/init carries server_id");
987 assert_eq!(key, identity.public);
988 }
989
990 #[test]
991 fn a_prologue_without_a_server_init_is_rejected() {
992 let identity = Identity::generate();
993
994 for prologue in [&b""[..], CLIENT_INIT] {
995 let result = Responder::new(&identity, prologue);
996 assert!(
997 result.is_err(),
998 "a prologue without server/init must be rejected"
999 );
1000 let err = result.err().expect("the rejection was asserted");
1001 let message = format!("{err:#}");
1002 assert!(
1003 message.contains("server_id") && message.contains("with_peer"),
1004 "error should name the missing key and the way out, got: {message}"
1005 );
1006 }
1007
1008 let result = Responder::new(&identity, b"not json at all");
1010 assert!(
1011 result.is_err(),
1012 "a prologue that is not JSON must be rejected"
1013 );
1014 let err = result.err().expect("the rejection was asserted");
1015 assert!(
1016 format!("{err:#}").contains("prologue is not a sequence of JSON documents"),
1017 "error should name the malformed prologue, got: {err:#}"
1018 );
1019 }
1020
1021 #[test]
1022 fn prologue_with_duplicate_server_id_is_rejected() {
1023 let identity = Identity::generate();
1024 let first = Identity::generate().public_base64();
1025 let second = Identity::generate().public_base64();
1026 let mut prologue = prologue(&first);
1027 prologue.extend_from_slice(&server_init(&second));
1028
1029 let result = Responder::new(&identity, &prologue);
1030 assert!(result.is_err(), "two server/init documents are ambiguous");
1031 let err = result.err().expect("the rejection was asserted");
1032 assert!(
1033 format!("{err:#}").contains("more than one `server/init`"),
1034 "error should name the duplicate, got: {err:#}"
1035 );
1036 }
1037
1038 #[test]
1039 fn an_identity_mismatch_is_rejected_before_the_handshake() {
1040 let mut identity = Identity::generate();
1041 identity.public = Identity::generate().public;
1042 let prologue = prologue(&Identity::generate().public_base64());
1043 let result = Responder::with_peer(&identity, &[0u8; 32], &prologue);
1044 assert!(result.is_err(), "a mismatched identity must be rejected");
1045 let err = result.err().expect("the rejection was asserted");
1046 assert!(
1047 format!("{err:#}").contains("does not match"),
1048 "error should name the mismatch, got: {err:#}"
1049 );
1050 }
1051
1052 #[test]
1053 fn a_server_init_without_a_usable_server_id_is_rejected() {
1054 let identity = Identity::generate();
1055
1056 let mut missing = CLIENT_INIT.to_vec();
1057 missing.extend_from_slice(br#"{"type":"server/init","payload":{"version":1}}"#);
1058 let result = Responder::new(&identity, &missing);
1059 assert!(result.is_err(), "a server/init without server_id must fail");
1060 assert!(
1061 format!("{:#}", result.err().expect("the rejection was asserted"))
1062 .contains("payload.server_id"),
1063 "the error must name the missing field"
1064 );
1065
1066 let mut wrong_type = CLIENT_INIT.to_vec();
1067 wrong_type.extend_from_slice(br#"{"type":"server/init","payload":{"server_id":42}}"#);
1068 let result = Responder::new(&identity, &wrong_type);
1069 assert!(result.is_err(), "a non-string server_id must fail");
1070 assert!(
1071 format!("{:#}", result.err().expect("the rejection was asserted"))
1072 .contains("payload.server_id")
1073 );
1074 }
1075
1076 #[test]
1077 fn a_server_id_that_is_not_a_canonical_key_is_rejected() {
1078 let identity = Identity::generate();
1079
1080 for server_id in ["short", &"!".repeat(43), &"a".repeat(43)] {
1083 let result = Responder::new(&identity, &prologue(server_id));
1084 assert!(
1085 result.is_err(),
1086 "{server_id:?} must not be accepted as a key"
1087 );
1088 let message = format!("{:#}", result.err().expect("the rejection was asserted"));
1089 assert!(
1090 message.contains("canonical 43-character"),
1091 "the error must name the encoding, got: {message}"
1092 );
1093 }
1094
1095 let id = "A".repeat(43);
1097 assert_eq!(
1098 initiator_key_from_prologue(&prologue(&id)).expect("a canonical key is accepted"),
1099 {
1100 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
1101 use base64::Engine as _;
1102 let bytes = URL_SAFE_NO_PAD.decode(&id).expect("the id is base64url");
1103 let mut key = [0u8; 32];
1104 key.copy_from_slice(&bytes);
1105 key
1106 }
1107 );
1108 }
1109
1110 #[test]
1111 fn identity_debug_redacts_the_secret() {
1112 let identity = Identity::generate();
1113 let text = format!("{identity:?}");
1114 assert!(text.contains(&identity.public_base64()));
1115 assert!(!text.contains(&identity.secret_base64()));
1116 assert!(text.contains("<redacted>"));
1117 }
1118
1119 #[test]
1120 fn a_failed_read_can_be_retried_with_another_psk() {
1121 let (mut initiator, mut peer) = handshake_after_message_1(&RECORD_PSK, &SENTINEL_PSK);
1125 let message_2 = peer_write(&mut peer, b"{}");
1126
1127 let error = initiator
1128 .read_message(&message_2)
1129 .expect_err("a message 2 sealed with the Sentinel key must not authenticate");
1130 assert_eq!(
1131 error.downcast_ref::<snow::Error>(),
1132 Some(&snow::Error::Decrypt),
1133 "a wrong PSK is an authentication failure, not a length or state failure"
1134 );
1135
1136 let (outcome, payload) = initiator
1137 .read_message_with_sentinel(&message_2)
1138 .expect("the same bytes authenticate under the Sentinel key");
1139 assert_eq!(outcome, PskOutcome::SentinelFallback);
1140 assert_eq!(payload, b"{}");
1141 assert!(initiator.handshake_finished());
1142
1143 let peer_hash = peer.get_handshake_hash().to_vec();
1146 let mut ours = initiator.into_transport().expect("initiator transport");
1147 assert_eq!(
1148 ours.handshake_hash().to_vec(),
1149 peer_hash,
1150 "the retried handshake derived a hash the peer does not share"
1151 );
1152 let mut theirs = peer.into_transport_mode().expect("the peer's transport");
1153
1154 let ciphertext = ours.encrypt(b"from the initiator").expect("encrypt");
1155 let mut plaintext = vec![0u8; MAX_MESSAGE_LEN];
1156 let len = theirs
1157 .read_message(&ciphertext, &mut plaintext)
1158 .expect("the peer decrypts");
1159 assert_eq!(&plaintext[..len], b"from the initiator");
1160
1161 let mut ciphertext = vec![0u8; MAX_MESSAGE_LEN];
1162 let len = theirs
1163 .write_message(b"from the responder", &mut ciphertext)
1164 .expect("the peer encrypts");
1165 assert_eq!(
1166 ours.decrypt(&ciphertext[..len]).expect("decrypt"),
1167 b"from the responder"
1168 );
1169 }
1170
1171 #[test]
1172 fn a_successful_read_is_not_retried() {
1173 let (mut initiator, mut peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1174 let message_2 = peer_write(&mut peer, b"{}");
1175
1176 let (outcome, payload) = initiator
1177 .read_message_with_sentinel(&message_2)
1178 .expect("message 2 authenticates under the selected key");
1179 assert_eq!(outcome, PskOutcome::SelectedKey);
1180 assert_eq!(payload, b"{}");
1181 assert!(initiator.handshake_finished());
1182 }
1183
1184 #[test]
1185 fn a_successful_read_returns_a_foreign_payload() {
1186 let (mut initiator, mut peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1189 let message_2 = peer_write(&mut peer, b"not-empty");
1190
1191 let (outcome, payload) = initiator
1192 .read_message_with_sentinel(&message_2)
1193 .expect("message 2 authenticates under the selected key");
1194 assert_eq!(outcome, PskOutcome::SelectedKey);
1195 assert_eq!(payload, b"not-empty");
1196 }
1197
1198 #[test]
1199 fn the_sentinel_key_cannot_be_the_selected_key() {
1200 let server = Identity::generate();
1201 let client = Identity::generate();
1202 let mut initiator =
1203 Initiator::new(&server, &client.public, Suite::ChaChaPoly, TEST_PROLOGUE)
1204 .expect("build the initiator");
1205 initiator
1206 .set_psk(&SENTINEL_PSK)
1207 .expect("the Sentinel key is a valid PSK");
1208
1209 let error = initiator
1212 .read_message_with_sentinel(&[0u8; 4])
1213 .expect_err("there is no second key to retry under");
1214 let text = format!("{error:#}");
1215 assert!(
1216 text.contains("Sentinel"),
1217 "the error must name the Sentinel key, got: {text}"
1218 );
1219 assert!(!initiator.handshake_finished());
1220 }
1221
1222 #[test]
1223 fn the_last_psk_write_wins() {
1224 let server = Identity::generate();
1225 let client = Identity::generate();
1226 let mut initiator =
1227 Initiator::new(&server, &client.public, Suite::ChaChaPoly, TEST_PROLOGUE)
1228 .expect("build the initiator");
1229 initiator
1230 .set_psk(&RECORD_PSK)
1231 .expect("select the record's key");
1232 initiator
1233 .set_psk(&SENTINEL_PSK)
1234 .expect("select the Sentinel key again");
1235
1236 let error = initiator
1237 .read_message_with_sentinel(&[0u8; 4])
1238 .expect_err("the Sentinel key was the last write, so there is nothing to retry under");
1239 assert!(
1240 format!("{error:#}").contains("Sentinel"),
1241 "the error must name the Sentinel key, got: {error:#}"
1242 );
1243 }
1244
1245 #[test]
1246 fn only_a_decrypt_failure_is_retried() {
1247 assert!(should_retry_under_sentinel(&snow::Error::Decrypt));
1248
1249 for error in [
1250 snow::Error::Input,
1251 snow::Error::Dh,
1252 snow::Error::Rng,
1253 snow::Error::State(snow::error::StateProblem::NotTurnToRead),
1254 ] {
1255 assert!(
1256 !should_retry_under_sentinel(&error),
1257 "{error:?} is not an authentication failure and must not be retried"
1258 );
1259 }
1260 }
1261
1262 #[test]
1263 fn a_frame_shorter_than_the_tag_is_not_retried() {
1264 let (mut initiator, _peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1265
1266 let error = initiator
1267 .read_message_with_sentinel(&[0u8; 12])
1268 .expect_err("12 bytes cannot carry an authentication tag");
1269 assert!(
1270 error.downcast_ref::<snow::Error>().is_none(),
1271 "the capacity guard, not snow, must reject a frame below the tag length"
1272 );
1273 assert!(
1274 format!("{error:#}").contains("16-byte"),
1275 "the error must name the tag length, got: {error:#}"
1276 );
1277 }
1278
1279 #[test]
1280 fn a_frame_in_the_input_band_is_not_retried() {
1281 let (mut initiator, _peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1282
1283 let error = initiator
1287 .read_message_with_sentinel(&[0u8; 20])
1288 .expect_err("20 bytes cannot carry a message-2 ephemeral key");
1289 assert_eq!(
1290 error.downcast_ref::<snow::Error>(),
1291 Some(&snow::Error::Input)
1292 );
1293 assert!(
1297 !format!("{error:#}").contains("under the Sentinel key"),
1298 "a frame in the input band must not reach the retry, got: {error:#}"
1299 );
1300 }
1301
1302 #[test]
1303 fn a_truncated_tag_is_retried_and_still_fails() {
1304 let (mut initiator, _peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
1305
1306 let error = initiator
1309 .read_message_with_sentinel(&[0u8; 40])
1310 .expect_err("a truncated tag must not authenticate");
1311 assert_eq!(
1312 error.downcast_ref::<snow::Error>(),
1313 Some(&snow::Error::Decrypt)
1314 );
1315 }
1316}