Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: cross validate more tests with chrome

Karl Seguinfda59823ade5
diff --git a/src/TestHTTPServer.zig b/src/TestHTTPServer.zig
index 644d99c84..9a6303812 100644
--- a/src/TestHTTPServer.zig
+++ b/src/TestHTTPServer.zig
@@ -124,15 +124,40 @@ pub fn sendFile(req: *std.http.Server.Request, file_path: []const u8) !void {
};
defer file.close(lp.io);
+ var headers: [8]std.http.Header = undefined;
+ headers[0] = .{ .name = "content-type", .value = getContentType(unescaped_file_path) };
+ var header_count: usize = 1;
+
+ // Like WPT, a `<file>.headers` next to the file adds its "Name: value"
+ // lines to the response.
+ var headers_buf: [1024]u8 = undefined;
+ var headers_fba = std.heap.FixedBufferAllocator.init(&headers_buf);
+ const headers_path = try std.fmt.allocPrint(fba.allocator(), "{s}.headers", .{unescaped_file_path});
+ if (std.Io.Dir.cwd().readFileAlloc(lp.io, headers_path, headers_fba.allocator(), .limited(headers_buf.len))) |content| {
+ var lines = std.mem.tokenizeAny(u8, content, "\r\n");
+ while (lines.next()) |line| {
+ const colon = std.mem.findScalar(u8, line, ':') orelse return error.InvalidHeadersFile;
+ if (header_count == headers.len) {
+ return error.TooManyHeaders;
+ }
+ headers[header_count] = .{
+ .name = std.mem.trim(u8, line[0..colon], " "),
+ .value = std.mem.trim(u8, line[colon + 1 ..], " "),
+ };
+ header_count += 1;
+ }
+ } else |err| switch (err) {
+ error.FileNotFound => {},
+ else => return err,
+ }
+
const stat = try file.stat(lp.io);
var send_buffer: [4096]u8 = undefined;
var res = try req.respondStreaming(&send_buffer, .{
.content_length = stat.size,
.respond_options = .{
- .extra_headers = &.{
- .{ .name = "content-type", .value = getContentType(unescaped_file_path) },
- },
+ .extra_headers = headers[0..header_count],
},
});
diff --git a/src/browser/parser/Parser.zig b/src/browser/parser/Parser.zig
index 23f0a0f6b..a34bdca9f 100644
--- a/src/browser/parser/Parser.zig
+++ b/src/browser/parser/Parser.zig
@@ -113,6 +113,8 @@ context: ?*Element = null,
fragment: bool = false,
xml_error: bool = false,
+// An XML entity that xml5ever doesn't know is only an error without a DTD.
+seen_doctype: bool = false,
terminated: bool = false,
appends_until_terminate_check: u16 = TERMINATE_CHECK_INTERVAL,
inserted_since_checkpoint: u16 = 0,
@@ -484,26 +486,29 @@ fn parseErrorCallback(ctx: *anyopaque, err: h5e.StringSlice) callconv(.c) void {
// xml5ever xml error callback indicating a well-formedness violating.
fn xmlParseErrorCallback(ctx: *anyopaque, err: h5e.StringSlice) callconv(.c) void {
const self: *Parser = @ptrCast(@alignCast(ctx));
- if (isWellFormednessError(err.slice())) {
+ // Without a DTD to declare it, an unknown entity breaks the "Entity
+ // Declared" well-formedness constraint.
+ if (isWellFormednessError(err.slice(), self.seen_doctype == false)) {
self.xml_error = true;
}
}
fn validateErrorCallback(ctx: *anyopaque, err: h5e.StringSlice) callconv(.c) void {
const has_error: *bool = @ptrCast(@alignCast(ctx));
- if (isWellFormednessError(err.slice())) {
+ // Lenient: a page that fails this goes through the HTML parser instead.
+ if (isWellFormednessError(err.slice(), false)) {
has_error.* = true;
}
}
-fn isWellFormednessError(msg: []const u8) bool {
+fn isWellFormednessError(msg: []const u8, unknown_entity_is_error: bool) bool {
if (std.mem.startsWith(u8, msg, "Bad character") and msg.len > "Bad character".len) {
// discouraged by legal code point
return false;
}
if (std.mem.startsWith(u8, msg, "Invalid character reference")) {
- // xml5ever doesn't know about this entity, but it could be valid
- return false;
+ // xml5ever doesn't know about this entity, but a DTD could declare it
+ return unknown_entity_is_error;
}
return true;
}
@@ -647,6 +652,7 @@ fn appendDoctypeToDocument(ctx: *anyopaque, name: h5e.StringSlice, public_id: h5
if (self.terminated) {
return;
}
+ self.seen_doctype = true;
const cp = self.frame._ce_reactions.push();
defer self.frame._ce_reactions.popAndInvoke(cp, self.frame);
self._appendDoctypeToDocument(name.slice(), public_id.slice(), system_id.slice()) catch |err| {
diff --git a/src/browser/tests/beacon.html b/src/browser/tests/beacon.html
index 0af16dbb7..f75f4558b 100644
--- a/src/browser/tests/beacon.html
+++ b/src/browser/tests/beacon.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="testing.js"></script>
<body></body>
diff --git a/src/browser/tests/cookie_store.html b/src/browser/tests/cookie_store.html
index cde2587af..536a3e243 100644
--- a/src/browser/tests/cookie_store.html
+++ b/src/browser/tests/cookie_store.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="testing.js"></script>
<script>
// The module scripts below interleave at each await and share cookieStore,
@@ -329,16 +330,27 @@
<script id=change-event-from-document-cookie type=module>
const state = await testing.async();
const events = [];
- const handler = (e) => { if (isAbout(e, 'ev-from-doc')) events.push(e); };
+ let waiter = null;
+ const handler = (e) => {
+ if (isAbout(e, 'ev-from-doc')) {
+ events.push(e);
+ waiter?.();
+ }
+ };
cookieStore.addEventListener('change', handler);
+ // Chrome delivers document.cookie changes later than a setTimeout(0), so
+ // wait for the event itself.
+ const nextEvent = () => new Promise(r => { waiter = r; });
+ let next = nextEvent();
document.cookie = 'ev-from-doc=v1; path=/';
- await new Promise(r => setTimeout(r, 0));
+ await next;
const lenAfterSet = events.length;
+ next = nextEvent();
document.cookie = 'ev-from-doc=DELETED; path=/; max-age=0';
- await new Promise(r => setTimeout(r, 0));
+ await next;
const lenAfterDelete = events.length;
@@ -375,14 +387,15 @@
</script>
<script id=rejections type=module>
- // Invalid calls reject with a TypeError rather than throwing.
+ // Invalid calls reject with a TypeError rather than throwing. Only the
+ // error type is checked: messages differ between browsers.
async function rejection(fn) {
const promise = fn();
try {
await promise;
return 'resolved';
} catch (e) {
- return `${e.name}: ${e.message}`;
+ return e.name;
}
}
@@ -394,7 +407,7 @@
state.resolve();
await state.done(() => {
- testing.expectEqual('TypeError: get requires a name or url', results[0]);
- testing.expectEqual('TypeError: value is required', results[1]);
+ testing.expectEqual('TypeError', results[0]);
+ testing.expectEqual('TypeError', results[1]);
});
</script>
diff --git a/src/browser/tests/crypto-worker.js.headers b/src/browser/tests/crypto-worker.js.headers
new file mode 100644
index 000000000..660445099
--- /dev/null
+++ b/src/browser/tests/crypto-worker.js.headers
@@ -0,0 +1 @@
+Cross-Origin-Embedder-Policy: require-corp
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.html
index 080286468..c53f2408c 100644
--- a/src/browser/tests/crypto.html
+++ b/src/browser/tests/crypto.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="testing.js"></script>
<script id=getRandomValues>
@@ -153,22 +154,31 @@
// [EnforceRange]: -8 used to wrap to 2^32 - 8 bits.
nan: await derive(NaN),
infinity: await derive(Infinity),
- negative: await derive(-8),
tooLarge: await derive(2 ** 32 + 8),
+ };
+ // Lightpanda only: Chrome has neither [EnforceRange] here nor a PBKDF2 cost
+ // limit, so each of these is a huge job that stalls its crypto thread.
+ const costly = testing.IS_TEST_RUNNER ? {
+ negative: await derive(-8),
// Valid lengths whose cost (blocks * iterations) is over the PBKDF2 limit.
hugeLength: await derive(2 ** 32 - 8, 100000),
hugeIterations: await derive(256, 2 ** 24 + 1),
- };
+ } : null;
state.resolve();
await state.done(() => {
testing.expectEqual(null, results.ok);
testing.expectEqual("OperationError", results.nullLength);
- for (const name of ["nan", "infinity", "negative", "tooLarge"]) {
- testing.expectEqual(`${name}: TypeError`, `${name}: ${results[name]}`);
+ testing.diverges("Chrome doesn't apply [EnforceRange] to deriveBits' length", () => {
+ for (const name of ["nan", "infinity", "tooLarge"]) {
+ testing.expectEqual(`${name}: TypeError`, `${name}: ${results[name]}`);
+ }
+ });
+ if (costly) {
+ testing.expectEqual("TypeError", costly.negative);
+ testing.expectEqual("OperationError", costly.hugeLength);
+ testing.expectEqual("OperationError", costly.hugeIterations);
}
- testing.expectEqual("OperationError", results.hugeLength);
- testing.expectEqual("OperationError", results.hugeIterations);
});
</script>
@@ -311,11 +321,12 @@
// A pair whose private key would have no usages is rejected.
const emptyPrivate = await errorName(() => gen("SHA-256", ["encrypt"]));
// Generation blocks the main thread, so the modulus is capped at 4096 bits.
- const tooLarge = await errorName(() => crypto.subtle.generateKey(
+ // Lightpanda only: Chrome has no cap, and takes seconds to generate one.
+ const tooLarge = testing.IS_TEST_RUNNER ? await errorName(() => crypto.subtle.generateKey(
{ name: "RSA-OAEP", modulusLength: 8192, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
true,
["encrypt", "decrypt"],
- ));
+ )) : null;
const rawExport = await errorName(() => crypto.subtle.exportKey("raw", k.publicKey));
state.resolve();
@@ -327,7 +338,9 @@
testing.expectEqual("InvalidAccessError", aesNameOnRsa);
testing.expectEqual("InvalidAccessError", rsaNameOnAes);
testing.expectEqual("SyntaxError", emptyPrivate);
- testing.expectEqual("OperationError", tooLarge);
+ if (testing.IS_TEST_RUNNER) {
+ testing.expectEqual("OperationError", tooLarge);
+ }
testing.expectEqual("NotSupportedError", rawExport);
});
</script>
@@ -932,7 +945,9 @@
testing.expectEqual(null, results.maxSalt);
testing.expectEqual("OperationError", results.saltTooLong);
testing.expectEqual(false, results.longSaltVerify);
- testing.expectEqual(false, results.hugeSaltVerify);
+ testing.diverges("Chrome rejects a saltLength past 2^31 - 1", () => {
+ testing.expectEqual(false, results.hugeSaltVerify);
+ });
testing.expectEqual("TypeError", results.noSalt);
testing.expectEqual("TypeError", results.noSaltObject);
testing.expectEqual("TypeError", results.negativeSalt);
@@ -1392,7 +1407,9 @@
testing.expectEqual("NotSupportedError", results.encryptWithKw);
testing.expectEqual("OperationError", results.wrongKwKey);
testing.expectEqual("OperationError", results.kwTooShort);
- testing.expectEqual("OperationError", results.kwNotMultipleOf8);
+ testing.diverges("Chrome reports DataError for AES-KW input that isn't a multiple of 8 bytes", () => {
+ testing.expectEqual("OperationError", results.kwNotMultipleOf8);
+ });
testing.expectEqual("DataError", results.notJson);
testing.expectEqual("DataError", results.jwkWithoutKty);
testing.expectEqual("DataError", results.extFalseExtractable);
@@ -1478,9 +1495,12 @@
state.resolve();
await state.done(() => {
// Compared with the case name, so a failure says which one.
- for (const ok of ["aes", "aesWithoutAlg", "kw", "cbc192", "ctr256", "hmac", "hmacSha1", "useMatches", "extFalseLocked", "keyOpsWider"]) {
+ for (const ok of ["aes", "aesWithoutAlg", "kw", "ctr256", "hmac", "hmacSha1", "useMatches", "extFalseLocked", "keyOpsWider"]) {
testing.expectEqual(`${ok}: null`, `${ok}: ${results[ok]}`);
}
+ testing.diverges("Chrome doesn't support 192-bit AES keys", () => {
+ testing.expectEqual("cbc192: null", `cbc192: ${results.cbc192}`);
+ });
for (const bad of ["ktyMissing", "ktyRsa", "kMissing", "algLength", "algMode", "algLowercase", "hmacAlgHash",
"aesUseSig", "hmacUseEnc", "keyOpsMissing", "keyOpsDuplicate", "aesExtFalse", "hmacExtFalse", "unwrapExtFalse"]) {
testing.expectEqual(`${bad}: DataError`, `${bad}: ${results[bad]}`);
@@ -1532,8 +1552,9 @@
testing.expectEqual(ks1.join(","), full.slice(0, 16).join(","));
testing.expectEqual(ks2.join(","), full.slice(16).join(","));
+ // The spec doesn't name the error: ours is OperationError, Chrome's
+ // DataError.
testing.expectEqual(true, overLengthError !== null);
- testing.expectEqual("OperationError", overLengthError.name);
});
</script>
@@ -1930,8 +1951,10 @@
testing.expectEqual("OperationError", results.genNull);
testing.expectEqual("DataError", results.importNull);
testing.expectEqual(null, results.genMax);
- testing.expectEqual("OperationError", results.genOverMax);
- testing.expectEqual("OperationError", results.genGigantic);
+ testing.diverges("Lightpanda caps generated HMAC keys at 2^16 bits; Chrome has no cap", () => {
+ testing.expectEqual("OperationError", results.genOverMax);
+ testing.expectEqual("OperationError", results.genGigantic);
+ });
testing.expectEqual("NotSupportedError", results.deriveUnknown);
testing.expectEqual("AES-GCM 128", `${aesWithHash.algorithm.name} ${aesWithHash.algorithm.length}`);
});
@@ -1943,13 +1966,18 @@
// Empty usages: SyntaxError.
const results = [
await captureGenKeyReject("Ed25519", true, ["encrypt"], "SyntaxError"),
+ await captureGenKeyReject("Ed25519", true, [], "SyntaxError"),
+ ];
+ const results448 = [
await captureGenKeyReject({ name: "Ed448" }, true, ["deriveBits"], "SyntaxError"),
await captureGenKeyReject("X448", true, ["sign"], "SyntaxError"),
- await captureGenKeyReject("Ed25519", true, [], "SyntaxError"),
];
state.resolve();
await state.done(() => {
assertGenKeyRejects(results);
+ testing.diverges("Chrome doesn't implement Ed448/X448: NotSupportedError", () => {
+ assertGenKeyRejects(results448);
+ });
});
</script>
@@ -2271,7 +2299,9 @@
testing.expectEqual(true, results.verify);
testing.expectEqual(false, results.verifyOther);
testing.expectEqual(false, results.verifyShort);
- testing.expectEqual(false, results.smallOrder);
+ testing.diverges("Chrome (BoringSSL) accepts a small-order Ed25519 key", () => {
+ testing.expectEqual(false, results.smallOrder);
+ });
testing.expectEqual(hex(pub), results.raw);
testing.expectEqual("302a300506032b6570032100" + hex(pub), results.spki);
testing.expectEqual("302e020100300506032b657004220420" + hex(seed), results.pkcs8);
@@ -2732,14 +2762,18 @@
"sign string data=TypeError",
"encrypt bad data bad algo=TypeError",
"hkdf info transferred by salt=true",
- "gcm iv transferred by tagLength=OperationError"
];
+ const gcmIv = out.pop();
state.resolve();
await state.done(() => {
+ testing.expectEqual(expected.length, out.length);
for (let i = 0; i < expected.length; i++) {
testing.expectEqual(expected[i], out[i]);
}
+ testing.diverges("Chrome reads AES-GCM's tagLength before its iv", () => {
+ testing.expectEqual("gcm iv transferred by tagLength=OperationError", gcmIv);
+ });
});
</script>
@@ -2930,12 +2964,13 @@
const results = {};
// HKDF and PBKDF2 have no export operation: NotSupportedError comes before
// the extractable check (Chrome 152 still gives InvalidAccessError).
+ const noExport = {};
for (const format of ["raw", "jwk", "spki", "pkcs8"]) {
- results[`hkdf ${format}`] = await outcome(() => subtle.exportKey(format, hkdf));
- results[`pbkdf2 ${format}`] = await outcome(() => subtle.exportKey(format, pbkdf2));
+ noExport[`hkdf ${format}`] = await outcome(() => subtle.exportKey(format, hkdf));
+ noExport[`pbkdf2 ${format}`] = await outcome(() => subtle.exportKey(format, pbkdf2));
}
- results["wrap hkdf"] = await outcome(() => subtle.wrapKey("raw", hkdf, kw, "AES-KW"));
- results["wrap pbkdf2"] = await outcome(() => subtle.wrapKey("raw", pbkdf2, kw, "AES-KW"));
+ noExport["wrap hkdf"] = await outcome(() => subtle.wrapKey("raw", hkdf, kw, "AES-KW"));
+ noExport["wrap pbkdf2"] = await outcome(() => subtle.wrapKey("raw", pbkdf2, kw, "AES-KW"));
// The wrapping key's checks come first.
results["wrap hkdf, unwrap-only key"] = await outcome(() => subtle.wrapKey("raw", hkdf, unwrapOnly, "AES-KW"));
// An exportable algorithm still checks extractable before the format.
@@ -2961,17 +2996,21 @@
state.resolve();
await state.done(() => {
+ testing.diverges("Chrome checks extractable before the export operation", () => {
+ testing.expectEqual({
+ "hkdf raw": "NotSupportedError",
+ "pbkdf2 raw": "NotSupportedError",
+ "hkdf jwk": "NotSupportedError",
+ "pbkdf2 jwk": "NotSupportedError",
+ "hkdf spki": "NotSupportedError",
+ "pbkdf2 spki": "NotSupportedError",
+ "hkdf pkcs8": "NotSupportedError",
+ "pbkdf2 pkcs8": "NotSupportedError",
+ "wrap hkdf": "NotSupportedError",
+ "wrap pbkdf2": "NotSupportedError",
+ }, noExport);
+ });
testing.expectEqual({
- "hkdf raw": "NotSupportedError",
- "pbkdf2 raw": "NotSupportedError",
- "hkdf jwk": "NotSupportedError",
- "pbkdf2 jwk": "NotSupportedError",
- "hkdf spki": "NotSupportedError",
- "pbkdf2 spki": "NotSupportedError",
- "hkdf pkcs8": "NotSupportedError",
- "pbkdf2 pkcs8": "NotSupportedError",
- "wrap hkdf": "NotSupportedError",
- "wrap pbkdf2": "NotSupportedError",
"wrap hkdf, unwrap-only key": "InvalidAccessError",
"aes locked raw": "InvalidAccessError",
"aes locked spki": "InvalidAccessError",
@@ -3012,16 +3051,18 @@
const counter = new Uint8Array(16);
const encrypted = await subtle.encrypt({ name: "AES-CTR", counter, length: 64 }, aes, new Uint8Array(4));
const results = {
- algorithmSame: aes.algorithm === algorithm,
- usagesSame: aes.usages === usages,
- algorithmSeen: `${aes.algorithm.name}/${aes.algorithm.length}`,
- usagesSeen: aes.usages.join(),
stillEncrypts: encrypted.byteLength,
stillNotSigning: await subtle.sign("HMAC", aes, new Uint8Array(1)).then(() => "signed", (e) => e.name),
exportedAlg: (await subtle.exportKey("jwk", aes)).alg,
// Each key has its own objects, even the two keys of a pair.
pairAlgorithmsDiffer: pair.publicKey.algorithm !== pair.privateKey.algorithm,
pairUsagesDiffer: pair.publicKey.usages !== pair.privateKey.usages,
+ };
+ const cached = {
+ algorithmSame: aes.algorithm === algorithm,
+ usagesSame: aes.usages === usages,
+ algorithmSeen: `${aes.algorithm.name}/${aes.algorithm.length}`,
+ usagesSeen: aes.usages.join(),
publicAlgorithmSame: pair.publicKey.algorithm === pair.publicKey.algorithm,
privateUsagesSame: pair.privateKey.usages === pair.privateKey.usages,
// So are its nested members.
@@ -3033,21 +3074,25 @@
state.resolve();
await state.done(() => {
testing.expectEqual({
- algorithmSame: true,
- usagesSame: true,
- algorithmSeen: "HMAC/1",
- usagesSeen: "encrypt,decrypt,sign",
stillEncrypts: 4,
stillNotSigning: "InvalidAccessError",
exportedAlg: "A256CTR",
pairAlgorithmsDiffer: true,
pairUsagesDiffer: true,
- publicAlgorithmSame: true,
- privateUsagesSame: true,
- hmacHashSame: true,
- rsaHashSame: true,
- rsaExponentSame: true,
}, results);
+ testing.diverges("Chrome builds a new algorithm/usages object on every read", () => {
+ testing.expectEqual({
+ algorithmSame: true,
+ usagesSame: true,
+ algorithmSeen: "HMAC/1",
+ usagesSeen: "encrypt,decrypt,sign",
+ publicAlgorithmSame: true,
+ privateUsagesSame: true,
+ hmacHashSame: true,
+ rsaHashSame: true,
+ rsaExponentSame: true,
+ }, cached);
+ });
});
</script>
@@ -3123,7 +3168,7 @@
results["publicExponent Uint16Array"] = await rsa(new Uint16Array([1, 1]));
results["publicExponent DataView"] = await rsa(new DataView(new Uint8Array([1, 0, 1]).buffer));
results["publicExponent ArrayBuffer"] = await rsa(new Uint8Array([1, 0, 1]).buffer);
- results["publicExponent shared"] = await rsa(new Uint8Array(new SharedArrayBuffer(3)));
+ const sharedExponent = await rsa(new Uint8Array(new SharedArrayBuffer(3)));
// A shared keyData is a TypeError of its conversion, before the algorithm.
results["import view, unknown algorithm"] = await outcome(() => subtle.importKey("raw", view, "NOPE", false, ["encrypt"]));
// A SharedArrayBuffer is a BufferSource that fails its conversion, not a
@@ -3156,7 +3201,6 @@
expected["publicExponent Uint16Array"] = "TypeError";
expected["publicExponent DataView"] = "TypeError";
expected["publicExponent ArrayBuffer"] = "TypeError";
- expected["publicExponent shared"] = "TypeError";
expected["import view, unknown algorithm"] = "TypeError";
expected["import jwk sab"] = "TypeError";
expected["import jwk sab, unknown algorithm"] = "TypeError";
@@ -3167,6 +3211,9 @@
state.resolve();
await state.done(() => {
testing.expectEqual(expected, results);
+ testing.diverges("Chrome takes a shared publicExponent", () => {
+ testing.expectEqual("TypeError", sharedExponent);
+ });
});
</script>
@@ -3194,6 +3241,8 @@
// A length that doesn't fill the last byte is kept (Chrome 152 clones this
// key as null).
await same("hmac", await subtle.generateKey({ name: "HMAC", hash: "SHA-384", length: 100 }, true, ["sign"]), "jwk");
+ const hmacPartialByte = results["hmac"];
+ delete results["hmac"];
const ec = await subtle.generateKey({ name: "ECDSA", namedCurve: "P-384" }, true, ["sign", "verify"]);
await same("ecdsa public", ec.publicKey, "spki");
await same("ecdsa private", ec.privateKey, "pkcs8");
@@ -3233,7 +3282,6 @@
testing.expectEqual({
"aes-gcm": true,
"aes-kw": true,
- "hmac": true,
"ecdsa public": true,
"ecdsa private": true,
"ecdh public": true,
@@ -3250,6 +3298,9 @@
"hkdf": true,
"one clone": true,
}, results);
+ testing.diverges("Chrome clones an HMAC key whose length isn't whole bytes as null", () => {
+ testing.expectEqual(true, hmacPartialByte);
+ });
});
</script>
@@ -3341,7 +3392,7 @@
results["import raw-public ec sign"] = await outcome(() => subtle.importKey("raw-public", ecRaw, { name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]));
// HKDF and PBKDF2 still have no export operation.
const hkdf = await subtle.importKey("raw-secret", bytes16, "HKDF", false, ["deriveBits"]);
- results["export raw-secret hkdf"] = await outcome(() => subtle.exportKey("raw-secret", hkdf));
+ const hkdfExport = await outcome(() => subtle.exportKey("raw-secret", hkdf));
state.resolve();
await state.done(() => {
@@ -3363,7 +3414,9 @@
"export raw-public rsa": "NotSupportedError",
"import raw-public rsa": "NotSupportedError",
"import raw-public ec sign": "SyntaxError",
- "export raw-secret hkdf": "NotSupportedError",
}, results);
+ testing.diverges("Chrome checks extractable before the export operation", () => {
+ testing.expectEqual("NotSupportedError", hkdfExport);
+ });
});
</script>
diff --git a/src/browser/tests/crypto.html.headers b/src/browser/tests/crypto.html.headers
new file mode 100644
index 000000000..63b60e490
--- /dev/null
+++ b/src/browser/tests/crypto.html.headers
@@ -0,0 +1,2 @@
+Cross-Origin-Opener-Policy: same-origin
+Cross-Origin-Embedder-Policy: require-corp
diff --git a/src/browser/tests/data_transfer.html b/src/browser/tests/data_transfer.html
index 61ea259ab..40222474c 100644
--- a/src/browser/tests/data_transfer.html
+++ b/src/browser/tests/data_transfer.html
@@ -1,6 +1,7 @@
<!DOCTYPE html>
<head>
<title>Test DataTransfer Web API</title>
+ <meta name=lp-mode content=test>
<script src="./testing.js"></script>
</head>
@@ -11,7 +12,7 @@
testing.expectEqual(0, dt.items.length);
testing.expectEqual(0, dt.files.length);
testing.expectEqual("none", dt.dropEffect);
- testing.expectEqual("uninitialized", dt.effectAllowed);
+ testing.expectEqual("none", dt.effectAllowed);
testing.expectEqual(true, dt.items instanceof DataTransferItemList);
testing.expectEqual(true, dt.files instanceof FileList);
}
@@ -20,14 +21,16 @@
<script id=effects>
{
const dt = new DataTransfer();
- dt.dropEffect = "copy";
- testing.expectEqual("copy", dt.dropEffect);
- dt.dropEffect = "bogus"; // invalid ignored
- testing.expectEqual("copy", dt.dropEffect);
- dt.effectAllowed = "copyMove";
- testing.expectEqual("copyMove", dt.effectAllowed);
- dt.effectAllowed = "nope"; // invalid ignored
- testing.expectEqual("copyMove", dt.effectAllowed);
+ testing.diverges("Chrome ignores both setters outside a drag", () => {
+ dt.dropEffect = "copy";
+ testing.expectEqual("copy", dt.dropEffect);
+ dt.dropEffect = "bogus"; // invalid ignored
+ testing.expectEqual("copy", dt.dropEffect);
+ dt.effectAllowed = "copyMove";
+ testing.expectEqual("copyMove", dt.effectAllowed);
+ dt.effectAllowed = "nope"; // invalid ignored
+ testing.expectEqual("copyMove", dt.effectAllowed);
+ });
}
</script>
@@ -80,14 +83,24 @@
}
</script>
-<script id=get_as_string>
-{
+<script id=get_as_string type=module>
+ const state = await testing.async();
const dt = new DataTransfer();
dt.setData("text/plain", "world");
let got = null;
- dt.items[0].getAsString(function (s) { got = s; });
- testing.expectEqual("world", got);
-}
+ // The callback runs in a queued task, not before.
+ dt.items[0].getAsString((s) => {
+ got = s;
+ state.resolve();
+ });
+ const sync = got;
+ await Promise.resolve();
+ const afterMicrotask = got;
+ await state.done(() => {
+ testing.expectEqual(null, sync);
+ testing.expectEqual(null, afterMicrotask);
+ testing.expectEqual("world", got);
+ });
</script>
<script id=remove_and_clear>
diff --git a/src/browser/tests/domparser.html b/src/browser/tests/domparser.html
index 5d42993eb..a56bf5744 100644
--- a/src/browser/tests/domparser.html
+++ b/src/browser/tests/domparser.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="testing.js"></script>
<body></body>
@@ -13,7 +14,7 @@
{
const parser = new DOMParser();
let d = parser.parseFromString('', 'text/xml');
- testing.expectEqual('<parsererror>error</parsererror>', new XMLSerializer().serializeToString(d));
+ testing.expectEqual(1, d.getElementsByTagName('parsererror').length);
}
}
</script>
@@ -515,12 +516,18 @@
<script id=xml-parsererror>
{
const p = new DOMParser();
- const isError = (doc) => {
- const root = doc.documentElement;
- return root.localName === 'parsererror'
- && root.namespaceURI === 'http://www.mozilla.org/newlayout/xml/parsererror.xml'
- && doc.childNodes.length === 1;
- };
+ // Chrome renders its own error page instead (an XHTML <parsererror>, in
+ // the partial document when there is one), so it is detected by name.
+ const isError = (doc) => doc.getElementsByTagName('parsererror').length !== 0;
+
+ // The spec's error document: <parsererror>, in the Mozilla error
+ // namespace, as its only child.
+ const errorDoc = p.parseFromString('<a>', 'text/xml');
+ testing.expectEqual(1, errorDoc.childNodes.length);
+ testing.diverges("Chrome's error document is an XHTML page", () => {
+ testing.expectEqual('parsererror', errorDoc.documentElement.localName);
+ testing.expectEqual('http://www.mozilla.org/newlayout/xml/parsererror.xml', errorDoc.documentElement.namespaceURI);
+ });
// well-formedness errors -> <parsererror> document
for (const bad of [
@@ -538,12 +545,16 @@
'<?1x?><a/>',
'<?xml version="2.0"?><a/>', // only 1.x versions are accepted
'<?xml version="10.0"?><a/>',
- '<?xml version="1."?><a/>',
'<?xml version=1.0?><a/>',
'<?xml encoding="UTF-8"?><a/>', // version is required
+ '<a>&undefined;</a>', // no DTD declares the entity
]) {
testing.expectEqual(bad + ' -> error', bad + (isError(p.parseFromString(bad, 'text/xml')) ? ' -> error' : ' -> ok'));
}
+ // VersionNum is '1.' [0-9]+.
+ testing.diverges("Chrome accepts version=\"1.\"", () => {
+ testing.expectEqual(true, isError(p.parseFromString('<?xml version="1."?><a/>', 'text/xml')));
+ });
// legal documents must not be flagged
for (const good of [
@@ -559,7 +570,8 @@
// DOCTYPE internal subset (old Illustrator exports); xml5ever has no DTD
// support, so the entities stay unexpanded, but the document must parse.
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [\n\t<!ENTITY ns_svg "http://www.w3.org/2000/svg">\n]>\n<svg xmlns="&ns_svg;"><rect/></svg>',
- '<a>&undefined;</a>',
+ // A DTD could declare it.
+ '<!DOCTYPE a SYSTEM "a.dtd"><a>&undefined;</a>',
'<a>\x7F</a>', // discouraged but legal code points
]) {
testing.expectEqual(good + ' -> ok', good + (isError(p.parseFromString(good, 'text/xml')) ? ' -> error' : ' -> ok'));
diff --git a/src/browser/webapi/DataTransfer.zig b/src/browser/webapi/DataTransfer.zig
index 44190ea9c..d8ce98c09 100644
--- a/src/browser/webapi/DataTransfer.zig
+++ b/src/browser/webapi/DataTransfer.zig
@@ -57,7 +57,7 @@ _item_list: *DataTransferItemList,
// holds is released at frame teardown (same path as `<input type=file>`).
_files: *FileList,
_drop_effect: []const u8 = "none",
-_effect_allowed: []const u8 = "uninitialized",
+_effect_allowed: []const u8 = "none",
pub fn init(frame: *Frame) !*DataTransfer {
const arena = try frame.getArena(.medium, "DataTransfer");
diff --git a/src/browser/webapi/DataTransferItem.zig b/src/browser/webapi/DataTransferItem.zig
index a089fc3a9..6d5d70b4c 100644
--- a/src/browser/webapi/DataTransferItem.zig
+++ b/src/browser/webapi/DataTransferItem.zig
@@ -73,20 +73,72 @@ fn getAsFile(self: *const DataTransferItem) ?*File {
}
// https://html.spec.whatwg.org/multipage/dnd.html#dom-datatransferitem-getasstring
-// v1 invokes the callback synchronously with the string value. File items and a
-// missing callback are no-ops, per spec.
-pub fn getAsString(self: *const DataTransferItem, cb_: ?js.Function) !void {
+// The callback runs in a queued task.
+pub fn getAsString(self: *DataTransferItem, cb_: ?js.Function.Global, exec: *js.Execution) !void {
const cb = cb_ orelse return;
- const s = switch (self._payload) {
+ errdefer cb.release();
+
+ const value = switch (self._payload) {
.string => |str| str,
- .file => return,
- };
- var caught: js.TryCatch.Caught = .{};
- cb.tryCall(void, .{s}, &caught) catch {
- log.debug(.js, "getAsString callback", .{ .caught = caught, .source = "DataTransferItem" });
+ .file => {
+ // noop
+ cb.release();
+ return;
+ },
};
+
+ const req = try exec._factory.create(StringRequest{
+ .exec = exec,
+ .callback = cb,
+ .value = value,
+ .data_transfer = self._data_transfer,
+ });
+ errdefer exec._factory.destroy(req);
+
+ try exec.js.scheduler.add(req, StringRequest.run, 0, .{
+ .name = "DataTransferItem.getAsString",
+ .finalizer = StringRequest.cancelled,
+ });
+ // `value` lives in the DataTransfer's arena.
+ self._data_transfer.acquireRef();
}
+const StringRequest = struct {
+ exec: *js.Execution,
+ value: []const u8,
+ callback: js.Function.Global,
+ data_transfer: *DataTransfer,
+
+ fn deinit(self: *StringRequest) void {
+ const exec = self.exec;
+ self.callback.release();
+ self.data_transfer.releaseRef(exec.page);
+ exec._factory.destroy(self);
+ }
+
+ fn cancelled(ctx: *anyopaque) void {
+ const self: *StringRequest = @ptrCast(@alignCast(ctx));
+ self.deinit();
+ }
+
+ fn run(ctx: *anyopaque) anyerror!?u32 {
+ const self: *StringRequest = @ptrCast(@alignCast(ctx));
+ defer self.deinit();
+
+ const exec = self.exec;
+ var ls: js.Local.Scope = undefined;
+ exec.js.localScope(&ls);
+ defer ls.deinit();
+
+ ls.toLocal(self.callback).call(void, .{self.value}) catch |err| {
+ exec.page.recordJsError(err);
+ log.debug(.js, "getAsString callback", .{ .err = err });
+ };
+ ls.local.runMicrotasks();
+ return null;
+ }
+};
+
pub const JsApi = struct {
pub const bridge = js.Bridge(DataTransferItem);