Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions moli-cdp-smoke/moli_cdp_smoke/fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -971,6 +971,16 @@ def _dispatch(self) -> None:
f"globalThis.__semanticCacheRequest = {count};",
max_age=3600,
)
elif route == "/cached-image-redirect/first.png":
outer._increment_request_count(route)
self.send_response(HTTPStatus.MOVED_PERMANENTLY)
self.send_header("Location", "/cached-image-redirect/final.png")
self.send_header("Cache-Control", "public, max-age=600")
self.send_header("Content-Length", "0")
self.end_headers()
elif route == "/cached-image-redirect/final.png":
outer._increment_request_count(route)
self._send_png(TRANSPARENT_PNG)
elif route == "/semantic-resource-page":
self._send_cacheable(
"text/html; charset=utf-8",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,10 @@ async def settle() -> bool:
assert_equal(await page.evaluate("[...document.fonts].find(f => f.family === 'DispatchPaint').status"),
"loaded", f"{case} CSS font decoded")
elif kind == "css-image":
request_id = resource_requests()[-1]["requestId"]
request = resource_requests()[-1]
if is_moli_browser() and not worker and policy is None and admission in ("direct", "unmatched", "response"):
assert_equal(request["initiator"]["type"], "parser", f"{case} CSS image initiator")
request_id = request["requestId"]
body = await cdp.send("Network.getResponseBody", {"requestId": request_id})
data = base64.b64decode(body["body"]) if body.get("base64Encoded") else body["body"].encode()
assert_equal(data, expected_body, f"{case} complete image response body")
Expand Down
70 changes: 70 additions & 0 deletions moli-cdp-smoke/moli_cdp_smoke/groups/network.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import asyncio
import base64
import json
from pathlib import Path
Expand All @@ -9,6 +10,7 @@
from . import SmokeState
from ..assertions import SmokeError, assert_equal, wait_until
from ..config import is_moli_browser
from ..diagnostics import new_cdp_session
from ..fixture import TRANSPARENT_PNG
from ..helpers import isolated_network_page, read_io_to_eof, attach_cdp_event_collector, evaluate_xhr

Expand Down Expand Up @@ -2076,6 +2078,74 @@ def saw_completed_requests() -> bool:
"maxResourceBufferSize": 2_000_000,
},
)
if is_moli_browser():
await _verify_cached_image_redirect_with_response_interception(state)


