Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: Blob shared per origin

Karl Seguin86bf28216ad0
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zig
index 0a78cd0e2..0f8add6e4 100644
--- a/src/browser/Frame.zig
+++ b/src/browser/Frame.zig
@@ -169,9 +169,6 @@ _manual_slot_assignments: Node.AssignedSlotLookup = .empty,
/// ```
_event_target_attr_listeners: GlobalEventHandlersLookup = .empty,
-// Blob URL registry for URL.createObjectURL/revokeObjectURL
-_blob_urls: std.StringHashMapUnmanaged(*Blob) = .{},
-
// FileLists owned by `<input type=file>` elements. Each holds refs on its
// File objects (reference counted via their Blob proto); released at teardown.
_file_lists: std.ArrayList(*FileList) = .{},
@@ -188,7 +185,7 @@ _queued_events: *std.ArrayList(QueuedEvent) = undefined,
_style_manager: StyleManager,
_script_manager: ScriptManager,
-_http_owner: HttpClient.Owner = .{},
+_http_owner: HttpClient.Owner,
// List of active live ranges (for mutation updates per DOM spec)
_live_ranges: std.DoublyLinkedList = .{},
@@ -378,9 +375,10 @@ pub fn init(self: *Frame, frame_id: u32, page: *Page, opts: InitOpts) !void {
._script_manager = undefined,
._ce_reactions = .{ .allocator = arena },
._event_manager = EventManager.init(arena, self),
+ ._http_owner = undefined,
};
self._queued_events = &self._queued_events_1;
- self._http_owner.blob_urls = &self._blob_urls;
+ self._http_owner = .init(&page.blob_urls, &self.origin);
var screen: *Screen = undefined;
var visual_viewport: *VisualViewport = undefined;
@@ -489,12 +487,7 @@ pub fn deinit(self: *Frame) void {
{
// Release all objects we're referencing
- {
- var it = self._blob_urls.valueIterator();
- while (it.next()) |blob| {
- blob.*.releaseRef(page);
- }
- }
+ page.revokeBlobUrlsFor(self._frame_id);
for (self._file_lists.items) |file_list| {
for (file_list._files) |file| {
@@ -639,6 +632,13 @@ pub fn navigate(self: *Frame, request_url: [:0]const u8, opts: NavigateOpts) !vo
const is_blob = !is_about_blank and std.mem.startsWith(u8, request_url, "blob:");
if (is_about_blank or is_blob) {
+ if (is_blob) {
+ if (!Blob.urlBelongsToOrigin(request_url, opts.initiator_origin)) {
+ log.warn(.js, "invalid blob", .{ .url = request_url });
+ return error.BlobNotFound;
+ }
+ }
+
self.url = if (is_about_blank) "about:blank" else try self.arena.dupeZ(u8, request_url);
// even though about:blank navigations may share the same _data_, we
@@ -675,14 +675,8 @@ pub fn navigate(self: *Frame, request_url: [:0]const u8, opts: NavigateOpts) !vo
// Content injection
if (is_blob) {
- // For navigation, walk up the parent chain to find blob URLs
- // (e.g., parent creates blob URL and sets iframe.src to it)
const blob = blk: {
- var current: ?*Frame = self.parent;
- while (current) |frame| {
- if (frame._blob_urls.get(request_url)) |b| break :blk b;
- current = frame.parent;
- }
+ if (self._page.blob_urls.get(request_url)) |entry| break :blk entry.blob;
log.warn(.js, "invalid blob", .{ .url = request_url });
return error.BlobNotFound;
};
@@ -960,6 +954,11 @@ fn scheduleNavigationWithArena(originator: *Frame, arena: Allocator, request_url
nav_opts.initiator_url = dup;
}
}
+ if (nav_opts.initiator_origin == null) {
+ if (originator.origin) |o| {
+ nav_opts.initiator_origin = try arena.dupe(u8, o);
+ }
+ }
const qn = try arena.create(QueuedNavigation);
qn.* = .{
@@ -1819,6 +1818,7 @@ pub fn iframeAddedCallback(self: *Frame, iframe: *IFrame) !void {
.reason = .initialFrameNavigation,
.referer = parent_url,
.initiator_url = parent_url,
+ .initiator_origin = self.origin,
}) catch |err| {
// extra defensive..maybe navigate added a new frame, and the index it
// was added at was removed. Or maybe this frame was removed somehow
@@ -1918,7 +1918,7 @@ pub fn openPopup(self: *Frame, opts: OpenPopupOpts) !*Frame {
// not impossible that navigate adds popups, so remove by index
errdefer _ = page.popups.swapRemove(popup_index);
- popup.navigate(resolved_url, .{ .reason = .script }) catch |err| {
+ popup.navigate(resolved_url, .{ .reason = .script, .initiator_origin = self.origin }) catch |err| {
log.warn(.frame, "popup navigate failure", .{ .url = resolved_url, .err = err });
return err;
};
@@ -2181,7 +2181,7 @@ pub fn loadExternalStylesheet(self: *Frame, link: *Element.Html.Link, href: []co
.resource_type = .stylesheet,
.notification = session.notification,
.shutdown_callback = HttpClient.noopShutdown, // syncRequest installs its own
- }) catch |err| {
+ }, &self._http_owner) catch |err| {
log.warn(.http, "external stylesheet fetch", .{ .err = err, .url = resolved });
return self.fireElementEvent(element, comptime .wrap("error"));
};
@@ -3156,6 +3156,7 @@ pub const NavigateOpts = struct {
// because a Referrer-Policy can suppress the Referer header without
// affecting SameSite (which always considers the real initiator).
initiator_url: ?[:0]const u8 = null,
+ initiator_origin: ?[]const u8 = null,
force: bool = false,
kind: NavigationKind = .{ .push = null },
};
@@ -3481,6 +3482,12 @@ test "WebApi: Frames" {
try testing.htmlRunner("frames", .{});
}
+test "WebApi: Frame Blob" {
+ const filter: testing.LogFilter = .init(&.{.frame, .browser, .js});
+ defer filter.deinit();
+ try testing.htmlRunner("frames/blob", .{});
+}
+
test "WebApi: Integration" {
try testing.htmlRunner("integration", .{});
}
diff --git a/src/browser/Page.zig b/src/browser/Page.zig
index d63c467ef..ff95daa5e 100644
--- a/src/browser/Page.zig
+++ b/src/browser/Page.zig
@@ -27,6 +27,7 @@ const Session = @import("Session.zig");
const Factory = @import("Factory.zig");
const Viewport = @import("Viewport.zig");
+const Blob = @import("webapi/Blob.zig");
const SharedWorkerGlobalScope = @import("webapi/SharedWorkerGlobalScope.zig");
const v8 = js.v8;
@@ -74,6 +75,9 @@ frame_arena: Allocator,
// lifetime.
origins: std.StringHashMapUnmanaged(*js.Origin) = .empty,
+// Blob URL store for URL.createObjectURL.
+blob_urls: Blob.UrlMap = .empty,
+
// Identity tracking for the main world. All main-world contexts in this Page
// share this, ensuring object identity works across same-origin frames.
identity: js.Identity = .{},
@@ -177,6 +181,19 @@ pub fn deinit(self: *Page) void {
}
self.shared_workers = .empty;
+ {
+ if (comptime IS_DEBUG) {
+ std.debug.assert(self.blob_urls.count() == 0);
+ }
+
+ // Defensive cleanup
+ var it = self.blob_urls.valueIterator();
+ while (it.next()) |entry| {
+ entry.blob.releaseRef(self);
+ }
+ self.blob_urls = .empty;
+ }
+
const session = self.session;
lp.metrics.js_heap_size_bytes.observe(session.browser.env.isolate.getHeapStatistics().total_physical_size);
defer session.browser.env.memoryPressureNotification(.moderate);
@@ -245,6 +262,35 @@ pub fn getOrCreateOrigin(self: *Page, key_: ?[]const u8) !*js.Origin {
return origin;
}
+pub fn createBlobUrl(self: *Page, blob: *Blob, origin: ?[]const u8, creator_frame_id: u32) ![]const u8 {
+ var uuid: [36]u8 = undefined;
+ @import("../id.zig").uuidv4(&uuid);
+
+ const url = try std.fmt.allocPrint(self.frame_arena, "blob:{s}/{s}", .{ origin orelse "null", uuid });
+ try self.blob_urls.put(self.frame_arena, url, .{ .blob = blob, .creator = creator_frame_id });
+ blob.acquireRef();
+ return url;
+}
+
+pub fn revokeBlobUrl(self: *Page, url: []const u8) void {
+ if (self.blob_urls.fetchRemove(url)) |entry| {
+ entry.value.blob.releaseRef(self);
+ }
+}
+
+pub fn revokeBlobUrlsFor(self: *Page, creator: u32) void {
+ var it = self.blob_urls.iterator();
+ while (it.next()) |entry| {
+ if (entry.value_ptr.creator != creator) {
+ continue;
+ }
+ entry.value_ptr.blob.releaseRef(self);
+ self.blob_urls.removeByPtr(entry.key_ptr);
+ // Removal invalidates the iterator; restart. Entry counts are tiny.
+ it = self.blob_urls.iterator();
+ }
+}
+
pub fn releaseOrigin(self: *Page, origin: *js.Origin) void {
const rc = origin.rc;
if (rc == 1) {
diff --git a/src/browser/ScriptManager.zig b/src/browser/ScriptManager.zig
index 26c90f0cb..9dc324690 100644
--- a/src/browser/ScriptManager.zig
+++ b/src/browser/ScriptManager.zig
@@ -365,7 +365,7 @@ pub fn addFromElement(self: *ScriptManager, comptime from_parser: bool, script_e
.resource_type = .script,
.notification = frame._session.notification,
.shutdown_callback = HttpClient.noopShutdown, // syncRequest installs its own
- });
+ }, &frame._http_owner);
script.source = .{ .remote = response.body };
script.status = response.status;
diff --git a/src/browser/tests/frames/blob/blob_url.html b/src/browser/tests/frames/blob/blob_url.html
new file mode 100644
index 000000000..24cb817f5
--- /dev/null
+++ b/src/browser/tests/frames/blob/blob_url.html
@@ -0,0 +1,159 @@
+<!DOCTYPE html>
+<script src="../../testing.js"></script>
+<body></body>
+
+<!--
+ Blob URLs are scoped to an origin, not to the frame that created them: any
+ same-origin context (iframe, popup, worker) must be able to resolve them.
+ Messages are tagged — the test scripts run concurrently and all listen on
+ the same window.
+-->
+
+<script id=iframe_fetches_parent_blob type=module>
+ {
+ const state = await testing.async();
+ window.addEventListener('message', function handler(e) {
+ if (!e.data || e.data.t !== 'iframe_fetch') return;
+ window.removeEventListener('message', handler);
+ state.resolve(e.data.v);
+ });
+
+ const blobUrl = URL.createObjectURL(new Blob(['parent-payload'], { type: 'text/plain' }));
+
+ const iframe = document.createElement('iframe');
+ document.documentElement.appendChild(iframe);
+ const doc = iframe.contentDocument;
+ doc.write('<!DOCTYPE html><html><body><script>' +
+ "fetch('" + blobUrl + "').then((r) => r.text()).then(" +
+ " (v) => parent.postMessage({ t: 'iframe_fetch', v }, '*')," +
+ " (err) => parent.postMessage({ t: 'iframe_fetch', v: 'error: ' + err }, '*'));" +
+ '<\/script></body></html>');
+ doc.close();
+
+ await state.done((data) => {
+ testing.expectEqual('parent-payload', data);
+ URL.revokeObjectURL(blobUrl);
+ });
+ }
+</script>
+
+<script id=parent_fetches_iframe_blob type=module>
+ {
+ const state = await testing.async();
+
+ const iframe = document.createElement('iframe');
+ document.documentElement.appendChild(iframe);
+ const doc = iframe.contentDocument;
+ doc.write('<!DOCTYPE html><html><body><script>' +
+ "window.blobUrl = URL.createObjectURL(new Blob(['iframe-payload'], { type: 'text/plain' }));" +
+ '<\/script></body></html>');
+ doc.close();
+
+ const blobUrl = iframe.contentWindow.blobUrl;
+ const result = await fetch(blobUrl).then(
+ (r) => r.text(),
+ (err) => 'error: ' + err,
+ );
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual('iframe-payload', result);
+ });
+ }
+</script>
+
+<script id=iframe_blocking_script_from_blob type=module>
+ {
+ // A parser-inserted <script src> is fetched synchronously (syncRequest);
+ // the parent-minted blob URL must resolve through the iframe's owner.
+ const blobUrl = URL.createObjectURL(new Blob(["window.blobScriptRan = 'yes';"], { type: 'text/javascript' }));
+
+ const iframe = document.createElement('iframe');
+ document.documentElement.appendChild(iframe);
+ const doc = iframe.contentDocument;
+ doc.write('<!DOCTYPE html><html><body><script src="' + blobUrl + '"><\/script></body></html>');
+ doc.close();
+
+ testing.expectEqual('yes', iframe.contentWindow.blobScriptRan);
+ URL.revokeObjectURL(blobUrl);
+ }
+</script>
+
+<script id=cross_origin_iframe_cannot_fetch_blob type=module>
+ {
+ // A data: document has an opaque origin; even knowing the URL, its fetch
+ // of a parent-minted blob URL must be rejected.
+ const state = await testing.async();
+ window.addEventListener('message', function handler(e) {
+ if (!e.data || e.data.t !== 'xorigin_blob') return;
+ window.removeEventListener('message', handler);
+ state.resolve(e.data.v);
+ });
+
+ const blobUrl = URL.createObjectURL(new Blob(['secret'], { type: 'text/plain' }));
+
+ const iframe = document.createElement('iframe');
+ iframe.src = "data:text/html,<script>" +
+ "fetch('" + blobUrl + "').then((r) => r.text()).then(" +
+ " (v) => parent.postMessage({ t: 'xorigin_blob', v: 'got: ' + v }, '*')," +
+ " () => parent.postMessage({ t: 'xorigin_blob', v: 'rejected' }, '*'));" +
+ "<\/script>";
+ document.documentElement.appendChild(iframe);
+
+ await state.done((data) => {
+ testing.expectEqual('rejected', data);
+ URL.revokeObjectURL(blobUrl);
+ });
+ }
+</script>
+
+<script id=cross_origin_iframe_cannot_navigate_to_blob type=module>
+ {
+ // If the navigation were allowed, the blob document would load and post
+ // 'navigated'. When refused, nothing observable happens in the iframe
+ // (the queued re-navigation already tore its document down), so give the
+ // navigation a beat and assert no message arrived.
+ const state = await testing.async();
+ let result = 'blocked';
+ window.addEventListener('message', function handler(e) {
+ if (!e.data || e.data.t !== 'xorigin_blob_nav') return;
+ window.removeEventListener('message', handler);
+ result = e.data.v;
+ });
+
+ const html = "<script>parent.postMessage({ t: 'xorigin_blob_nav', v: 'navigated' }, '*')<\/script>";
+ const blobUrl = URL.createObjectURL(new Blob([html], { type: 'text/html' }));
+
+ const iframe = document.createElement('iframe');
+ iframe.src = "data:text/html,<script>location.href = '" + blobUrl + "';<\/script>";
+ document.documentElement.appendChild(iframe);
+
+ setTimeout(() => state.resolve(), 75);
+ await state.done(() => {
+ testing.expectEqual('blocked', result);
+ URL.revokeObjectURL(blobUrl);
+ });
+ }
+</script>
+
+<script id=popup_navigates_to_blob type=module>
+ {
+ const state = await testing.async();
+ window.addEventListener('message', function handler(e) {
+ if (!e.data || e.data.t !== 'popup_nav') return;
+ window.removeEventListener('message', handler);
+ state.resolve(e.data.v);
+ });
+
+ const html = "<body><p id=marker>loaded</p><script>" +
+ "opener.postMessage({ t: 'popup_nav', v: document.getElementById('marker').textContent }, '*');" +
+ "<\/script></body>";
+ const blobUrl = URL.createObjectURL(new Blob([html], { type: 'text/html' }));
+ const w = window.open(blobUrl);
+
+ await state.done((data) => {
+ testing.expectEqual('loaded', data);
+ w.close();
+ URL.revokeObjectURL(blobUrl);
+ });
+ }
+</script>
diff --git a/src/browser/tests/shared_worker/shared_worker.html b/src/browser/tests/shared_worker/shared_worker.html
index 30757854c..18eb00891 100644
--- a/src/browser/tests/shared_worker/shared_worker.html
+++ b/src/browser/tests/shared_worker/shared_worker.html
@@ -105,6 +105,29 @@
}
</script>
+<script id="shared_worker_from_blob_url" type=module>
+ // A blob: SharedWorker must resolve its initial script even though the
+ // fetch goes through the worker's own HTTP owner, not the creating
+ // frame's — blob URLs are resolvable from any same-origin context.
+ {
+ const state = await testing.async();
+ const blob = new Blob([
+ "onconnect = (e) => { const port = e.ports[0]; port.onmessage = (m) => port.postMessage({ echo: m.data, from: 'blob-shared-worker' }); };",
+ ], { type: 'text/javascript' });
+ const blobUrl = URL.createObjectURL(blob);
+ const worker = new SharedWorker(blobUrl);
+
+ worker.port.onmessage = (event) => state.resolve(event.data);
+ worker.port.postMessage('hi');
+
+ await state.done((response) => {
+ testing.expectEqual('hi', response.echo);
+ testing.expectEqual('blob-shared-worker', response.from);
+ URL.revokeObjectURL(blobUrl);
+ });
+ }
+</script>
+
<script id="shared_worker_structured_clone" type=module>
// Messages cross a context boundary: the receiver gets an independent
// structured clone, and unserializable values throw a DataCloneError.
diff --git a/src/browser/tests/worker/fetch-url-worker.js b/src/browser/tests/worker/fetch-url-worker.js
new file mode 100644
index 000000000..325771e26
--- /dev/null
+++ b/src/browser/tests/worker/fetch-url-worker.js
@@ -0,0 +1,8 @@
+onmessage = async (e) => {
+ try {
+ const res = await fetch(e.data);
+ postMessage({ ok: true, text: await res.text() });
+ } catch (err) {
+ postMessage({ ok: false, err: String(err) });
+ }
+};
diff --git a/src/browser/tests/worker/import-blob-worker.js b/src/browser/tests/worker/import-blob-worker.js
new file mode 100644
index 000000000..ed9233925
--- /dev/null
+++ b/src/browser/tests/worker/import-blob-worker.js
@@ -0,0 +1,8 @@
+onmessage = (e) => {
+ try {
+ importScripts(e.data);
+ postMessage({ ok: true, value: self.importedValue });
+ } catch (err) {
+ postMessage({ ok: false, err: String(err) });
+ }
+};
diff --git a/src/browser/tests/worker/worker.html b/src/browser/tests/worker/worker.html
index 23201b9bd..cd3512535 100644
--- a/src/browser/tests/worker/worker.html
+++ b/src/browser/tests/worker/worker.html
@@ -484,6 +484,43 @@
}
</script>
+<script id="worker_fetch_page_blob_url" type=module>
+ // A blob URL created on the page must be fetchable from inside the worker:
+ // blob URLs are resolvable from any same-origin context, not just the
+ // creating frame.
+ {
+ const state = await testing.async();
+ const blobUrl = URL.createObjectURL(new Blob(['blob-payload'], { type: 'text/plain' }));
+ const worker = new Worker('./fetch-url-worker.js');
+ worker.onmessage = (event) => state.resolve(event.data);
+ worker.postMessage(blobUrl);
+
+ await state.done((data) => {
+ testing.expectTrue(data.ok, 'worker blob fetch failed: ' + data.err);
+ testing.expectEqual('blob-payload', data.text);
+ URL.revokeObjectURL(blobUrl);
+ });
+ }
+</script>
+
+<script id="worker_importscripts_blob_url" type=module>
+ // importScripts fetches synchronously (syncRequest); the blob URL minted
+ // on the page must resolve through the worker's owner.
+ {
+ const state = await testing.async();
+ const blobUrl = URL.createObjectURL(new Blob(["self.importedValue = 'from-blob-import';"], { type: 'text/javascript' }));
+ const worker = new Worker('./import-blob-worker.js');
+ worker.onmessage = (event) => state.resolve(event.data);
+ worker.postMessage(blobUrl);
+
+ await state.done((data) => {
+ testing.expectTrue(data.ok, 'importScripts(blob) failed: ' + data.err);
+ testing.expectEqual('from-blob-import', data.value);
+ URL.revokeObjectURL(blobUrl);
+ });
+ }
+</script>
+
<script id="worker_from_blob_url_revoked_before_delivery" type=module>
// Revoking right after construction must not invalidate the queued
// script response: it's delivered on a later tick, after the blob's
diff --git a/src/browser/webapi/Blob.zig b/src/browser/webapi/Blob.zig
index 4b7dfbfda..0b03d63b4 100644
--- a/src/browser/webapi/Blob.zig
+++ b/src/browser/webapi/Blob.zig
@@ -51,6 +51,24 @@ pub const Type = union(enum) {
file: *@import("File.zig"),
};
+// Stored in Page.blob_urls.
+pub const UrlEntry = struct {
+ blob: *Blob,
+ creator: u32, // frame_id of creator
+};
+pub const UrlMap = std.StringHashMapUnmanaged(UrlEntry);
+
+// A blob URL is encoded as: blob:{origin}/{uuid}. So, given an origin, we can
+// check if it should be able to access a given bolb URL.
+pub fn urlBelongsToOrigin(url: []const u8, origin_: ?[]const u8) bool {
+ const origin = origin_ orelse "null";
+ if (!std.mem.startsWith(u8, url, "blob:")) {
+ return false;
+ }
+ const rest = url["blob:".len..];
+ return rest.len > origin.len and rest[origin.len] == '/' and std.mem.startsWith(u8, rest, origin);
+}
+
const InitOptions = struct {
/// MIME type.
type: []const u8 = "",
diff --git a/src/browser/webapi/URL.zig b/src/browser/webapi/URL.zig
index b130275e5..102289700 100644
--- a/src/browser/webapi/URL.zig
+++ b/src/browser/webapi/URL.zig
@@ -317,34 +317,20 @@ pub fn canParse(url: []const u8, maybe_base: ?[]const u8) bool {
}
pub fn createObjectURL(blob: *Blob, exec: *const Execution) ![]const u8 {
- var uuid_buf: [36]u8 = undefined;
- @import("../../id.zig").uuidv4(&uuid_buf);
-
switch (exec.js.global) {
- inline else => |g| {
- const blob_url = try std.fmt.allocPrint(
- g.arena,
- "blob:{s}/{s}",
- .{ g.origin orelse "null", uuid_buf },
- );
- try g._blob_urls.put(g.arena, blob_url, blob);
- blob.acquireRef();
- return blob_url;
- },
+ inline else => |g| return g._page.createBlobUrl(blob, g.origin, g._frame_id),
}
}
pub fn revokeObjectURL(url: []const u8, exec: *const Execution) void {
- // Per spec: silently ignore non-blob URLs
- if (!std.mem.startsWith(u8, url, "blob:")) {
- return;
- }
-
switch (exec.js.global) {
inline else => |g| {
- if (g._blob_urls.fetchRemove(url)) |entry| {
- entry.value.releaseRef(g._page);
+ if (!Blob.urlBelongsToOrigin(url, g.origin)) {
+ // different origin cannot revoke an object URL. Failure should
+ // be silent
+ return;
}
+ g._page.revokeBlobUrl(url);
},
}
}
diff --git a/src/browser/webapi/WorkerGlobalScope.zig b/src/browser/webapi/WorkerGlobalScope.zig
index 85c707ed3..f9282718c 100644
--- a/src/browser/webapi/WorkerGlobalScope.zig
+++ b/src/browser/webapi/WorkerGlobalScope.zig
@@ -33,7 +33,6 @@ const HttpClient = @import("../../network/HttpClient.zig");
const EventManagerBase = @import("../EventManagerBase.zig");
const ScriptManagerBase = @import("../ScriptManagerBase.zig");
-const Blob = @import("Blob.zig");
const Event = @import("Event.zig");
const Crypto = @import("Crypto.zig");
const Console = @import("Console.zig");
@@ -69,7 +68,7 @@ _page: *Page,
_session: *Session,
_factory: *Factory,
_identity: JS.Identity = .{},
-_http_owner: HttpClient.Owner = .{},
+_http_owner: HttpClient.Owner,
arena: Allocator,
call_arena: Allocator,
@@ -82,9 +81,6 @@ buf: [1024]u8 = undefined, // same size as frame.buf
charset: []const u8 = "UTF-8",
js: *JS.Context,
-// Blob URL registry for URL.createObjectURL/revokeObjectURL.
-_blob_urls: std.StringHashMapUnmanaged(*Blob) = .{},
-
// HTTP attribution
_frame_id: u32,
_loader_id: u32,
@@ -163,9 +159,10 @@ pub fn init(
._script_manager = undefined,
._location = .{ ._url = url },
._performance = .init(),
+ ._http_owner = undefined,
});
- self._http_owner.blob_urls = &self._blob_urls;
+ self._http_owner = .init(&frame._page.blob_urls, &self.origin);
self._script_manager = ScriptManagerBase.init(
arena,
@@ -207,10 +204,7 @@ pub fn deinit(self: *WorkerGlobalScope) void {
self._identity.deinit();
self._script_manager.deinit();
- var it = self._blob_urls.valueIterator();
- while (it.next()) |blob| {
- blob.*.releaseRef(page);
- }
+ page.revokeBlobUrlsFor(self._frame_id);
browser.env.destroyContext(self.js);
session.releaseArena(self.call_arena);
session.releaseArena(self.local_arena);
@@ -412,7 +406,7 @@ fn importScript(self: *WorkerGlobalScope, arena: Allocator, url: [:0]const u8) !
.resource_type = .script,
.notification = session.notification,
.shutdown_callback = HttpClient.noopShutdown, // syncRequest installs its own
- }) catch |err| {
+ }, &self._http_owner) catch |err| {
log.warn(.http, "importScript", .{ .url = resolved_url, .err = err });
return error.NetworkError;
};
diff --git a/src/cdp/CDP.zig b/src/cdp/CDP.zig
index fa00b2a70..fb6fc4c5c 100644
--- a/src/cdp/CDP.zig
+++ b/src/cdp/CDP.zig
@@ -1508,5 +1508,5 @@ test "cdp: syncRequest short-circuits after disconnect" {
.resource_type = .fetch,
.notification = undefined,
.shutdown_callback = @import("../network/HttpClient.zig").noopShutdown,
- }));
+ }, undefined));
}
diff --git a/src/network/HttpClient.zig b/src/network/HttpClient.zig
index 0bc88b563..8fdb05d63 100644
--- a/src/network/HttpClient.zig
+++ b/src/network/HttpClient.zig
@@ -1017,7 +1017,7 @@ const SyncContext = struct {
}
};
-pub fn syncRequest(self: *Client, allocator: Allocator, req: Request) !SyncResponse {
+pub fn syncRequest(self: *Client, allocator: Allocator, req: Request, owner: *Owner) !SyncResponse {
if (self.inbox.terminated) {
// request() takes ownership of req.headers on every path; we return
// before calling it, so free the curl_slist here to avoid leaking it.
@@ -1036,7 +1036,7 @@ pub fn syncRequest(self: *Client, allocator: Allocator, req: Request) !SyncRespo
r.done_callback = SyncContext.doneCallback;
r.error_callback = SyncContext.errorCallback;
r.shutdown_callback = SyncContext.shutdownCallback;
- const transfer = try self.newRequest(r, null);
+ const transfer = try self.newRequest(r, owner);
const frame_id = req.frame_id;
self.blocking_requests.putNoClobber(self.allocator, frame_id, transfer.id) catch |err| {
@@ -1728,11 +1728,22 @@ pub const Owner = struct {
transfers: std.DoublyLinkedList = .{},
websockets: std.DoublyLinkedList = .{},
- // The owning Frame's / WorkerGlobalScope's blob: registry,
- blob_urls: ?*const std.StringHashMapUnmanaged(*Blob) = null,
+ // The Page-level blob: URL store, shared by every context on the page.
+ blob_urls: *const Blob.UrlMap,
+
+ // The owning Frame's / WorkerGlobalScope's origin slot. Pointer because
+ // it can change during navigation.
+ origin: *const ?[]const u8,
const Blob = @import("../browser/webapi/Blob.zig");
+ pub fn init(blob_urls: *const Blob.UrlMap, origin: *const ?[]const u8) Owner {
+ return .{
+ .blob_urls = blob_urls,
+ .origin = origin,
+ };
+ }
+
pub fn addTransfer(self: *Owner, t: *Transfer) void {
self.transfers.append(&t.owner_node);
}
@@ -2909,10 +2920,11 @@ const Synthetic = struct {
content_type = parsed.content_type;
body = parsed.body;
} else {
- // blob: — resolved against the owning frame's registry.
const owner = transfer.owner orelse return error.BlobNotFound;
- const blob_urls = owner.blob_urls orelse return error.BlobNotFound;
- const blob = blob_urls.get(url) orelse return error.BlobNotFound;
+ if (!Owner.Blob.urlBelongsToOrigin(url, owner.origin.*)) {
+ return error.BlobNotFound;
+ }
+ const blob = (owner.blob_urls.get(url) orelse return error.BlobNotFound).blob;
// blob can be removed by the time we run, dupe it.
content_type = try arena.dupe(u8, blob._mime);
body = try arena.dupe(u8, blob._slice);
@@ -3101,7 +3113,7 @@ test "HttpClient: fulfillIntercepted survives a done_callback that tears down th
defer client.processGraveyard();
defer client.transfers.deinit(testing.allocator);
- var owner: Owner = .{};
+ var owner: Owner = .init(undefined, undefined);
const Ctx = struct {
client: *Client,
@@ -3416,7 +3428,7 @@ test "HttpClient: abortParked survives an error_callback that tears down the own
defer client.processGraveyard();
defer client.transfers.deinit(testing.allocator);
- var owner: Owner = .{};
+ var owner: Owner = .init(undefined, undefined);
const Ctx = struct {
client: *Client,
@@ -3492,7 +3504,7 @@ test "HttpClient: abort survives an error_callback that tears down the owner" {
defer client.processGraveyard();
defer client.transfers.deinit(testing.allocator);
- var owner: Owner = .{};
+ var owner: Owner = .init(undefined, undefined);
const Ctx = struct {
client: *Client,