| 1 | use std::sync::{Arc, Mutex}; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use chatsvc::{EventKind, Realtime, RealtimeConfig, RealtimeEvent, StatusKind}; |
| 5 | use futures_util::{SinkExt, StreamExt}; |
| 6 | use serde_json::{Value, json}; |
| 7 | use session::Session; |
| 8 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 9 | use tokio::net::{TcpListener, TcpStream}; |
| 10 | use tokio_tungstenite::tungstenite::Message; |
| 11 | |
| 12 | type Calls = Arc<Mutex<Vec<(String, Value)>>>; |
| 13 | |
| 14 | async 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 | |
| 28 | fn 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 | |
| 33 | async 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 | ]; |
| 62 | for payload in payloads { |
| 63 | websocket.send(binding_event(payload)).await.unwrap(); |
| 64 | } |
| 65 | websocket.send(Message::text(json!({"method": "Runtime.bindingCalled", "params": {"name": "someoneElse", "payload": "x"}}).to_string())).await.unwrap(); |
| 66 | websocket.send(Message::text(json!({"method": "Runtime.bindingCalled", "params": {"name": "__chatsvcRealtime", "payload": "garbage"}}).to_string())).await.unwrap(); |
| 67 | } |
| 68 | } |
| 69 | return; |
| 70 | } |
| 71 | let mut discard = [0u8; 1024]; |
| 72 | let _ = stream.read(&mut discard).await.unwrap(); |
| 73 | let targets = json!([{"type": "page", "url": "https://teams.cloud.microsoft/v2/", "webSocketDebuggerUrl": format!("ws://127.0.0.1:{port}/devtools/page/0")}]); |
| 74 | let body = targets.to_string(); |
| 75 | let response = format!( |
| 76 | "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", |
| 77 | body.len() |
| 78 | ); |
| 79 | stream.write_all(response.as_bytes()).await.unwrap(); |
| 80 | } |
| 81 | |
| 82 | fn quiet_config() -> RealtimeConfig { |
| 83 | RealtimeConfig { |
| 84 | ensure_interval: Duration::from_secs(3600), |
| 85 | ..RealtimeConfig::default() |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | #[tokio::test] |
| 90 | async fn forwards_decoded_events_and_drops_foreign_or_garbage_payloads() { |
| 91 | let (endpoint, calls) = start_tab().await; |
| 92 | let session = Session::connect(&endpoint).await.unwrap(); |
| 93 | let mut realtime = Realtime::start_with(&session, quiet_config()) |
| 94 | .await |
| 95 | .unwrap(); |
| 96 | |
| 97 | let RealtimeEvent::Status(status) = realtime.recv().await.unwrap() else { |
| 98 | panic!("expected status first") |
| 99 | }; |
| 100 | assert_eq!(status.kind, StatusKind::Connected); |
| 101 | let RealtimeEvent::Message(message) = realtime.recv().await.unwrap() else { |
| 102 | panic!("expected message") |
| 103 | }; |
| 104 | assert_eq!(message.kind, EventKind::NewMessage); |
| 105 | assert_eq!(message.conversation_id.as_deref(), Some("19:abc@thread.v2")); |
| 106 | let RealtimeEvent::Message(typing) = realtime.recv().await.unwrap() else { |
| 107 | panic!("expected typing") |
| 108 | }; |
| 109 | assert_eq!(typing.kind, EventKind::Typing); |
| 110 | assert_eq!(typing.conversation_id, None); |
| 111 | |
| 112 | let methods: Vec<String> = calls |
| 113 | .lock() |
| 114 | .unwrap() |
| 115 | .iter() |
| 116 | .map(|(method, _)| method.clone()) |
| 117 | .filter(|method| method != "Runtime.evaluate") |
| 118 | .collect(); |
| 119 | assert_eq!( |
| 120 | &methods[..4], |
| 121 | [ |
| 122 | "Runtime.enable", |
| 123 | "Page.enable", |
| 124 | "Runtime.addBinding", |
| 125 | "Page.addScriptToEvaluateOnNewDocument" |
| 126 | ] |
| 127 | ); |
| 128 | realtime.stop().await; |
| 129 | } |
| 130 | |
| 131 | #[tokio::test] |
| 132 | async fn start_injects_worker_and_ensures_with_default_host() { |
| 133 | let (endpoint, calls) = start_tab().await; |
| 134 | let session = Session::connect(&endpoint).await.unwrap(); |
| 135 | let realtime = Realtime::start_with(&session, quiet_config()) |
| 136 | .await |
| 137 | .unwrap(); |
| 138 | assert_eq!(realtime.host(), "go-eu.trouter.teams.microsoft.com"); |
| 139 | let recorded = calls.lock().unwrap().clone(); |
| 140 | let expressions: Vec<&str> = recorded |
| 141 | .iter() |
| 142 | .filter(|(method, _)| method == "Runtime.evaluate") |
| 143 | .filter_map(|(_, params)| params["expression"].as_str()) |
| 144 | .collect(); |
| 145 | assert!( |
| 146 | expressions |
| 147 | .iter() |
| 148 | .any(|expression| expression.contains("window.__chatsvcTrouter.ensure(")) |
| 149 | ); |
| 150 | assert!( |
| 151 | expressions |
| 152 | .iter() |
| 153 | .all(|expression| !expression.contains("Bearer ey")) |
| 154 | ); |
| 155 | let ensure = expressions |
| 156 | .iter() |
| 157 | .find(|expression| expression.contains("window.__chatsvcTrouter.ensure(")) |
| 158 | .unwrap(); |
| 159 | let arguments_json = ensure |
| 160 | .split_once("const args = ") |
| 161 | .and_then(|(_, rest)| rest.split_once(";\n").or_else(|| rest.split_once(';'))) |
| 162 | .map(|(json, _)| json) |
| 163 | .unwrap(); |
| 164 | let arguments: serde_json::Value = serde_json::from_str(arguments_json).unwrap(); |
| 165 | assert_eq!( |
| 166 | arguments, |
| 167 | serde_json::json!({"forwardPresence": false, "host": "go-eu.trouter.teams.microsoft.com"}) |
| 168 | ); |
| 169 | realtime.stop().await; |
| 170 | } |
| 171 | |
| 172 | #[tokio::test] |
| 173 | async fn stop_unregisters_in_the_page_and_removes_the_injected_script() { |
| 174 | let (endpoint, calls) = start_tab().await; |
| 175 | let session = Session::connect(&endpoint).await.unwrap(); |
| 176 | let realtime = Realtime::start_with(&session, quiet_config()) |
| 177 | .await |
| 178 | .unwrap(); |
| 179 | realtime.stop().await; |
| 180 | let recorded = calls.lock().unwrap().clone(); |
| 181 | let stop_call = recorded.iter().rposition(|(method, params)| { |
| 182 | method == "Runtime.evaluate" |
| 183 | && params["expression"].as_str() |
| 184 | == Some("window.__chatsvcTrouter ? window.__chatsvcTrouter.stop() : null") |
| 185 | }); |
| 186 | let remove_call = recorded.iter().rposition(|(method, params)| { |
| 187 | method == "Page.removeScriptToEvaluateOnNewDocument" && params["identifier"] == "9" |
| 188 | }); |
| 189 | assert!(stop_call.is_some() && remove_call.is_some()); |
| 190 | assert!(stop_call < remove_call); |
| 191 | } |