| 1 | use std::sync::{Arc, Mutex}; |
| 2 | |
| 3 | use futures_util::{SinkExt, StreamExt}; |
| 4 | use serde_json::{Value, json}; |
| 5 | use session::{App, Error, Scope, Session}; |
| 6 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 7 | use tokio::net::{TcpListener, TcpStream}; |
| 8 | use tokio_tungstenite::tungstenite::Message; |
| 9 | |
| 10 | type Calls = Arc<Mutex<Vec<(String, Value)>>>; |
| 11 | |
| 12 | struct MockTab { |
| 13 | endpoint: String, |
| 14 | calls: Calls, |
| 15 | } |
| 16 | |
| 17 | async fn start_tab(evaluate_value: Value) -> MockTab { |
| 18 | let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 19 | let port = listener.local_addr().unwrap().port(); |
| 20 | let calls: Calls = Arc::new(Mutex::new(Vec::new())); |
| 21 | let seen = calls.clone(); |
| 22 | tokio::spawn(async move { |
| 23 | loop { |
| 24 | let (stream, _) = listener.accept().await.unwrap(); |
| 25 | tokio::spawn(serve(stream, port, evaluate_value.clone(), seen.clone())); |
| 26 | } |
| 27 | }); |
| 28 | MockTab { |
| 29 | endpoint: format!("http://127.0.0.1:{port}"), |
| 30 | calls, |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | async fn serve(mut stream: TcpStream, port: u16, evaluate_value: Value, calls: Calls) { |
| 35 | let mut peek = [0u8; 16]; |
| 36 | let count = stream.peek(&mut peek).await.unwrap(); |
| 37 | if !peek[..count].starts_with(b"GET /json") { |
| 38 | let mut websocket = tokio_tungstenite::accept_async(stream).await.unwrap(); |
| 39 | while let Some(Ok(Message::Text(text))) = websocket.next().await { |
| 40 | let call: Value = serde_json::from_str(text.as_str()).unwrap(); |
| 41 | let method = call["method"].as_str().unwrap().to_owned(); |
| 42 | calls.lock().unwrap().push((method.clone(), call["params"].clone())); |
| 43 | let result = match method.as_str() { |
| 44 | "Runtime.evaluate" => json!({"result": {"type": "object", "value": evaluate_value}}), |
| 45 | "Page.addScriptToEvaluateOnNewDocument" => json!({"identifier": "7"}), |
| 46 | "Runtime.disable" => { |
| 47 | websocket.send(Message::text(json!({"id": call["id"], "error": {"message": "nope"}}).to_string())).await.unwrap(); |
| 48 | continue; |
| 49 | } |
| 50 | _ => json!({}), |
| 51 | }; |
| 52 | websocket |
| 53 | .send(Message::text(json!({"id": call["id"], "result": result}).to_string())) |
| 54 | .await |
| 55 | .unwrap(); |
| 56 | if method == "Runtime.addBinding" { |
| 57 | let name = call["params"]["name"].clone(); |
| 58 | for payload in ["first", "second"] { |
| 59 | let event = json!({"method": "Runtime.bindingCalled", "params": {"name": name, "payload": payload, "executionContextId": 1}}); |
| 60 | websocket.send(Message::text(event.to_string())).await.unwrap(); |
| 61 | } |
| 62 | let navigation = json!({"method": "Page.frameNavigated", "params": {"frame": {"url": "https://teams.cloud.microsoft/"}}}); |
| 63 | websocket.send(Message::text(navigation.to_string())).await.unwrap(); |
| 64 | } |
| 65 | } |
| 66 | return; |
| 67 | } |
| 68 | let mut discard = [0u8; 1024]; |
| 69 | let _ = stream.read(&mut discard).await.unwrap(); |
| 70 | let targets = json!([{"type": "page", "url": "https://teams.cloud.microsoft/v2/", "webSocketDebuggerUrl": format!("ws://127.0.0.1:{port}/devtools/page/0")}]); |
| 71 | let body = targets.to_string(); |
| 72 | let response = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); |
| 73 | stream.write_all(response.as_bytes()).await.unwrap(); |
| 74 | } |
| 75 | |
| 76 | #[tokio::test] |
| 77 | async fn binding_calls_arrive_as_events_in_order() { |
| 78 | let tab = start_tab(Value::Null).await; |
| 79 | let session = Session::connect(&tab.endpoint).await.unwrap(); |
| 80 | let (control, mut events) = session.subscribe(App::Teams).await.unwrap(); |
| 81 | control.enable_events().await.unwrap(); |
| 82 | control.add_binding("sink").await.unwrap(); |
| 83 | |
| 84 | let first = events.recv().await.unwrap(); |
| 85 | assert_eq!(first.binding_payload("sink"), Some("first")); |
| 86 | assert_eq!(events.recv().await.unwrap().binding_payload("sink"), Some("second")); |
| 87 | assert_eq!(events.recv().await.unwrap().method, "Page.frameNavigated"); |
| 88 | |
| 89 | let methods: Vec<String> = tab.calls.lock().unwrap().iter().map(|(method, _)| method.clone()).collect(); |
| 90 | assert_eq!(methods, ["Runtime.enable", "Page.enable", "Runtime.addBinding"]); |
| 91 | } |
| 92 | |
| 93 | #[tokio::test] |
| 94 | async fn inject_script_registers_for_new_documents_and_runs_now() { |
| 95 | let tab = start_tab(json!("done")).await; |
| 96 | let session = Session::connect(&tab.endpoint).await.unwrap(); |
| 97 | let (control, _events) = session.subscribe(App::Teams).await.unwrap(); |
| 98 | let identifier = control.inject_script("window.__x = 1").await.unwrap(); |
| 99 | assert_eq!(identifier, "7"); |
| 100 | let calls = tab.calls.lock().unwrap(); |
| 101 | assert_eq!(calls[0].0, "Page.addScriptToEvaluateOnNewDocument"); |
| 102 | assert_eq!(calls[0].1["source"], "window.__x = 1"); |
| 103 | assert_eq!(calls[1].0, "Runtime.evaluate"); |
| 104 | assert_eq!(calls[1].1["expression"], "window.__x = 1"); |
| 105 | } |
| 106 | |
| 107 | #[tokio::test] |
| 108 | async fn concurrent_calls_get_their_own_answers_and_errors_are_typed() { |
| 109 | let tab = start_tab(Value::Null).await; |
| 110 | let session = Session::connect(&tab.endpoint).await.unwrap(); |
| 111 | let (control, _events) = session.subscribe(App::Teams).await.unwrap(); |
| 112 | let (identifier, failure) = tokio::join!( |
| 113 | control.call("Page.addScriptToEvaluateOnNewDocument", json!({"source": ""})), |
| 114 | control.call("Runtime.disable", json!({})), |
| 115 | ); |
| 116 | assert_eq!(identifier.unwrap()["identifier"], "7"); |
| 117 | assert!(matches!(failure.unwrap_err(), Error::Cdp(reason) if reason == "nope")); |
| 118 | } |
| 119 | |
| 120 | #[tokio::test] |
| 121 | async fn events_survive_dropping_the_control() { |
| 122 | let tab = start_tab(Value::Null).await; |
| 123 | let session = Session::connect(&tab.endpoint).await.unwrap(); |
| 124 | let (control, mut events) = session.subscribe(App::Teams).await.unwrap(); |
| 125 | control.add_binding("sink").await.unwrap(); |
| 126 | drop(control); |
| 127 | let mut received = 0; |
| 128 | while let Some(_event) = events.next().await { |
| 129 | received += 1; |
| 130 | if received == 3 { |
| 131 | break; |
| 132 | } |
| 133 | } |
| 134 | assert_eq!(received, 3); |
| 135 | } |
| 136 | |
| 137 | #[tokio::test] |
| 138 | async fn run_with_token_splices_body_after_the_token_lookup() { |
| 139 | let tab = start_tab(json!({"ok": true})).await; |
| 140 | let session = Session::connect(&tab.endpoint).await.unwrap(); |
| 141 | let scope = Scope::new("https://ic3.teams.office.com", "Teams.AccessAsUser.All"); |
| 142 | let answer = session |
| 143 | .run_with_token(App::Teams, &scope, "return {ok: !!token};", &json!({"host": "h"}), true) |
| 144 | .await |
| 145 | .unwrap(); |
| 146 | assert_eq!(answer["ok"], true); |
| 147 | let calls = tab.calls.lock().unwrap(); |
| 148 | let expression = calls[0].1["expression"].as_str().unwrap(); |
| 149 | let lookup = expression.find("if (!token) return {noToken").unwrap(); |
| 150 | let body = expression.find("return {ok: !!token};").unwrap(); |
| 151 | assert!(lookup < body); |
| 152 | assert!(expression.contains(r#"const args = {"host":"h"};"#)); |
| 153 | assert!(expression.contains(r#""forceRefresh":true"#)); |
| 154 | assert!(expression.contains(r#""scope":"Teams.AccessAsUser.All""#)); |
| 155 | } |
| 156 | |
| 157 | #[tokio::test] |
| 158 | async fn run_with_token_maps_missing_token_to_typed_errors() { |
| 159 | let tab = start_tab(json!({"noToken": true, "refreshError": "invalid_grant"})).await; |
| 160 | let session = Session::connect(&tab.endpoint).await.unwrap(); |
| 161 | let scope = Scope::new("https://ic3.teams.office.com", "Teams.AccessAsUser.All"); |
| 162 | let error = session |
| 163 | .run_with_token(App::Teams, &scope, "return 1;", &json!({}), false) |
| 164 | .await |
| 165 | .unwrap_err(); |
| 166 | assert!(matches!(error, Error::NoFreshToken { .. }), "{error}"); |
| 167 | |
| 168 | let tab = start_tab(json!({"noToken": true, "refreshError": "the app is not granted x"})).await; |
| 169 | let session = Session::connect(&tab.endpoint).await.unwrap(); |
| 170 | let error = session |
| 171 | .run_with_token(App::Teams, &scope, "return 1;", &json!({}), false) |
| 172 | .await |
| 173 | .unwrap_err(); |
| 174 | assert!(matches!(error, Error::LoginRequired(_)), "{error}"); |
| 175 | } |