Cotton code
207 lines · 8.0 KB · RustRaw
use serde_json::{json, Value};use super::*;fn parse(text: &str) -> Value {    serde_json::from_str(text).expect("JSON")}/// Attach `client` and answer the attach with `session`.fn attached(router: &mut Router, client: ClientId, session: &str) {    let command = parse(&router.attach(client));    assert_eq!(command["method"], "Target.attachToBrowserTarget");    let routed = router.from_chrome(        &json!({ "id": command["id"], "result": { "sessionId": session } }).to_string(),    );    assert_eq!(routed.attached, Some((client, Ok(()))));}fn sent(action: FromClient) -> Value {    match action {        FromClient::ToChrome(text) => parse(&text),        FromClient::ToClient(text) => panic!("refused: {text}"),    }}fn refused(action: FromClient) -> Value {    match action {        FromClient::ToClient(text) => parse(&text),        FromClient::ToChrome(text) => panic!("sent to Chrome: {text}"),    }}/// RULE: A browser-broker client's command with no session is sent under that client's own browser session, and its answer comes back with the client's own id.#[test]fn a_command_with_no_session_goes_under_the_client_s_own_browser_session() {    let mut router = Router::new();    attached(&mut router, 1, "B1");    attached(&mut router, 2, "B2");    let forwarded = sent(router.from_client(1, r#"{"id":7,"method":"Target.getTargets"}"#));    assert_eq!(forwarded["sessionId"], "B1");    assert_ne!(forwarded["id"], 7, "the broker's own id goes down the pipe");    let routed = router.from_chrome(        &json!({ "id": forwarded["id"], "sessionId": "B1", "result": { "targetInfos": [] } })            .to_string(),    );    assert_eq!(routed.deliveries.len(), 1);    let (client, answer) = &routed.deliveries[0];    assert_eq!(*client, 1);    let answer = parse(answer);    assert_eq!(answer["id"], 7);    assert!(answer.get("sessionId").is_none(), "the browser session is the client's invisible default");}/// RULE: A browser-broker client can never address a session another client owns; the broker refuses it without sending it.////// Two agents in two sessions share one signed-in browser. A session id is/// all it takes to drive a page, so a guessed or overheard one must be worth/// nothing to a client that did not attach it.#[test]fn a_session_another_client_owns_is_refused_and_never_sent() {    let mut router = Router::new();    attached(&mut router, 1, "B1");    attached(&mut router, 2, "B2");    // Chrome attaches a page under client 2's browser session.    router.from_chrome(        &json!({ "method": "Target.attachedToTarget", "sessionId": "B2",                 "params": { "sessionId": "P2", "targetInfo": { "type": "page" } } })        .to_string(),    );    for session in ["B2", "P2", "made-up"] {        let answer = refused(router.from_client(            1,            &json!({ "id": 3, "sessionId": session, "method": "Runtime.evaluate",                     "params": { "expression": "document.cookie" } })            .to_string(),        ));        assert_eq!(answer["id"], 3);        assert_eq!(answer["error"]["message"], "Session with given id not found.");    }    // Client 2's own page is its to drive.    let forwarded = sent(router.from_client(        2,        r#"{"id":4,"sessionId":"P2","method":"Runtime.evaluate","params":{"expression":"1"}}"#,    ));    assert_eq!(forwarded["sessionId"], "P2");}/// RULE: Events reach only the browser-broker client that owns their session, and the pipe's own events reach nobody.#[test]fn events_go_only_to_the_client_that_owns_their_session() {    let mut router = Router::new();    attached(&mut router, 1, "B1");    attached(&mut router, 2, "B2");    router.from_chrome(        &json!({ "method": "Target.attachedToTarget", "sessionId": "B1",                 "params": { "sessionId": "P1" } })        .to_string(),    );    let routed = router.from_chrome(        r#"{"method":"Page.frameNavigated","sessionId":"P1","params":{"frame":{"url":"https://example.com"}}}"#,    );    assert_eq!(routed.deliveries.len(), 1);    assert_eq!(routed.deliveries[0].0, 1);    assert_eq!(parse(&routed.deliveries[0].1)["sessionId"], "P1");    let routed = router.from_chrome(r#"{"method":"Target.targetCreated","params":{}}"#);    assert!(routed.deliveries.is_empty(), "an event with no session is the pipe's own");    let routed = router.from_chrome(r#"{"method":"Page.loadEventFired","sessionId":"P9"}"#);    assert!(routed.deliveries.is_empty(), "a session nobody owns reaches nobody");}/// RULE: The browser broker refuses Browser.close, the crash commands and Target.exposeDevToolsProtocol from every client.////// The browser is shared and signed in: closing or crashing it takes it from/// every other session, and exposeDevToolsProtocol hands a web page's own/// JavaScript a channel to the browser target.#[test]fn closing_crashing_or_exposing_the_shared_browser_is_refused() {    let mut router = Router::new();    attached(&mut router, 1, "B1");    for method in REFUSED {        let answer = refused(router.from_client(            1,            &json!({ "id": 9, "method": method, "params": { "targetId": "T", "bindingName": "cdp" } })                .to_string(),        ));        assert_eq!(answer["id"], 9, "{method}");        let message = answer["error"]["message"].as_str().unwrap_or_default();        assert!(message.contains("refused by Cotton's browser broker"), "{method}: {message}");    }}#[test]fn a_client_that_is_not_attached_yet_sends_nothing() {    let mut router = Router::new();    let answer = refused(router.from_client(5, r#"{"id":1,"method":"Target.getTargets"}"#));    assert_eq!(answer["id"], 1);}#[test]fn a_session_a_command_of_the_client_s_attached_is_its_own() {    let mut router = Router::new();    attached(&mut router, 1, "B1");    let forwarded = sent(router.from_client(        1,        r#"{"id":2,"method":"Target.attachToTarget","params":{"targetId":"T","flatten":true}}"#,    ));    router.from_chrome(        &json!({ "id": forwarded["id"], "sessionId": "B1", "result": { "sessionId": "P7" } })            .to_string(),    );    assert!(router.owns(1, "P7"));}#[test]fn a_detached_session_is_forgotten() {    let mut router = Router::new();    attached(&mut router, 1, "B1");    router.from_chrome(        r#"{"method":"Target.attachedToTarget","sessionId":"B1","params":{"sessionId":"P1"}}"#,    );    router.from_chrome(        r#"{"method":"Target.detachedFromTarget","sessionId":"B1","params":{"sessionId":"P1"}}"#,    );    assert!(!router.owns(1, "P1"));}#[test]fn a_client_that_leaves_has_its_sessions_detached_and_its_answers_dropped() {    let mut router = Router::new();    attached(&mut router, 1, "B1");    attached(&mut router, 2, "B2");    router.from_chrome(        r#"{"method":"Target.attachedToTarget","sessionId":"B1","params":{"sessionId":"P1"}}"#,    );    let in_flight = sent(router.from_client(1, r#"{"id":5,"method":"Target.getTargets"}"#));    let commands: Vec<Value> = router.detach(1).iter().map(|text| parse(text)).collect();    let detached: Vec<&str> = commands        .iter()        .map(|command| {            assert_eq!(command["method"], "Target.detachFromTarget");            command["params"]["sessionId"].as_str().unwrap_or_default()        })        .collect();    assert_eq!(detached, ["P1", "B1"], "children first, then the browser session");    assert!(!router.owns(1, "B1") && !router.owns(1, "P1"));    assert!(router.owns(2, "B2"), "another client is untouched");    let routed = router.from_chrome(&json!({ "id": in_flight["id"], "result": {} }).to_string());    assert!(routed.deliveries.is_empty(), "an answer for a client that left goes nowhere");}#[test]fn an_attach_chrome_refused_is_said() {    let mut router = Router::new();    let command = parse(&router.attach(3));    let routed = router.from_chrome(        &json!({ "id": command["id"], "error": { "code": -32000, "message": "nope" } }).to_string(),    );    assert!(matches!(routed.attached, Some((3, Err(_)))));    assert_eq!(router.browser_session(3), None);}