BlueGit

ict rusty-teams

Files

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

realtime.rs

realtime.rs 8.2 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 native: false,
87 ..RealtimeConfig::default()
88 }
89}
90
91#[tokio::test]
92async fn forwards_decoded_events_and_drops_foreign_or_garbage_payloads() {
93 let (endpoint, calls) = start_tab().await;
94 let session = Session::connect(&endpoint).await.unwrap();
95 let mut realtime = Realtime::start_with(&session, quiet_config())
96 .await
97 .unwrap();
98
99 let RealtimeEvent::Status(status) = realtime.recv().await.unwrap() else {
100 panic!("expected status first")
101 };
102 assert_eq!(status.kind, StatusKind::Connected);
103 let RealtimeEvent::Message(message) = realtime.recv().await.unwrap() else {
104 panic!("expected message")
105 };
106 assert_eq!(message.kind, EventKind::NewMessage);
107 assert_eq!(message.conversation_id.as_deref(), Some("19:abc@thread.v2"));
108 let RealtimeEvent::Message(typing) = realtime.recv().await.unwrap() else {
109 panic!("expected typing")
110 };
111 assert_eq!(typing.kind, EventKind::Typing);
112 assert_eq!(typing.conversation_id, None);
113 let RealtimeEvent::Typing(sender_typing) = realtime.recv().await.unwrap() else {
114 panic!("expected typing with sender")
115 };
116 assert!(sender_typing.active);
117 assert_eq!(sender_typing.user_id, "abc-1");
118 assert_eq!(sender_typing.display_name, "Ada");
119 assert_eq!(sender_typing.conversation_id, "19:abc@thread.v2");
120
121 let methods: Vec<String> = calls
122 .lock()
123 .unwrap()
124 .iter()
125 .map(|(method, _)| method.clone())
126 .filter(|method| method != "Runtime.evaluate")
127 .collect();
128 assert_eq!(
129 &methods[..4],
130 [
131 "Runtime.enable",
132 "Page.enable",
133 "Runtime.addBinding",
134 "Page.addScriptToEvaluateOnNewDocument"
135 ]
136 );
137 realtime.stop().await;
138}
139
140#[tokio::test]
141async fn start_injects_worker_and_ensures_with_default_host() {
142 let (endpoint, calls) = start_tab().await;
143 let session = Session::connect(&endpoint).await.unwrap();
144 let realtime = Realtime::start_with(&session, quiet_config())
145 .await
146 .unwrap();
147 assert_eq!(realtime.host(), "go-eu.trouter.teams.microsoft.com");
148 let recorded = calls.lock().unwrap().clone();
149 let expressions: Vec<&str> = recorded
150 .iter()
151 .filter(|(method, _)| method == "Runtime.evaluate")
152 .filter_map(|(_, params)| params["expression"].as_str())
153 .collect();
154 assert!(
155 expressions
156 .iter()
157 .any(|expression| expression.contains("window.__chatsvcTrouter.ensure("))
158 );
159 assert!(
160 expressions
161 .iter()
162 .all(|expression| !expression.contains("Bearer ey"))
163 );
164 let ensure = expressions
165 .iter()
166 .find(|expression| expression.contains("window.__chatsvcTrouter.ensure("))
167 .unwrap();
168 let arguments_json = ensure
169 .split_once("const args = ")
170 .and_then(|(_, rest)| rest.split_once(";\n").or_else(|| rest.split_once(';')))
171 .map(|(json, _)| json)
172 .unwrap();
173 let arguments: serde_json::Value = serde_json::from_str(arguments_json).unwrap();
174 assert_eq!(
175 arguments,
176 serde_json::json!({"host": "go-eu.trouter.teams.microsoft.com", "activity": "inactive"})
177 );
178 realtime.stop().await;
179}
180
181#[tokio::test]
182async fn stop_unregisters_in_the_page_and_removes_the_injected_script() {
183 let (endpoint, calls) = start_tab().await;
184 let session = Session::connect(&endpoint).await.unwrap();
185 let realtime = Realtime::start_with(&session, quiet_config())
186 .await
187 .unwrap();
188 realtime.stop().await;
189 let recorded = calls.lock().unwrap().clone();
190 let stop_call = recorded.iter().rposition(|(method, params)| {
191 method == "Runtime.evaluate"
192 && params["expression"].as_str()
193 == Some("window.__chatsvcTrouter ? window.__chatsvcTrouter.stop() : null")
194 });
195 let remove_call = recorded.iter().rposition(|(method, params)| {
196 method == "Page.removeScriptToEvaluateOnNewDocument" && params["identifier"] == "9"
197 });
198 assert!(stop_call.is_some() && remove_call.is_some());
199 assert!(stop_call < remove_call);
200}