BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / tests / realtime.rs

realtime.rs

realtime.rs 8.1 KiB Download Raw
1use std::sync::{Arc, Mutex};
2use std::time::Duration;
3
4use chatsvc::{EventKind, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
5use futures_util::{SinkExt, StreamExt};
6use serde_json::{Value, json};
7use session::Session;
8use tokio::io::{AsyncReadExt, AsyncWriteExt};
9use tokio::net::{TcpListener, TcpStream};
10use tokio_tungstenite::tungstenite::Message;
11
12type Calls = Arc<Mutex<Vec<(String, Value)>>>;
13
14async fn start_tab() -> (String, Calls) {
15 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
16 let port = listener.local_addr().unwrap().port();
17 let calls: Calls = Arc::new(Mutex::new(Vec::new()));
18 let seen = calls.clone();
19 tokio::spawn(async move {
20 loop {
21 let (stream, _) = listener.accept().await.unwrap();
22 tokio::spawn(serve(stream, port, seen.clone()));
23 }
24 });
25 (format!("http://127.0.0.1:{port}"), calls)
26}
27
28fn binding_event(payload: Value) -> Message {
29 let event = json!({"method": "Runtime.bindingCalled", "params": {"name": "__chatsvcRealtime", "payload": payload.to_string()}});
30 Message::text(event.to_string())
31}
32
33async fn serve(mut stream: TcpStream, port: u16, calls: Calls) {
34 let mut peek = [0u8; 16];
35 let count = stream.peek(&mut peek).await.unwrap();
36 if !peek[..count].starts_with(b"GET /json") {
37 let mut websocket = tokio_tungstenite::accept_async(stream).await.unwrap();
38 while let Some(Ok(Message::Text(text))) = websocket.next().await {
39 let call: Value = serde_json::from_str(text.as_str()).unwrap();
40 let method = call["method"].as_str().unwrap().to_owned();
41 calls
42 .lock()
43 .unwrap()
44 .push((method.clone(), call["params"].clone()));
45 let result = match method.as_str() {
46 "Runtime.evaluate" => json!({"result": {"type": "string", "value": "ready"}}),
47 "Page.addScriptToEvaluateOnNewDocument" => json!({"identifier": "9"}),
48 _ => json!({}),
49 };
50 websocket
51 .send(Message::text(
52 json!({"id": call["id"], "result": result}).to_string(),
53 ))
54 .await
55 .unwrap();
56 if method == "Runtime.addBinding" {
57 let payloads = [
58 json!({"channel": "status", "kind": "connected", "detail": ""}),
59 json!({"channel": "event", "resourceType": "NewMessage", "eventKind": "new_message", "conversationId": "19:abc@thread.v2", "messageId": "1", "receivedAt": 1791368146999i64}),
60 json!({"channel": "event", "resourceType": "NewMessage", "eventKind": "typing", "conversationId": null, "messageId": null, "receivedAt": 1791368147000i64}),
61 json!({"channel": "event", "resourceType": "NewMessage", "eventKind": "typing", "conversationId": "19:abc@thread.v2", "messageId": null, "receivedAt": 1791368148000i64, "typing": "start", "senderId": "abc-1", "senderName": "Ada"}),
62 ];
63 for payload in payloads {
64 websocket.send(binding_event(payload)).await.unwrap();
65 }
66 websocket.send(Message::text(json!({"method": "Runtime.bindingCalled", "params": {"name": "someoneElse", "payload": "x"}}).to_string())).await.unwrap();
67 websocket.send(Message::text(json!({"method": "Runtime.bindingCalled", "params": {"name": "__chatsvcRealtime", "payload": "garbage"}}).to_string())).await.unwrap();
68 }
69 }
70 return;
71 }
72 let mut discard = [0u8; 1024];
73 let _ = stream.read(&mut discard).await.unwrap();
74 let targets = json!([{"type": "page", "url": "https://teams.cloud.microsoft/v2/", "webSocketDebuggerUrl": format!("ws://127.0.0.1:{port}/devtools/page/0")}]);
75 let body = targets.to_string();
76 let response = format!(
77 "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
78 body.len()
79 );
80 stream.write_all(response.as_bytes()).await.unwrap();
81}
82
83fn quiet_config() -> RealtimeConfig {
84 RealtimeConfig {
85 ensure_interval: Duration::from_secs(3600),
86 ..RealtimeConfig::default()
87 }
88}
89
90#[tokio::test]
91async fn forwards_decoded_events_and_drops_foreign_or_garbage_payloads() {
92 let (endpoint, calls) = start_tab().await;
93 let session = Session::connect(&endpoint).await.unwrap();
94 let mut realtime = Realtime::start_with(&session, quiet_config())
95 .await
96 .unwrap();
97
98 let RealtimeEvent::Status(status) = realtime.recv().await.unwrap() else {
99 panic!("expected status first")
100 };
101 assert_eq!(status.kind, StatusKind::Connected);
102 let RealtimeEvent::Message(message) = realtime.recv().await.unwrap() else {
103 panic!("expected message")
104 };
105 assert_eq!(message.kind, EventKind::NewMessage);
106 assert_eq!(message.conversation_id.as_deref(), Some("19:abc@thread.v2"));
107 let RealtimeEvent::Message(typing) = realtime.recv().await.unwrap() else {
108 panic!("expected typing")
109 };
110 assert_eq!(typing.kind, EventKind::Typing);
111 assert_eq!(typing.conversation_id, None);
112 let RealtimeEvent::Typing(sender_typing) = realtime.recv().await.unwrap() else {
113 panic!("expected typing with sender")
114 };
115 assert!(sender_typing.active);
116 assert_eq!(sender_typing.user_id, "abc-1");
117 assert_eq!(sender_typing.display_name, "Ada");
118 assert_eq!(sender_typing.conversation_id, "19:abc@thread.v2");
119
120 let methods: Vec<String> = calls
121 .lock()
122 .unwrap()
123 .iter()
124 .map(|(method, _)| method.clone())
125 .filter(|method| method != "Runtime.evaluate")
126 .collect();
127 assert_eq!(
128 &methods[..4],
129 [
130 "Runtime.enable",
131 "Page.enable",
132 "Runtime.addBinding",
133 "Page.addScriptToEvaluateOnNewDocument"
134 ]
135 );
136 realtime.stop().await;
137}
138
139#[tokio::test]
140async fn start_injects_worker_and_ensures_with_default_host() {
141 let (endpoint, calls) = start_tab().await;
142 let session = Session::connect(&endpoint).await.unwrap();
143 let realtime = Realtime::start_with(&session, quiet_config())
144 .await
145 .unwrap();
146 assert_eq!(realtime.host(), "go-eu.trouter.teams.microsoft.com");
147 let recorded = calls.lock().unwrap().clone();
148 let expressions: Vec<&str> = recorded
149 .iter()
150 .filter(|(method, _)| method == "Runtime.evaluate")
151 .filter_map(|(_, params)| params["expression"].as_str())
152 .collect();
153 assert!(
154 expressions
155 .iter()
156 .any(|expression| expression.contains("window.__chatsvcTrouter.ensure("))
157 );
158 assert!(
159 expressions
160 .iter()
161 .all(|expression| !expression.contains("Bearer ey"))
162 );
163 let ensure = expressions
164 .iter()
165 .find(|expression| expression.contains("window.__chatsvcTrouter.ensure("))
166 .unwrap();
167 let arguments_json = ensure
168 .split_once("const args = ")
169 .and_then(|(_, rest)| rest.split_once(";\n").or_else(|| rest.split_once(';')))
170 .map(|(json, _)| json)
171 .unwrap();
172 let arguments: serde_json::Value = serde_json::from_str(arguments_json).unwrap();
173 assert_eq!(
174 arguments,
175 serde_json::json!({"host": "go-eu.trouter.teams.microsoft.com", "activity": "inactive"})
176 );
177 realtime.stop().await;
178}
179
180#[tokio::test]
181async fn stop_unregisters_in_the_page_and_removes_the_injected_script() {
182 let (endpoint, calls) = start_tab().await;
183 let session = Session::connect(&endpoint).await.unwrap();
184 let realtime = Realtime::start_with(&session, quiet_config())
185 .await
186 .unwrap();
187 realtime.stop().await;
188 let recorded = calls.lock().unwrap().clone();
189 let stop_call = recorded.iter().rposition(|(method, params)| {
190 method == "Runtime.evaluate"
191 && params["expression"].as_str()
192 == Some("window.__chatsvcTrouter ? window.__chatsvcTrouter.stop() : null")
193 });
194 let remove_call = recorded.iter().rposition(|(method, params)| {
195 method == "Page.removeScriptToEvaluateOnNewDocument" && params["identifier"] == "9"
196 });
197 assert!(stop_call.is_some() && remove_call.is_some());
198 assert!(stop_call < remove_call);
199}