Skip to main content

rightkit_browser/
cdp_ext.rs

1//! Caller-facing CDP surface added in 0.4.0: request interception, the accessibility tree,
2//! exception events, page scale and per-page download behaviour.
3//!
4//! Everything here that decodes or builds a CDP message is a pure function over JSON or over the
5//! generated parameter types, so the unit tests feed recorded wire messages through it without a
6//! browser. The `BrowserPage` methods in `page.rs` only send what these functions build.
7
8use crate::error::{BrowserError, Result};
9use chromiumoxide::cdp::browser_protocol::browser::{
10    SetDownloadBehaviorBehavior, SetDownloadBehaviorParams,
11};
12use chromiumoxide::cdp::browser_protocol::emulation::SetPageScaleFactorParams;
13use chromiumoxide::cdp::browser_protocol::fetch::{
14    ContinueRequestParams, FailRequestParams, FulfillRequestParams, HeaderEntry, RequestId,
15};
16use chromiumoxide::cdp::browser_protocol::network::ErrorReason;
17use futures::future::BoxFuture;
18use serde::Serialize;
19use serde_json::Value;
20use std::path::PathBuf;
21use std::sync::Arc;
22use std::time::Duration;
23
24/// How long an interceptor may take before the request is failed (fail closed).
25pub(crate) const INTERCEPTOR_TIMEOUT: Duration = Duration::from_secs(30);
26
27/// Structured exceptions kept per page (oldest dropped first).
28pub const MAX_EXCEPTIONS: usize = 200;
29
30// ---- request interception ------------------------------------------------------------------
31
32/// Which stage a paused request is at.
33#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
34pub enum InterceptStage {
35    /// Before the request leaves the browser. Redirect hops arrive here too.
36    Request,
37    /// After response headers arrived (only when response-stage patterns are enabled).
38    Response,
39}
40
41/// One `Fetch.requestPaused` event, decoded.
42#[derive(Clone, Debug, PartialEq, Serialize)]
43pub struct InterceptedRequest {
44    /// CDP fetch request id (what the answer is addressed to).
45    pub request_id: String,
46    pub url: String,
47    pub method: String,
48    /// Request headers, in the order CDP reported them.
49    pub headers: Vec<(String, String)>,
50    /// CDP resource type, e.g. `Document`, `XHR`, `Image`.
51    pub resource_type: String,
52    /// CDP frame id of the frame that issued the request.
53    pub frame_id: String,
54    pub has_post_data: bool,
55    /// Set when this request is a redirect hop: the id of the request whose redirect caused it.
56    /// Revalidate the new `url` here (origin pin) exactly as for a first request.
57    pub redirected_from: Option<String>,
58    pub stage: InterceptStage,
59    pub response_status: Option<i64>,
60    pub response_headers: Vec<(String, String)>,
61}
62
63impl InterceptedRequest {
64    /// True for a request created by following a redirect.
65    pub fn is_redirect(&self) -> bool {
66        self.redirected_from.is_some()
67    }
68
69    /// First header value with this name (case-insensitive).
70    pub fn header(&self, name: &str) -> Option<&str> {
71        self.headers
72            .iter()
73            .find(|(k, _)| k.eq_ignore_ascii_case(name))
74            .map(|(_, v)| v.as_str())
75    }
76
77    /// Decode the params of a `Fetch.requestPaused` event (CDP wire form).
78    pub fn from_cdp_value(v: &Value) -> Option<Self> {
79        let request = v.get("request")?;
80        let text = |o: &Value, k: &str| o.get(k).and_then(Value::as_str).map(str::to_string);
81        let response_status = v.get("responseStatusCode").and_then(Value::as_i64);
82        let stage = if response_status.is_some() || v.get("responseErrorReason").is_some() {
83            InterceptStage::Response
84        } else {
85            InterceptStage::Request
86        };
87        Some(Self {
88            request_id: text(v, "requestId")?,
89            url: text(request, "url")?,
90            method: text(request, "method").unwrap_or_else(|| "GET".into()),
91            headers: request
92                .get("headers")
93                .map(header_object)
94                .unwrap_or_default(),
95            resource_type: text(v, "resourceType").unwrap_or_default(),
96            frame_id: text(v, "frameId").unwrap_or_default(),
97            has_post_data: request
98                .get("hasPostData")
99                .and_then(Value::as_bool)
100                .unwrap_or(false),
101            redirected_from: text(v, "redirectedRequestId"),
102            stage,
103            response_status,
104            response_headers: v
105                .get("responseHeaders")
106                .map(header_entries)
107                .unwrap_or_default(),
108        })
109    }
110}
111
112/// Overrides for a continued request. Anything left `None` is unchanged.
113#[derive(Clone, Debug, Default, PartialEq)]
114pub struct ContinueOverrides {
115    /// Rewrites the URL without the page seeing it. Not re-checked against the network policy.
116    pub url: Option<String>,
117    pub method: Option<String>,
118    /// Replaces the request headers entirely.
119    pub headers: Option<Vec<(String, String)>>,
120    pub post_data: Option<Vec<u8>>,
121}
122
123/// Why a request is failed; maps to the CDP `Network.ErrorReason` the page sees.
124#[derive(Clone, Copy, Debug, Eq, PartialEq)]
125pub enum InterceptFailure {
126    Failed,
127    Aborted,
128    AccessDenied,
129    ConnectionRefused,
130    NameNotResolved,
131    BlockedByClient,
132}
133
134impl InterceptFailure {
135    fn reason(self) -> ErrorReason {
136        match self {
137            Self::Failed => ErrorReason::Failed,
138            Self::Aborted => ErrorReason::Aborted,
139            Self::AccessDenied => ErrorReason::AccessDenied,
140            Self::ConnectionRefused => ErrorReason::ConnectionRefused,
141            Self::NameNotResolved => ErrorReason::NameNotResolved,
142            Self::BlockedByClient => ErrorReason::BlockedByClient,
143        }
144    }
145}
146
147/// The answer to one paused request.
148#[derive(Clone, Debug, PartialEq)]
149pub enum InterceptDecision {
150    /// Let it through unchanged.
151    Continue,
152    /// Let it through with changes.
153    ContinueWith(ContinueOverrides),
154    /// Answer it from here; nothing reaches the network.
155    Fulfill {
156        status: u16,
157        headers: Vec<(String, String)>,
158        body: Vec<u8>,
159        phrase: Option<String>,
160    },
161    /// Fail it with a network error.
162    Fail(InterceptFailure),
163}
164
165/// Caller-supplied hook, consulted for every request the page makes (redirect hops included).
166///
167/// It runs after the session's [`crate::NetworkPolicy`]: a request the policy refuses is failed
168/// without the hook seeing it, so a hook can only narrow what the policy allows. A hook that
169/// takes longer than 30 s fails the request.
170pub type RequestInterceptor =
171    Arc<dyn Fn(InterceptedRequest) -> BoxFuture<'static, InterceptDecision> + Send + Sync>;
172
173/// The CDP command that answers a paused request.
174#[derive(Debug)]
175pub(crate) enum PausedCommand {
176    Continue(ContinueRequestParams),
177    Fulfill(FulfillRequestParams),
178    Fail(FailRequestParams),
179}
180
181pub(crate) fn command_for(id: RequestId, decision: InterceptDecision) -> PausedCommand {
182    match decision {
183        InterceptDecision::Continue => PausedCommand::Continue(ContinueRequestParams::new(id)),
184        InterceptDecision::ContinueWith(o) => {
185            let mut p = ContinueRequestParams::new(id);
186            p.url = o.url;
187            p.method = o.method;
188            p.headers = o.headers.map(header_entries_out);
189            p.post_data = o.post_data.map(|b| base64(&b).into());
190            PausedCommand::Continue(p)
191        }
192        InterceptDecision::Fulfill {
193            status,
194            headers,
195            body,
196            phrase,
197        } => {
198            let mut p = FulfillRequestParams::new(id, i64::from(status));
199            p.response_headers = Some(header_entries_out(headers));
200            if !body.is_empty() {
201                p.body = Some(base64(&body).into());
202            }
203            p.response_phrase = phrase;
204            PausedCommand::Fulfill(p)
205        }
206        InterceptDecision::Fail(f) => PausedCommand::Fail(FailRequestParams::new(id, f.reason())),
207    }
208}
209
210/// Ask the hook, failing the request when it does not answer in `limit`.
211pub(crate) async fn run_interceptor(
212    hook: &RequestInterceptor,
213    request: InterceptedRequest,
214    limit: Duration,
215) -> InterceptDecision {
216    match tokio::time::timeout(limit, hook(request)).await {
217        Ok(d) => d,
218        Err(_) => InterceptDecision::Fail(InterceptFailure::Failed),
219    }
220}
221
222// ---- accessibility tree --------------------------------------------------------------------
223
224/// One node of `Accessibility.getFullAXTree`.
225#[derive(Clone, Debug, PartialEq, Serialize)]
226pub struct AxNode {
227    pub node_id: String,
228    pub ignored: bool,
229    pub role: Option<String>,
230    pub name: Option<String>,
231    pub description: Option<String>,
232    /// The node's value (text fields, sliders). Chrome masks password values itself.
233    pub value: Option<Value>,
234    /// Other AX properties (`focused`, `disabled`, `level`, ...) as name and raw value.
235    pub properties: Vec<(String, Value)>,
236    pub parent_id: Option<String>,
237    pub child_ids: Vec<String>,
238    /// Backend DOM node id, usable with `DOM.resolveNode`.
239    pub backend_dom_node_id: Option<i64>,
240    pub frame_id: Option<String>,
241}
242
243impl AxNode {
244    /// Property by name.
245    pub fn property(&self, name: &str) -> Option<&Value> {
246        self.properties
247            .iter()
248            .find(|(k, _)| k == name)
249            .map(|(_, v)| v)
250    }
251}
252
253/// One non-ignored node of an accessibility tree that has a role, as carried by an observation.
254#[derive(Clone, Debug, PartialEq, Serialize)]
255pub struct AxSummary {
256    pub role: String,
257    /// Accessible name; empty when the node has none.
258    pub name: String,
259    /// CDP frame id of the node's document (empty when Chrome reports none).
260    pub frame_id: String,
261}
262
263/// Summarize an accessibility tree: ignored nodes and nodes without a role are dropped.
264pub(crate) fn summarize_ax(nodes: &[AxNode]) -> Vec<AxSummary> {
265    nodes
266        .iter()
267        .filter(|n| !n.ignored)
268        .filter_map(|n| {
269            let role = n.role.as_ref().filter(|r| !r.is_empty())?;
270            Some(AxSummary {
271                role: role.clone(),
272                name: n.name.clone().unwrap_or_default(),
273                frame_id: n.frame_id.clone().unwrap_or_default(),
274            })
275        })
276        .collect()
277}
278
279/// Decode the result of `Accessibility.getFullAXTree` (`{"nodes":[...]}`).
280pub(crate) fn parse_ax_tree(result: &Value) -> Vec<AxNode> {
281    let ax_value =
282        |n: &Value, k: &str| -> Option<Value> { n.get(k).and_then(|x| x.get("value")).cloned() };
283    let ax_text = |n: &Value, k: &str| -> Option<String> {
284        ax_value(n, k).and_then(|v| match v {
285            Value::String(s) => Some(s),
286            Value::Null => None,
287            other => Some(other.to_string()),
288        })
289    };
290    result
291        .get("nodes")
292        .and_then(Value::as_array)
293        .map(|nodes| {
294            nodes
295                .iter()
296                .filter_map(|n| {
297                    Some(AxNode {
298                        node_id: n.get("nodeId").and_then(Value::as_str)?.to_string(),
299                        ignored: n.get("ignored").and_then(Value::as_bool).unwrap_or(false),
300                        role: ax_text(n, "role"),
301                        name: ax_text(n, "name"),
302                        description: ax_text(n, "description"),
303                        value: ax_value(n, "value"),
304                        properties: n
305                            .get("properties")
306                            .and_then(Value::as_array)
307                            .map(|ps| {
308                                ps.iter()
309                                    .filter_map(|p| {
310                                        Some((
311                                            p.get("name")?.as_str()?.to_string(),
312                                            p.get("value")
313                                                .and_then(|v| v.get("value"))
314                                                .cloned()
315                                                .unwrap_or(Value::Null),
316                                        ))
317                                    })
318                                    .collect()
319                            })
320                            .unwrap_or_default(),
321                        parent_id: n
322                            .get("parentId")
323                            .and_then(Value::as_str)
324                            .map(str::to_string),
325                        child_ids: n
326                            .get("childIds")
327                            .and_then(Value::as_array)
328                            .map(|c| {
329                                c.iter()
330                                    .filter_map(Value::as_str)
331                                    .map(str::to_string)
332                                    .collect()
333                            })
334                            .unwrap_or_default(),
335                        backend_dom_node_id: n.get("backendDOMNodeId").and_then(Value::as_i64),
336                        frame_id: n.get("frameId").and_then(Value::as_str).map(str::to_string),
337                    })
338                })
339                .collect()
340        })
341        .unwrap_or_default()
342}
343
344// ---- exceptions ----------------------------------------------------------------------------
345
346/// One frame of an exception's stack.
347#[derive(Clone, Debug, PartialEq, Serialize)]
348pub struct ExceptionFrame {
349    pub function_name: String,
350    pub url: String,
351    /// Zero-based, as CDP reports it.
352    pub line: i64,
353    pub column: i64,
354}
355
356/// One `Runtime.exceptionThrown` event: an uncaught exception or unhandled rejection.
357#[derive(Clone, Debug, PartialEq, Serialize)]
358pub struct PageException {
359    /// `exceptionDetails.text`, usually `Uncaught`.
360    pub text: String,
361    /// The thrown value's description (`Error: boom\n    at ...`) when CDP gave one.
362    pub description: Option<String>,
363    pub url: Option<String>,
364    pub line: i64,
365    pub column: i64,
366    /// Milliseconds since the epoch, as CDP reports it.
367    pub timestamp_ms: f64,
368    pub stack: Vec<ExceptionFrame>,
369}
370
371impl PageException {
372    /// Best single-line-or-more message: the description, else the text.
373    pub fn message(&self) -> &str {
374        self.description.as_deref().unwrap_or(&self.text)
375    }
376
377    /// Decode the params of a `Runtime.exceptionThrown` event (CDP wire form).
378    pub fn from_cdp_value(v: &Value) -> Option<Self> {
379        let d = v.get("exceptionDetails")?;
380        Some(Self {
381            text: d.get("text").and_then(Value::as_str)?.to_string(),
382            description: d
383                .get("exception")
384                .and_then(|e| e.get("description"))
385                .and_then(Value::as_str)
386                .map(str::to_string),
387            url: d.get("url").and_then(Value::as_str).map(str::to_string),
388            line: d.get("lineNumber").and_then(Value::as_i64).unwrap_or(0),
389            column: d.get("columnNumber").and_then(Value::as_i64).unwrap_or(0),
390            timestamp_ms: v.get("timestamp").and_then(Value::as_f64).unwrap_or(0.0),
391            stack: d
392                .get("stackTrace")
393                .and_then(|s| s.get("callFrames"))
394                .and_then(Value::as_array)
395                .map(|frames| {
396                    frames
397                        .iter()
398                        .map(|f| ExceptionFrame {
399                            function_name: f
400                                .get("functionName")
401                                .and_then(Value::as_str)
402                                .unwrap_or_default()
403                                .to_string(),
404                            url: f
405                                .get("url")
406                                .and_then(Value::as_str)
407                                .unwrap_or_default()
408                                .to_string(),
409                            line: f.get("lineNumber").and_then(Value::as_i64).unwrap_or(0),
410                            column: f.get("columnNumber").and_then(Value::as_i64).unwrap_or(0),
411                        })
412                        .collect()
413                })
414                .unwrap_or_default(),
415        })
416    }
417}
418
419// ---- page scale and downloads ----------------------------------------------------------------
420
421/// Validated `Emulation.setPageScaleFactor` parameters.
422pub(crate) fn page_scale_params(scale: f64) -> Result<SetPageScaleFactorParams> {
423    if !scale.is_finite() || scale <= 0.0 {
424        return Err(BrowserError::Invalid(format!(
425            "page scale must be a positive finite number, got {scale}"
426        )));
427    }
428    Ok(SetPageScaleFactorParams::new(scale))
429}
430
431/// What the page does with a download.
432#[derive(Clone, Debug, Eq, PartialEq)]
433pub enum DownloadBehavior {
434    /// Refuse every download.
435    Deny,
436    /// Save under the file's own name into `dir`.
437    Allow { dir: PathBuf },
438    /// Save into `dir` named by the download's GUID (no name collisions, no caller-controlled names).
439    AllowAndName { dir: PathBuf },
440    /// Chrome's default behaviour.
441    Default,
442}
443
444/// Validated `Browser.setDownloadBehavior` parameters. A directory must be absolute and exist.
445pub(crate) fn download_params(behavior: &DownloadBehavior) -> Result<SetDownloadBehaviorParams> {
446    let dir_text = |dir: &PathBuf| -> Result<String> {
447        if !dir.is_absolute() {
448            return Err(BrowserError::Invalid(format!(
449                "download directory must be absolute: {}",
450                dir.display()
451            )));
452        }
453        if !dir.is_dir() {
454            return Err(BrowserError::Invalid(format!(
455                "download directory does not exist: {}",
456                dir.display()
457            )));
458        }
459        Ok(dir.to_string_lossy().into_owned())
460    };
461    Ok(match behavior {
462        DownloadBehavior::Deny => SetDownloadBehaviorParams::new(SetDownloadBehaviorBehavior::Deny),
463        DownloadBehavior::Default => {
464            SetDownloadBehaviorParams::new(SetDownloadBehaviorBehavior::Default)
465        }
466        DownloadBehavior::Allow { dir } => {
467            let mut p = SetDownloadBehaviorParams::new(SetDownloadBehaviorBehavior::Allow);
468            p.download_path = Some(dir_text(dir)?);
469            p
470        }
471        DownloadBehavior::AllowAndName { dir } => {
472            let mut p = SetDownloadBehaviorParams::new(SetDownloadBehaviorBehavior::AllowAndName);
473            p.download_path = Some(dir_text(dir)?);
474            p
475        }
476    })
477}
478
479// ---- helpers ---------------------------------------------------------------------------------
480
481/// `Network.Headers`: a JSON object of name to value.
482fn header_object(v: &Value) -> Vec<(String, String)> {
483    v.as_object()
484        .map(|o| {
485            o.iter()
486                .map(|(k, v)| {
487                    (
488                        k.clone(),
489                        v.as_str()
490                            .map(str::to_string)
491                            .unwrap_or_else(|| v.to_string()),
492                    )
493                })
494                .collect()
495        })
496        .unwrap_or_default()
497}
498
499/// `Fetch.HeaderEntry` array.
500fn header_entries(v: &Value) -> Vec<(String, String)> {
501    v.as_array()
502        .map(|a| {
503            a.iter()
504                .filter_map(|h| {
505                    Some((
506                        h.get("name")?.as_str()?.to_string(),
507                        h.get("value")?.as_str()?.to_string(),
508                    ))
509                })
510                .collect()
511        })
512        .unwrap_or_default()
513}
514
515fn header_entries_out(h: Vec<(String, String)>) -> Vec<HeaderEntry> {
516    h.into_iter().map(|(n, v)| HeaderEntry::new(n, v)).collect()
517}
518
519/// Standard base64 with padding (CDP `binary`).
520pub(crate) fn base64(bytes: &[u8]) -> String {
521    const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
522    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
523    for c in bytes.chunks(3) {
524        let n = (u32::from(c[0]) << 16)
525            | (u32::from(*c.get(1).unwrap_or(&0)) << 8)
526            | u32::from(*c.get(2).unwrap_or(&0));
527        out.push(T[(n >> 18) as usize & 63] as char);
528        out.push(T[(n >> 12) as usize & 63] as char);
529        out.push(if c.len() > 1 {
530            T[(n >> 6) as usize & 63] as char
531        } else {
532            '='
533        });
534        out.push(if c.len() > 2 {
535            T[n as usize & 63] as char
536        } else {
537            '='
538        });
539    }
540    out
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546    use futures::FutureExt;
547    use serde_json::json;
548
549    // Recorded from Chrome 13x: a main-frame navigation, then the redirect hop it produced.
550    fn paused_document() -> Value {
551        json!({
552            "requestId": "interception-job-1.0",
553            "request": {
554                "url": "https://example.test/start",
555                "method": "GET",
556                "headers": {
557                    "Upgrade-Insecure-Requests": "1",
558                    "User-Agent": "Mozilla/5.0 HeadlessChrome/130.0.0.0",
559                    "sec-ch-ua": "\"Chromium\";v=\"130\""
560                },
561                "initialPriority": "VeryHigh",
562                "referrerPolicy": "strict-origin-when-cross-origin"
563            },
564            "frameId": "FRAME-1",
565            "resourceType": "Document",
566            "networkId": "1234.5"
567        })
568    }
569
570    fn paused_redirect_hop() -> Value {
571        json!({
572            "requestId": "interception-job-2.0",
573            "request": {
574                "url": "http://169.254.169.254/latest/meta-data/",
575                "method": "POST",
576                "hasPostData": true,
577                "headers": {"Content-Type": "application/json"},
578                "initialPriority": "High",
579                "referrerPolicy": "no-referrer"
580            },
581            "frameId": "FRAME-1",
582            "resourceType": "XHR",
583            "networkId": "1234.6",
584            "redirectedRequestId": "interception-job-1.0"
585        })
586    }
587
588    fn paused_response_stage() -> Value {
589        json!({
590            "requestId": "interception-job-3.0",
591            "request": {"url": "https://example.test/a.png", "method": "GET", "headers": {}},
592            "frameId": "FRAME-1",
593            "resourceType": "Image",
594            "responseStatusCode": 302,
595            "responseStatusText": "Found",
596            "responseHeaders": [
597                {"name": "Location", "value": "https://elsewhere.test/a.png"},
598                {"name": "Content-Length", "value": "0"}
599            ]
600        })
601    }
602
603    #[test]
604    fn decodes_a_document_request() {
605        let r = InterceptedRequest::from_cdp_value(&paused_document()).unwrap();
606        assert_eq!(r.request_id, "interception-job-1.0");
607        assert_eq!(r.url, "https://example.test/start");
608        assert_eq!(r.method, "GET");
609        assert_eq!(r.resource_type, "Document");
610        assert_eq!(r.frame_id, "FRAME-1");
611        assert_eq!(r.stage, InterceptStage::Request);
612        assert!(!r.is_redirect());
613        assert!(!r.has_post_data);
614        assert_eq!(r.header("upgrade-insecure-requests"), Some("1"));
615        assert_eq!(r.header("x-missing"), None);
616    }
617
618    #[test]
619    fn decodes_a_redirect_hop_so_the_new_url_can_be_revalidated() {
620        let r = InterceptedRequest::from_cdp_value(&paused_redirect_hop()).unwrap();
621        assert!(r.is_redirect());
622        assert_eq!(r.redirected_from.as_deref(), Some("interception-job-1.0"));
623        assert_eq!(r.url, "http://169.254.169.254/latest/meta-data/");
624        assert_eq!(r.method, "POST");
625        assert!(r.has_post_data);
626    }
627
628    #[test]
629    fn decodes_the_response_stage() {
630        let r = InterceptedRequest::from_cdp_value(&paused_response_stage()).unwrap();
631        assert_eq!(r.stage, InterceptStage::Response);
632        assert_eq!(r.response_status, Some(302));
633        assert_eq!(
634            r.response_headers[0],
635            ("Location".into(), "https://elsewhere.test/a.png".into())
636        );
637    }
638
639    #[test]
640    fn rejects_a_paused_event_without_a_request() {
641        assert!(InterceptedRequest::from_cdp_value(&json!({"requestId": "x"})).is_none());
642        assert!(InterceptedRequest::from_cdp_value(&json!({"request": {"url": "u"}})).is_none());
643    }
644
645    #[test]
646    fn the_typed_event_round_trips_through_the_decoder() {
647        use chromiumoxide::cdp::browser_protocol::fetch::EventRequestPaused;
648        let typed: EventRequestPaused = serde_json::from_value(paused_document()).unwrap();
649        let wire = serde_json::to_value(&typed).unwrap();
650        let r = InterceptedRequest::from_cdp_value(&wire).unwrap();
651        assert_eq!(r.url, "https://example.test/start");
652        assert_eq!(r.resource_type, "Document");
653        assert_eq!(r.request_id, "interception-job-1.0");
654    }
655
656    fn id() -> RequestId {
657        RequestId::new("interception-job-1.0")
658    }
659
660    #[test]
661    fn continue_builds_a_bare_continue() {
662        let PausedCommand::Continue(p) = command_for(id(), InterceptDecision::Continue) else {
663            panic!("expected continue");
664        };
665        assert_eq!(
666            serde_json::to_value(&p).unwrap(),
667            json!({"requestId": "interception-job-1.0"})
668        );
669    }
670
671    #[test]
672    fn continue_with_overrides_sets_only_what_was_given() {
673        let d = InterceptDecision::ContinueWith(ContinueOverrides {
674            url: Some("https://example.test/other".into()),
675            headers: Some(vec![("X-Pin".into(), "1".into())]),
676            post_data: Some(b"ab".to_vec()),
677            ..Default::default()
678        });
679        let PausedCommand::Continue(p) = command_for(id(), d) else {
680            panic!("expected continue");
681        };
682        assert_eq!(
683            serde_json::to_value(&p).unwrap(),
684            json!({
685                "requestId": "interception-job-1.0",
686                "url": "https://example.test/other",
687                "headers": [{"name": "X-Pin", "value": "1"}],
688                "postData": "YWI="
689            })
690        );
691    }
692
693    #[test]
694    fn fulfill_carries_status_headers_and_a_base64_body() {
695        let d = InterceptDecision::Fulfill {
696            status: 200,
697            headers: vec![("Content-Type".into(), "text/plain".into())],
698            body: b"hello".to_vec(),
699            phrase: Some("OK".into()),
700        };
701        let PausedCommand::Fulfill(p) = command_for(id(), d) else {
702            panic!("expected fulfill");
703        };
704        assert_eq!(
705            serde_json::to_value(&p).unwrap(),
706            json!({
707                "requestId": "interception-job-1.0",
708                "responseCode": 200,
709                "responseHeaders": [{"name": "Content-Type", "value": "text/plain"}],
710                "body": "aGVsbG8=",
711                "responsePhrase": "OK"
712            })
713        );
714    }
715
716    #[test]
717    fn fulfill_with_an_empty_body_omits_it() {
718        let d = InterceptDecision::Fulfill {
719            status: 204,
720            headers: vec![],
721            body: vec![],
722            phrase: None,
723        };
724        let PausedCommand::Fulfill(p) = command_for(id(), d) else {
725            panic!("expected fulfill");
726        };
727        let v = serde_json::to_value(&p).unwrap();
728        assert!(v.get("body").is_none());
729        assert_eq!(v["responseCode"], 204);
730    }
731
732    #[test]
733    fn fail_maps_to_the_network_error_reason() {
734        for (f, name) in [
735            (InterceptFailure::BlockedByClient, "BlockedByClient"),
736            (InterceptFailure::AccessDenied, "AccessDenied"),
737            (InterceptFailure::Aborted, "Aborted"),
738            (InterceptFailure::NameNotResolved, "NameNotResolved"),
739        ] {
740            let PausedCommand::Fail(p) = command_for(id(), InterceptDecision::Fail(f)) else {
741                panic!("expected fail");
742            };
743            assert_eq!(
744                serde_json::to_value(&p).unwrap(),
745                json!({"requestId": "interception-job-1.0", "errorReason": name})
746            );
747        }
748    }
749
750    #[test]
751    fn base64_matches_the_rfc_vectors() {
752        for (i, o) in [
753            ("", ""),
754            ("f", "Zg=="),
755            ("fo", "Zm8="),
756            ("foo", "Zm9v"),
757            ("foob", "Zm9vYg=="),
758            ("fooba", "Zm9vYmE="),
759            ("foobar", "Zm9vYmFy"),
760        ] {
761            assert_eq!(base64(i.as_bytes()), o);
762        }
763    }
764
765    fn request(url: &str) -> InterceptedRequest {
766        InterceptedRequest {
767            url: url.into(),
768            ..InterceptedRequest::from_cdp_value(&paused_document()).unwrap()
769        }
770    }
771
772    #[tokio::test]
773    async fn the_hook_decides_by_url_including_redirect_hops() {
774        // An origin pin: only example.test passes, every other hop fails.
775        let hook: RequestInterceptor = Arc::new(|r: InterceptedRequest| {
776            async move {
777                if r.url.starts_with("https://example.test/") {
778                    InterceptDecision::Continue
779                } else {
780                    InterceptDecision::Fail(InterceptFailure::BlockedByClient)
781                }
782            }
783            .boxed()
784        });
785        let limit = Duration::from_secs(5);
786        assert_eq!(
787            run_interceptor(&hook, request("https://example.test/x"), limit).await,
788            InterceptDecision::Continue
789        );
790        let hop = InterceptedRequest::from_cdp_value(&paused_redirect_hop()).unwrap();
791        assert_eq!(
792            run_interceptor(&hook, hop, limit).await,
793            InterceptDecision::Fail(InterceptFailure::BlockedByClient)
794        );
795    }
796
797    #[tokio::test]
798    async fn a_hook_that_never_answers_fails_the_request() {
799        let hook: RequestInterceptor = Arc::new(|_: InterceptedRequest| {
800            futures::future::pending::<InterceptDecision>().boxed()
801        });
802        let d = run_interceptor(
803            &hook,
804            request("https://example.test/x"),
805            Duration::from_millis(20),
806        )
807        .await;
808        assert_eq!(d, InterceptDecision::Fail(InterceptFailure::Failed));
809    }
810
811    // Recorded Accessibility.getFullAXTree result (trimmed): a page with a heading and a button.
812    fn ax_tree() -> Value {
813        json!({"nodes": [
814            {
815                "nodeId": "1", "ignored": false,
816                "role": {"type": "internalRole", "value": "RootWebArea"},
817                "name": {"type": "computedString", "value": "Demo"},
818                "properties": [
819                    {"name": "focusable", "value": {"type": "booleanOrUndefined", "value": true}}
820                ],
821                "childIds": ["2", "3", "4"],
822                "backendDOMNodeId": 1,
823                "frameId": "FRAME-1"
824            },
825            {
826                "nodeId": "2", "ignored": false,
827                "role": {"type": "role", "value": "heading"},
828                "name": {"type": "computedString", "value": "Welcome"},
829                "properties": [
830                    {"name": "level", "value": {"type": "integer", "value": 1}}
831                ],
832                "parentId": "1", "childIds": [], "backendDOMNodeId": 7
833            },
834            {
835                "nodeId": "3", "ignored": false,
836                "role": {"type": "role", "value": "button"},
837                "name": {"type": "computedString", "value": "Save"},
838                "value": {"type": "string", "value": "go"},
839                "properties": [
840                    {"name": "disabled", "value": {"type": "boolean", "value": true}}
841                ],
842                "parentId": "1", "backendDOMNodeId": 9
843            },
844            {
845                "nodeId": "4", "ignored": true,
846                "ignoredReasons": [{"name": "notRendered", "value": {"type": "boolean", "value": true}}],
847                "role": {"type": "role", "value": "none"},
848                "parentId": "1"
849            },
850            {"ignored": false}
851        ]})
852    }
853
854    #[test]
855    fn decodes_the_ax_tree() {
856        let nodes = parse_ax_tree(&ax_tree());
857        assert_eq!(nodes.len(), 4, "a node without an id is dropped");
858        let root = &nodes[0];
859        assert_eq!(root.role.as_deref(), Some("RootWebArea"));
860        assert_eq!(root.name.as_deref(), Some("Demo"));
861        assert_eq!(root.child_ids, vec!["2", "3", "4"]);
862        assert_eq!(root.frame_id.as_deref(), Some("FRAME-1"));
863        assert_eq!(root.property("focusable"), Some(&json!(true)));
864
865        let heading = &nodes[1];
866        assert_eq!(heading.role.as_deref(), Some("heading"));
867        assert_eq!(heading.property("level"), Some(&json!(1)));
868        assert_eq!(heading.parent_id.as_deref(), Some("1"));
869        assert_eq!(heading.backend_dom_node_id, Some(7));
870
871        let button = &nodes[2];
872        assert_eq!(button.name.as_deref(), Some("Save"));
873        assert_eq!(button.value, Some(json!("go")));
874        assert_eq!(button.property("disabled"), Some(&json!(true)));
875
876        assert!(nodes[3].ignored);
877        assert_eq!(nodes[3].name, None);
878    }
879
880    #[test]
881    fn an_empty_or_malformed_ax_result_is_an_empty_tree() {
882        assert!(parse_ax_tree(&json!({})).is_empty());
883        assert!(parse_ax_tree(&json!({"nodes": "x"})).is_empty());
884    }
885
886    #[test]
887    fn the_typed_ax_result_round_trips_through_the_decoder() {
888        use chromiumoxide::cdp::browser_protocol::accessibility::GetFullAxTreeReturns;
889        let typed: GetFullAxTreeReturns = serde_json::from_value(ax_tree_typed_safe()).unwrap();
890        let nodes = parse_ax_tree(&serde_json::to_value(&typed).unwrap());
891        assert_eq!(nodes.len(), 2);
892        assert_eq!(nodes[1].name.as_deref(), Some("Welcome"));
893    }
894
895    fn ax_tree_typed_safe() -> Value {
896        json!({"nodes": [
897            {"nodeId": "1", "ignored": false,
898             "role": {"type": "internalRole", "value": "RootWebArea"},
899             "childIds": ["2"]},
900            {"nodeId": "2", "ignored": false,
901             "role": {"type": "role", "value": "heading"},
902             "name": {"type": "computedString", "value": "Welcome"},
903             "parentId": "1"}
904        ]})
905    }
906
907    // Recorded Runtime.exceptionThrown for `setTimeout(() => { throw new Error("boom") })`.
908    fn exception_event() -> Value {
909        json!({
910            "timestamp": 1760000000123.5,
911            "exceptionDetails": {
912                "exceptionId": 1,
913                "text": "Uncaught",
914                "lineNumber": 11,
915                "columnNumber": 14,
916                "scriptId": "42",
917                "url": "https://example.test/app.js",
918                "stackTrace": {"callFrames": [
919                    {"functionName": "tick", "scriptId": "42",
920                     "url": "https://example.test/app.js", "lineNumber": 11, "columnNumber": 14},
921                    {"functionName": "", "scriptId": "42",
922                     "url": "https://example.test/app.js", "lineNumber": 20, "columnNumber": 2}
923                ]},
924                "exception": {
925                    "type": "object", "subtype": "error", "className": "Error",
926                    "description": "Error: boom\n    at tick (https://example.test/app.js:12:15)",
927                    "objectId": "1.2.3"
928                },
929                "executionContextId": 3
930            }
931        })
932    }
933
934    #[test]
935    fn decodes_an_exception_event() {
936        let e = PageException::from_cdp_value(&exception_event()).unwrap();
937        assert_eq!(e.text, "Uncaught");
938        assert!(e.message().starts_with("Error: boom"));
939        assert_eq!(e.url.as_deref(), Some("https://example.test/app.js"));
940        assert_eq!((e.line, e.column), (11, 14));
941        assert_eq!(e.timestamp_ms, 1760000000123.5);
942        assert_eq!(e.stack.len(), 2);
943        assert_eq!(e.stack[0].function_name, "tick");
944        assert_eq!(e.stack[1].function_name, "");
945    }
946
947    #[test]
948    fn an_exception_without_a_thrown_value_falls_back_to_the_text() {
949        let e = PageException::from_cdp_value(&json!({
950            "timestamp": 1.0,
951            "exceptionDetails": {"exceptionId": 2, "text": "Uncaught (in promise)",
952                                  "lineNumber": 0, "columnNumber": 0}
953        }))
954        .unwrap();
955        assert_eq!(e.message(), "Uncaught (in promise)");
956        assert!(e.stack.is_empty());
957        assert!(PageException::from_cdp_value(&json!({"timestamp": 1.0})).is_none());
958    }
959
960    #[test]
961    fn the_typed_exception_round_trips_through_the_decoder() {
962        use chromiumoxide::cdp::js_protocol::runtime::EventExceptionThrown;
963        let typed: EventExceptionThrown = serde_json::from_value(exception_event()).unwrap();
964        let e = PageException::from_cdp_value(&serde_json::to_value(&typed).unwrap()).unwrap();
965        assert!(e.message().starts_with("Error: boom"));
966        assert_eq!(e.stack.len(), 2);
967        assert_eq!(e.timestamp_ms, 1760000000123.5);
968    }
969
970    #[test]
971    fn page_scale_must_be_positive_and_finite() {
972        assert_eq!(
973            serde_json::to_value(page_scale_params(1.5).unwrap()).unwrap(),
974            json!({"pageScaleFactor": 1.5})
975        );
976        for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {
977            assert!(matches!(
978                page_scale_params(bad),
979                Err(BrowserError::Invalid(_))
980            ));
981        }
982    }
983
984    #[test]
985    fn download_behaviour_carries_the_explicit_directory() {
986        let dir = tempfile::tempdir().unwrap();
987        let path = dir.path().to_path_buf();
988        let v = serde_json::to_value(
989            download_params(&DownloadBehavior::Allow { dir: path.clone() }).unwrap(),
990        )
991        .unwrap();
992        assert_eq!(v["behavior"], "allow");
993        assert_eq!(v["downloadPath"], &*path.to_string_lossy());
994        let v = serde_json::to_value(
995            download_params(&DownloadBehavior::AllowAndName { dir: path }).unwrap(),
996        )
997        .unwrap();
998        assert_eq!(v["behavior"], "allowAndName");
999        assert_eq!(
1000            serde_json::to_value(download_params(&DownloadBehavior::Deny).unwrap()).unwrap(),
1001            json!({"behavior": "deny"})
1002        );
1003        assert_eq!(
1004            serde_json::to_value(download_params(&DownloadBehavior::Default).unwrap()).unwrap(),
1005            json!({"behavior": "default"})
1006        );
1007    }
1008
1009    #[test]
1010    fn download_directory_must_be_absolute_and_exist() {
1011        let rel = DownloadBehavior::Allow {
1012            dir: PathBuf::from("downloads"),
1013        };
1014        assert!(matches!(
1015            download_params(&rel),
1016            Err(BrowserError::Invalid(_))
1017        ));
1018        let missing = tempfile::tempdir().unwrap().path().join("nope");
1019        let gone = DownloadBehavior::AllowAndName { dir: missing };
1020        assert!(matches!(
1021            download_params(&gone),
1022            Err(BrowserError::Invalid(_))
1023        ));
1024    }
1025
1026    #[test]
1027    fn ax_summary_drops_ignored_and_roleless_nodes() {
1028        let node = |role: Option<&str>, name: Option<&str>, ignored: bool| AxNode {
1029            node_id: "1".into(),
1030            ignored,
1031            role: role.map(str::to_string),
1032            name: name.map(str::to_string),
1033            description: None,
1034            value: None,
1035            properties: Vec::new(),
1036            parent_id: None,
1037            child_ids: Vec::new(),
1038            backend_dom_node_id: None,
1039            frame_id: Some("FRAME-1".into()),
1040        };
1041        let nodes = vec![
1042            node(Some("button"), Some("Save"), false),
1043            node(Some("generic"), None, true),
1044            node(None, Some("orphan"), false),
1045            node(Some(""), None, false),
1046            node(Some("link"), None, false),
1047        ];
1048        assert_eq!(
1049            summarize_ax(&nodes),
1050            vec![
1051                AxSummary {
1052                    role: "button".into(),
1053                    name: "Save".into(),
1054                    frame_id: "FRAME-1".into(),
1055                },
1056                AxSummary {
1057                    role: "link".into(),
1058                    name: String::new(),
1059                    frame_id: "FRAME-1".into(),
1060                },
1061            ]
1062        );
1063    }
1064}