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