async def _verify_cached_image_redirect_with_response_interception(state: SmokeState) -> None:
first_path = "/cached-image-redirect/first.png"
final_path = "/cached-image-redirect/final.png"
first_url, final_url = (state.fixture + path for path in (first_path, final_path))
start_image = """url => {
const image = new Image();
globalThis.cachedRedirectImageLoaded = new Promise(resolve => {
image.onload = () => resolve(image.naturalWidth > 0);
image.onerror = () => resolve(false);
});
image.src = url;
document.body.append(image);
}"""
async with isolated_network_page(state) as isolated:
await isolated.page.evaluate(start_image, first_url)
async with asyncio.timeout(10):
assert_equal(await isolated.page.evaluate("cachedRedirectImageLoaded"), True, "prime image redirect cache")
await wait_until(
lambda: bool(_completed_request_id(isolated.subresource_events, "Image", final_url)),
"image redirect cache priming completed",
)
# A new target uses the same HTTP cache without reusing the decoded image.
await isolated.page.close()
page = await isolated.context.new_page()
await page.goto(f"{state.fixture}/plain", wait_until="load", timeout=10_000)
cdp = await new_cdp_session(isolated.context, page)
await cdp.send("Network.enable")
await cdp.send("Fetch.enable", {"patterns": [{
"resourceType": "Image", "urlPattern": "*", "requestStage": "Response",
}]})
with attach_cdp_event_collector(cdp, [
"Fetch.requestPaused", "Network.requestWillBeSent", "Network.requestServedFromCache",
"Network.requestWillBeSentExtraInfo", "Network.responseReceivedExtraInfo",
"Network.loadingFinished",
]) as events:
await page.evaluate(start_image, first_url)
await wait_until(lambda: any(e["method"] == "Fetch.requestPaused" for e in events),
"cached redirect final image response pause")
pause = next(e["params"] for e in events if e["method"] == "Fetch.requestPaused")
assert_equal(pause["responseStatusCode"], 200, "cached redirect final image response status")
network_id = pause["networkId"]
await cdp.send("Fetch.continueResponse", {"requestId": pause["requestId"]})
async with asyncio.timeout(10):
assert_equal(await page.evaluate("cachedRedirectImageLoaded"), True, "intercepted cached redirect image loaded")
await wait_until(lambda: any(e["method"] == "Network.loadingFinished" and
e["params"]["requestId"] == network_id for e in events),
"cached redirect image Network completion")
requests = [e["params"] for e in events if e["method"] == "Network.requestWillBeSent"
and e["params"]["request"]["url"] in (first_url, final_url)]
assert_equal([(p["request"]["url"], p["requestId"]) for p in requests],
[(first_url, network_id), (final_url, network_id)], "cached redirect request URLs and IDs")
assert_equal(requests[1]["redirectResponse"]["url"], first_url, "cached redirect preceding response URL")
assert_equal(requests[1]["redirectResponse"]["status"], 301, "cached redirect preceding response status")
assert_equal(requests[1]["redirectHasExtraInfo"], False, "cached hop has no wire ExtraInfo")
methods = [e["method"] for e in events if e["params"].get("requestId") == network_id]
assert_equal(methods, ["Network.requestWillBeSent", "Network.requestServedFromCache",
"Network.requestWillBeSent", "Network.requestWillBeSentExtraInfo",
"Network.responseReceivedExtraInfo", "Network.loadingFinished"],
"cached redirect Network event order")
origin_hits = await page.evaluate("""async ([first, final]) => Promise.all([first, final].map(path =>
fetch('/fetch-dispatch/status?path=' + encodeURIComponent(path))
.then(response => response.json()).then(result => result.requests)))""", [first_path, final_path])
assert_equal(origin_hits, [1, 2], "the cached first hop avoids a second origin dispatch")
state.record("network_cached_image_redirect_response_interception")


async def _verify_blocked_websocket_events(state: SmokeState) -> None:
Expand Down
64 changes: 57 additions & 7 deletions moli-fetch/src/network_fetch_result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use moli_cookie_jar::StoredCookieQueryReport;
use parking_lot::Mutex;
use url::Url;

use crate::RedirectInfo;
use crate::{NetworkRequestExtraInfo, RedirectInfo, Request};

const MAX_OBSERVED_EXCHANGES: usize = 32;
const MAX_OBSERVED_HEADER_BLOCK_BYTES: usize = 256 * 1024;
Expand Down Expand Up @@ -197,6 +197,27 @@ pub(crate) struct NetworkObservationRecorder {
state: Arc<Mutex<NetworkObservationRecorderState>>,
}

#[derive(Clone)]
pub(crate) struct NetworkRequestObserver(
Arc<dyn Fn(Vec<RedirectInfo>, NetworkRequestExtraInfo) + Send + Sync>,
);

impl NetworkRequestObserver {
pub(crate) fn new(
observer: impl Fn(Vec<RedirectInfo>, NetworkRequestExtraInfo) + Send + Sync + 'static,
) -> Self {
Self(Arc::new(observer))
}
}

impl fmt::Debug for NetworkRequestObserver {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("NetworkRequestObserver")
.finish_non_exhaustive()
}
}

