1pub mod account;
8pub mod command;
9pub mod error;
10
11pub use error::{ProtocolError, ProtocolResult};
12
13use serde::{Deserialize, Serialize};
14use std::str::FromStr;
15use uuid::Uuid;
16
17pub type SessionId = Uuid;
19
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct Message {
27 #[serde(rename = "type", deserialize_with = "message_type_from_str")]
29 pub msg_type: MessageType,
30
31 #[serde(skip_serializing_if = "Option::is_none")]
33 pub session: Option<SessionId>,
34
35 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub channel: Option<String>,
43
44 #[serde(skip_serializing_if = "Option::is_none")]
46 pub payload: Option<MessagePayload>,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case")]
52#[non_exhaustive]
53pub enum MessageType {
54 SessionCreate,
56 SessionJoin,
58 SessionJoined,
60 SessionLeft,
62 SessionError,
64 Input,
66 Output,
68 Resize,
70 Ping,
72 Pong,
74 Auth,
76 SessionResume,
78 BackendAway,
80 BackendBack,
82 FrontendJoined,
84 Replay,
86 MachineHello,
89 Challenge,
92 MachineProof,
95 SessionRecord,
99 SessionRecordGone,
102 SessionRecordsKept,
107}
108
109impl FromStr for MessageType {
110 type Err = ProtocolError;
111
112 fn from_str(s: &str) -> Result<Self, Self::Err> {
113 match s {
114 "session_create" => Ok(Self::SessionCreate),
115 "session_join" => Ok(Self::SessionJoin),
116 "session_joined" => Ok(Self::SessionJoined),
117 "session_left" => Ok(Self::SessionLeft),
118 "session_error" => Ok(Self::SessionError),
119 "input" => Ok(Self::Input),
120 "output" => Ok(Self::Output),
121 "resize" => Ok(Self::Resize),
122 "ping" => Ok(Self::Ping),
123 "pong" => Ok(Self::Pong),
124 "auth" => Ok(Self::Auth),
125 "session_resume" => Ok(Self::SessionResume),
126 "backend_away" => Ok(Self::BackendAway),
127 "backend_back" => Ok(Self::BackendBack),
128 "frontend_joined" => Ok(Self::FrontendJoined),
129 "replay" => Ok(Self::Replay),
130 "machine_hello" => Ok(Self::MachineHello),
131 "challenge" => Ok(Self::Challenge),
132 "machine_proof" => Ok(Self::MachineProof),
133 "session_record" => Ok(Self::SessionRecord),
134 "session_record_gone" => Ok(Self::SessionRecordGone),
135 "session_records_kept" => Ok(Self::SessionRecordsKept),
136 other => Err(ProtocolError::UnknownType(other.to_string())),
137 }
138 }
139}
140
141impl MessageType {
142 pub fn to_str(&self) -> &'static str {
144 match self {
145 Self::SessionCreate => "session_create",
146 Self::SessionJoin => "session_join",
147 Self::SessionJoined => "session_joined",
148 Self::SessionLeft => "session_left",
149 Self::SessionError => "session_error",
150 Self::Input => "input",
151 Self::Output => "output",
152 Self::Resize => "resize",
153 Self::Ping => "ping",
154 Self::Pong => "pong",
155 Self::Auth => "auth",
156 Self::SessionResume => "session_resume",
157 Self::BackendAway => "backend_away",
158 Self::BackendBack => "backend_back",
159 Self::FrontendJoined => "frontend_joined",
160 Self::Replay => "replay",
161 Self::MachineHello => "machine_hello",
162 Self::Challenge => "challenge",
163 Self::MachineProof => "machine_proof",
164 Self::SessionRecord => "session_record",
165 Self::SessionRecordGone => "session_record_gone",
166 Self::SessionRecordsKept => "session_records_kept",
167 }
168 }
169
170 pub fn is_io(&self) -> bool {
172 matches!(self, Self::Input | Self::Output)
173 }
174
175 pub fn requires_session(&self) -> bool {
177 !matches!(
178 self,
179 Self::Ping
180 | Self::Pong
181 | Self::Auth
182 | Self::SessionCreate | Self::SessionError | Self::MachineHello | Self::Challenge
186 | Self::MachineProof
187 )
188 }
189}
190
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196pub enum MessagePayload {
197 InputData {
201 data: Vec<u8>,
203 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
205 paste: bool,
206 },
207 OutputData {
210 data: Vec<u8>,
212 },
213 Resize {
216 columns: u16,
218 rows: u16,
220 },
221 Sealed {
224 data: Vec<u8>,
226 },
227 AuthToken {
229 token: String,
231 #[serde(default = "first_protocol")]
234 protocol: u16,
235 },
236 SessionCreated {
240 session_id: SessionId,
242 frontend_token: String,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
246 resume_secret: Option<String>,
247 #[serde(default = "first_protocol")]
250 protocol: u16,
251 },
252 ResumeSecret {
254 secret: String,
256 },
257 SessionOptions {
260 replay: bool,
262 },
263 Frontend {
266 frontend: u64,
268 #[serde(default)]
271 history: u32,
272 #[serde(default)]
275 rows: u16,
276 },
277 JoinOptions {
281 history: u32,
283 #[serde(default)]
287 rows: u16,
288 },
289 ReplayData {
292 frontend: u64,
294 data: Vec<u8>,
296 },
297 MachineId {
299 machine: String,
301 #[serde(default = "first_protocol")]
303 protocol: u16,
304 },
305 Challenge {
307 nonce: Vec<u8>,
309 #[serde(default = "first_protocol")]
311 protocol: u16,
312 },
313 Signature {
315 signature: Vec<u8>,
317 },
318 Record {
321 sealed_name: Vec<u8>,
323 sealed_key: Vec<u8>,
326 #[serde(default)]
329 signature: Vec<u8>,
330 },
331 RecordsKept {
334 channels: Vec<String>,
336 #[serde(default)]
339 previous: Vec<SessionId>,
340 },
341 ErrorReason {
343 reason: String,
345 },
346}
347
348pub fn machine_proof_message(nonce: &[u8], machine: &str) -> Vec<u8> {
351 let mut message = b"teter-machine-auth-v1 ".to_vec();
352 message.extend_from_slice(nonce);
353 message.extend_from_slice(machine.as_bytes());
354 message
355}
356
357pub const BACKEND_LEFT: &str = "the backend left the session";
362
363pub const SESSION_GONE: &str = "the session is gone";
366
367pub fn ends_the_session(reason: &str) -> bool {
370 reason == BACKEND_LEFT || reason == SESSION_GONE
371}
372
373pub const MAX_CHANNEL: usize = 64;
375
376pub fn valid_channel(channel: &str) -> bool {
380 !channel.is_empty()
381 && channel.len() <= MAX_CHANNEL
382 && channel.bytes().all(|b| b.is_ascii_alphanumeric())
383}
384
385impl Message {
386 #[must_use]
388 pub fn on_channel(self, channel: Option<String>) -> Self {
389 Self { channel, ..self }
390 }
391}
392
393pub const PROTOCOL: u16 = 3;
399
400pub const MIN_PROTOCOL: u16 = 2;
402
403const fn first_protocol() -> u16 {
405 1
406}
407
408pub fn check_relay_protocol(relay: u16) -> Result<(), String> {
416 if relay < PROTOCOL {
417 Err(format!(
418 "the relay speaks relay protocol {relay}, older than this teter's {PROTOCOL}: upgrade \
419 the relay"
420 ))
421 } else {
422 Ok(())
423 }
424}
425
426pub fn protocol_of(json: &str) -> Option<u16> {
430 let value: serde_json::Value = serde_json::from_str(json).ok()?;
431 let payload = value.get("payload")?.as_object()?;
432 payload
433 .values()
434 .find_map(|inner| inner.get("protocol")?.as_u64())
435 .and_then(|protocol| u16::try_from(protocol).ok())
436}
437
438pub fn check_protocol(client: u16, min: u16, max: u16) -> Result<(), String> {
445 if client > max {
446 Err(format!(
447 "this teter speaks relay protocol {client}, newer than the relay's {max}: upgrade the \
448 relay"
449 ))
450 } else if client < min {
451 Err(format!(
452 "this teter speaks relay protocol {client}, older than the relay accepts ({min} to \
453 {max}): upgrade teter"
454 ))
455 } else {
456 Ok(())
457 }
458}
459
460pub fn serialize_message(msg: &Message) -> ProtocolResult<String> {
462 serde_json::to_string(msg).map_err(ProtocolError::Serialization)
463}
464
465pub fn deserialize_message(json: &str) -> ProtocolResult<Message> {
474 if !json.trim_start().starts_with('{') {
476 return Err(ProtocolError::Deserialization(
477 <serde_json::Error as serde::de::Error>::custom("a message is a JSON object"),
478 ));
479 }
480 let msg: Message = serde_json::from_str(json).map_err(|e| classify_decode_error(json, e))?;
481
482 if msg.msg_type.requires_session() && msg.session.is_none() {
483 return Err(ProtocolError::MissingSession);
484 }
485 if msg
486 .channel
487 .as_deref()
488 .is_some_and(|channel| !valid_channel(channel))
489 {
490 return Err(ProtocolError::InvalidChannel);
491 }
492
493 Ok(msg)
494}
495
496fn message_type_from_str<'de, D>(deserializer: D) -> Result<MessageType, D::Error>
499where
500 D: serde::Deserializer<'de>,
501{
502 let name = std::borrow::Cow::<'de, str>::deserialize(deserializer)?;
503 name.parse().map_err(serde::de::Error::custom)
504}
505
506fn classify_decode_error(json: &str, err: serde_json::Error) -> ProtocolError {
510 let Ok(serde_json::Value::Object(fields)) = serde_json::from_str(json) else {
511 return ProtocolError::Deserialization(err);
512 };
513 let type_ = match fields.get("type") {
514 None => return ProtocolError::MissingType,
515 Some(serde_json::Value::String(t)) if t.is_empty() => return ProtocolError::MissingType,
516 Some(serde_json::Value::String(t)) => t,
517 Some(_) => return ProtocolError::Deserialization(err),
518 };
519 if let Err(unknown) = type_.parse::<MessageType>() {
520 return unknown;
521 }
522 if let Some(session) = fields.get("session")
523 && serde_json::from_value::<Option<SessionId>>(session.clone()).is_err()
524 {
525 return ProtocolError::InvalidSession { source: err };
526 }
527 if let Some(payload) = fields.get("payload")
528 && serde_json::from_value::<Option<MessagePayload>>(payload.clone()).is_err()
529 {
530 return ProtocolError::InvalidPayload {
531 type_: type_.clone(),
532 source: err,
533 };
534 }
535 ProtocolError::Deserialization(err)
536}
537
538impl Message {
541 pub fn session_create() -> Self {
543 Self {
544 msg_type: MessageType::SessionCreate,
545 session: None,
546 channel: None,
547 payload: None,
548 }
549 }
550
551 pub fn session_create_replaying() -> Self {
554 Self {
555 msg_type: MessageType::SessionCreate,
556 session: None,
557 channel: None,
558 payload: Some(MessagePayload::SessionOptions { replay: true }),
559 }
560 }
561
562 pub fn session_join(session: SessionId) -> Self {
564 Self {
565 msg_type: MessageType::SessionJoin,
566 session: Some(session),
567 channel: None,
568 payload: None,
569 }
570 }
571
572 pub fn session_join_with_history(session: SessionId, history: u32, rows: u16) -> Self {
576 if history == 0 {
577 return Self::session_join(session);
578 }
579 Self {
580 payload: Some(MessagePayload::JoinOptions { history, rows }),
581 ..Self::session_join(session)
582 }
583 }
584
585 pub fn session_joined(session: SessionId, frontend_token: String) -> Self {
587 Self {
588 msg_type: MessageType::SessionJoined,
589 session: Some(session),
590 channel: None,
591 payload: Some(MessagePayload::SessionCreated {
592 session_id: session,
593 frontend_token,
594 resume_secret: None,
595 protocol: PROTOCOL,
596 }),
597 }
598 }
599
600 pub fn session_created(
603 session: SessionId,
604 frontend_token: String,
605 resume_secret: String,
606 ) -> Self {
607 Self {
608 msg_type: MessageType::SessionJoined,
609 session: Some(session),
610 channel: None,
611 payload: Some(MessagePayload::SessionCreated {
612 session_id: session,
613 frontend_token,
614 resume_secret: Some(resume_secret),
615 protocol: PROTOCOL,
616 }),
617 }
618 }
619
620 pub fn session_resume(session: SessionId, secret: String) -> Self {
622 Self {
623 msg_type: MessageType::SessionResume,
624 session: Some(session),
625 channel: None,
626 payload: Some(MessagePayload::ResumeSecret { secret }),
627 }
628 }
629
630 pub fn frontend_joined(session: SessionId, frontend: u64, history: u32, rows: u16) -> Self {
632 Self {
633 msg_type: MessageType::FrontendJoined,
634 session: Some(session),
635 channel: None,
636 payload: Some(MessagePayload::Frontend {
637 frontend,
638 history,
639 rows,
640 }),
641 }
642 }
643
644 pub fn replay(session: SessionId, frontend: u64, data: Vec<u8>) -> Self {
646 Self {
647 msg_type: MessageType::Replay,
648 session: Some(session),
649 channel: None,
650 payload: Some(MessagePayload::ReplayData { frontend, data }),
651 }
652 }
653
654 pub fn backend_away(session: SessionId) -> Self {
656 Self {
657 msg_type: MessageType::BackendAway,
658 session: Some(session),
659 channel: None,
660 payload: None,
661 }
662 }
663
664 pub fn backend_back(session: SessionId) -> Self {
666 Self {
667 msg_type: MessageType::BackendBack,
668 session: Some(session),
669 channel: None,
670 payload: None,
671 }
672 }
673
674 pub fn session_left(session: SessionId) -> Self {
676 Self {
677 msg_type: MessageType::SessionLeft,
678 session: Some(session),
679 channel: None,
680 payload: None,
681 }
682 }
683
684 pub fn session_error(session: Option<SessionId>, reason: String) -> Self {
687 Self {
688 msg_type: MessageType::SessionError,
689 session,
690 channel: None,
691 payload: Some(MessagePayload::ErrorReason { reason }),
692 }
693 }
694
695 pub fn input(session: SessionId, data: Vec<u8>) -> Self {
697 Self {
698 msg_type: MessageType::Input,
699 session: Some(session),
700 channel: None,
701 payload: Some(MessagePayload::InputData { data, paste: false }),
702 }
703 }
704
705 pub fn paste_input(session: SessionId, data: Vec<u8>) -> Self {
707 Self {
708 msg_type: MessageType::Input,
709 session: Some(session),
710 channel: None,
711 payload: Some(MessagePayload::InputData { data, paste: true }),
712 }
713 }
714
715 pub fn output(session: SessionId, data: Vec<u8>) -> Self {
717 Self {
718 msg_type: MessageType::Output,
719 session: Some(session),
720 channel: None,
721 payload: Some(MessagePayload::OutputData { data }),
722 }
723 }
724
725 pub fn sealed_resize(session: SessionId, data: Vec<u8>) -> Self {
727 Self {
728 msg_type: MessageType::Resize,
729 session: Some(session),
730 channel: None,
731 payload: Some(MessagePayload::Sealed { data }),
732 }
733 }
734
735 pub fn resize(session: SessionId, columns: u16, rows: u16) -> Self {
737 Self {
738 msg_type: MessageType::Resize,
739 session: Some(session),
740 channel: None,
741 payload: Some(MessagePayload::Resize { columns, rows }),
742 }
743 }
744
745 pub fn auth(token: String) -> Self {
747 Self {
748 msg_type: MessageType::Auth,
749 session: None,
750 channel: None,
751 payload: Some(MessagePayload::AuthToken {
752 token,
753 protocol: PROTOCOL,
754 }),
755 }
756 }
757
758 pub fn ping() -> Self {
760 Self {
761 msg_type: MessageType::Ping,
762 session: None,
763 channel: None,
764 payload: None,
765 }
766 }
767
768 pub fn pong() -> Self {
770 Self {
771 msg_type: MessageType::Pong,
772 session: None,
773 channel: None,
774 payload: None,
775 }
776 }
777}
778
779#[derive(Debug, Clone, PartialEq, Eq)]
781pub enum Role {
782 Backend,
784 Frontend,
786}
787
788impl FromStr for Role {
789 type Err = ProtocolError;
790
791 fn from_str(s: &str) -> Result<Self, Self::Err> {
792 match s {
793 "backend" => Ok(Self::Backend),
794 "frontend" => Ok(Self::Frontend),
795 other => Err(ProtocolError::UnknownType(other.to_string())),
796 }
797 }
798}
799
800impl Role {
801 pub fn to_str(&self) -> &'static str {
803 match self {
804 Self::Backend => "backend",
805 Self::Frontend => "frontend",
806 }
807 }
808
809 pub fn parse_opt(s: &str) -> Option<Self> {
811 s.parse().ok()
812 }
813}
814
815#[cfg(test)]
816mod tests {
817 use super::*;
818
819 fn roundtrip(msg: &Message) -> String {
820 let json = serialize_message(msg).unwrap();
821 let restored = deserialize_message(&json).unwrap();
822 assert_eq!(*msg, restored);
823 json
824 }
825
826 #[test]
827 fn test_session_create_roundtrip() {
828 let msg = Message::session_create();
829 roundtrip(&msg);
830 }
831
832 #[test]
833 fn test_session_join_roundtrip() {
834 let sid = SessionId::new_v4();
835 let msg = Message::session_join(sid);
836 roundtrip(&msg);
837 }
838
839 #[test]
840 fn test_session_joined_roundtrip() {
841 let sid = SessionId::new_v4();
842 let token = "test-token-123".to_string();
843 let msg = Message::session_joined(sid, token.clone());
844 roundtrip(&msg);
845
846 if let Some(MessagePayload::SessionCreated {
847 session_id,
848 frontend_token,
849 resume_secret,
850 ..
851 }) = &msg.payload
852 {
853 assert_eq!(*session_id, sid);
854 assert_eq!(*frontend_token, token);
855 assert_eq!(*resume_secret, None);
856 } else {
857 panic!("expected SessionCreated payload");
858 }
859 assert!(!serialize_message(&msg).unwrap().contains("resume_secret"));
861 }
862
863 #[test]
864 fn test_replay_messages_roundtrip() {
865 let sid = SessionId::new_v4();
866 let create = Message::session_create_replaying();
867 let json = roundtrip(&create);
868 assert!(
869 json.contains(r#"{"SessionOptions":{"replay":true}}"#),
870 "{json}"
871 );
872 let joined = Message::frontend_joined(sid, 7, 0, 0);
873 let json = roundtrip(&joined);
874 assert!(json.contains(r#""type":"frontend_joined""#), "{json}");
875 assert!(
876 json.contains(r#"{"Frontend":{"frontend":7,"history":0,"rows":0}}"#),
877 "{json}"
878 );
879 let old = deserialize_message(
881 r#"{"type":"frontend_joined","session":"7011b901-812b-4f0b-83bb-da42e6148c81","payload":{"Frontend":{"frontend":7}}}"#,
882 )
883 .unwrap();
884 assert!(matches!(
885 old.payload,
886 Some(MessagePayload::Frontend {
887 frontend: 7,
888 history: 0,
889 rows: 0
890 })
891 ));
892 let replay = Message::replay(sid, 7, b"hi".to_vec());
893 let json = roundtrip(&replay);
894 assert!(
895 json.contains(r#"{"ReplayData":{"frontend":7,"data":[104,105]}}"#),
896 "{json}"
897 );
898 for (name, ty) in [
899 ("frontend_joined", MessageType::FrontendJoined),
900 ("replay", MessageType::Replay),
901 ] {
902 assert_eq!(name.parse::<MessageType>().unwrap(), ty);
903 assert_eq!(ty.to_str(), name);
904 assert!(ty.requires_session());
905 }
906 }
907
908 #[test]
909 fn test_resume_messages_roundtrip() {
910 let sid = SessionId::new_v4();
911 let created = Message::session_created(sid, "tok".into(), "sec".into());
912 let json = roundtrip(&created);
913 assert!(json.contains(r#""resume_secret":"sec""#), "{json}");
914 let resume = Message::session_resume(sid, "sec".into());
915 let json = roundtrip(&resume);
916 assert!(json.contains(r#""type":"session_resume""#), "{json}");
917 assert!(
918 json.contains(r#"{"ResumeSecret":{"secret":"sec"}}"#),
919 "{json}"
920 );
921 for msg in [Message::backend_away(sid), Message::backend_back(sid)] {
922 let json = roundtrip(&msg);
923 assert_eq!(deserialize_message(&json).unwrap(), msg);
924 }
925 for (name, ty) in [
926 ("session_resume", MessageType::SessionResume),
927 ("backend_away", MessageType::BackendAway),
928 ("backend_back", MessageType::BackendBack),
929 ] {
930 assert_eq!(name.parse::<MessageType>().unwrap(), ty);
931 assert_eq!(ty.to_str(), name);
932 assert!(ty.requires_session());
933 }
934 }
935
936 #[test]
937 fn test_session_left_roundtrip() {
938 let sid = SessionId::new_v4();
939 let msg = Message::session_left(sid);
940 roundtrip(&msg);
941 }
942
943 #[test]
944 fn test_session_error_roundtrip() {
945 let sid = SessionId::new_v4();
946 let msg = Message::session_error(Some(sid), "connection lost".to_string());
947 roundtrip(&msg);
948 }
949
950 #[test]
951 fn test_input_roundtrip() {
952 let sid = SessionId::new_v4();
953 let data = vec![0x1b, 0x5b, 0x41]; let msg = Message::input(sid, data.clone());
955 roundtrip(&msg);
956
957 if let Some(MessagePayload::InputData { data: received, .. }) = &msg.payload {
958 assert_eq!(*received, data);
959 } else {
960 panic!("expected InputData payload");
961 }
962 }
963
964 #[test]
965 fn test_output_roundtrip() {
966 let sid = SessionId::new_v4();
967 let data = b"Hello, teter!\n".to_vec();
968 let msg = Message::output(sid, data.clone());
969 roundtrip(&msg);
970
971 if let Some(MessagePayload::OutputData { data: received }) = &msg.payload {
972 assert_eq!(*received, data);
973 } else {
974 panic!("expected OutputData payload");
975 }
976 }
977
978 #[test]
979 fn test_resize_roundtrip() {
980 let sid = SessionId::new_v4();
981 let msg = Message::resize(sid, 120, 40);
982 roundtrip(&msg);
983
984 if let Some(MessagePayload::Resize { columns, rows }) = &msg.payload {
985 assert_eq!(*columns, 120);
986 assert_eq!(*rows, 40);
987 } else {
988 panic!("expected Resize payload");
989 }
990 }
991
992 #[test]
993 fn paste_input_is_marked_and_plain_input_leaves_the_mark_out() {
994 let sid = SessionId::new_v4();
995 let paste = Message::paste_input(sid, vec![1, 2]);
996 roundtrip(&paste);
997 let json = serialize_message(&paste).unwrap();
998 assert!(
999 json.contains(r#"{"InputData":{"data":[1,2],"paste":true}}"#),
1000 "{json}"
1001 );
1002 let plain = Message::input(sid, vec![1, 2]);
1003 let json = serialize_message(&plain).unwrap();
1004 assert!(json.contains(r#"{"InputData":{"data":[1,2]}}"#), "{json}");
1005 let read = deserialize_message(&json).unwrap();
1007 assert_eq!(
1008 read.payload,
1009 Some(MessagePayload::InputData {
1010 data: vec![1, 2],
1011 paste: false
1012 })
1013 );
1014 }
1015
1016 #[test]
1017 fn a_sealed_resize_roundtrips() {
1018 let sid = SessionId::new_v4();
1019 let msg = Message::sealed_resize(sid, vec![1, 2, 255]);
1020 roundtrip(&msg);
1021 assert_eq!(msg.msg_type, MessageType::Resize);
1022 assert_eq!(msg.session, Some(sid));
1023 assert_eq!(
1024 msg.payload,
1025 Some(MessagePayload::Sealed {
1026 data: vec![1, 2, 255]
1027 })
1028 );
1029 let json = serialize_message(&msg).unwrap();
1030 assert!(
1031 json.contains(r#""payload":{"Sealed":{"data":[1,2,255]}}"#),
1032 "{json}"
1033 );
1034 }
1035
1036 #[test]
1037 fn test_ping_roundtrip() {
1038 let msg = Message::ping();
1039 roundtrip(&msg);
1040 }
1041
1042 #[test]
1043 fn test_pong_roundtrip() {
1044 let msg = Message::pong();
1045 roundtrip(&msg);
1046 }
1047
1048 #[test]
1049 fn test_message_type_from_str() {
1050 assert_eq!(MessageType::from_str("input").unwrap(), MessageType::Input);
1051 assert_eq!(
1052 MessageType::from_str("session_create").unwrap(),
1053 MessageType::SessionCreate
1054 );
1055 assert!(MessageType::from_str("unknown_type").is_err());
1056 }
1057
1058 #[test]
1059 fn test_message_type_to_str() {
1060 assert_eq!(MessageType::Input.to_str(), "input");
1061 assert_eq!(MessageType::Output.to_str(), "output");
1062 assert_eq!(MessageType::Resize.to_str(), "resize");
1063 assert_eq!(MessageType::Ping.to_str(), "ping");
1064 }
1065
1066 #[test]
1067 fn test_requires_session() {
1068 assert!(!MessageType::Ping.requires_session());
1069 assert!(!MessageType::Pong.requires_session());
1070 assert!(MessageType::Input.requires_session());
1071 assert!(MessageType::Output.requires_session());
1072 assert!(!MessageType::Auth.requires_session());
1073 assert!(!MessageType::SessionError.requires_session());
1074 assert!(MessageType::SessionJoin.requires_session());
1075 }
1076
1077 #[test]
1078 fn the_protocol_is_read_from_a_first_message_that_does_not_decode() {
1079 assert_eq!(
1080 protocol_of(r#"{"type":"auth","payload":{"AuthToken":{"protocol":7}}}"#),
1081 Some(7)
1082 );
1083 assert_eq!(protocol_of(r#"{"type":"ping"}"#), None);
1084 assert_eq!(protocol_of("not json"), None);
1085 assert!(check_relay_protocol(PROTOCOL).is_ok());
1086 }
1087
1088 #[test]
1089 fn protocols_outside_the_range_say_what_to_upgrade() {
1090 assert_eq!(check_protocol(2, 1, 2), Ok(()));
1091 assert!(
1092 check_protocol(3, 1, 2)
1093 .unwrap_err()
1094 .contains("upgrade the relay")
1095 );
1096 assert!(
1097 check_protocol(0, 1, 2)
1098 .unwrap_err()
1099 .contains("upgrade teter")
1100 );
1101 }
1102
1103 #[test]
1104 fn test_auth_roundtrip() {
1105 let json = roundtrip(&Message::auth("secret".to_string()));
1106 assert_eq!(
1107 json,
1108 r#"{"type":"auth","payload":{"AuthToken":{"token":"secret","protocol":3}}}"#
1109 );
1110 let old = deserialize_message(r#"{"type":"auth","payload":{"AuthToken":{"token":"t"}}}"#)
1112 .unwrap();
1113 assert_eq!(
1114 old.payload,
1115 Some(MessagePayload::AuthToken {
1116 token: "t".to_owned(),
1117 protocol: 1
1118 })
1119 );
1120 assert_eq!("auth".parse::<MessageType>().unwrap(), MessageType::Auth);
1121 assert_eq!(MessageType::Auth.to_str(), "auth");
1122 }
1123
1124 #[test]
1125 fn test_session_error_without_session_roundtrip() {
1126 let json = roundtrip(&Message::session_error(
1127 None,
1128 "authentication failed".to_string(),
1129 ));
1130 assert!(!json.contains("session\""), "{json}");
1131 }
1132
1133 #[test]
1134 fn test_missing_session_rejected() {
1135 let json = r#"{"type":"input"}"#;
1137 assert!(matches!(
1138 deserialize_message(json),
1139 Err(ProtocolError::MissingSession)
1140 ));
1141 }
1142
1143 #[test]
1144 fn test_missing_type_rejected() {
1145 let json = r#"{"session":"00000000-0000-0000-0000-000000000000"}"#;
1146 assert!(deserialize_message(json).is_err());
1147 }
1148
1149 const SID: &str = "00000000-0000-0000-0000-000000000000";
1150
1151 fn invalid_payload_type(json: &str) -> String {
1152 match deserialize_message(json) {
1153 Err(ProtocolError::InvalidPayload { type_, .. }) => type_,
1154 other => panic!("expected InvalidPayload, got {other:?}"),
1155 }
1156 }
1157
1158 #[test]
1159 fn test_invalid_payload_names_the_type() {
1160 let json = format!(
1161 r#"{{"type":"resize","session":"{SID}","payload":{{"Resize":{{"columns":"wide","rows":24}}}}}}"#
1162 );
1163 assert_eq!(invalid_payload_type(&json), "resize");
1164 }
1165
1166 #[test]
1167 fn test_invalid_payload_type_with_whitespace() {
1168 let json = format!(
1169 r#"{{ "session" : "{SID}", "payload" : {{ "InputData" : {{ "data" : "x" }} }}, "type" : "input" }}"#
1170 );
1171 assert_eq!(invalid_payload_type(&json), "input");
1172 }
1173
1174 #[test]
1175 fn test_not_a_message_gives_deserialization_error() {
1176 for json in [
1177 "[1, 2]".to_string(),
1178 "not json".to_string(),
1179 format!(r#"{{"type":5,"session":"{SID}"}}"#),
1180 ] {
1181 let err = deserialize_message(&json).unwrap_err();
1182 assert!(
1183 matches!(err, ProtocolError::Deserialization(_)),
1184 "{json}: {err:?}"
1185 );
1186 assert!(err.to_string().starts_with("failed to decode"), "{err}");
1187 }
1188 }
1189
1190 #[test]
1191 fn test_missing_or_empty_type_gives_missing_type() {
1192 for json in [
1193 format!(r#"{{"session":"{SID}"}}"#),
1194 format!(r#"{{"type":"","session":"{SID}"}}"#),
1195 ] {
1196 assert!(
1197 matches!(deserialize_message(&json), Err(ProtocolError::MissingType)),
1198 "{json}"
1199 );
1200 }
1201 }
1202
1203 #[test]
1204 fn test_unknown_type_gives_unknown_type() {
1205 let json = format!(r#"{{"type":"bogus","session":"{SID}"}}"#);
1206 assert!(matches!(
1207 deserialize_message(&json),
1208 Err(ProtocolError::UnknownType(t)) if t == "bogus"
1209 ));
1210 }
1211
1212 #[test]
1213 fn test_bad_session_names_the_session() {
1214 for json in [
1215 r#"{"type":"input","session":"not-a-uuid","payload":{"InputData":{"data":[1]}}}"#,
1216 r#"{"type":"input","session":5,"payload":{"InputData":{"data":[1]}}}"#,
1217 ] {
1218 let err = deserialize_message(json).unwrap_err();
1219 assert!(
1220 matches!(err, ProtocolError::InvalidSession { .. }),
1221 "{json}: {err:?}"
1222 );
1223 assert!(err.to_string().contains("session"), "{err}");
1224 }
1225 }
1226
1227 #[test]
1228 fn test_non_canonical_forms_are_rejected() {
1229 for json in [
1230 r#"["ping"]"#,
1231 r#"["input","00000000-0000-0000-0000-000000000000"]"#,
1232 r#"["ping",null,null]"#,
1233 r#"{"type":{"ping":null}}"#,
1234 ] {
1235 assert!(
1236 matches!(
1237 deserialize_message(json),
1238 Err(ProtocolError::Deserialization(_))
1239 ),
1240 "{json}"
1241 );
1242 }
1243 }
1244
1245 #[test]
1246 fn test_decode_error_keeps_position() {
1247 let json = format!(
1248 r#"{{"type":"resize","session":"{SID}","payload":{{"Resize":{{"columns":"wide","rows":24}}}}}}"#
1249 );
1250 match deserialize_message(&json) {
1251 Err(ProtocolError::InvalidPayload { source, .. }) => {
1252 assert_eq!(source.line(), 1);
1253 assert!(source.column() > 0);
1254 }
1255 other => panic!("expected InvalidPayload, got {other:?}"),
1256 }
1257 }
1258
1259 #[test]
1260 fn test_null_fields_are_absent() {
1261 let json = r#"{"type":"ping","session":null,"payload":null}"#;
1262 assert_eq!(deserialize_message(json).unwrap(), Message::ping());
1263 }
1264
1265 #[test]
1266 fn test_only_the_session_ending_reasons_end_the_session() {
1267 assert!(ends_the_session(BACKEND_LEFT));
1268 assert!(ends_the_session(SESSION_GONE));
1269 assert!(!ends_the_session("silent past the heartbeat timeout"));
1270 assert!(!ends_the_session(""));
1271 }
1272
1273 #[test]
1274 fn test_io_flag() {
1275 assert!(MessageType::Input.is_io());
1276 assert!(MessageType::Output.is_io());
1277 assert!(!MessageType::Resize.is_io());
1278 assert!(!MessageType::Ping.is_io());
1279 }
1280
1281 #[test]
1282 fn test_role_to_from_str() {
1283 assert_eq!(Role::Backend.to_str(), "backend");
1284 assert_eq!(Role::Frontend.to_str(), "frontend");
1285 assert_eq!(Role::parse_opt("backend"), Some(Role::Backend));
1286 assert_eq!(Role::parse_opt("frontend"), Some(Role::Frontend));
1287 assert_eq!(Role::parse_opt("unknown"), None);
1288 }
1289
1290 #[test]
1291 fn test_role_from_str_trait() {
1292 assert_eq!("backend".parse::<Role>().unwrap(), Role::Backend);
1293 assert_eq!("frontend".parse::<Role>().unwrap(), Role::Frontend);
1294 assert!("unknown".parse::<Role>().is_err());
1295 }
1296
1297 #[test]
1298 fn test_auth_token_roundtrip() {
1299 let msg = Message {
1300 msg_type: MessageType::SessionCreate,
1301 session: None,
1302 channel: None,
1303 payload: Some(MessagePayload::AuthToken {
1304 token: "backend-secret-token".to_string(),
1305 protocol: PROTOCOL,
1306 }),
1307 };
1308 roundtrip(&msg);
1309 }
1310
1311 #[test]
1312 fn test_error_reason_roundtrip() {
1313 let sid = SessionId::new_v4();
1314 let msg = Message {
1315 msg_type: MessageType::SessionError,
1316 session: Some(sid),
1317 channel: None,
1318 payload: Some(MessagePayload::ErrorReason {
1319 reason: "relay overload".to_string(),
1320 }),
1321 };
1322 roundtrip(&msg);
1323 }
1324
1325 #[test]
1326 fn test_session_id_generation() {
1327 let id1 = SessionId::new_v4();
1328 let id2 = SessionId::new_v4();
1329 assert_ne!(id1, id2);
1330 }
1331
1332 #[test]
1333 fn a_channel_travels_and_one_that_is_not_an_opaque_id_is_refused() {
1334 let msg = Message::output(SessionId::nil(), vec![1]).on_channel(Some("a1B2".into()));
1335 let json = serialize_message(&msg).unwrap();
1336 assert!(json.contains(r#""channel":"a1B2""#), "{json}");
1337 assert_eq!(deserialize_message(&json).unwrap(), msg);
1338 let plain = serialize_message(&Message::output(SessionId::nil(), vec![1])).unwrap();
1340 assert!(!plain.contains("channel"), "{plain}");
1341 for bad in ["", "my session", "a/b", &"x".repeat(MAX_CHANNEL + 1)] {
1342 let json = serialize_message(
1343 &Message::session_join(SessionId::nil()).on_channel(Some(bad.to_owned())),
1344 )
1345 .unwrap();
1346 assert!(
1347 matches!(
1348 deserialize_message(&json),
1349 Err(ProtocolError::InvalidChannel)
1350 ),
1351 "{bad:?}"
1352 );
1353 }
1354 assert!(valid_channel(&"f".repeat(MAX_CHANNEL)));
1355 }
1356}