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 #[serde(default, skip_serializing_if = "is_false")]
279 sealed_history: bool,
280 },
281 JoinOptions {
285 history: u32,
287 #[serde(default)]
291 rows: u16,
292 #[serde(default, skip_serializing_if = "is_false")]
296 sealed_history: bool,
297 },
298 ReplayData {
301 frontend: u64,
303 data: Vec<u8>,
305 },
306 MachineId {
308 machine: String,
310 #[serde(default = "first_protocol")]
312 protocol: u16,
313 },
314 Challenge {
316 nonce: Vec<u8>,
318 #[serde(default = "first_protocol")]
320 protocol: u16,
321 #[serde(default, skip_serializing_if = "Vec::is_empty")]
324 rotations: Vec<crate::account::KeyRotation>,
325 },
326 Signature {
328 signature: Vec<u8>,
330 },
331 Record {
334 sealed_name: Vec<u8>,
336 sealed_key: Vec<u8>,
339 #[serde(default)]
342 signature: Vec<u8>,
343 },
344 RecordsKept {
347 channels: Vec<String>,
349 #[serde(default)]
352 previous: Vec<SessionId>,
353 },
354 ErrorReason {
356 reason: String,
358 },
359}
360
361pub fn machine_proof_message(nonce: &[u8], machine: &str) -> Vec<u8> {
364 let mut message = b"teter-machine-auth-v1 ".to_vec();
365 message.extend_from_slice(nonce);
366 message.extend_from_slice(machine.as_bytes());
367 message
368}
369
370pub const BACKEND_LEFT: &str = "the backend left the session";
375
376pub const SESSION_GONE: &str = "the session is gone";
379
380pub fn ends_the_session(reason: &str) -> bool {
383 reason == BACKEND_LEFT || reason == SESSION_GONE
384}
385
386pub const MAX_CHANNEL: usize = 64;
388
389pub fn valid_channel(channel: &str) -> bool {
393 !channel.is_empty()
394 && channel.len() <= MAX_CHANNEL
395 && channel.bytes().all(|b| b.is_ascii_alphanumeric())
396}
397
398impl Message {
399 #[must_use]
401 pub fn on_channel(self, channel: Option<String>) -> Self {
402 Self { channel, ..self }
403 }
404}
405
406pub const PROTOCOL: u16 = 3;
412
413pub const MIN_PROTOCOL: u16 = 2;
415
416#[expect(
418 clippy::trivially_copy_pass_by_ref,
419 reason = "serde passes a reference"
420)]
421fn is_false(value: &bool) -> bool {
422 !*value
423}
424
425const fn first_protocol() -> u16 {
427 1
428}
429
430pub fn check_relay_protocol(relay: u16) -> Result<(), String> {
438 if relay < PROTOCOL {
439 Err(format!(
440 "the relay speaks relay protocol {relay}, older than this teter's {PROTOCOL}: upgrade \
441 the relay"
442 ))
443 } else {
444 Ok(())
445 }
446}
447
448pub fn protocol_of(json: &str) -> Option<u16> {
452 let value: serde_json::Value = serde_json::from_str(json).ok()?;
453 let payload = value.get("payload")?.as_object()?;
454 payload
455 .values()
456 .find_map(|inner| inner.get("protocol")?.as_u64())
457 .and_then(|protocol| u16::try_from(protocol).ok())
458}
459
460pub fn check_protocol(client: u16, min: u16, max: u16) -> Result<(), String> {
467 if client > max {
468 Err(format!(
469 "this teter speaks relay protocol {client}, newer than the relay's {max}: upgrade the \
470 relay"
471 ))
472 } else if client < min {
473 Err(format!(
474 "this teter speaks relay protocol {client}, older than the relay accepts ({min} to \
475 {max}): upgrade teter"
476 ))
477 } else {
478 Ok(())
479 }
480}
481
482pub fn serialize_message(msg: &Message) -> ProtocolResult<String> {
484 serde_json::to_string(msg).map_err(ProtocolError::Serialization)
485}
486
487pub fn deserialize_message(json: &str) -> ProtocolResult<Message> {
496 if !json.trim_start().starts_with('{') {
498 return Err(ProtocolError::Deserialization(
499 <serde_json::Error as serde::de::Error>::custom("a message is a JSON object"),
500 ));
501 }
502 let msg: Message = serde_json::from_str(json).map_err(|e| classify_decode_error(json, e))?;
503
504 if msg.msg_type.requires_session() && msg.session.is_none() {
505 return Err(ProtocolError::MissingSession);
506 }
507 if msg
508 .channel
509 .as_deref()
510 .is_some_and(|channel| !valid_channel(channel))
511 {
512 return Err(ProtocolError::InvalidChannel);
513 }
514
515 Ok(msg)
516}
517
518fn message_type_from_str<'de, D>(deserializer: D) -> Result<MessageType, D::Error>
521where
522 D: serde::Deserializer<'de>,
523{
524 let name = std::borrow::Cow::<'de, str>::deserialize(deserializer)?;
525 name.parse().map_err(serde::de::Error::custom)
526}
527
528fn classify_decode_error(json: &str, err: serde_json::Error) -> ProtocolError {
532 let Ok(serde_json::Value::Object(fields)) = serde_json::from_str(json) else {
533 return ProtocolError::Deserialization(err);
534 };
535 let type_ = match fields.get("type") {
536 None => return ProtocolError::MissingType,
537 Some(serde_json::Value::String(t)) if t.is_empty() => return ProtocolError::MissingType,
538 Some(serde_json::Value::String(t)) => t,
539 Some(_) => return ProtocolError::Deserialization(err),
540 };
541 if let Err(unknown) = type_.parse::<MessageType>() {
542 return unknown;
543 }
544 if let Some(session) = fields.get("session")
545 && serde_json::from_value::<Option<SessionId>>(session.clone()).is_err()
546 {
547 return ProtocolError::InvalidSession { source: err };
548 }
549 if let Some(payload) = fields.get("payload")
550 && serde_json::from_value::<Option<MessagePayload>>(payload.clone()).is_err()
551 {
552 return ProtocolError::InvalidPayload {
553 type_: type_.clone(),
554 source: err,
555 };
556 }
557 ProtocolError::Deserialization(err)
558}
559
560impl Message {
563 pub fn session_create() -> Self {
565 Self {
566 msg_type: MessageType::SessionCreate,
567 session: None,
568 channel: None,
569 payload: None,
570 }
571 }
572
573 pub fn session_create_replaying() -> Self {
576 Self {
577 msg_type: MessageType::SessionCreate,
578 session: None,
579 channel: None,
580 payload: Some(MessagePayload::SessionOptions { replay: true }),
581 }
582 }
583
584 pub fn session_join(session: SessionId) -> Self {
586 Self {
587 msg_type: MessageType::SessionJoin,
588 session: Some(session),
589 channel: None,
590 payload: None,
591 }
592 }
593
594 pub fn session_join_with_history(session: SessionId, history: u32, rows: u16) -> Self {
598 Self::session_join_with_options(session, history, rows, false)
599 }
600
601 pub fn session_join_with_options(
605 session: SessionId,
606 history: u32,
607 rows: u16,
608 sealed_history: bool,
609 ) -> Self {
610 if history == 0 && !sealed_history {
611 return Self::session_join(session);
612 }
613 Self {
614 payload: Some(MessagePayload::JoinOptions {
615 history,
616 rows,
617 sealed_history,
618 }),
619 ..Self::session_join(session)
620 }
621 }
622
623 pub fn session_joined(session: SessionId, frontend_token: String) -> Self {
625 Self {
626 msg_type: MessageType::SessionJoined,
627 session: Some(session),
628 channel: None,
629 payload: Some(MessagePayload::SessionCreated {
630 session_id: session,
631 frontend_token,
632 resume_secret: None,
633 protocol: PROTOCOL,
634 }),
635 }
636 }
637
638 pub fn session_created(
641 session: SessionId,
642 frontend_token: String,
643 resume_secret: String,
644 ) -> Self {
645 Self {
646 msg_type: MessageType::SessionJoined,
647 session: Some(session),
648 channel: None,
649 payload: Some(MessagePayload::SessionCreated {
650 session_id: session,
651 frontend_token,
652 resume_secret: Some(resume_secret),
653 protocol: PROTOCOL,
654 }),
655 }
656 }
657
658 pub fn session_resume(session: SessionId, secret: String) -> Self {
660 Self {
661 msg_type: MessageType::SessionResume,
662 session: Some(session),
663 channel: None,
664 payload: Some(MessagePayload::ResumeSecret { secret }),
665 }
666 }
667
668 pub fn frontend_joined(session: SessionId, frontend: u64, history: u32, rows: u16) -> Self {
670 Self::frontend_joined_with(session, frontend, history, rows, false)
671 }
672
673 pub fn frontend_joined_with(
676 session: SessionId,
677 frontend: u64,
678 history: u32,
679 rows: u16,
680 sealed_history: bool,
681 ) -> Self {
682 Self {
683 msg_type: MessageType::FrontendJoined,
684 session: Some(session),
685 channel: None,
686 payload: Some(MessagePayload::Frontend {
687 frontend,
688 history,
689 rows,
690 sealed_history,
691 }),
692 }
693 }
694
695 pub fn replay(session: SessionId, frontend: u64, data: Vec<u8>) -> Self {
697 Self {
698 msg_type: MessageType::Replay,
699 session: Some(session),
700 channel: None,
701 payload: Some(MessagePayload::ReplayData { frontend, data }),
702 }
703 }
704
705 pub fn backend_away(session: SessionId) -> Self {
707 Self {
708 msg_type: MessageType::BackendAway,
709 session: Some(session),
710 channel: None,
711 payload: None,
712 }
713 }
714
715 pub fn backend_back(session: SessionId) -> Self {
717 Self {
718 msg_type: MessageType::BackendBack,
719 session: Some(session),
720 channel: None,
721 payload: None,
722 }
723 }
724
725 pub fn session_left(session: SessionId) -> Self {
727 Self {
728 msg_type: MessageType::SessionLeft,
729 session: Some(session),
730 channel: None,
731 payload: None,
732 }
733 }
734
735 pub fn session_error(session: Option<SessionId>, reason: String) -> Self {
738 Self {
739 msg_type: MessageType::SessionError,
740 session,
741 channel: None,
742 payload: Some(MessagePayload::ErrorReason { reason }),
743 }
744 }
745
746 pub fn input(session: SessionId, data: Vec<u8>) -> Self {
748 Self {
749 msg_type: MessageType::Input,
750 session: Some(session),
751 channel: None,
752 payload: Some(MessagePayload::InputData { data, paste: false }),
753 }
754 }
755
756 pub fn paste_input(session: SessionId, data: Vec<u8>) -> Self {
758 Self {
759 msg_type: MessageType::Input,
760 session: Some(session),
761 channel: None,
762 payload: Some(MessagePayload::InputData { data, paste: true }),
763 }
764 }
765
766 pub fn output(session: SessionId, data: Vec<u8>) -> Self {
768 Self {
769 msg_type: MessageType::Output,
770 session: Some(session),
771 channel: None,
772 payload: Some(MessagePayload::OutputData { data }),
773 }
774 }
775
776 pub fn sealed_resize(session: SessionId, data: Vec<u8>) -> Self {
778 Self {
779 msg_type: MessageType::Resize,
780 session: Some(session),
781 channel: None,
782 payload: Some(MessagePayload::Sealed { data }),
783 }
784 }
785
786 pub fn resize(session: SessionId, columns: u16, rows: u16) -> Self {
788 Self {
789 msg_type: MessageType::Resize,
790 session: Some(session),
791 channel: None,
792 payload: Some(MessagePayload::Resize { columns, rows }),
793 }
794 }
795
796 pub fn auth(token: String) -> Self {
798 Self {
799 msg_type: MessageType::Auth,
800 session: None,
801 channel: None,
802 payload: Some(MessagePayload::AuthToken {
803 token,
804 protocol: PROTOCOL,
805 }),
806 }
807 }
808
809 pub fn ping() -> Self {
811 Self {
812 msg_type: MessageType::Ping,
813 session: None,
814 channel: None,
815 payload: None,
816 }
817 }
818
819 pub fn pong() -> Self {
821 Self {
822 msg_type: MessageType::Pong,
823 session: None,
824 channel: None,
825 payload: None,
826 }
827 }
828}
829
830#[derive(Debug, Clone, PartialEq, Eq)]
832pub enum Role {
833 Backend,
835 Frontend,
837}
838
839impl FromStr for Role {
840 type Err = ProtocolError;
841
842 fn from_str(s: &str) -> Result<Self, Self::Err> {
843 match s {
844 "backend" => Ok(Self::Backend),
845 "frontend" => Ok(Self::Frontend),
846 other => Err(ProtocolError::UnknownType(other.to_string())),
847 }
848 }
849}
850
851impl Role {
852 pub fn to_str(&self) -> &'static str {
854 match self {
855 Self::Backend => "backend",
856 Self::Frontend => "frontend",
857 }
858 }
859
860 pub fn parse_opt(s: &str) -> Option<Self> {
862 s.parse().ok()
863 }
864}
865
866#[cfg(test)]
867mod tests {
868 use super::*;
869
870 fn roundtrip(msg: &Message) -> String {
871 let json = serialize_message(msg).unwrap();
872 let restored = deserialize_message(&json).unwrap();
873 assert_eq!(*msg, restored);
874 json
875 }
876
877 #[test]
878 fn test_session_create_roundtrip() {
879 let msg = Message::session_create();
880 roundtrip(&msg);
881 }
882
883 #[test]
884 fn test_session_join_roundtrip() {
885 let sid = SessionId::new_v4();
886 let msg = Message::session_join(sid);
887 roundtrip(&msg);
888 }
889
890 #[test]
891 fn test_session_joined_roundtrip() {
892 let sid = SessionId::new_v4();
893 let token = "test-token-123".to_string();
894 let msg = Message::session_joined(sid, token.clone());
895 roundtrip(&msg);
896
897 if let Some(MessagePayload::SessionCreated {
898 session_id,
899 frontend_token,
900 resume_secret,
901 ..
902 }) = &msg.payload
903 {
904 assert_eq!(*session_id, sid);
905 assert_eq!(*frontend_token, token);
906 assert_eq!(*resume_secret, None);
907 } else {
908 panic!("expected SessionCreated payload");
909 }
910 assert!(!serialize_message(&msg).unwrap().contains("resume_secret"));
912 }
913
914 #[test]
915 fn test_replay_messages_roundtrip() {
916 let sid = SessionId::new_v4();
917 let create = Message::session_create_replaying();
918 let json = roundtrip(&create);
919 assert!(
920 json.contains(r#"{"SessionOptions":{"replay":true}}"#),
921 "{json}"
922 );
923 let joined = Message::frontend_joined(sid, 7, 0, 0);
924 let json = roundtrip(&joined);
925 assert!(json.contains(r#""type":"frontend_joined""#), "{json}");
926 assert!(
927 json.contains(r#"{"Frontend":{"frontend":7,"history":0,"rows":0}}"#),
928 "{json}"
929 );
930 let old = deserialize_message(
932 r#"{"type":"frontend_joined","session":"7011b901-812b-4f0b-83bb-da42e6148c81","payload":{"Frontend":{"frontend":7}}}"#,
933 )
934 .unwrap();
935 assert!(matches!(
936 old.payload,
937 Some(MessagePayload::Frontend {
938 frontend: 7,
939 history: 0,
940 rows: 0,
941 sealed_history: false
942 })
943 ));
944 let replay = Message::replay(sid, 7, b"hi".to_vec());
945 let json = roundtrip(&replay);
946 assert!(
947 json.contains(r#"{"ReplayData":{"frontend":7,"data":[104,105]}}"#),
948 "{json}"
949 );
950 for (name, ty) in [
951 ("frontend_joined", MessageType::FrontendJoined),
952 ("replay", MessageType::Replay),
953 ] {
954 assert_eq!(name.parse::<MessageType>().unwrap(), ty);
955 assert_eq!(ty.to_str(), name);
956 assert!(ty.requires_session());
957 }
958 }
959
960 #[test]
961 fn test_resume_messages_roundtrip() {
962 let sid = SessionId::new_v4();
963 let created = Message::session_created(sid, "tok".into(), "sec".into());
964 let json = roundtrip(&created);
965 assert!(json.contains(r#""resume_secret":"sec""#), "{json}");
966 let resume = Message::session_resume(sid, "sec".into());
967 let json = roundtrip(&resume);
968 assert!(json.contains(r#""type":"session_resume""#), "{json}");
969 assert!(
970 json.contains(r#"{"ResumeSecret":{"secret":"sec"}}"#),
971 "{json}"
972 );
973 for msg in [Message::backend_away(sid), Message::backend_back(sid)] {
974 let json = roundtrip(&msg);
975 assert_eq!(deserialize_message(&json).unwrap(), msg);
976 }
977 for (name, ty) in [
978 ("session_resume", MessageType::SessionResume),
979 ("backend_away", MessageType::BackendAway),
980 ("backend_back", MessageType::BackendBack),
981 ] {
982 assert_eq!(name.parse::<MessageType>().unwrap(), ty);
983 assert_eq!(ty.to_str(), name);
984 assert!(ty.requires_session());
985 }
986 }
987
988 #[test]
989 fn test_session_left_roundtrip() {
990 let sid = SessionId::new_v4();
991 let msg = Message::session_left(sid);
992 roundtrip(&msg);
993 }
994
995 #[test]
996 fn test_session_error_roundtrip() {
997 let sid = SessionId::new_v4();
998 let msg = Message::session_error(Some(sid), "connection lost".to_string());
999 roundtrip(&msg);
1000 }
1001
1002 #[test]
1003 fn test_input_roundtrip() {
1004 let sid = SessionId::new_v4();
1005 let data = vec![0x1b, 0x5b, 0x41]; let msg = Message::input(sid, data.clone());
1007 roundtrip(&msg);
1008
1009 if let Some(MessagePayload::InputData { data: received, .. }) = &msg.payload {
1010 assert_eq!(*received, data);
1011 } else {
1012 panic!("expected InputData payload");
1013 }
1014 }
1015
1016 #[test]
1017 fn test_output_roundtrip() {
1018 let sid = SessionId::new_v4();
1019 let data = b"Hello, teter!\n".to_vec();
1020 let msg = Message::output(sid, data.clone());
1021 roundtrip(&msg);
1022
1023 if let Some(MessagePayload::OutputData { data: received }) = &msg.payload {
1024 assert_eq!(*received, data);
1025 } else {
1026 panic!("expected OutputData payload");
1027 }
1028 }
1029
1030 #[test]
1031 fn test_resize_roundtrip() {
1032 let sid = SessionId::new_v4();
1033 let msg = Message::resize(sid, 120, 40);
1034 roundtrip(&msg);
1035
1036 if let Some(MessagePayload::Resize { columns, rows }) = &msg.payload {
1037 assert_eq!(*columns, 120);
1038 assert_eq!(*rows, 40);
1039 } else {
1040 panic!("expected Resize payload");
1041 }
1042 }
1043
1044 #[test]
1045 fn paste_input_is_marked_and_plain_input_leaves_the_mark_out() {
1046 let sid = SessionId::new_v4();
1047 let paste = Message::paste_input(sid, vec![1, 2]);
1048 roundtrip(&paste);
1049 let json = serialize_message(&paste).unwrap();
1050 assert!(
1051 json.contains(r#"{"InputData":{"data":[1,2],"paste":true}}"#),
1052 "{json}"
1053 );
1054 let plain = Message::input(sid, vec![1, 2]);
1055 let json = serialize_message(&plain).unwrap();
1056 assert!(json.contains(r#"{"InputData":{"data":[1,2]}}"#), "{json}");
1057 let read = deserialize_message(&json).unwrap();
1059 assert_eq!(
1060 read.payload,
1061 Some(MessagePayload::InputData {
1062 data: vec![1, 2],
1063 paste: false
1064 })
1065 );
1066 }
1067
1068 #[test]
1069 fn a_sealed_resize_roundtrips() {
1070 let sid = SessionId::new_v4();
1071 let msg = Message::sealed_resize(sid, vec![1, 2, 255]);
1072 roundtrip(&msg);
1073 assert_eq!(msg.msg_type, MessageType::Resize);
1074 assert_eq!(msg.session, Some(sid));
1075 assert_eq!(
1076 msg.payload,
1077 Some(MessagePayload::Sealed {
1078 data: vec![1, 2, 255]
1079 })
1080 );
1081 let json = serialize_message(&msg).unwrap();
1082 assert!(
1083 json.contains(r#""payload":{"Sealed":{"data":[1,2,255]}}"#),
1084 "{json}"
1085 );
1086 }
1087
1088 #[test]
1089 fn test_ping_roundtrip() {
1090 let msg = Message::ping();
1091 roundtrip(&msg);
1092 }
1093
1094 #[test]
1095 fn test_pong_roundtrip() {
1096 let msg = Message::pong();
1097 roundtrip(&msg);
1098 }
1099
1100 #[test]
1101 fn test_message_type_from_str() {
1102 assert_eq!(MessageType::from_str("input").unwrap(), MessageType::Input);
1103 assert_eq!(
1104 MessageType::from_str("session_create").unwrap(),
1105 MessageType::SessionCreate
1106 );
1107 assert!(MessageType::from_str("unknown_type").is_err());
1108 }
1109
1110 #[test]
1111 fn test_message_type_to_str() {
1112 assert_eq!(MessageType::Input.to_str(), "input");
1113 assert_eq!(MessageType::Output.to_str(), "output");
1114 assert_eq!(MessageType::Resize.to_str(), "resize");
1115 assert_eq!(MessageType::Ping.to_str(), "ping");
1116 }
1117
1118 #[test]
1119 fn test_requires_session() {
1120 assert!(!MessageType::Ping.requires_session());
1121 assert!(!MessageType::Pong.requires_session());
1122 assert!(MessageType::Input.requires_session());
1123 assert!(MessageType::Output.requires_session());
1124 assert!(!MessageType::Auth.requires_session());
1125 assert!(!MessageType::SessionError.requires_session());
1126 assert!(MessageType::SessionJoin.requires_session());
1127 }
1128
1129 #[test]
1130 fn the_protocol_is_read_from_a_first_message_that_does_not_decode() {
1131 assert_eq!(
1132 protocol_of(r#"{"type":"auth","payload":{"AuthToken":{"protocol":7}}}"#),
1133 Some(7)
1134 );
1135 assert_eq!(protocol_of(r#"{"type":"ping"}"#), None);
1136 assert_eq!(protocol_of("not json"), None);
1137 assert!(check_relay_protocol(PROTOCOL).is_ok());
1138 }
1139
1140 #[test]
1141 fn protocols_outside_the_range_say_what_to_upgrade() {
1142 assert_eq!(check_protocol(2, 1, 2), Ok(()));
1143 assert!(
1144 check_protocol(3, 1, 2)
1145 .unwrap_err()
1146 .contains("upgrade the relay")
1147 );
1148 assert!(
1149 check_protocol(0, 1, 2)
1150 .unwrap_err()
1151 .contains("upgrade teter")
1152 );
1153 }
1154
1155 #[test]
1156 fn test_auth_roundtrip() {
1157 let json = roundtrip(&Message::auth("secret".to_string()));
1158 assert_eq!(
1159 json,
1160 r#"{"type":"auth","payload":{"AuthToken":{"token":"secret","protocol":3}}}"#
1161 );
1162 let old = deserialize_message(r#"{"type":"auth","payload":{"AuthToken":{"token":"t"}}}"#)
1164 .unwrap();
1165 assert_eq!(
1166 old.payload,
1167 Some(MessagePayload::AuthToken {
1168 token: "t".to_owned(),
1169 protocol: 1
1170 })
1171 );
1172 assert_eq!("auth".parse::<MessageType>().unwrap(), MessageType::Auth);
1173 assert_eq!(MessageType::Auth.to_str(), "auth");
1174 }
1175
1176 #[test]
1177 fn test_session_error_without_session_roundtrip() {
1178 let json = roundtrip(&Message::session_error(
1179 None,
1180 "authentication failed".to_string(),
1181 ));
1182 assert!(!json.contains("session\""), "{json}");
1183 }
1184
1185 #[test]
1186 fn test_missing_session_rejected() {
1187 let json = r#"{"type":"input"}"#;
1189 assert!(matches!(
1190 deserialize_message(json),
1191 Err(ProtocolError::MissingSession)
1192 ));
1193 }
1194
1195 #[test]
1196 fn test_missing_type_rejected() {
1197 let json = r#"{"session":"00000000-0000-0000-0000-000000000000"}"#;
1198 assert!(deserialize_message(json).is_err());
1199 }
1200
1201 const SID: &str = "00000000-0000-0000-0000-000000000000";
1202
1203 fn invalid_payload_type(json: &str) -> String {
1204 match deserialize_message(json) {
1205 Err(ProtocolError::InvalidPayload { type_, .. }) => type_,
1206 other => panic!("expected InvalidPayload, got {other:?}"),
1207 }
1208 }
1209
1210 #[test]
1211 fn test_invalid_payload_names_the_type() {
1212 let json = format!(
1213 r#"{{"type":"resize","session":"{SID}","payload":{{"Resize":{{"columns":"wide","rows":24}}}}}}"#
1214 );
1215 assert_eq!(invalid_payload_type(&json), "resize");
1216 }
1217
1218 #[test]
1219 fn test_invalid_payload_type_with_whitespace() {
1220 let json = format!(
1221 r#"{{ "session" : "{SID}", "payload" : {{ "InputData" : {{ "data" : "x" }} }}, "type" : "input" }}"#
1222 );
1223 assert_eq!(invalid_payload_type(&json), "input");
1224 }
1225
1226 #[test]
1227 fn test_not_a_message_gives_deserialization_error() {
1228 for json in [
1229 "[1, 2]".to_string(),
1230 "not json".to_string(),
1231 format!(r#"{{"type":5,"session":"{SID}"}}"#),
1232 ] {
1233 let err = deserialize_message(&json).unwrap_err();
1234 assert!(
1235 matches!(err, ProtocolError::Deserialization(_)),
1236 "{json}: {err:?}"
1237 );
1238 assert!(err.to_string().starts_with("failed to decode"), "{err}");
1239 }
1240 }
1241
1242 #[test]
1243 fn test_missing_or_empty_type_gives_missing_type() {
1244 for json in [
1245 format!(r#"{{"session":"{SID}"}}"#),
1246 format!(r#"{{"type":"","session":"{SID}"}}"#),
1247 ] {
1248 assert!(
1249 matches!(deserialize_message(&json), Err(ProtocolError::MissingType)),
1250 "{json}"
1251 );
1252 }
1253 }
1254
1255 #[test]
1256 fn test_unknown_type_gives_unknown_type() {
1257 let json = format!(r#"{{"type":"bogus","session":"{SID}"}}"#);
1258 assert!(matches!(
1259 deserialize_message(&json),
1260 Err(ProtocolError::UnknownType(t)) if t == "bogus"
1261 ));
1262 }
1263
1264 #[test]
1265 fn test_bad_session_names_the_session() {
1266 for json in [
1267 r#"{"type":"input","session":"not-a-uuid","payload":{"InputData":{"data":[1]}}}"#,
1268 r#"{"type":"input","session":5,"payload":{"InputData":{"data":[1]}}}"#,
1269 ] {
1270 let err = deserialize_message(json).unwrap_err();
1271 assert!(
1272 matches!(err, ProtocolError::InvalidSession { .. }),
1273 "{json}: {err:?}"
1274 );
1275 assert!(err.to_string().contains("session"), "{err}");
1276 }
1277 }
1278
1279 #[test]
1280 fn test_non_canonical_forms_are_rejected() {
1281 for json in [
1282 r#"["ping"]"#,
1283 r#"["input","00000000-0000-0000-0000-000000000000"]"#,
1284 r#"["ping",null,null]"#,
1285 r#"{"type":{"ping":null}}"#,
1286 ] {
1287 assert!(
1288 matches!(
1289 deserialize_message(json),
1290 Err(ProtocolError::Deserialization(_))
1291 ),
1292 "{json}"
1293 );
1294 }
1295 }
1296
1297 #[test]
1298 fn test_decode_error_keeps_position() {
1299 let json = format!(
1300 r#"{{"type":"resize","session":"{SID}","payload":{{"Resize":{{"columns":"wide","rows":24}}}}}}"#
1301 );
1302 match deserialize_message(&json) {
1303 Err(ProtocolError::InvalidPayload { source, .. }) => {
1304 assert_eq!(source.line(), 1);
1305 assert!(source.column() > 0);
1306 }
1307 other => panic!("expected InvalidPayload, got {other:?}"),
1308 }
1309 }
1310
1311 #[test]
1312 fn test_null_fields_are_absent() {
1313 let json = r#"{"type":"ping","session":null,"payload":null}"#;
1314 assert_eq!(deserialize_message(json).unwrap(), Message::ping());
1315 }
1316
1317 #[test]
1318 fn test_only_the_session_ending_reasons_end_the_session() {
1319 assert!(ends_the_session(BACKEND_LEFT));
1320 assert!(ends_the_session(SESSION_GONE));
1321 assert!(!ends_the_session("silent past the heartbeat timeout"));
1322 assert!(!ends_the_session(""));
1323 }
1324
1325 #[test]
1326 fn test_io_flag() {
1327 assert!(MessageType::Input.is_io());
1328 assert!(MessageType::Output.is_io());
1329 assert!(!MessageType::Resize.is_io());
1330 assert!(!MessageType::Ping.is_io());
1331 }
1332
1333 #[test]
1334 fn test_role_to_from_str() {
1335 assert_eq!(Role::Backend.to_str(), "backend");
1336 assert_eq!(Role::Frontend.to_str(), "frontend");
1337 assert_eq!(Role::parse_opt("backend"), Some(Role::Backend));
1338 assert_eq!(Role::parse_opt("frontend"), Some(Role::Frontend));
1339 assert_eq!(Role::parse_opt("unknown"), None);
1340 }
1341
1342 #[test]
1343 fn test_role_from_str_trait() {
1344 assert_eq!("backend".parse::<Role>().unwrap(), Role::Backend);
1345 assert_eq!("frontend".parse::<Role>().unwrap(), Role::Frontend);
1346 assert!("unknown".parse::<Role>().is_err());
1347 }
1348
1349 #[test]
1350 fn test_auth_token_roundtrip() {
1351 let msg = Message {
1352 msg_type: MessageType::SessionCreate,
1353 session: None,
1354 channel: None,
1355 payload: Some(MessagePayload::AuthToken {
1356 token: "backend-secret-token".to_string(),
1357 protocol: PROTOCOL,
1358 }),
1359 };
1360 roundtrip(&msg);
1361 }
1362
1363 #[test]
1364 fn test_error_reason_roundtrip() {
1365 let sid = SessionId::new_v4();
1366 let msg = Message {
1367 msg_type: MessageType::SessionError,
1368 session: Some(sid),
1369 channel: None,
1370 payload: Some(MessagePayload::ErrorReason {
1371 reason: "relay overload".to_string(),
1372 }),
1373 };
1374 roundtrip(&msg);
1375 }
1376
1377 #[test]
1378 fn test_session_id_generation() {
1379 let id1 = SessionId::new_v4();
1380 let id2 = SessionId::new_v4();
1381 assert_ne!(id1, id2);
1382 }
1383
1384 #[test]
1385 fn a_channel_travels_and_one_that_is_not_an_opaque_id_is_refused() {
1386 let msg = Message::output(SessionId::nil(), vec![1]).on_channel(Some("a1B2".into()));
1387 let json = serialize_message(&msg).unwrap();
1388 assert!(json.contains(r#""channel":"a1B2""#), "{json}");
1389 assert_eq!(deserialize_message(&json).unwrap(), msg);
1390 let plain = serialize_message(&Message::output(SessionId::nil(), vec![1])).unwrap();
1392 assert!(!plain.contains("channel"), "{plain}");
1393 for bad in ["", "my session", "a/b", &"x".repeat(MAX_CHANNEL + 1)] {
1394 let json = serialize_message(
1395 &Message::session_join(SessionId::nil()).on_channel(Some(bad.to_owned())),
1396 )
1397 .unwrap();
1398 assert!(
1399 matches!(
1400 deserialize_message(&json),
1401 Err(ProtocolError::InvalidChannel)
1402 ),
1403 "{bad:?}"
1404 );
1405 }
1406 assert!(valid_channel(&"f".repeat(MAX_CHANNEL)));
1407 }
1408}