impl fmt::Debug for NetworkObservationRecorder {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let state = self.state.lock();
Expand All @@ -209,11 +230,19 @@ impl fmt::Debug for NetworkObservationRecorder {
}

impl NetworkObservationRecorder {
pub(crate) fn set_current_request_cookie_report(
pub(crate) fn begin_request(
&self,
request: &Request,
cookie_report: Option<StoredCookieQueryReport>,
) {
self.state.lock().current_request_cookie_report = cookie_report;
let mut state = self.state.lock();
state.current_request_cookie_report = cookie_report;
state.request_observer = request.network_request_observer().cloned();
state.redirect_chain = if state.request_observer.is_some() {
request.redirect_chain().to_vec()
} else {
Vec::new()
};
}

pub(crate) fn record_request_header_block(&self, data: &[u8]) {
Expand All @@ -223,13 +252,31 @@ impl NetworkObservationRecorder {
state.journal.truncated = true;
return;
}
let cookie_report = state.current_request_cookie_report.clone();
let request = NetworkRequestObservation::from_header_block(
data,
state.current_request_cookie_report.clone(),
);
let hop = state.redirect_chain.len();
let notification = if state.last_reported_hop == Some(hop) {
None
} else {
state.request_observer.take().map(|observer| {
state.last_reported_hop = Some(hop);
let info = NetworkRequestExtraInfo {
headers: request.headers.clone(),
cookie_report: request.cookie_report.clone().unwrap_or_default(),
};
(observer, std::mem::take(&mut state.redirect_chain), info)
})
};
state
.journal
.exchanges
.push(NetworkExchangeObservation::request_only(
NetworkRequestObservation::from_header_block(data, cookie_report),
));
.push(NetworkExchangeObservation::request_only(request));
drop(state);
if let Some((observer, redirects, info)) = notification {
(observer.0)(redirects, info);
}
}

pub(crate) fn record_response_header_line(&self, data: &[u8]) {
Expand Down Expand Up @@ -298,6 +345,9 @@ impl NetworkObservationRecorder {
struct NetworkObservationRecorderState {
journal: NetworkObservationJournal,
current_request_cookie_report: Option<StoredCookieQueryReport>,
redirect_chain: Vec<RedirectInfo>,
last_reported_hop: Option<usize>,
request_observer: Option<NetworkRequestObserver>,
pending_response: Option<PendingResponseObservation>,
}

Expand Down
23 changes: 21 additions & 2 deletions moli-fetch/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use moli_url::{WebOrigin, same_origin};
use url::Url;

use crate::{
FetchConfig, FetchPriorityHint, FetchUrlList, RedirectInfo,
network_fetch_result::NetworkObservationRecorder,
FetchConfig, FetchPriorityHint, FetchUrlList, NetworkRequestExtraInfo, RedirectInfo,
network_fetch_result::{NetworkObservationRecorder, NetworkRequestObserver},
};

/// Plain HTTP exchanges and browser Fetch requests have different security
Expand Down Expand Up @@ -87,6 +87,7 @@ pub struct Request {
pub cookie_context: NetworkCookieRequestContext,
timeout_policy: RequestTimeoutPolicy,
network_observation_recorder: Option<NetworkObservationRecorder>,
network_request_observer: Option<NetworkRequestObserver>,
browser_identity: Option<std::sync::Arc<moli_browser_profile::BrowserIdentityProfile>>,
redirect_policy: Option<RequestRedirectPolicy>,
}
Expand Down Expand Up @@ -638,6 +639,7 @@ impl Request {
cookie_context: NetworkCookieRequestContext::top_level_navigation("GET"),
timeout_policy: RequestTimeoutPolicy::default(),
network_observation_recorder: None,
network_request_observer: None,
browser_identity: None,
redirect_policy: None,
})
Expand Down Expand Up @@ -678,6 +680,7 @@ impl Request {
cookie_context: NetworkCookieRequestContext::top_level_navigation("GET"),
timeout_policy: RequestTimeoutPolicy::default(),
network_observation_recorder: None,
network_request_observer: None,
browser_identity: None,
redirect_policy: None,
}
Expand Down Expand Up @@ -751,6 +754,7 @@ impl Request {
cookie_context: NetworkCookieRequestContext::subresource(method),
timeout_policy: RequestTimeoutPolicy::default(),
network_observation_recorder: None,
network_request_observer: None,
browser_identity: None,
redirect_policy: None,
}
Expand Down Expand Up @@ -1042,6 +1046,21 @@ impl Request {
self.network_observation_recorder.as_ref()
}

/// On fetches with network metadata, report the first HTTP request header
/// block for each hop. The callback runs on the fetch thread and receives
/// the redirects already followed and that hop's request headers and cookie report.
pub fn with_network_request_observer(
mut self,
observer: impl Fn(Vec<RedirectInfo>, NetworkRequestExtraInfo) + Send + Sync + 'static,
) -> Self {
self.network_request_observer = Some(NetworkRequestObserver::new(observer));
self
}

pub(crate) fn network_request_observer(&self) -> Option<&NetworkRequestObserver> {
self.network_request_observer.as_ref()
}

pub fn redirect_handling(&self) -> RequestRedirectHandling {
self.redirect_handling
}
Expand Down
50 changes: 25 additions & 25 deletions moli-fetch/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -955,14 +955,6 @@ impl RuntimeOwner {
Ok(route) => route,
Err(error) => return Err((job.response_tx, error)),
};
if let Err(error) = configure_network_observation(
&mut easy,
&job.request,
request_cookie_report.as_ref(),
proxy_route.is_proxy() && job.current_url.scheme() == "https",
) {
return Err((job.response_tx, error));
}
let outgoing_headers = match configure_easy(
&mut easy,
&self.config,
Expand Down Expand Up @@ -994,6 +986,14 @@ impl RuntimeOwner {
request_cookie_report.clone(),
request_extra_info.as_ref(),
);
if let Err(error) = configure_network_observation(
&mut easy,
&job.request,
request_cookie_report.as_ref(),
proxy_route.is_proxy() && job.current_url.scheme() == "https",
) {
return Err((job.response_tx, error));
}

let label = job.current_url.to_string();
let dns_resolution = match curl_dns_resolution(&self.config, &job.current_url, &proxy_route)
Expand Down Expand Up @@ -1168,14 +1168,6 @@ impl RuntimeOwner {
Ok(route) => route,
Err(error) => return Err((Box::new(job), Some(easy), error)),
};
if let Err(error) = configure_network_observation(
&mut easy,
&job.request,
request_cookie_report.as_ref(),
proxy_route.is_proxy() && job.current_url.scheme() == "https",
) {
return Err((Box::new(job), Some(easy), error));
}
let outgoing_headers = match configure_easy(
&mut easy,
&self.config,
Expand Down Expand Up @@ -1205,6 +1197,14 @@ impl RuntimeOwner {
request_cookie_report.clone(),
request_extra_info.as_ref(),
);
if let Err(error) = configure_network_observation(
&mut easy,
&job.request,
request_cookie_report.as_ref(),
proxy_route.is_proxy() && job.current_url.scheme() == "https",
) {
return Err((Box::new(job), Some(easy), error));
}
let collector = easy
.get_mut()
.streaming_mut()
Expand Down Expand Up @@ -1406,14 +1406,6 @@ impl RuntimeOwner {
Ok(route) => route,
Err(error) => return Err((Box::new(job), Some(easy), error)),
};
if let Err(error) = configure_network_observation(
&mut easy,
&job.request,
request_cookie_report.as_ref(),
proxy_route.is_proxy() && job.current_url.scheme() == "https",
) {
return Err((Box::new(job), Some(easy), error));
}
let outgoing_headers = match configure_easy(
&mut easy,
&self.config,
Expand Down Expand Up @@ -1445,6 +1437,14 @@ impl RuntimeOwner {
request_cookie_report.clone(),
request_extra_info.as_ref(),
);
if let Err(error) = configure_network_observation(
&mut easy,
&job.request,
request_cookie_report.as_ref(),
proxy_route.is_proxy() && job.current_url.scheme() == "https",
) {
return Err((Box::new(job), Some(easy), error));
}
let collector = easy
.get_mut()
.raw_streaming_mut()
Expand Down Expand Up @@ -3059,7 +3059,7 @@ fn configure_network_observation(
let recorder = request.network_observation_recorder().cloned();
let verbose = recorder.is_some() || capture_proxy_connect_response;
if let Some(recorder) = recorder.as_ref() {
recorder.set_current_request_cookie_report(request_cookie_report.cloned());
recorder.begin_request(request, request_cookie_report.cloned());
}
easy.get_mut()
.begin_transfer(recorder, capture_proxy_connect_response);
Expand Down
Loading
Loading