Lightpanda: the headless browser designed for AI and automation
webapi: more accurate window.isSecureContext
Karl Seguin7cb98ad977c8
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex befb536a1..38e078594 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -617,6 +617,29 @@ pub fn isSameOrigin(self: *const Frame, url: [:0]const u8) bool {return URL.isSameOrigin(url, current_origin);}+// Like Chrome, every ancestor must be potentially trustworthy, not just the+// top-level document the spec looks at: an https iframe inside an http page+// is not a secure context.+pub fn isSecureContext(self: *const Frame) bool {+ var frame: ?*const Frame = self;+ while (frame) |f| : (frame = f.parent) {+ if (f.isPotentiallyTrustworthy() == false) {+ return false;+ }+ }+ return true;+}++fn isPotentiallyTrustworthy(self: *const Frame) bool {+ if (self.origin) |origin| {+ return URL.isPotentiallyTrustworthy(origin);+ }+ // No origin: either an opaque one (data:, which is never trustworthy), a+ // file: document, or an about:blank/srcdoc with nothing to inherit from.+ const url = self.url;+ return std.mem.eql(u8, url, "about:blank") or std.mem.eql(u8, url, "about:srcdoc") or std.mem.startsWith(u8, url, "file:");+}+pub fn navigate(self: *Frame, request_url: [:0]const u8, opts: NavigateOpts) !void {lp.assert(self._load_state == .waiting, "frame.renavigate", .{});const session = self._session;@@ -3900,6 +3923,44 @@ test "Page: isSameOrigin" {try testing.expectEqual(false, frame.isSameOrigin("//origin.com/foo"));}+test "Frame: isSecureContext" {+ var top: Frame = undefined;+ top.parent = null;+ var child: Frame = undefined;+ child.parent = ⊤+ child.url = "about:blank";+ child.origin = null;++ top.url = "https://origin.com/";+ top.origin = "https://origin.com";+ try testing.expectEqual(true, top.isSecureContext());++ child.origin = "http://127.0.0.1:9582";+ try testing.expectEqual(true, child.isSecureContext());+ child.origin = "http://sub.localhost";+ try testing.expectEqual(true, child.isSecureContext());+ child.origin = "http://origin.com";+ try testing.expectEqual(false, child.isSecureContext());++ // no origin: about:blank/srcdoc with nothing to inherit, file: or opaque+ child.origin = null;+ try testing.expectEqual(true, child.isSecureContext());+ child.url = "about:srcdoc";+ try testing.expectEqual(true, child.isSecureContext());+ child.url = "file:///tmp/index.html";+ try testing.expectEqual(true, child.isSecureContext());+ child.url = "data:text/html,hello";+ try testing.expectEqual(false, child.isSecureContext());++ // a trustworthy frame inside an untrustworthy one isn't a secure context+ top.url = "http://origin.com/";+ top.origin = "http://origin.com";+ child.url = "https://origin.com/";+ child.origin = "https://origin.com";+ try testing.expectEqual(false, top.isSecureContext());+ try testing.expectEqual(false, child.isSecureContext());+}+test "Frame: superseded documents omit DOMContentLoaded and load" {const cases = [_]struct { trigger: []const u8, expected: []const u8 }{.{ .trigger = "location.assign('/next');", .expected = "complete" },diff --git a/src/browser/URL.zig b/src/browser/URL.zigindex 01c305bdb..de07480be 100644--- a/src/browser/URL.zig+++ b/src/browser/URL.zig@@ -220,14 +220,14 @@ pub fn getProtocol(raw: []const u8) []const u8 {return raw[0 .. pos + 1];}-pub fn isSecure(raw: [:0]const u8) bool {+pub fn isSecure(raw: []const u8) bool {return std.mem.startsWith(u8, raw, "https:") or std.mem.startsWith(u8, raw, "wss:");}/// Cryptographic scheme or loopback host. Browsers let such origins use/// secure-only features (Secure cookies, prefixed cookie names) so that/// plain-http local development behaves like production.-pub fn isPotentiallyTrustworthy(raw: [:0]const u8) bool {+pub fn isPotentiallyTrustworthy(raw: []const u8) bool {return isSecure(raw) or isLoopbackHost(getHostname(raw));}diff --git a/src/browser/global_scope.zig b/src/browser/global_scope.zigindex ec6f2c0ca..cd2904bbd 100644--- a/src/browser/global_scope.zig+++ b/src/browser/global_scope.zig@@ -81,6 +81,13 @@ pub const GlobalScope = union(enum) {};}+ pub fn isSecureContext(self: GlobalScope) bool {+ return switch (self) {+ .frame => |f| f.isSecureContext(),+ .worker => |w| w._secure_context,+ };+ }+pub fn frameId(self: GlobalScope) u32 {return switch (self) {inline else => |g| g._frame_id,diff --git a/src/browser/js/Context.zig b/src/browser/js/Context.zigindex e57740f34..365bff203 100644--- a/src/browser/js/Context.zig+++ b/src/browser/js/Context.zig@@ -253,6 +253,12 @@ pub fn setOrigin(self: *Context, key: ?[]const u8) !void {// one context to access another.const token_local = v8.v8__Global__Get(&origin.security_token, isolate.handle);v8.v8__Context__SetSecurityToken(ls.local.handle, token_local);++ // navigator.serviceWorker is [SecureContext]. With the feature+ // disabled, Env.createContext has already removed it.+ if (self.global == .frame and self.page.session.experimental_features.serviceworker and self.execution.isSecureContext() == false) {+ env.hideServiceWorker(true, ls.local.handle, v8.v8__Context__Global(ls.local.handle).?);+ }}}diff --git a/src/browser/js/Env.zig b/src/browser/js/Env.zigindex ba8cfb4fa..5fd7acfc1 100644--- a/src/browser/js/Env.zig+++ b/src/browser/js/Env.zig@@ -420,7 +420,8 @@ fn _createContext(self: *Env, global: anytype, params: ContextParams) !*Contextreturn context;}-// When ServiceWorkers are disabled (as they are by default), this must be false:+// When ServiceWorkers are disabled (as they are by default), or the frame isn't+// a secure context, this must be false:// 'serviceWorker' in navigator// If you disable ServiceWorkers in FireFox (about:config) this is the behavior// you get, and it seems to be the safest way to not break sites. BUT, the@@ -428,7 +429,7 @@ fn _createContext(self: *Env, global: anytype, params: ContextParams) !*Context// its own Navigator.prototype (2 Gets + 1 Delete).// (If this proves to be an issue, we could swap the logic, and dynamically ADD// it when it is enabled, but that's a lot more code).-fn hideServiceWorker(self: *const Env, comptime is_frame: bool, v8_context: *const v8.Context, global_obj: *const v8.Object) void {+pub fn hideServiceWorker(self: *const Env, comptime is_frame: bool, v8_context: *const v8.Context, global_obj: *const v8.Object) void {if (comptime is_frame) {self.deletePrototypeMember(v8_context, global_obj, "navigator", "service_worker");}diff --git a/src/browser/js/Execution.zig b/src/browser/js/Execution.zigindex 2011f8fe1..f9f0d03c2 100644--- a/src/browser/js/Execution.zig+++ b/src/browser/js/Execution.zig@@ -131,6 +131,10 @@ pub fn origin(self: *const Execution) ?[]const u8 {return self.js.global.origin();}+pub fn isSecureContext(self: *const Execution) bool {+ return self.js.global.isSecureContext();+}+pub fn frameId(self: *const Execution) u32 {return self.js.global.frameId();}diff --git a/src/browser/tests/service_worker/realm-worker.js b/src/browser/tests/service_worker/realm-worker.jsindex e452bc54a..a9db5e924 100644--- a/src/browser/tests/service_worker/realm-worker.js+++ b/src/browser/tests/service_worker/realm-worker.js@@ -16,6 +16,8 @@ const report = {// Blink has this as [Exposed=Window]; a service worker would get// ExtendableCookieChangeEvent, which we don't implement.hasCookieChangeEvent: typeof CookieChangeEvent !== 'undefined',+ // Inherited from a page served from loopback; always true for a service worker.+ isSecureContext: self.isSecureContext,};// A global postMessage exists on DedicatedWorkerGlobalScope only.@@ -28,6 +30,7 @@ if (typeof postMessage === 'function') {if (report.hasCookieChangeEvent) bad.push('CookieChangeEvent');if (!report.hasCookieStoreCtor) bad.push('missing CookieStore');if (!report.hasCookieStoreProp) bad.push('missing cookieStore');+ if (report.isSecureContext !== true) bad.push('isSecureContext');if (bad.length) {throw new Error('service worker realm: ' + bad.join(', '));}diff --git a/src/browser/tests/service_worker/service_worker.html b/src/browser/tests/service_worker/service_worker.htmlindex 0fbc7d528..1e3211f5e 100644--- a/src/browser/tests/service_worker/service_worker.html+++ b/src/browser/tests/service_worker/service_worker.html@@ -23,6 +23,24 @@}</script>+<script id="service_worker_absent_outside_secure_context" type=module>+ // navigator.serviceWorker is [SecureContext]. A data: document has an opaque+ // origin, so it isn't one, and (like Chrome) doesn't get the accessor.+ {+ const state = await testing.async();+ window.addEventListener('message', (e) => state.resolve(e.data));++ const f = document.createElement('iframe');+ f.src = "data:text/html,<script>parent.postMessage({secure: isSecureContext, sw: 'serviceWorker' in navigator}, '*')<\/script>";+ document.body.appendChild(f);++ await state.done((data) => {+ testing.expectEqual(false, data.secure);+ testing.expectEqual(false, data.sw);+ });+ }+</script>+<script id="service_worker_realm_exclusions" type=module>// A service worker's realm is worker_common_apis, not worker_extended_apis:// the blocking APIs a dedicated/shared worker gets must not be there. A@@ -54,6 +72,7 @@// Both realms keep the async pieces.testing.expectEqual(true, fromDedicated.hasFetch);testing.expectEqual(true, fromDedicated.hasWebSocket);+ testing.expectEqual(true, fromDedicated.isSecureContext);// CookieStore is [Exposed=(ServiceWorker,Window)]: none of the three// should be reachable from a dedicated worker.testing.expectEqual(false, fromDedicated.hasCookieStoreCtor);diff --git a/src/browser/tests/window/window.html b/src/browser/tests/window/window.htmlindex 0500b152b..8347c24be 100644--- a/src/browser/tests/window/window.html+++ b/src/browser/tests/window/window.html@@ -12,6 +12,22 @@testing.expectEqual(1920, innerWidth);</script>+<script id=is_secure_context>+ {+ // The test server is on 127.0.0.1: loopback is potentially trustworthy.+ testing.expectEqual(true, window.isSecureContext);+ // Readonly, not [Replaceable].+ window.isSecureContext = false;+ testing.expectEqual(true, window.isSecureContext);++ // about:blank inherits its parent's origin.+ const iframe = document.createElement('iframe');+ document.body.appendChild(iframe);+ testing.expectEqual(true, iframe.contentWindow.isSecureContext);+ iframe.remove();+ }+</script>+<script id=load>let call1 = 0;let call2 = 0;diff --git a/src/browser/webapi/Navigator.zig b/src/browser/webapi/Navigator.zigindex 146c2db43..4c09aac52 100644--- a/src/browser/webapi/Navigator.zig+++ b/src/browser/webapi/Navigator.zig@@ -164,10 +164,9 @@ fn getStorage(self: *Navigator) *StorageManager {return &self._storage;}-// NOTE, Env.createContext will remove the binding for this API at runtime if-// ServiceWorkers are not enabled (and by default, they are not).-// TODO: service workers should only exist where window.isSecureContext === true,-// but we always return false.+// NOTE, the binding for this API is removed at runtime if ServiceWorkers are+// not enabled (Env.createContext; by default, they are not) or if the frame+// isn't a secure context (Context.setOrigin).fn getServiceWorker(self: *Navigator, frame: *Frame) !*ServiceWorkerContainer {if (self._service_worker) |sw| {return sw;diff --git a/src/browser/webapi/Window.zig b/src/browser/webapi/Window.zigindex 099a27dd0..5118fb774 100644--- a/src/browser/webapi/Window.zig+++ b/src/browser/webapi/Window.zig@@ -344,6 +344,10 @@ fn getSelection(self: *const Window) *Selection {return &self._document._selection;}+fn getIsSecureContext(self: *const Window) bool {+ return self._frame.isSecureContext();+}+fn getFrameElement(self: *const Window) ?*Element.Html.IFrame {return self._frame.iframe;}@@ -1239,11 +1243,7 @@ pub const JsApi = struct {pub const scroll = bridge.function(Window.scrollTo, .{});pub const scrollBy = bridge.function(Window.scrollBy, .{});- // Return false since we don't have secure-context-only APIs implemented- // (webcam, geolocation, clipboard, etc.)- // This is safer and could help avoid processing errors by hinting at- // sites not to try to access those features- pub const isSecureContext = bridge.property(false, .{ .template = false });+ pub const isSecureContext = bridge.accessor(Window.getIsSecureContext, null, .{});// [Replaceable] (CSSOM-View): the getter reads the page's runtime viewport// (overridable via Emulation.setDeviceMetricsOverride); the setter overwritesdiff --git a/src/browser/webapi/WorkerGlobalScope.zig b/src/browser/webapi/WorkerGlobalScope.zigindex c00b296c3..54a71ee56 100644--- a/src/browser/webapi/WorkerGlobalScope.zig+++ b/src/browser/webapi/WorkerGlobalScope.zig@@ -80,6 +80,10 @@ local_arena: Allocator,url: [:0]const u8,// Same-origin constraint: a worker's origin is inherited from its parent frame.origin: ?[]const u8 = null,+// Inherited from the creating frame, captured at creation since the worker+// can outlive it. Always true for a service worker: only a secure context can+// register one.+_secure_context: bool,buf: [1024]u8 = undefined, // same size as frame.buf// Document charset (matches Page.charset). Workers default to UTF-8.charset: []const u8 = "UTF-8",@@ -151,6 +155,7 @@ pub fn init(.url = url,.arena = arena,.origin = frame.origin,+ ._secure_context = tag == .service or frame.isSecureContext(),.js = undefined,._call_arena = call_arena,._local_arena = local_arena,@@ -314,6 +319,10 @@ pub fn performance(self: *WorkerGlobalScope) *Performance {return self._performance;}+fn getIsSecureContext(self: *const WorkerGlobalScope) bool {+ return self._secure_context;+}+pub fn getLocation(self: *WorkerGlobalScope) *WorkerLocation {return &self._location;}@@ -629,6 +638,5 @@ pub const JsApi = struct {pub const setInterval = bridge.function(WorkerGlobalScope.setInterval, .{});pub const clearInterval = bridge.function(WorkerGlobalScope.clearInterval, .{});- // Return false since workers don't have secure-context-only APIs- pub const isSecureContext = bridge.property(false, .{ .template = false });+ pub const isSecureContext = bridge.accessor(WorkerGlobalScope.getIsSecureContext, null, .{});};