From 0b6210cd37b68b94252cb798598b12974a20e1c1 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Tue, 21 May 2024 22:56:19 +0200 Subject: Adding upstream version 5.28.2+dfsg1+~cs23.11.12.3. Signed-off-by: Daniel Baumann --- test/wpt/runner/runner.mjs | 356 ++ test/wpt/runner/util.mjs | 172 + test/wpt/runner/worker.mjs | 164 + test/wpt/server/routes/network-partition-key.mjs | 111 + test/wpt/server/routes/redirect.mjs | 104 + test/wpt/server/server.mjs | 397 ++ test/wpt/server/websocket.mjs | 46 + test/wpt/start-FileAPI.mjs | 26 + test/wpt/start-cacheStorage.mjs | 26 + test/wpt/start-fetch.mjs | 31 + test/wpt/start-mimesniff.mjs | 31 + test/wpt/start-websockets.mjs | 47 + test/wpt/start-xhr.mjs | 12 + test/wpt/status/FileAPI.status.json | 75 + test/wpt/status/fetch.status.json | 457 ++ test/wpt/status/mimesniff.status.json | 7 + .../service-workers/cache-storage.status.json | 24 + test/wpt/status/websockets.status.json | 115 + test/wpt/status/xhr/formdata.status.json | 1 + test/wpt/tests/.azure-pipelines.yml | 595 +++ test/wpt/tests/.gitattributes | 1 + test/wpt/tests/.gitignore | 52 + test/wpt/tests/.mailmap | 9 + test/wpt/tests/.taskcluster.yml | 82 + test/wpt/tests/CODEOWNERS | 6 + test/wpt/tests/CODE_OF_CONDUCT.md | 138 + test/wpt/tests/CONTRIBUTING.md | 11 + .../FileAPI/Blob-methods-from-detached-frame.html | 59 + .../BlobURL/cross-partition.tentative.https.html | 276 ++ .../tests/FileAPI/BlobURL/support/file_test2.txt | 0 test/wpt/tests/FileAPI/BlobURL/test2-manual.html | 62 + .../progress_event_bubbles_cancelable.html | 33 + .../FileAPI/FileReader/support/file_test1.txt | 0 .../FileAPI/FileReader/test_errors-manual.html | 72 + .../FileReader/test_notreadableerrors-manual.html | 42 + .../FileReader/test_securityerrors-manual.html | 40 + test/wpt/tests/FileAPI/FileReader/workers.html | 27 + test/wpt/tests/FileAPI/FileReaderSync.worker.js | 56 + test/wpt/tests/FileAPI/META.yml | 6 + .../tests/FileAPI/blob/Blob-array-buffer.any.js | 45 + .../FileAPI/blob/Blob-constructor-dom.window.js | 53 + .../FileAPI/blob/Blob-constructor-endings.html | 104 + .../wpt/tests/FileAPI/blob/Blob-constructor.any.js | 468 ++ .../tests/FileAPI/blob/Blob-in-worker.worker.js | 9 + .../tests/FileAPI/blob/Blob-slice-overflow.any.js | 32 + test/wpt/tests/FileAPI/blob/Blob-slice.any.js | 231 + .../tests/FileAPI/blob/Blob-stream-byob-crash.html | 11 + .../FileAPI/blob/Blob-stream-sync-xhr-crash.html | 13 + test/wpt/tests/FileAPI/blob/Blob-stream.any.js | 83 + test/wpt/tests/FileAPI/blob/Blob-text.any.js | 64 + .../FileAPI/file/File-constructor-endings.html | 104 + .../wpt/tests/FileAPI/file/File-constructor.any.js | 155 + .../file/Worker-read-file-constructor.worker.js | 15 + .../FileAPI/file/resources/echo-content-escaped.py | 26 + .../FileAPI/file/send-file-form-controls.html | 113 + .../FileAPI/file/send-file-form-iso-2022-jp.html | 65 + .../FileAPI/file/send-file-form-punctuation.html | 226 + .../tests/FileAPI/file/send-file-form-utf-8.html | 62 + .../FileAPI/file/send-file-form-windows-1252.html | 62 + .../file/send-file-form-x-user-defined.html | 63 + test/wpt/tests/FileAPI/file/send-file-form.html | 25 + .../file/send-file-formdata-controls.any.js | 69 + .../file/send-file-formdata-punctuation.any.js | 144 + .../FileAPI/file/send-file-formdata-utf-8.any.js | 33 + .../tests/FileAPI/file/send-file-formdata.any.js | 8 + test/wpt/tests/FileAPI/fileReader.any.js | 59 + .../tests/FileAPI/filelist-section/filelist.html | 57 + .../filelist_multiple_selected_files-manual.html | 64 + .../filelist_selected_file-manual.html | 64 + .../FileAPI/filelist-section/support/upload.txt | 1 + .../FileAPI/filelist-section/support/upload.zip | Bin 0 -> 220 bytes test/wpt/tests/FileAPI/historical.https.html | 65 + test/wpt/tests/FileAPI/idlharness-manual.html | 45 + test/wpt/tests/FileAPI/idlharness.any.js | 19 + test/wpt/tests/FileAPI/idlharness.html | 37 + test/wpt/tests/FileAPI/idlharness.worker.js | 17 + test/wpt/tests/FileAPI/progress-manual.html | 49 + .../Determining-Encoding.any.js | 81 + .../FileReader-event-handler-attributes.any.js | 17 + .../FileReader-multiple-reads.any.js | 81 + .../reading-data-section/filereader_abort.any.js | 38 + .../reading-data-section/filereader_error.any.js | 19 + .../reading-data-section/filereader_events.any.js | 19 + .../filereader_file-manual.html | 69 + .../filereader_file_img-manual.html | 47 + .../filereader_readAsArrayBuffer.any.js | 23 + .../filereader_readAsBinaryString.any.js | 23 + .../filereader_readAsDataURL.any.js | 54 + .../filereader_readAsText.any.js | 36 + .../filereader_readystate.any.js | 19 + .../reading-data-section/filereader_result.any.js | 82 + .../reading-data-section/support/blue-100x100.png | Bin 0 -> 227 bytes test/wpt/tests/FileAPI/support/Blob.js | 70 + .../support/document-domain-setter.sub.html | 7 + test/wpt/tests/FileAPI/support/empty-document.html | 3 + .../FileAPI/support/historical-serviceworker.js | 5 + test/wpt/tests/FileAPI/support/incumbent.sub.html | 22 + .../tests/FileAPI/support/send-file-form-helper.js | 282 ++ .../FileAPI/support/send-file-formdata-helper.js | 99 + test/wpt/tests/FileAPI/support/upload.txt | 1 + test/wpt/tests/FileAPI/support/url-origin.html | 6 + test/wpt/tests/FileAPI/unicode.html | 46 + .../tests/FileAPI/url/cross-global-revoke.sub.html | 62 + .../url/multi-global-origin-serialization.sub.html | 26 + .../tests/FileAPI/url/resources/create-helper.html | 7 + .../tests/FileAPI/url/resources/create-helper.js | 4 + .../wpt/tests/FileAPI/url/resources/fetch-tests.js | 71 + .../tests/FileAPI/url/resources/revoke-helper.html | 7 + .../tests/FileAPI/url/resources/revoke-helper.js | 9 + test/wpt/tests/FileAPI/url/sandboxed-iframe.html | 32 + test/wpt/tests/FileAPI/url/unicode-origin.sub.html | 23 + test/wpt/tests/FileAPI/url/url-charset.window.js | 34 + test/wpt/tests/FileAPI/url/url-format.any.js | 70 + .../tests/FileAPI/url/url-in-tags-revoke.window.js | 115 + test/wpt/tests/FileAPI/url/url-in-tags.window.js | 48 + test/wpt/tests/FileAPI/url/url-lifetime.html | 56 + test/wpt/tests/FileAPI/url/url-reload.window.js | 36 + test/wpt/tests/FileAPI/url/url-with-fetch.any.js | 72 + test/wpt/tests/FileAPI/url/url-with-xhr.any.js | 68 + .../url/url_createobjecturl_file-manual.html | 45 + .../url/url_createobjecturl_file_img-manual.html | 28 + .../FileAPI/url/url_xmlhttprequest_img-ref.html | 12 + .../tests/FileAPI/url/url_xmlhttprequest_img.html | 27 + test/wpt/tests/LICENSE.md | 11 + test/wpt/tests/README.md | 124 + test/wpt/tests/common/CustomCorsResponse.py | 30 + test/wpt/tests/common/META.yml | 3 + test/wpt/tests/common/PrefixedLocalStorage.js | 116 + .../tests/common/PrefixedLocalStorage.js.headers | 1 + test/wpt/tests/common/PrefixedPostMessage.js | 100 + .../tests/common/PrefixedPostMessage.js.headers | 1 + test/wpt/tests/common/README.md | 10 + test/wpt/tests/common/__init__.py | 0 test/wpt/tests/common/arrays.js | 31 + test/wpt/tests/common/blank-with-cors.html | 0 test/wpt/tests/common/blank-with-cors.html.headers | 1 + test/wpt/tests/common/blank.html | 0 test/wpt/tests/common/custom-cors-response.js | 32 + test/wpt/tests/common/dispatcher/README.md | 228 + test/wpt/tests/common/dispatcher/dispatcher.js | 256 + test/wpt/tests/common/dispatcher/dispatcher.py | 53 + .../common/dispatcher/executor-service-worker.js | 24 + .../wpt/tests/common/dispatcher/executor-worker.js | 12 + test/wpt/tests/common/dispatcher/executor.html | 15 + .../tests/common/dispatcher/remote-executor.html | 12 + test/wpt/tests/common/domain-setter.sub.html | 8 + test/wpt/tests/common/dummy.xhtml | 2 + test/wpt/tests/common/dummy.xml | 1 + test/wpt/tests/common/echo.py | 6 + test/wpt/tests/common/gc.js | 52 + test/wpt/tests/common/get-host-info.sub.js | 63 + test/wpt/tests/common/get-host-info.sub.js.headers | 1 + test/wpt/tests/common/media.js | 61 + test/wpt/tests/common/media.js.headers | 1 + test/wpt/tests/common/object-association.js | 74 + .../wpt/tests/common/object-association.js.headers | 1 + .../wpt/tests/common/performance-timeline-utils.js | 56 + .../common/performance-timeline-utils.js.headers | 1 + test/wpt/tests/common/proxy-all.sub.pac | 3 + test/wpt/tests/common/redirect-opt-in.py | 20 + test/wpt/tests/common/redirect.py | 19 + test/wpt/tests/common/refresh.py | 11 + test/wpt/tests/common/reftest-wait.js | 39 + test/wpt/tests/common/reftest-wait.js.headers | 1 + test/wpt/tests/common/rendering-utils.js | 19 + test/wpt/tests/common/sab.js | 21 + test/wpt/tests/common/security-features/README.md | 460 ++ .../wpt/tests/common/security-features/__init__.py | 0 .../security-features/resources/common.sub.js | 1311 ++++++ .../resources/common.sub.js.headers | 1 + .../common/security-features/scope/__init__.py | 0 .../common/security-features/scope/document.py | 36 + .../scope/template/document.html.template | 30 + .../scope/template/worker.js.template | 29 + .../tests/common/security-features/scope/util.py | 43 + .../tests/common/security-features/scope/worker.py | 44 + .../security-features/subresource/__init__.py | 0 .../common/security-features/subresource/audio.py | 18 + .../security-features/subresource/document.py | 12 + .../common/security-features/subresource/empty.py | 14 + .../common/security-features/subresource/font.py | 76 + .../common/security-features/subresource/image.py | 116 + .../security-features/subresource/referrer.py | 4 + .../common/security-features/subresource/script.py | 14 + .../security-features/subresource/shared-worker.py | 13 + .../security-features/subresource/static-import.py | 61 + .../security-features/subresource/stylesheet.py | 61 + .../security-features/subresource/subresource.py | 199 + .../common/security-features/subresource/svg.py | 37 + .../subresource/template/document.html.template | 16 + .../subresource/template/font.css.template | 9 + .../subresource/template/image.css.template | 3 + .../subresource/template/script.js.template | 3 + .../subresource/template/shared-worker.js.template | 5 + .../subresource/template/static-import.js.template | 1 + .../subresource/template/svg.css.template | 3 + .../subresource/template/svg.embedded.template | 5 + .../subresource/template/worker.js.template | 3 + .../common/security-features/subresource/video.py | 17 + .../common/security-features/subresource/worker.py | 13 + .../common/security-features/subresource/xhr.py | 16 + .../tools/format_spec_src_json.py | 24 + .../common/security-features/tools/generate.py | 462 ++ .../common/security-features/tools/spec.src.json | 533 +++ .../security-features/tools/spec_validator.py | 251 + .../tools/template/disclaimer.template | 1 + .../tools/template/spec_json.js.template | 1 + .../tools/template/test.debug.html.template | 26 + .../tools/template/test.release.html.template | 22 + .../tests/common/security-features/tools/util.py | 228 + test/wpt/tests/common/security-features/types.md | 62 + test/wpt/tests/common/slow-redirect.py | 29 + test/wpt/tests/common/slow.py | 6 + test/wpt/tests/common/square.png | Bin 0 -> 18299 bytes test/wpt/tests/common/stringifiers.js | 57 + test/wpt/tests/common/stringifiers.js.headers | 1 + test/wpt/tests/common/subset-tests-by-key.js | 83 + test/wpt/tests/common/subset-tests.js | 60 + .../common/test-setting-immutable-prototype.js | 67 + .../test-setting-immutable-prototype.js.headers | 1 + test/wpt/tests/common/text-plain.txt | 4 + .../common/third_party/reftest-analyzer.xhtml | 934 ++++ test/wpt/tests/common/utils.js | 98 + test/wpt/tests/common/utils.js.headers | 1 + test/wpt/tests/common/window-name-setter.html | 12 + test/wpt/tests/common/worklet-reftest.js | 50 + test/wpt/tests/common/worklet-reftest.js.headers | 1 + test/wpt/tests/fetch/META.yml | 7 + test/wpt/tests/fetch/README.md | 6 + test/wpt/tests/fetch/api/abort/cache.https.any.js | 47 + .../tests/fetch/api/abort/destroyed-context.html | 27 + test/wpt/tests/fetch/api/abort/general.any.js | 572 +++ test/wpt/tests/fetch/api/abort/keepalive.html | 85 + test/wpt/tests/fetch/api/abort/request.any.js | 85 + .../api/abort/serviceworker-intercepted.https.html | 212 + .../wpt/tests/fetch/api/basic/accept-header.any.js | 34 + .../fetch/api/basic/block-mime-as-script.html | 43 + .../tests/fetch/api/basic/conditional-get.any.js | 38 + .../fetch/api/basic/error-after-response.any.js | 24 + .../fetch/api/basic/header-value-combining.any.js | 15 + .../fetch/api/basic/header-value-null-byte.any.js | 5 + test/wpt/tests/fetch/api/basic/historical.any.js | 17 + .../fetch/api/basic/http-response-code.any.js | 14 + .../wpt/tests/fetch/api/basic/integrity.sub.any.js | 87 + test/wpt/tests/fetch/api/basic/keepalive.any.js | 43 + .../tests/fetch/api/basic/mediasource.window.js | 5 + .../tests/fetch/api/basic/mode-no-cors.sub.any.js | 29 + .../tests/fetch/api/basic/mode-same-origin.any.js | 28 + test/wpt/tests/fetch/api/basic/referrer.any.js | 29 + .../api/basic/request-forbidden-headers.any.js | 100 + test/wpt/tests/fetch/api/basic/request-head.any.js | 6 + .../fetch/api/basic/request-headers-case.any.js | 13 + .../api/basic/request-headers-nonascii.any.js | 29 + .../tests/fetch/api/basic/request-headers.any.js | 82 + .../basic/request-referrer-redirected-worker.html | 17 + .../tests/fetch/api/basic/request-referrer.any.js | 24 + .../tests/fetch/api/basic/request-upload.any.js | 135 + .../tests/fetch/api/basic/request-upload.h2.any.js | 186 + .../fetch/api/basic/response-null-body.any.js | 38 + .../tests/fetch/api/basic/response-url.sub.any.js | 16 + test/wpt/tests/fetch/api/basic/scheme-about.any.js | 26 + .../tests/fetch/api/basic/scheme-blob.sub.any.js | 125 + test/wpt/tests/fetch/api/basic/scheme-data.any.js | 43 + .../tests/fetch/api/basic/scheme-others.sub.any.js | 31 + test/wpt/tests/fetch/api/basic/status.h2.any.js | 17 + .../tests/fetch/api/basic/stream-response.any.js | 40 + .../fetch/api/basic/stream-safe-creation.any.js | 54 + test/wpt/tests/fetch/api/basic/text-utf8.any.js | 74 + test/wpt/tests/fetch/api/body/cloned-any.js | 50 + test/wpt/tests/fetch/api/body/formdata.any.js | 14 + test/wpt/tests/fetch/api/body/mime-type.any.js | 127 + test/wpt/tests/fetch/api/cors/cors-basic.any.js | 43 + .../fetch/api/cors/cors-cookies-redirect.any.js | 49 + test/wpt/tests/fetch/api/cors/cors-cookies.any.js | 56 + .../fetch/api/cors/cors-expose-star.sub.any.js | 41 + .../tests/fetch/api/cors/cors-filtering.sub.any.js | 69 + .../wpt/tests/fetch/api/cors/cors-keepalive.any.js | 118 + .../api/cors/cors-multiple-origins.sub.any.js | 22 + .../tests/fetch/api/cors/cors-no-preflight.any.js | 41 + test/wpt/tests/fetch/api/cors/cors-origin.any.js | 51 + .../fetch/api/cors/cors-preflight-cache.any.js | 46 + .../cors/cors-preflight-not-cors-safelisted.any.js | 19 + .../fetch/api/cors/cors-preflight-redirect.any.js | 37 + .../fetch/api/cors/cors-preflight-referrer.any.js | 51 + .../cors/cors-preflight-response-validation.any.js | 33 + .../fetch/api/cors/cors-preflight-star.any.js | 86 + .../fetch/api/cors/cors-preflight-status.any.js | 37 + .../wpt/tests/fetch/api/cors/cors-preflight.any.js | 62 + .../api/cors/cors-redirect-credentials.any.js | 52 + .../fetch/api/cors/cors-redirect-preflight.any.js | 46 + test/wpt/tests/fetch/api/cors/cors-redirect.any.js | 42 + test/wpt/tests/fetch/api/cors/data-url-iframe.html | 58 + .../fetch/api/cors/data-url-shared-worker.html | 53 + test/wpt/tests/fetch/api/cors/data-url-worker.html | 50 + .../fetch/api/cors/resources/corspreflight.js | 58 + .../api/cors/resources/not-cors-safelisted.json | 13 + .../wpt/tests/fetch/api/cors/sandboxed-iframe.html | 14 + .../fetch/api/crashtests/body-window-destroy.html | 11 + test/wpt/tests/fetch/api/crashtests/request.html | 8 + .../api/credentials/authentication-basic.any.js | 17 + .../credentials/authentication-redirection.any.js | 29 + .../wpt/tests/fetch/api/credentials/cookies.any.js | 49 + .../fetch/api/headers/header-setcookie.any.js | 266 ++ .../api/headers/header-values-normalize.any.js | 72 + .../tests/fetch/api/headers/header-values.any.js | 63 + .../tests/fetch/api/headers/headers-basic.any.js | 275 ++ .../tests/fetch/api/headers/headers-casing.any.js | 54 + .../tests/fetch/api/headers/headers-combine.any.js | 66 + .../tests/fetch/api/headers/headers-errors.any.js | 96 + .../tests/fetch/api/headers/headers-no-cors.any.js | 59 + .../fetch/api/headers/headers-normalize.any.js | 56 + .../tests/fetch/api/headers/headers-record.any.js | 357 ++ .../fetch/api/headers/headers-structure.any.js | 20 + test/wpt/tests/fetch/api/idlharness.any.js | 21 + .../fetch/api/policies/csp-blocked-worker.html | 16 + test/wpt/tests/fetch/api/policies/csp-blocked.html | 15 + .../fetch/api/policies/csp-blocked.html.headers | 1 + test/wpt/tests/fetch/api/policies/csp-blocked.js | 13 + .../fetch/api/policies/csp-blocked.js.headers | 1 + test/wpt/tests/fetch/api/policies/nested-policy.js | 1 + .../fetch/api/policies/nested-policy.js.headers | 1 + .../referrer-no-referrer-service-worker.https.html | 18 + .../api/policies/referrer-no-referrer-worker.html | 17 + .../fetch/api/policies/referrer-no-referrer.html | 15 + .../api/policies/referrer-no-referrer.html.headers | 1 + .../fetch/api/policies/referrer-no-referrer.js | 19 + .../api/policies/referrer-no-referrer.js.headers | 1 + .../referrer-origin-service-worker.https.html | 18 + ...gin-when-cross-origin-service-worker.https.html | 17 + .../referrer-origin-when-cross-origin-worker.html | 16 + .../referrer-origin-when-cross-origin.html | 16 + .../referrer-origin-when-cross-origin.html.headers | 1 + .../policies/referrer-origin-when-cross-origin.js | 21 + .../referrer-origin-when-cross-origin.js.headers | 1 + .../fetch/api/policies/referrer-origin-worker.html | 17 + .../tests/fetch/api/policies/referrer-origin.html | 16 + .../api/policies/referrer-origin.html.headers | 1 + .../tests/fetch/api/policies/referrer-origin.js | 30 + .../fetch/api/policies/referrer-origin.js.headers | 1 + .../referrer-unsafe-url-service-worker.https.html | 18 + .../api/policies/referrer-unsafe-url-worker.html | 17 + .../fetch/api/policies/referrer-unsafe-url.html | 16 + .../api/policies/referrer-unsafe-url.html.headers | 1 + .../fetch/api/policies/referrer-unsafe-url.js | 21 + .../api/policies/referrer-unsafe-url.js.headers | 1 + .../redirect-back-to-original-origin.any.js | 38 + .../tests/fetch/api/redirect/redirect-count.any.js | 51 + .../api/redirect/redirect-empty-location.any.js | 21 + .../fetch/api/redirect/redirect-keepalive.any.js | 94 + .../redirect-location-escape.tentative.any.js | 46 + .../fetch/api/redirect/redirect-location.any.js | 73 + .../fetch/api/redirect/redirect-method.any.js | 112 + .../tests/fetch/api/redirect/redirect-mode.any.js | 59 + .../fetch/api/redirect/redirect-origin.any.js | 68 + .../api/redirect/redirect-referrer-override.any.js | 104 + .../fetch/api/redirect/redirect-referrer.any.js | 66 + .../fetch/api/redirect/redirect-schemes.any.js | 19 + .../fetch/api/redirect/redirect-to-dataurl.any.js | 28 + .../fetch/api/redirect/redirect-upload.h2.any.js | 33 + .../destination/fetch-destination-frame.https.html | 51 + .../fetch-destination-iframe.https.html | 51 + .../fetch-destination-no-load-event.https.html | 124 + .../fetch-destination-prefetch.https.html | 46 + .../fetch-destination-worker.https.html | 60 + .../destination/fetch-destination.https.html | 435 ++ .../fetch/api/request/destination/resources/dummy | 0 .../api/request/destination/resources/dummy.es | 0 .../request/destination/resources/dummy.es.headers | 1 + .../api/request/destination/resources/dummy.html | 0 .../api/request/destination/resources/dummy.png | Bin 0 -> 18299 bytes .../api/request/destination/resources/dummy.ttf | Bin 0 -> 2528 bytes .../request/destination/resources/dummy_audio.mp3 | Bin 0 -> 20498 bytes .../request/destination/resources/dummy_audio.oga | Bin 0 -> 18541 bytes .../request/destination/resources/dummy_video.mp4 | Bin 0 -> 67369 bytes .../request/destination/resources/dummy_video.ogv | Bin 0 -> 94372 bytes .../request/destination/resources/dummy_video.webm | Bin 0 -> 96902 bytes .../request/destination/resources/empty.https.html | 0 .../resources/fetch-destination-worker-frame.js | 20 + .../resources/fetch-destination-worker-iframe.js | 20 + .../fetch-destination-worker-no-load-event.js | 20 + .../resources/fetch-destination-worker.js | 12 + .../api/request/destination/resources/importer.js | 1 + .../fetch/api/request/forbidden-method.any.js | 13 + .../construct-in-detached-frame.window.js | 11 + .../api/request/multi-globals/current/current.html | 3 + .../request/multi-globals/incumbent/incumbent.html | 14 + .../api/request/multi-globals/url-parsing.html | 27 + .../fetch/api/request/request-bad-port.any.js | 92 + .../request-cache-default-conditional.any.js | 170 + .../fetch/api/request/request-cache-default.any.js | 39 + .../api/request/request-cache-force-cache.any.js | 67 + .../api/request/request-cache-no-cache.any.js | 25 + .../api/request/request-cache-no-store.any.js | 37 + .../request/request-cache-only-if-cached.any.js | 66 + .../fetch/api/request/request-cache-reload.any.js | 51 + test/wpt/tests/fetch/api/request/request-cache.js | 223 + .../tests/fetch/api/request/request-clone.sub.html | 63 + .../fetch/api/request/request-consume-empty.any.js | 101 + .../tests/fetch/api/request/request-consume.any.js | 145 + .../fetch/api/request/request-disturbed.any.js | 109 + .../tests/fetch/api/request/request-error.any.js | 56 + test/wpt/tests/fetch/api/request/request-error.js | 57 + .../tests/fetch/api/request/request-headers.any.js | 178 + .../fetch/api/request/request-init-001.sub.html | 112 + .../fetch/api/request/request-init-002.any.js | 60 + .../fetch/api/request/request-init-003.sub.html | 84 + .../api/request/request-init-contenttype.any.js | 141 + .../fetch/api/request/request-init-priority.any.js | 26 + .../fetch/api/request/request-init-stream.any.js | 147 + .../fetch/api/request/request-keepalive-quota.html | 97 + .../fetch/api/request/request-keepalive.any.js | 17 + .../request/request-reset-attributes.https.html | 96 + .../fetch/api/request/request-structure.any.js | 143 + .../wpt/tests/fetch/api/request/resources/cache.py | 67 + .../tests/fetch/api/request/resources/hello.txt | 1 + .../resources/request-reset-attributes-worker.js | 19 + test/wpt/tests/fetch/api/request/url-encoding.html | 25 + .../tests/fetch/api/resources/authentication.py | 14 + .../fetch/api/resources/bad-chunk-encoding.py | 13 + test/wpt/tests/fetch/api/resources/basic.html | 5 + test/wpt/tests/fetch/api/resources/cache.py | 18 + test/wpt/tests/fetch/api/resources/clean-stash.py | 6 + test/wpt/tests/fetch/api/resources/cors-top.txt | 1 + .../tests/fetch/api/resources/cors-top.txt.headers | 1 + test/wpt/tests/fetch/api/resources/data.json | 1 + .../api/resources/dump-authorization-header.py | 14 + .../tests/fetch/api/resources/echo-content.h2.py | 7 + test/wpt/tests/fetch/api/resources/echo-content.py | 12 + test/wpt/tests/fetch/api/resources/empty.txt | 0 .../fetch/api/resources/infinite-slow-response.py | 35 + .../tests/fetch/api/resources/inspect-headers.py | 24 + .../tests/fetch/api/resources/keepalive-helper.js | 99 + .../fetch/api/resources/keepalive-iframe.html | 21 + .../api/resources/keepalive-redirect-iframe.html | 23 + .../api/resources/keepalive-redirect-window.html | 42 + test/wpt/tests/fetch/api/resources/method.py | 18 + test/wpt/tests/fetch/api/resources/preflight.py | 78 + .../fetch/api/resources/redirect-empty-location.py | 3 + test/wpt/tests/fetch/api/resources/redirect.h2.py | 14 + test/wpt/tests/fetch/api/resources/redirect.py | 73 + .../fetch/api/resources/sandboxed-iframe.html | 34 + .../fetch/api/resources/script-with-header.py | 7 + test/wpt/tests/fetch/api/resources/stash-put.py | 19 + test/wpt/tests/fetch/api/resources/stash-take.py | 9 + test/wpt/tests/fetch/api/resources/status.py | 11 + .../fetch/api/resources/sw-intercept-abort.js | 19 + test/wpt/tests/fetch/api/resources/sw-intercept.js | 10 + test/wpt/tests/fetch/api/resources/top.txt | 1 + test/wpt/tests/fetch/api/resources/trickle.py | 15 + test/wpt/tests/fetch/api/resources/utils.js | 105 + test/wpt/tests/fetch/api/response/json.any.js | 14 + .../api/response/many-empty-chunks-crash.html | 14 + .../response/multi-globals/current/current.html | 3 + .../multi-globals/incumbent/incumbent.html | 16 + .../response/multi-globals/relevant/relevant.html | 2 + .../api/response/multi-globals/url-parsing.html | 27 + .../response/response-body-read-task-handling.html | 86 + .../api/response/response-cancel-stream.any.js | 64 + .../api/response/response-clone-iframe.window.js | 32 + .../tests/fetch/api/response/response-clone.any.js | 140 + .../api/response/response-consume-empty.any.js | 99 + .../api/response/response-consume-stream.any.js | 61 + .../tests/fetch/api/response/response-consume.html | 317 ++ .../api/response/response-error-from-stream.any.js | 59 + .../tests/fetch/api/response/response-error.any.js | 27 + .../fetch/api/response/response-from-stream.any.js | 23 + .../fetch/api/response/response-init-001.any.js | 64 + .../fetch/api/response/response-init-002.any.js | 61 + .../api/response/response-init-contenttype.any.js | 125 + .../api/response/response-static-error.any.js | 34 + .../fetch/api/response/response-static-json.any.js | 96 + .../api/response/response-static-redirect.any.js | 40 + .../api/response/response-stream-bad-chunk.any.js | 24 + .../response/response-stream-disturbed-1.any.js | 44 + .../response/response-stream-disturbed-2.any.js | 35 + .../response/response-stream-disturbed-3.any.js | 36 + .../response/response-stream-disturbed-4.any.js | 35 + .../response/response-stream-disturbed-5.any.js | 19 + .../response/response-stream-disturbed-6.any.js | 76 + .../response-stream-disturbed-by-pipe.any.js | 17 + .../api/response/response-stream-disturbed-util.js | 17 + .../response-stream-with-broken-then.any.js | 117 + .../connection-pool/network-partition-key.html | 264 ++ .../network-partition-about-blank-checker.html | 35 + .../resources/network-partition-checker.html | 30 + .../network-partition-iframe-checker.html | 22 + .../resources/network-partition-key.js | 47 + .../resources/network-partition-key.py | 130 + .../network-partition-worker-checker.html | 24 + .../resources/network-partition-worker.js | 15 + .../fetch/content-encoding/bad-gzip-body.any.js | 22 + .../tests/fetch/content-encoding/gzip-body.any.js | 16 + .../content-encoding/resources/bad-gzip-body.py | 3 + .../content-encoding/resources/foo.octetstream.gz | Bin 0 -> 64 bytes .../resources/foo.octetstream.gz.headers | 2 + .../fetch/content-encoding/resources/foo.text.gz | Bin 0 -> 57 bytes .../content-encoding/resources/foo.text.gz.headers | 2 + .../api-and-duplicate-headers.any.js | 23 + .../tests/fetch/content-length/content-length.html | 14 + .../content-length/content-length.html.headers | 1 + .../tests/fetch/content-length/parsing.window.js | 18 + .../content-length/resources/content-length.py | 10 + .../content-length/resources/content-lengths.json | 142 + .../resources/identical-duplicates.asis | 9 + .../tests/fetch/content-length/too-long.window.js | 4 + test/wpt/tests/fetch/content-type/README.md | 20 + .../fetch/content-type/multipart-malformed.any.js | 22 + .../tests/fetch/content-type/multipart.window.js | 33 + .../fetch/content-type/resources/content-type.py | 18 + .../content-type/resources/content-types.json | 122 + .../resources/script-content-types.json | 92 + .../tests/fetch/content-type/response.window.js | 72 + test/wpt/tests/fetch/content-type/script.window.js | 48 + test/wpt/tests/fetch/corb/README.md | 67 + .../corb/img-html-correctly-labeled.sub-ref.html | 4 + .../fetch/corb/img-html-correctly-labeled.sub.html | 11 + .../img-mime-types-coverage.tentative.sub.html | 85 + ...slabeled-as-html-nosniff.tentative.sub-ref.html | 4 + ...g-mislabeled-as-html-nosniff.tentative.sub.html | 11 + .../corb/img-png-mislabeled-as-html.sub-ref.html | 4 + .../fetch/corb/img-png-mislabeled-as-html.sub.html | 10 + .../img-svg-doctype-html-mimetype-empty.sub.html | 7 + .../img-svg-doctype-html-mimetype-svg.sub.html | 11 + .../tests/fetch/corb/img-svg-invalid.sub-ref.html | 5 + .../fetch/corb/img-svg-labeled-as-dash.sub.html | 6 + .../fetch/corb/img-svg-labeled-as-svg-xml.sub.html | 6 + .../wpt/tests/fetch/corb/img-svg-xml-decl.sub.html | 6 + test/wpt/tests/fetch/corb/img-svg.sub-ref.html | 5 + ...g-mislabeled-as-html-nosniff.tentative.sub.html | 24 + .../resources/css-mislabeled-as-html-nosniff.css | 1 + .../css-mislabeled-as-html-nosniff.css.headers | 2 + .../corb/resources/css-mislabeled-as-html.css | 1 + .../resources/css-mislabeled-as-html.css.headers | 1 + .../resources/css-with-json-parser-breaker.css | 3 + .../fetch/corb/resources/empty-labeled-as-png.png | 0 .../resources/empty-labeled-as-png.png.headers | 1 + .../corb/resources/html-correctly-labeled.html | 10 + .../resources/html-correctly-labeled.html.headers | 1 + .../tests/fetch/corb/resources/html-js-polyglot.js | 9 + .../corb/resources/html-js-polyglot.js.headers | 1 + .../fetch/corb/resources/html-js-polyglot2.js | 10 + .../corb/resources/html-js-polyglot2.js.headers | 1 + .../resources/js-mislabeled-as-html-nosniff.js | 1 + .../js-mislabeled-as-html-nosniff.js.headers | 2 + .../fetch/corb/resources/js-mislabeled-as-html.js | 1 + .../resources/js-mislabeled-as-html.js.headers | 1 + .../fetch/corb/resources/png-correctly-labeled.png | Bin 0 -> 1010 bytes .../resources/png-correctly-labeled.png.headers | 1 + .../resources/png-mislabeled-as-html-nosniff.png | Bin 0 -> 1010 bytes .../png-mislabeled-as-html-nosniff.png.headers | 2 + .../corb/resources/png-mislabeled-as-html.png | Bin 0 -> 1010 bytes .../resources/png-mislabeled-as-html.png.headers | 1 + .../fetch/corb/resources/response_block_probe.js | 1 + .../corb/resources/response_block_probe.js.headers | 1 + .../fetch/corb/resources/sniffable-resource.py | 11 + ...t-posts-html-containing-blob-url-to-parent.html | 16 + .../resources/svg-doctype-html-mimetype-empty.svg | 4 + .../svg-doctype-html-mimetype-empty.svg.headers | 1 + .../resources/svg-doctype-html-mimetype-svg.svg | 4 + .../svg-doctype-html-mimetype-svg.svg.headers | 1 + .../fetch/corb/resources/svg-labeled-as-dash.svg | 3 + .../corb/resources/svg-labeled-as-dash.svg.headers | 1 + .../corb/resources/svg-labeled-as-svg-xml.svg | 3 + .../resources/svg-labeled-as-svg-xml.svg.headers | 1 + .../tests/fetch/corb/resources/svg-xml-decl.svg | 4 + test/wpt/tests/fetch/corb/resources/svg.svg | 3 + .../wpt/tests/fetch/corb/resources/svg.svg.headers | 1 + .../fetch/corb/response_block.tentative.https.html | 50 + ...cript-html-correctly-labeled.tentative.sub.html | 32 + .../fetch/corb/script-html-js-polyglot.sub.html | 32 + .../script-html-via-cross-origin-blob-url.sub.html | 38 + .../script-js-mislabeled-as-html-nosniff.sub.html | 33 + .../corb/script-js-mislabeled-as-html.sub.html | 25 + ...rce-with-json-parser-breaker.tentative.sub.html | 85 + ...urce-with-nonsniffable-types.tentative.sub.html | 84 + .../style-css-mislabeled-as-html-nosniff.sub.html | 42 + .../corb/style-css-mislabeled-as-html.sub.html | 36 + .../style-css-with-json-parser-breaker.sub.html | 38 + .../corb/style-html-correctly-labeled.sub.html | 41 + .../fetch-in-iframe.html | 67 + .../cross-origin-resource-policy/fetch.any.js | 76 + .../fetch.https.any.js | 56 + .../cross-origin-resource-policy/iframe-loads.html | 46 + .../cross-origin-resource-policy/image-loads.html | 54 + .../resources/green.png | Bin 0 -> 87 bytes .../resources/hello.py | 6 + .../resources/iframe.py | 5 + .../resources/iframeFetch.html | 19 + .../resources/image.py | 22 + .../resources/redirect.py | 6 + .../resources/script.py | 6 + .../scheme-restriction.any.js | 7 + .../scheme-restriction.https.window.js | 13 + .../cross-origin-resource-policy/script-loads.html | 52 + .../cross-origin-resource-policy/syntax.any.js | 19 + test/wpt/tests/fetch/data-urls/README.md | 11 + test/wpt/tests/fetch/data-urls/base64.any.js | 18 + test/wpt/tests/fetch/data-urls/navigate.window.js | 75 + test/wpt/tests/fetch/data-urls/processing.any.js | 22 + .../tests/fetch/data-urls/resources/base64.json | 82 + .../tests/fetch/data-urls/resources/data-urls.json | 214 + test/wpt/tests/fetch/fetch-later/META.yml | 3 + test/wpt/tests/fetch/fetch-later/README.md | 3 + .../fetch-later/basic.tentative.https.window.js | 13 + .../tests/fetch/fetch-later/non-secure.window.js | 8 + .../sendondiscard.tentative.https.window.js | 28 + test/wpt/tests/fetch/h1-parsing/README.md | 5 + test/wpt/tests/fetch/h1-parsing/lone-cr.window.js | 23 + .../resources-with-0x00-in-header.window.js | 31 + .../wpt/tests/fetch/h1-parsing/resources/README.md | 6 + .../resources/blue-with-0x00-in-a-header.asis | Bin 0 -> 546 bytes .../resources/document-with-0x00-in-header.py | 4 + .../tests/fetch/h1-parsing/resources/message.py | 3 + .../resources/script-with-0x00-in-header.py | 4 + .../fetch/h1-parsing/resources/status-code.py | 6 + .../tests/fetch/h1-parsing/status-code.window.js | 98 + test/wpt/tests/fetch/http-cache/304-update.any.js | 146 + test/wpt/tests/fetch/http-cache/README.md | 72 + .../http-cache/basic-auth-cache-test-ref.html | 6 + .../fetch/http-cache/basic-auth-cache-test.html | 27 + test/wpt/tests/fetch/http-cache/cache-mode.any.js | 61 + test/wpt/tests/fetch/http-cache/cc-request.any.js | 202 + .../fetch/http-cache/credentials.tentative.any.js | 62 + test/wpt/tests/fetch/http-cache/freshness.any.js | 215 + test/wpt/tests/fetch/http-cache/heuristic.any.js | 93 + test/wpt/tests/fetch/http-cache/http-cache.js | 274 ++ test/wpt/tests/fetch/http-cache/invalidate.any.js | 235 + test/wpt/tests/fetch/http-cache/partial.any.js | 208 + test/wpt/tests/fetch/http-cache/post-patch.any.js | 46 + .../tests/fetch/http-cache/resources/http-cache.py | 124 + .../fetch/http-cache/resources/securedimage.py | 19 + .../resources/split-cache-popup-with-iframe.html | 34 + .../http-cache/resources/split-cache-popup.html | 28 + test/wpt/tests/fetch/http-cache/split-cache.html | 158 + test/wpt/tests/fetch/http-cache/status.any.js | 60 + test/wpt/tests/fetch/http-cache/vary.any.js | 313 ++ .../canvas-remote-read-remote-image-redirect.html | 28 + test/wpt/tests/fetch/metadata/META.yml | 4 + test/wpt/tests/fetch/metadata/README.md | 9 + .../tests/fetch/metadata/audio-worklet.https.html | 20 + .../fetch/metadata/embed.https.sub.tentative.html | 63 + .../metadata/fetch-preflight.https.sub.any.js | 29 + .../tests/fetch/metadata/fetch.https.sub.any.js | 58 + .../generated/appcache-manifest.https.sub.html | 341 ++ .../metadata/generated/audioworklet.https.sub.html | 271 ++ .../css-font-face.https.sub.tentative.html | 230 + .../generated/css-font-face.sub.tentative.html | 196 + .../generated/css-images.https.sub.tentative.html | 1384 ++++++ .../generated/css-images.sub.tentative.html | 1099 +++++ .../metadata/generated/element-a.https.sub.html | 482 ++ .../fetch/metadata/generated/element-a.sub.html | 342 ++ .../metadata/generated/element-area.https.sub.html | 482 ++ .../fetch/metadata/generated/element-area.sub.html | 342 ++ .../generated/element-audio.https.sub.html | 325 ++ .../metadata/generated/element-audio.sub.html | 229 + .../generated/element-embed.https.sub.html | 224 + .../metadata/generated/element-embed.sub.html | 190 + .../generated/element-frame.https.sub.html | 309 ++ .../metadata/generated/element-frame.sub.html | 250 + .../generated/element-iframe.https.sub.html | 309 ++ .../metadata/generated/element-iframe.sub.html | 250 + .../element-img-environment-change.https.sub.html | 357 ++ .../element-img-environment-change.sub.html | 270 ++ .../metadata/generated/element-img.https.sub.html | 645 +++ .../fetch/metadata/generated/element-img.sub.html | 456 ++ .../generated/element-input-image.https.sub.html | 229 + .../generated/element-input-image.sub.html | 184 + .../generated/element-link-icon.https.sub.html | 371 ++ .../metadata/generated/element-link-icon.sub.html | 279 ++ .../element-link-prefetch.https.optional.sub.html | 559 +++ .../element-link-prefetch.optional.sub.html | 275 ++ .../element-meta-refresh.https.optional.sub.html | 276 ++ .../element-meta-refresh.optional.sub.html | 225 + .../generated/element-picture.https.sub.html | 997 ++++ .../metadata/generated/element-picture.sub.html | 721 +++ .../generated/element-script.https.sub.html | 593 +++ .../metadata/generated/element-script.sub.html | 488 ++ .../generated/element-video-poster.https.sub.html | 243 + .../generated/element-video-poster.sub.html | 198 + .../generated/element-video.https.sub.html | 325 ++ .../metadata/generated/element-video.sub.html | 229 + .../fetch-via-serviceworker.https.sub.html | 683 +++ .../fetch/metadata/generated/fetch.https.sub.html | 302 ++ .../tests/fetch/metadata/generated/fetch.sub.html | 220 + .../generated/form-submission.https.sub.html | 522 +++ .../metadata/generated/form-submission.sub.html | 400 ++ .../metadata/generated/header-link.https.sub.html | 529 +++ .../generated/header-link.https.sub.tentative.html | 51 + .../fetch/metadata/generated/header-link.sub.html | 460 ++ .../header-refresh.https.optional.sub.html | 273 ++ .../generated/header-refresh.optional.sub.html | 222 + .../script-module-import-dynamic.https.sub.html | 254 + .../script-module-import-dynamic.sub.html | 214 + .../script-module-import-static.https.sub.html | 288 ++ .../generated/script-module-import-static.sub.html | 246 + .../generated/serviceworker.https.sub.html | 170 + .../metadata/generated/svg-image.https.sub.html | 367 ++ .../fetch/metadata/generated/svg-image.sub.html | 265 ++ .../generated/window-history.https.sub.html | 237 + .../metadata/generated/window-history.sub.html | 360 ++ .../generated/window-location.https.sub.html | 1184 +++++ .../metadata/generated/window-location.sub.html | 894 ++++ .../worker-dedicated-constructor.https.sub.html | 118 + .../worker-dedicated-constructor.sub.html | 204 + .../worker-dedicated-importscripts.https.sub.html | 268 ++ .../worker-dedicated-importscripts.sub.html | 228 + .../tests/fetch/metadata/navigation.https.sub.html | 23 + .../wpt/tests/fetch/metadata/object.https.sub.html | 62 + .../tests/fetch/metadata/paint-worklet.https.html | 19 + .../wpt/tests/fetch/metadata/portal.https.sub.html | 50 + .../tests/fetch/metadata/preload.https.sub.html | 50 + ...tiple-redirect-https-downgrade-upgrade.sub.html | 18 + .../redirect/redirect-http-upgrade.sub.html | 17 + .../redirect/redirect-https-downgrade.sub.html | 17 + .../wpt/tests/fetch/metadata/report.https.sub.html | 33 + .../metadata/report.https.sub.html.sub.headers | 3 + .../metadata/resources/appcache-iframe.sub.html | 15 + .../fetch/metadata/resources/dedicatedWorker.js | 1 + .../tests/fetch/metadata/resources/echo-as-json.py | 29 + .../fetch/metadata/resources/echo-as-script.py | 14 + .../fetch/metadata/resources/es-module.sub.js | 1 + .../fetch-via-serviceworker--fallback--sw.js | 3 + .../fetch-via-serviceworker--respondWith--sw.js | 3 + .../resources/fetch-via-serviceworker-frame.html | 3 + .../tests/fetch/metadata/resources/header-link.py | 15 + test/wpt/tests/fetch/metadata/resources/helper.js | 42 + .../tests/fetch/metadata/resources/helper.sub.js | 67 + .../fetch/metadata/resources/message-opener.html | 17 + .../fetch/metadata/resources/post-to-owner.py | 36 + .../fetch/metadata/resources/record-header.py | 145 + .../fetch/metadata/resources/record-headers.py | 73 + .../metadata/resources/redirectTestHelper.sub.js | 167 + .../resources/serviceworker-accessors-frame.html | 3 + .../resources/serviceworker-accessors.sw.js | 14 + .../tests/fetch/metadata/resources/sharedWorker.js | 9 + .../metadata/resources/unload-with-beacon.html | 12 + .../fetch/metadata/resources/xslt-test.sub.xml | 12 + .../serviceworker-accessors.https.sub.html | 51 + .../fetch/metadata/sharedworker.https.sub.html | 40 + test/wpt/tests/fetch/metadata/style.https.sub.html | 86 + test/wpt/tests/fetch/metadata/tools/README.md | 126 + .../fetch/metadata/tools/fetch-metadata.conf.yml | 806 ++++ test/wpt/tests/fetch/metadata/tools/generate.py | 195 + .../templates/appcache-manifest.sub.https.html | 63 + .../tools/templates/audioworklet.https.sub.html | 53 + .../tools/templates/css-font-face.sub.html | 60 + .../metadata/tools/templates/css-images.sub.html | 137 + .../metadata/tools/templates/element-a.sub.html | 72 + .../metadata/tools/templates/element-area.sub.html | 72 + .../tools/templates/element-audio.sub.html | 51 + .../tools/templates/element-embed.sub.html | 54 + .../tools/templates/element-frame.sub.html | 62 + .../tools/templates/element-iframe.sub.html | 62 + .../element-img-environment-change.sub.html | 78 + .../metadata/tools/templates/element-img.sub.html | 52 + .../tools/templates/element-input-image.sub.html | 48 + .../tools/templates/element-link-icon.sub.html | 75 + .../element-link-prefetch.optional.sub.html | 71 + .../element-meta-refresh.optional.sub.html | 60 + .../tools/templates/element-picture.sub.html | 101 + .../tools/templates/element-script.sub.html | 54 + .../tools/templates/element-video-poster.sub.html | 62 + .../tools/templates/element-video.sub.html | 51 + .../fetch-via-serviceworker.https.sub.html | 88 + .../fetch/metadata/tools/templates/fetch.sub.html | 42 + .../tools/templates/form-submission.sub.html | 87 + .../metadata/tools/templates/header-link.sub.html | 56 + .../templates/header-refresh.optional.sub.html | 59 + .../script-module-import-dynamic.sub.html | 35 + .../templates/script-module-import-static.sub.html | 53 + .../tools/templates/serviceworker.https.sub.html | 72 + .../metadata/tools/templates/svg-image.sub.html | 75 + .../tools/templates/window-history.sub.html | 134 + .../tools/templates/window-location.sub.html | 128 + .../worker-dedicated-constructor.sub.html | 49 + .../worker-dedicated-importscripts.sub.html | 54 + test/wpt/tests/fetch/metadata/track.https.sub.html | 119 + .../fetch/metadata/trailing-dot.https.sub.any.js | 30 + .../wpt/tests/fetch/metadata/unload.https.sub.html | 64 + .../fetch/metadata/window-open.https.sub.html | 199 + .../wpt/tests/fetch/metadata/worker.https.sub.html | 24 + test/wpt/tests/fetch/metadata/xslt.https.sub.html | 25 + test/wpt/tests/fetch/nosniff/image.html | 39 + test/wpt/tests/fetch/nosniff/importscripts.html | 14 + test/wpt/tests/fetch/nosniff/importscripts.js | 28 + .../tests/fetch/nosniff/parsing-nosniff.window.js | 27 + test/wpt/tests/fetch/nosniff/resources/css.py | 23 + test/wpt/tests/fetch/nosniff/resources/image.py | 24 + test/wpt/tests/fetch/nosniff/resources/js.py | 17 + test/wpt/tests/fetch/nosniff/resources/nosniff.py | 11 + test/wpt/tests/fetch/nosniff/resources/worker.py | 16 + .../nosniff/resources/x-content-type-options.json | 62 + test/wpt/tests/fetch/nosniff/script.html | 43 + test/wpt/tests/fetch/nosniff/stylesheet.html | 60 + test/wpt/tests/fetch/nosniff/worker.html | 28 + test/wpt/tests/fetch/orb/resources/data.json | 3 + .../tests/fetch/orb/resources/data_non_ascii.json | 1 + test/wpt/tests/fetch/orb/resources/empty.json | 1 + test/wpt/tests/fetch/orb/resources/font.ttf | Bin 0 -> 2528 bytes test/wpt/tests/fetch/orb/resources/image.png | Bin 0 -> 1010 bytes .../resources/js-unlabeled-utf16-without-bom.json | Bin 0 -> 70 bytes test/wpt/tests/fetch/orb/resources/js-unlabeled.js | 1 + .../fetch/orb/resources/png-mislabeled-as-html.png | Bin 0 -> 1010 bytes .../resources/png-mislabeled-as-html.png.headers | 1 + .../tests/fetch/orb/resources/png-unlabeled.png | Bin 0 -> 1010 bytes .../fetch/orb/resources/script-asm-js-invalid.js | 4 + .../fetch/orb/resources/script-asm-js-valid.js | 4 + .../tests/fetch/orb/resources/script-iso-8559-1.js | 4 + .../tests/fetch/orb/resources/script-utf16-bom.js | Bin 0 -> 92 bytes .../orb/resources/script-utf16-without-bom.js | Bin 0 -> 90 bytes test/wpt/tests/fetch/orb/resources/script.js | 4 + test/wpt/tests/fetch/orb/resources/sound.mp3 | Bin 0 -> 539 bytes test/wpt/tests/fetch/orb/resources/text.txt | 1 + test/wpt/tests/fetch/orb/resources/utils.js | 18 + .../tentative/compressed-image-sniffing.sub.html | 20 + .../fetch/orb/tentative/content-range.sub.any.js | 31 + .../img-mime-types-coverage.tentative.sub.html | 126 + .../img-png-mislabeled-as-html.sub-ref.html | 5 + .../tentative/img-png-mislabeled-as-html.sub.html | 7 + .../orb/tentative/img-png-unlabeled.sub-ref.html | 5 + .../fetch/orb/tentative/img-png-unlabeled.sub.html | 7 + .../fetch/orb/tentative/known-mime-type.sub.any.js | 86 + .../tests/fetch/orb/tentative/nosniff.sub.any.js | 59 + .../tentative/script-js-unlabeled-gziped.sub.html | 24 + .../fetch/orb/tentative/script-unlabeled.sub.html | 24 + .../script-utf16-without-bom-hint-charset.sub.html | 22 + .../tests/fetch/orb/tentative/status.sub.any.js | 33 + test/wpt/tests/fetch/orb/tentative/status.sub.html | 17 + .../orb/tentative/unknown-mime-type.sub.any.js | 28 + test/wpt/tests/fetch/origin/assorted.window.js | 211 + .../fetch/origin/resources/redirect-and-stash.py | 38 + .../fetch/origin/resources/referrer-policy.py | 7 + .../tests/fetch/private-network-access/META.yml | 7 + .../tests/fetch/private-network-access/README.md | 10 + ...no-preflight-required.tentative.https.window.js | 91 + ...ame-subresource-fetch.tentative.https.window.js | 330 ++ .../fenced-frame.tentative.https.window.js | 150 + ...-from-treat-as-public.tentative.https.window.js | 80 + .../fetch.tentative.https.window.js | 271 ++ .../fetch.tentative.window.js | 183 + .../iframe.tentative.https.window.js | 266 ++ .../iframe.tentative.window.js | 110 + .../mixed-content-fetch.tentative.https.window.js | 277 ++ .../nested-worker.tentative.https.window.js | 36 + .../nested-worker.tentative.window.js | 36 + .../preflight-cache.https.tentative.window.js | 88 + .../redirect.tentative.https.window.js | 640 +++ .../private-network-access/resources/executor.html | 9 + .../resources/fenced-frame-fetcher.https.html | 25 + .../fenced-frame-fetcher.https.html.headers | 1 + ...ed-frame-local-network-access-target.https.html | 8 + .../fenced-frame-local-network-access.https.html | 14 + ...d-frame-local-network-access.https.html.headers | 1 + .../private-network-access/resources/fetcher.html | 21 + .../private-network-access/resources/fetcher.js | 20 + .../private-network-access/resources/iframed.html | 7 + .../private-network-access/resources/iframer.html | 9 + .../private-network-access/resources/preflight.py | 175 + .../resources/service-worker-bridge.html | 155 + .../resources/service-worker.js | 18 + .../resources/shared-fetcher.js | 23 + .../resources/shared-worker-blob-fetcher.html | 50 + .../resources/shared-worker-fetcher.html | 19 + .../resources/socket-opener.html | 15 + .../resources/support.sub.js | 759 +++ .../resources/worker-blob-fetcher.html | 45 + .../resources/worker-fetcher.html | 18 + .../resources/worker-fetcher.js | 11 + .../resources/xhr-sender.html | 33 + ...rker-background-fetch.tentative.https.window.js | 142 + .../service-worker-fetch.tentative.https.window.js | 235 + ...service-worker-update.tentative.https.window.js | 106 + .../service-worker.tentative.https.window.js | 84 + ...red-worker-blob-fetch.tentative.https.window.js | 168 + .../shared-worker-blob-fetch.tentative.window.js | 173 + .../shared-worker-fetch.tentative.https.window.js | 167 + .../shared-worker-fetch.tentative.window.js | 154 + .../shared-worker.tentative.https.window.js | 34 + .../shared-worker.tentative.window.js | 34 + .../websocket.tentative.https.window.js | 40 + .../websocket.tentative.window.js | 40 + .../worker-blob-fetch.tentative.window.js | 155 + .../worker-fetch.tentative.https.window.js | 151 + .../worker-fetch.tentative.window.js | 154 + .../worker.tentative.https.window.js | 37 + .../worker.tentative.window.js | 37 + ...-from-treat-as-public.tentative.https.window.js | 83 + .../xhr.https.tentative.window.js | 142 + .../private-network-access/xhr.tentative.window.js | 195 + test/wpt/tests/fetch/range/blob.any.js | 233 + test/wpt/tests/fetch/range/data.any.js | 29 + test/wpt/tests/fetch/range/general.any.js | 140 + test/wpt/tests/fetch/range/general.window.js | 29 + .../fetch/range/non-matching-range-response.html | 34 + test/wpt/tests/fetch/range/resources/basic.html | 1 + test/wpt/tests/fetch/range/resources/long-wav.py | 134 + .../tests/fetch/range/resources/partial-script.py | 29 + .../tests/fetch/range/resources/partial-text.py | 53 + test/wpt/tests/fetch/range/resources/range-sw.js | 218 + test/wpt/tests/fetch/range/resources/stash-take.py | 7 + test/wpt/tests/fetch/range/resources/utils.js | 36 + .../fetch/range/resources/video-with-range.py | 43 + test/wpt/tests/fetch/range/sw.https.window.js | 228 + .../redirect-navigate/302-found-post-handler.py | 15 + .../fetch/redirect-navigate/302-found-post.html | 20 + .../fetch/redirect-navigate/preserve-fragment.html | 202 + .../redirect-navigate/resources/destination.html | 28 + test/wpt/tests/fetch/redirects/data.window.js | 25 + .../fetch/redirects/subresource-fragments.html | 39 + test/wpt/tests/fetch/security/1xx-response.any.js | 28 + ...g-markup-mitigation-data-url.tentative.sub.html | 229 + .../dangling-markup-mitigation.tentative.html | 147 + .../embedded-credentials.tentative.sub.html | 89 + .../redirect-to-url-with-credentials.https.html | 68 + .../support/embedded-credential-window.sub.html | 19 + .../stale-while-revalidate/fetch-sw.https.html | 65 + .../fetch/stale-while-revalidate/fetch.any.js | 32 + .../stale-while-revalidate/resources/stale-css.py | 28 + .../resources/stale-image.py | 40 + .../resources/stale-script.py | 32 + .../revalidate-not-blocked-by-csp.html | 69 + .../fetch/stale-while-revalidate/stale-css.html | 51 + .../fetch/stale-while-revalidate/stale-image.html | 55 + .../fetch/stale-while-revalidate/stale-script.html | 59 + .../fetch/stale-while-revalidate/sw-intercept.js | 14 + .../tests/interfaces/ANGLE_instanced_arrays.idl | 12 + test/wpt/tests/interfaces/CSP.idl | 56 + test/wpt/tests/interfaces/DOM-Parsing.idl | 26 + test/wpt/tests/interfaces/EXT_blend_minmax.idl | 10 + .../tests/interfaces/EXT_color_buffer_float.idl | 8 + .../interfaces/EXT_color_buffer_half_float.idl | 12 + .../tests/interfaces/EXT_disjoint_timer_query.idl | 30 + .../interfaces/EXT_disjoint_timer_query_webgl2.idl | 14 + test/wpt/tests/interfaces/EXT_float_blend.idl | 8 + test/wpt/tests/interfaces/EXT_frag_depth.idl | 8 + test/wpt/tests/interfaces/EXT_sRGB.idl | 12 + .../tests/interfaces/EXT_shader_texture_lod.idl | 8 + .../interfaces/EXT_texture_compression_bptc.idl | 12 + .../interfaces/EXT_texture_compression_rgtc.idl | 12 + .../interfaces/EXT_texture_filter_anisotropic.idl | 10 + test/wpt/tests/interfaces/EXT_texture_norm16.idl | 16 + test/wpt/tests/interfaces/FedCM.idl | 67 + test/wpt/tests/interfaces/FileAPI.idl | 100 + test/wpt/tests/interfaces/IndexedDB.idl | 226 + .../interfaces/KHR_parallel_shader_compile.idl | 9 + test/wpt/tests/interfaces/META.yml | 2 + .../tests/interfaces/OES_draw_buffers_indexed.idl | 26 + .../tests/interfaces/OES_element_index_uint.idl | 8 + .../wpt/tests/interfaces/OES_fbo_render_mipmap.idl | 8 + .../tests/interfaces/OES_standard_derivatives.idl | 9 + test/wpt/tests/interfaces/OES_texture_float.idl | 7 + .../tests/interfaces/OES_texture_float_linear.idl | 7 + .../tests/interfaces/OES_texture_half_float.idl | 9 + .../interfaces/OES_texture_half_float_linear.idl | 7 + .../tests/interfaces/OES_vertex_array_object.idl | 18 + test/wpt/tests/interfaces/OVR_multiview2.idl | 14 + test/wpt/tests/interfaces/README.md | 3 + test/wpt/tests/interfaces/SVG.idl | 693 +++ .../WEBGL_blend_equation_advanced_coherent.idl | 23 + .../tests/interfaces/WEBGL_clip_cull_distance.idl | 20 + .../tests/interfaces/WEBGL_color_buffer_float.idl | 11 + .../interfaces/WEBGL_compressed_texture_astc.idl | 41 + .../interfaces/WEBGL_compressed_texture_etc.idl | 19 + .../interfaces/WEBGL_compressed_texture_etc1.idl | 10 + .../interfaces/WEBGL_compressed_texture_pvrtc.idl | 13 + .../interfaces/WEBGL_compressed_texture_s3tc.idl | 13 + .../WEBGL_compressed_texture_s3tc_srgb.idl | 13 + .../tests/interfaces/WEBGL_debug_renderer_info.idl | 12 + test/wpt/tests/interfaces/WEBGL_debug_shaders.idl | 11 + test/wpt/tests/interfaces/WEBGL_depth_texture.idl | 9 + test/wpt/tests/interfaces/WEBGL_draw_buffers.idl | 46 + ...GL_draw_instanced_base_vertex_base_instance.idl | 14 + test/wpt/tests/interfaces/WEBGL_lose_context.idl | 10 + test/wpt/tests/interfaces/WEBGL_multi_draw.idl | 32 + ...ti_draw_instanced_base_vertex_base_instance.idl | 26 + .../tests/interfaces/WEBGL_provoking_vertex.idl | 13 + test/wpt/tests/interfaces/WebCryptoAPI.idl | 237 + test/wpt/tests/interfaces/accelerometer.idl | 40 + test/wpt/tests/interfaces/ambient-light.idl | 14 + test/wpt/tests/interfaces/anchors.idl | 37 + .../tests/interfaces/attribution-reporting-api.idl | 26 + test/wpt/tests/interfaces/audio-output.idl | 17 + test/wpt/tests/interfaces/autoplay-detection.idl | 19 + test/wpt/tests/interfaces/background-fetch.idl | 89 + test/wpt/tests/interfaces/background-sync.idl | 30 + test/wpt/tests/interfaces/badging.idl | 15 + test/wpt/tests/interfaces/battery-status.idl | 21 + test/wpt/tests/interfaces/beacon.idl | 8 + .../tests/interfaces/capture-handle-identity.idl | 27 + .../interfaces/captured-mouse-events.tentative.idl | 25 + test/wpt/tests/interfaces/clipboard-apis.idl | 51 + test/wpt/tests/interfaces/close-watcher.idl | 19 + test/wpt/tests/interfaces/compat.idl | 13 + test/wpt/tests/interfaces/compression.idl | 22 + test/wpt/tests/interfaces/compute-pressure.idl | 37 + test/wpt/tests/interfaces/console.idl | 34 + test/wpt/tests/interfaces/contact-picker.idl | 44 + test/wpt/tests/interfaces/content-index.idl | 46 + test/wpt/tests/interfaces/cookie-store.idl | 110 + .../wpt/tests/interfaces/credential-management.idl | 105 + .../tests/interfaces/csp-embedded-enforcement.idl | 8 + test/wpt/tests/interfaces/csp-next.idl | 21 + test/wpt/tests/interfaces/css-anchor-position.idl | 11 + .../wpt/tests/interfaces/css-animation-worklet.idl | 37 + test/wpt/tests/interfaces/css-animations-2.idl | 9 + test/wpt/tests/interfaces/css-animations.idl | 47 + test/wpt/tests/interfaces/css-cascade-6.idl | 10 + test/wpt/tests/interfaces/css-cascade.idl | 14 + test/wpt/tests/interfaces/css-color-5.idl | 12 + test/wpt/tests/interfaces/css-conditional.idl | 27 + test/wpt/tests/interfaces/css-contain-3.idl | 10 + test/wpt/tests/interfaces/css-contain.idl | 13 + test/wpt/tests/interfaces/css-counter-styles.idl | 23 + test/wpt/tests/interfaces/css-font-loading.idl | 134 + test/wpt/tests/interfaces/css-fonts.idl | 36 + test/wpt/tests/interfaces/css-highlight-api.idl | 27 + test/wpt/tests/interfaces/css-images-4.idl | 8 + test/wpt/tests/interfaces/css-layout-api.idl | 144 + test/wpt/tests/interfaces/css-masking.idl | 20 + test/wpt/tests/interfaces/css-nav.idl | 48 + test/wpt/tests/interfaces/css-nesting.idl | 10 + test/wpt/tests/interfaces/css-paint-api.idl | 39 + test/wpt/tests/interfaces/css-parser-api.idl | 76 + .../tests/interfaces/css-properties-values-api.idl | 23 + test/wpt/tests/interfaces/css-pseudo.idl | 16 + test/wpt/tests/interfaces/css-regions.idl | 29 + test/wpt/tests/interfaces/css-shadow-parts.idl | 8 + test/wpt/tests/interfaces/css-toggle.tentative.idl | 51 + test/wpt/tests/interfaces/css-transitions-2.idl | 9 + test/wpt/tests/interfaces/css-transitions.idl | 25 + test/wpt/tests/interfaces/css-typed-om.idl | 423 ++ test/wpt/tests/interfaces/css-view-transitions.idl | 18 + test/wpt/tests/interfaces/cssom-view.idl | 200 + test/wpt/tests/interfaces/cssom.idl | 169 + .../tests/interfaces/custom-state-pseudo-class.idl | 14 + test/wpt/tests/interfaces/datacue.idl | 12 + .../wpt/tests/interfaces/deprecation-reporting.idl | 15 + test/wpt/tests/interfaces/device-memory.idl | 14 + test/wpt/tests/interfaces/device-posture.idl | 20 + test/wpt/tests/interfaces/digital-goods.idl | 44 + .../interfaces/document-picture-in-picture.idl | 34 + test/wpt/tests/interfaces/dom.idl | 646 +++ test/wpt/tests/interfaces/edit-context.idl | 111 + test/wpt/tests/interfaces/element-timing.idl | 22 + test/wpt/tests/interfaces/encoding.idl | 59 + test/wpt/tests/interfaces/encrypted-media.idl | 125 + test/wpt/tests/interfaces/entries-api.idl | 71 + test/wpt/tests/interfaces/event-timing.idl | 29 + test/wpt/tests/interfaces/eyedropper-api.idl | 18 + test/wpt/tests/interfaces/fenced-frame.idl | 57 + test/wpt/tests/interfaces/fetch.idl | 117 + test/wpt/tests/interfaces/fido.idl | 47 + test/wpt/tests/interfaces/file-system-access.idl | 72 + test/wpt/tests/interfaces/filter-effects.idl | 341 ++ test/wpt/tests/interfaces/font-metrics-api.idl | 42 + test/wpt/tests/interfaces/fs.idl | 97 + test/wpt/tests/interfaces/fullscreen.idl | 35 + test/wpt/tests/interfaces/gamepad-extensions.idl | 71 + test/wpt/tests/interfaces/gamepad.idl | 49 + test/wpt/tests/interfaces/generic-sensor.idl | 60 + test/wpt/tests/interfaces/geolocation-sensor.idl | 47 + test/wpt/tests/interfaces/geolocation.idl | 65 + test/wpt/tests/interfaces/geometry.idl | 290 ++ .../interfaces/get-installed-related-apps.idl | 16 + test/wpt/tests/interfaces/gpc-spec.idl | 10 + test/wpt/tests/interfaces/gyroscope.idl | 24 + test/wpt/tests/interfaces/hr-time.idl | 19 + test/wpt/tests/interfaces/html-media-capture.idl | 8 + test/wpt/tests/interfaces/html.idl | 2725 +++++++++++ test/wpt/tests/interfaces/idle-detection.idl | 31 + test/wpt/tests/interfaces/image-capture.idl | 160 + test/wpt/tests/interfaces/image-resource.idl | 11 + test/wpt/tests/interfaces/ink-enhancement.idl | 32 + .../tests/interfaces/input-device-capabilities.idl | 24 + test/wpt/tests/interfaces/input-events.idl | 14 + .../wpt/tests/interfaces/intersection-observer.idl | 46 + .../tests/interfaces/intervention-reporting.idl | 14 + test/wpt/tests/interfaces/is-input-pending.idl | 16 + test/wpt/tests/interfaces/js-self-profiling.idl | 44 + test/wpt/tests/interfaces/keyboard-lock.idl | 14 + test/wpt/tests/interfaces/keyboard-map.idl | 15 + .../tests/interfaces/largest-contentful-paint.idl | 15 + test/wpt/tests/interfaces/layout-instability.idl | 20 + test/wpt/tests/interfaces/local-font-access.idl | 24 + test/wpt/tests/interfaces/longtasks.idl | 19 + test/wpt/tests/interfaces/magnetometer.idl | 46 + test/wpt/tests/interfaces/manifest-incubations.idl | 24 + test/wpt/tests/interfaces/mathml-core.idl | 9 + test/wpt/tests/interfaces/media-capabilities.idl | 115 + .../tests/interfaces/media-playback-quality.idl | 18 + test/wpt/tests/interfaces/media-source.idl | 91 + .../tests/interfaces/mediacapture-automation.idl | 36 + .../tests/interfaces/mediacapture-fromelement.idl | 17 + .../interfaces/mediacapture-handle-actions.idl | 31 + test/wpt/tests/interfaces/mediacapture-region.idl | 15 + test/wpt/tests/interfaces/mediacapture-streams.idl | 248 + .../tests/interfaces/mediacapture-transform.idl | 23 + .../wpt/tests/interfaces/mediacapture-viewport.idl | 14 + test/wpt/tests/interfaces/mediasession.idl | 84 + .../wpt/tests/interfaces/mediastream-recording.idl | 62 + test/wpt/tests/interfaces/model-element.idl | 9 + test/wpt/tests/interfaces/mst-content-hint.idl | 18 + test/wpt/tests/interfaces/navigation-timing.idl | 71 + test/wpt/tests/interfaces/netinfo.idl | 43 + test/wpt/tests/interfaces/notifications.idl | 101 + test/wpt/tests/interfaces/orientation-event.idl | 78 + test/wpt/tests/interfaces/orientation-sensor.idl | 35 + test/wpt/tests/interfaces/page-lifecycle.idl | 19 + test/wpt/tests/interfaces/paint-timing.idl | 7 + test/wpt/tests/interfaces/parakeet.tentative.idl | 32 + test/wpt/tests/interfaces/payment-handler.idl | 131 + test/wpt/tests/interfaces/payment-request.idl | 112 + .../interfaces/performance-measure-memory.idl | 30 + test/wpt/tests/interfaces/performance-timeline.idl | 49 + .../tests/interfaces/periodic-background-sync.idl | 34 + test/wpt/tests/interfaces/permissions-policy.idl | 29 + test/wpt/tests/interfaces/permissions-request.idl | 8 + test/wpt/tests/interfaces/permissions-revoke.idl | 8 + test/wpt/tests/interfaces/permissions.idl | 41 + test/wpt/tests/interfaces/picture-in-picture.idl | 41 + test/wpt/tests/interfaces/pointerevents.idl | 64 + test/wpt/tests/interfaces/pointerlock.idl | 28 + test/wpt/tests/interfaces/portals.idl | 50 + test/wpt/tests/interfaces/prefer-current-tab.idl | 8 + .../wpt/tests/interfaces/prerendering-revamped.idl | 15 + test/wpt/tests/interfaces/presentation-api.idl | 95 + .../tests/interfaces/private-click-measurement.idl | 8 + test/wpt/tests/interfaces/proximity.idl | 18 + test/wpt/tests/interfaces/push-api.idl | 93 + test/wpt/tests/interfaces/raw-camera-access.idl | 18 + test/wpt/tests/interfaces/real-world-meshing.idl | 21 + test/wpt/tests/interfaces/referrer-policy.idl | 16 + test/wpt/tests/interfaces/remote-playback.idl | 32 + test/wpt/tests/interfaces/reporting.idl | 39 + .../tests/interfaces/requestStorageAccessFor.idl | 12 + test/wpt/tests/interfaces/requestidlecallback.idl | 20 + test/wpt/tests/interfaces/resize-observer.idl | 37 + test/wpt/tests/interfaces/resource-timing.idl | 42 + test/wpt/tests/interfaces/sanitizer-api.idl | 38 + .../tests/interfaces/sanitizer-api.tentative.idl | 17 + test/wpt/tests/interfaces/savedata.idl | 10 + test/wpt/tests/interfaces/scheduling-apis.idl | 63 + test/wpt/tests/interfaces/screen-capture.idl | 85 + test/wpt/tests/interfaces/screen-orientation.idl | 35 + test/wpt/tests/interfaces/screen-wake-lock.idl | 24 + test/wpt/tests/interfaces/scroll-animations.idl | 46 + .../tests/interfaces/scroll-to-text-fragment.idl | 12 + .../interfaces/secure-payment-confirmation.idl | 52 + test/wpt/tests/interfaces/selection-api.idl | 46 + test/wpt/tests/interfaces/serial.idl | 85 + test/wpt/tests/interfaces/server-timing.idl | 17 + test/wpt/tests/interfaces/service-workers.idl | 240 + test/wpt/tests/interfaces/shape-detection-api.idl | 69 + test/wpt/tests/interfaces/shared-storage.idl | 80 + test/wpt/tests/interfaces/speech-api.idl | 202 + test/wpt/tests/interfaces/storage-access.idl | 9 + test/wpt/tests/interfaces/storage-buckets.idl | 53 + .../tests/interfaces/storage-buckets.tentative.idl | 36 + test/wpt/tests/interfaces/storage.idl | 25 + test/wpt/tests/interfaces/streams.idl | 222 + test/wpt/tests/interfaces/sub-apps.tentative.idl | 17 + test/wpt/tests/interfaces/svg-animations.idl | 68 + test/wpt/tests/interfaces/testutils.idl | 9 + test/wpt/tests/interfaces/text-detection-api.idl | 18 + test/wpt/tests/interfaces/touch-events.idl | 79 + test/wpt/tests/interfaces/trust-token-api.idl | 26 + test/wpt/tests/interfaces/trusted-types.idl | 71 + test/wpt/tests/interfaces/turtledove.idl | 120 + test/wpt/tests/interfaces/ua-client-hints.idl | 45 + test/wpt/tests/interfaces/uievents.idl | 248 + test/wpt/tests/interfaces/url.idl | 46 + test/wpt/tests/interfaces/urlpattern.idl | 59 + test/wpt/tests/interfaces/user-timing.idl | 34 + test/wpt/tests/interfaces/vibration.idl | 10 + test/wpt/tests/interfaces/video-rvfc.idl | 27 + test/wpt/tests/interfaces/virtual-keyboard.idl | 21 + .../interfaces/virtual-keyboard.tentative.idl | 15 + test/wpt/tests/interfaces/wai-aria.idl | 59 + test/wpt/tests/interfaces/wasm-js-api.idl | 110 + test/wpt/tests/interfaces/wasm-web-api.idl | 11 + test/wpt/tests/interfaces/web-animations-2.idl | 112 + test/wpt/tests/interfaces/web-animations.idl | 149 + test/wpt/tests/interfaces/web-app-launch.idl | 19 + test/wpt/tests/interfaces/web-bluetooth.idl | 252 + test/wpt/tests/interfaces/web-locks.idl | 50 + test/wpt/tests/interfaces/web-nfc.idl | 81 + test/wpt/tests/interfaces/web-otp.idl | 21 + test/wpt/tests/interfaces/web-share.idl | 16 + test/wpt/tests/interfaces/webaudio.idl | 674 +++ test/wpt/tests/interfaces/webauthn.idl | 350 ++ .../webcodecs-aac-codec-registration.idl | 17 + .../webcodecs-av1-codec-registration.idl | 20 + .../webcodecs-avc-codec-registration.idl | 25 + .../webcodecs-flac-codec-registration.idl | 13 + .../webcodecs-hevc-codec-registration.idl | 17 + .../webcodecs-opus-codec-registration.idl | 22 + .../webcodecs-vp9-codec-registration.idl | 12 + test/wpt/tests/interfaces/webcodecs.idl | 501 ++ .../tests/interfaces/webcrypto-secure-curves.idl | 8 + test/wpt/tests/interfaces/webdriver.idl | 9 + test/wpt/tests/interfaces/webgl1.idl | 745 +++ test/wpt/tests/interfaces/webgl2.idl | 582 +++ test/wpt/tests/interfaces/webgpu.idl | 1293 +++++ test/wpt/tests/interfaces/webhid.idl | 127 + test/wpt/tests/interfaces/webidl.idl | 48 + test/wpt/tests/interfaces/webmidi.idl | 91 + test/wpt/tests/interfaces/webnn.idl | 544 +++ .../tests/interfaces/webrtc-encoded-transform.idl | 128 + test/wpt/tests/interfaces/webrtc-ice.idl | 24 + test/wpt/tests/interfaces/webrtc-identity.idl | 97 + test/wpt/tests/interfaces/webrtc-priority.idl | 24 + test/wpt/tests/interfaces/webrtc-stats.idl | 288 ++ test/wpt/tests/interfaces/webrtc-svc.idl | 8 + test/wpt/tests/interfaces/webrtc.idl | 627 +++ test/wpt/tests/interfaces/websockets.idl | 48 + test/wpt/tests/interfaces/webtransport.idl | 145 + test/wpt/tests/interfaces/webusb.idl | 249 + test/wpt/tests/interfaces/webvr.tentative.idl | 204 + test/wpt/tests/interfaces/webvtt.idl | 40 + test/wpt/tests/interfaces/webxr-ar-module.idl | 29 + test/wpt/tests/interfaces/webxr-depth-sensing.idl | 57 + test/wpt/tests/interfaces/webxr-dom-overlays.idl | 31 + .../wpt/tests/interfaces/webxr-gamepads-module.idl | 8 + test/wpt/tests/interfaces/webxr-hand-input.idl | 66 + test/wpt/tests/interfaces/webxr-hit-test.idl | 69 + .../tests/interfaces/webxr-lighting-estimation.idl | 39 + test/wpt/tests/interfaces/webxr.idl | 295 ++ test/wpt/tests/interfaces/webxrlayers.idl | 221 + .../tests/interfaces/window-controls-overlay.idl | 28 + test/wpt/tests/interfaces/window-management.idl | 42 + test/wpt/tests/interfaces/xhr.idl | 99 + test/wpt/tests/lint.ignore | 707 +++ test/wpt/tests/mimesniff/META.yml | 3 + test/wpt/tests/mimesniff/README.md | 4 + .../tests/mimesniff/media/media-sniff.window.js | 32 + test/wpt/tests/mimesniff/media/resources/flac.flac | Bin 0 -> 8493 bytes .../mimesniff/media/resources/make-vectors.sh | 10 + .../tests/mimesniff/media/resources/mp3-raw.mp3 | Bin 0 -> 417 bytes .../mimesniff/media/resources/mp3-with-id3.mp3 | Bin 0 -> 644 bytes test/wpt/tests/mimesniff/media/resources/mp4.mp4 | Bin 0 -> 1231 bytes test/wpt/tests/mimesniff/media/resources/ogg.ogg | Bin 0 -> 3594 bytes test/wpt/tests/mimesniff/media/resources/wav.wav | Bin 0 -> 486 bytes test/wpt/tests/mimesniff/media/resources/webm.webm | Bin 0 -> 877 bytes test/wpt/tests/mimesniff/mime-types/README.md | 47 + .../mime-types/charset-parameter.window.js | 61 + test/wpt/tests/mimesniff/mime-types/parsing.any.js | 57 + .../mime-types/resources/generated-mime-types.json | 3526 ++++++++++++++ .../mime-types/resources/generated-mime-types.py | 48 + .../mimesniff/mime-types/resources/mime-charset.py | 19 + .../mime-types/resources/mime-groups.json | 159 + .../mimesniff/mime-types/resources/mime-types.json | 397 ++ test/wpt/tests/resources/.htaccess | 2 + test/wpt/tests/resources/META.yml | 2 + .../resources/SVGAnimationTestCase-testharness.js | 102 + test/wpt/tests/resources/accesskey.js | 34 + test/wpt/tests/resources/blank.html | 16 + test/wpt/tests/resources/channel.sub.js | 1097 +++++ test/wpt/tests/resources/check-layout-th.js | 252 + test/wpt/tests/resources/check-layout.js | 245 + test/wpt/tests/resources/chromium/README.md | 7 + .../resources/chromium/contacts_manager_mock.js | 90 + .../resources/chromium/content-index-helpers.js | 9 + .../chromium/enable-hyperlink-auditing.js | 2 + test/wpt/tests/resources/chromium/fake-hid.js | 297 ++ test/wpt/tests/resources/chromium/fake-serial.js | 443 ++ .../resources/chromium/generic_sensor_mocks.js | 519 ++ .../chromium/generic_sensor_mocks.js.headers | 1 + .../resources/chromium/mock-barcodedetection.js | 136 + .../chromium/mock-barcodedetection.js.headers | 1 + .../chromium/mock-battery-monitor.headers | 1 + .../resources/chromium/mock-battery-monitor.js | 61 + .../resources/chromium/mock-direct-sockets.js | 94 + .../tests/resources/chromium/mock-facedetection.js | 130 + .../chromium/mock-facedetection.js.headers | 1 + .../resources/chromium/mock-idle-detection.js | 80 + .../tests/resources/chromium/mock-imagecapture.js | 309 ++ .../resources/chromium/mock-managed-config.js | 91 + .../resources/chromium/mock-pressure-service.js | 134 + .../chromium/mock-pressure-service.js.headers | 1 + test/wpt/tests/resources/chromium/mock-subapps.js | 89 + .../tests/resources/chromium/mock-textdetection.js | 92 + .../chromium/mock-textdetection.js.headers | 1 + test/wpt/tests/resources/chromium/nfc-mock.js | 437 ++ .../tests/resources/chromium/web-bluetooth-test.js | 629 +++ .../chromium/web-bluetooth-test.js.headers | 1 + .../tests/resources/chromium/webusb-child-test.js | 47 + .../chromium/webusb-child-test.js.headers | 1 + test/wpt/tests/resources/chromium/webusb-test.js | 583 +++ .../resources/chromium/webusb-test.js.headers | 1 + .../resources/chromium/webxr-test-math-helper.js | 298 ++ .../chromium/webxr-test-math-helper.js.headers | 1 + test/wpt/tests/resources/chromium/webxr-test.js | 2125 +++++++++ .../tests/resources/chromium/webxr-test.js.headers | 1 + .../resources/declarative-shadow-dom-polyfill.js | 25 + test/wpt/tests/resources/idlharness-shadowrealm.js | 61 + test/wpt/tests/resources/idlharness.js | 3554 ++++++++++++++ test/wpt/tests/resources/idlharness.js.headers | 2 + test/wpt/tests/resources/readme.md | 14 + test/wpt/tests/resources/sriharness.js | 226 + test/wpt/tests/resources/test-only-api.js | 31 + test/wpt/tests/resources/test-only-api.js.headers | 2 + test/wpt/tests/resources/test-only-api.m.js | 5 + .../wpt/tests/resources/test-only-api.m.js.headers | 2 + test/wpt/tests/resources/test/README.md | 83 + test/wpt/tests/resources/test/conftest.py | 269 ++ test/wpt/tests/resources/test/harness.html | 26 + test/wpt/tests/resources/test/idl-helper.js | 24 + .../wpt/tests/resources/test/nested-testharness.js | 80 + test/wpt/tests/resources/test/requirements.txt | 1 + .../test/tests/functional/abortsignal.html | 49 + .../test/tests/functional/add_cleanup.html | 91 + .../test/tests/functional/add_cleanup_async.html | 85 + .../functional/add_cleanup_async_bad_return.html | 50 + .../functional/add_cleanup_async_rejection.html | 94 + .../add_cleanup_async_rejection_after_load.html | 52 + .../functional/add_cleanup_async_timeout.html | 57 + .../tests/functional/add_cleanup_bad_return.html | 61 + .../test/tests/functional/add_cleanup_count.html | 39 + .../test/tests/functional/add_cleanup_err.html | 45 + .../tests/functional/add_cleanup_err_multi.html | 52 + .../tests/functional/add_cleanup_sync_queue.html | 55 + .../test/tests/functional/api-tests-1.html | 991 ++++ .../test/tests/functional/api-tests-2.html | 62 + .../test/tests/functional/api-tests-3.html | 34 + .../test/tests/functional/assert-array-equals.html | 162 + .../test/tests/functional/assert-throws-dom.html | 55 + .../test/tests/functional/force_timeout.html | 60 + .../test/tests/functional/generate-callback.html | 153 + .../IdlDictionary/test_partial_interface_of.html | 89 + .../IdlInterface/test_exposed_wildcard.html | 233 + .../IdlInterface/test_immutable_prototype.html | 298 ++ .../IdlInterface/test_interface_mixin.html | 131 + .../IdlInterface/test_partial_interface_of.html | 187 + .../IdlInterface/test_primary_interface_of.html | 116 + .../IdlInterface/test_to_json_operation.html | 177 + .../idlharness/IdlNamespace/test_attribute.html | 100 + .../idlharness/IdlNamespace/test_operation.html | 242 + .../IdlNamespace/test_partial_namespace.html | 125 + .../test/tests/functional/iframe-callback.html | 116 + .../functional/iframe-consolidate-errors.html | 50 + .../tests/functional/iframe-consolidate-tests.html | 85 + .../test/tests/functional/iframe-msg.html | 84 + .../test/tests/functional/log-insertion.html | 46 + .../resources/test/tests/functional/no-title.html | 146 + .../resources/test/tests/functional/order.html | 36 + .../test/tests/functional/promise-async.html | 172 + .../test/tests/functional/promise-with-sync.html | 79 + .../resources/test/tests/functional/promise.html | 219 + .../resources/test/tests/functional/queue.html | 130 + .../test/tests/functional/setup-function-worker.js | 14 + .../tests/functional/setup-worker-service.html | 86 + .../tests/functional/single-page-test-fail.html | 28 + .../functional/single-page-test-no-assertions.html | 25 + .../tests/functional/single-page-test-no-body.html | 26 + .../tests/functional/single-page-test-pass.html | 28 + .../resources/test/tests/functional/step_wait.html | 57 + .../test/tests/functional/step_wait_func.html | 49 + .../functional/task-scheduling-promise-test.html | 241 + .../tests/functional/task-scheduling-test.html | 141 + .../functional/uncaught-exception-handle.html | 33 + .../functional/uncaught-exception-ignore.html | 35 + .../worker-dedicated-uncaught-allow.html | 45 + .../worker-dedicated-uncaught-single.html | 56 + .../tests/functional/worker-dedicated.sub.html | 88 + .../test/tests/functional/worker-error.js | 8 + .../test/tests/functional/worker-service.html | 115 + .../test/tests/functional/worker-shared.html | 73 + .../test/tests/functional/worker-uncaught-allow.js | 19 + .../tests/functional/worker-uncaught-single.js | 8 + .../resources/test/tests/functional/worker.js | 34 + .../test/tests/unit/IdlArray/is_json_type.html | 192 + .../get_reverse_inheritance_stack.html | 47 + .../IdlDictionary/test_partial_dictionary.html | 39 + .../test/tests/unit/IdlInterface/constructors.html | 26 + .../IdlInterface/default_to_json_operation.html | 114 + .../IdlInterface/do_member_unscopable_asserts.html | 56 + .../unit/IdlInterface/get_interface_object.html | 22 + .../IdlInterface/get_interface_object_owner.html | 21 + .../unit/IdlInterface/get_legacy_namespace.html | 20 + .../unit/IdlInterface/get_qualified_name.html | 20 + .../get_reverse_inheritance_stack.html | 49 + .../has_default_to_json_regular_operation.html | 47 + .../has_to_json_regular_operation.html | 31 + .../IdlInterface/should_have_interface_object.html | 30 + .../test_primary_interface_of_undefined.html | 29 + .../is_to_json_regular_operation.html | 42 + .../tests/unit/IdlInterfaceMember/toString.html | 36 + .../test/tests/unit/assert_implements.html | 43 + .../tests/unit/assert_implements_optional.html | 43 + .../test/tests/unit/assert_object_equals.html | 152 + .../tests/unit/async-test-return-restrictions.html | 135 + .../wpt/tests/resources/test/tests/unit/basic.html | 48 + .../tests/unit/exceptional-cases-timeouts.html | 120 + .../test/tests/unit/exceptional-cases.html | 392 ++ .../resources/test/tests/unit/format-value.html | 123 + .../wpt/tests/resources/test/tests/unit/helpers.js | 21 + .../tests/resources/test/tests/unit/late-test.html | 54 + .../test/tests/unit/promise_setup-timeout.html | 28 + .../resources/test/tests/unit/promise_setup.html | 333 ++ .../resources/test/tests/unit/single_test.html | 94 + .../test/tests/unit/test-return-restrictions.html | 156 + .../test/tests/unit/throwing-assertions.html | 268 ++ .../test/tests/unit/unpaired-surrogates.html | 143 + test/wpt/tests/resources/test/tox.ini | 13 + test/wpt/tests/resources/test/wptserver.py | 58 + test/wpt/tests/resources/testdriver-actions.js | 599 +++ test/wpt/tests/resources/testdriver-vendor.js | 0 .../tests/resources/testdriver-vendor.js.headers | 2 + test/wpt/tests/resources/testdriver.js | 958 ++++ test/wpt/tests/resources/testdriver.js.headers | 2 + test/wpt/tests/resources/testharness.js | 4933 ++++++++++++++++++++ test/wpt/tests/resources/testharness.js.headers | 2 + test/wpt/tests/resources/testharnessreport.js | 57 + .../tests/resources/testharnessreport.js.headers | 2 + test/wpt/tests/resources/webidl2/build.sh | 12 + test/wpt/tests/resources/webidl2/lib/README.md | 4 + test/wpt/tests/resources/webidl2/lib/VERSION.md | 1 + test/wpt/tests/resources/webidl2/lib/webidl2.js | 3824 +++++++++++++++ .../tests/resources/webidl2/lib/webidl2.js.headers | 1 + test/wpt/tests/service-workers/META.yml | 6 + .../tests/service-workers/cache-storage/META.yml | 3 + .../cache-storage/cache-abort.https.any.js | 81 + .../cache-storage/cache-add.https.any.js | 368 ++ .../cache-storage/cache-delete.https.any.js | 164 + ...e-keys-attributes-for-service-worker.https.html | 75 + .../cache-storage/cache-keys.https.any.js | 212 + .../cache-storage/cache-match.https.any.js | 437 ++ .../cache-storage/cache-matchAll.https.any.js | 244 + .../cache-storage/cache-put.https.any.js | 411 ++ .../cache-storage-buckets.https.any.js | 64 + .../cache-storage/cache-storage-keys.https.any.js | 35 + .../cache-storage/cache-storage-match.https.any.js | 245 + .../cache-storage/cache-storage.https.any.js | 239 + .../cache-storage/common.https.window.js | 44 + .../crashtests/cache-response-clone.https.html | 17 + .../cache-storage/credentials.https.html | 46 + .../cross-partition.https.tentative.html | 269 ++ .../cache-storage/resources/blank.html | 2 + .../cache-keys-attributes-for-service-worker.js | 22 + .../cache-storage/resources/common-worker.js | 15 + .../resources/credentials-iframe.html | 38 + .../cache-storage/resources/credentials-worker.js | 59 + .../cache-storage/resources/fetch-status.py | 2 + .../cache-storage/resources/iframe.html | 18 + .../cache-storage/resources/simple.txt | 1 + .../cache-storage/resources/test-helpers.js | 272 ++ .../cache-storage/resources/vary.py | 25 + .../cache-storage/sandboxed-iframes.https.html | 66 + .../tests/service-workers/idlharness.https.any.js | 53 + .../Service-Worker-Allowed-header.https.html | 88 + .../ServiceWorkerGlobalScope/close.https.html | 11 + ...extendable-message-event-constructor.https.html | 10 + .../extendable-message-event.https.html | 226 + .../fetch-on-the-right-interface.https.any.js | 14 + .../isSecureContext.https.html | 32 + .../isSecureContext.serviceworker.js | 5 + .../postmessage.https.html | 83 + .../registration-attribute.https.html | 107 + .../resources/close-worker.js | 5 + .../resources/error-worker.js | 12 + .../extendable-message-event-constructor-worker.js | 197 + .../extendable-message-event-loopback-worker.js | 36 + .../extendable-message-event-ping-worker.js | 23 + .../extendable-message-event-pong-worker.js | 18 + .../resources/extendable-message-event-utils.js | 78 + .../resources/extendable-message-event-worker.js | 5 + .../resources/postmessage-loopback-worker.js | 15 + .../resources/postmessage-ping-worker.js | 15 + .../resources/postmessage-pong-worker.js | 4 + .../registration-attribute-newer-worker.js | 33 + .../resources/registration-attribute-worker.js | 139 + .../resources/unregister-controlling-worker.html | 0 .../resources/unregister-worker.js | 25 + .../resources/update-worker.js | 22 + .../resources/update-worker.py | 16 + .../service-worker-error-event.https.html | 31 + .../ServiceWorkerGlobalScope/unregister.https.html | 139 + .../ServiceWorkerGlobalScope/update.https.html | 48 + .../about-blank-replacement.https.html | 181 + ...ate-event-after-install-state-change.https.html | 33 + .../activation-after-registration.https.html | 28 + .../service-worker/activation.https.html | 168 + .../service-worker/active.https.html | 50 + .../claim-affect-other-registration.https.html | 136 + .../service-worker/claim-fetch.https.html | 90 + .../claim-not-using-registration.https.html | 131 + .../claim-shared-worker-fetch.https.html | 71 + .../claim-using-registration.https.html | 103 + .../service-worker/claim-with-redirect.https.html | 59 + .../service-worker/claim-worker-fetch.https.html | 83 + .../service-worker/client-id.https.html | 60 + .../service-worker/client-navigate.https.html | 107 + .../client-url-of-blob-url-worker.https.html | 29 + .../clients-get-client-types.https.html | 108 + .../clients-get-cross-origin.https.html | 69 + .../clients-get-resultingClientId.https.html | 177 + .../service-worker/clients-get.https.html | 154 + .../clients-matchall-blob-url-worker.https.html | 85 + .../clients-matchall-client-types.https.html | 92 + .../clients-matchall-exact-controller.https.html | 67 + .../clients-matchall-frozen.https.html | 64 + ...lients-matchall-include-uncontrolled.https.html | 117 + .../clients-matchall-on-evaluation.https.html | 24 + .../clients-matchall-order.https.html | 427 ++ .../service-worker/clients-matchall.https.html | 50 + ...ntrolled-dedicatedworker-postMessage.https.html | 44 + .../controlled-iframe-postMessage.https.html | 67 + .../controller-on-disconnect.https.html | 40 + .../service-worker/controller-on-load.https.html | 46 + .../service-worker/controller-on-reload.https.html | 58 + ...ntroller-with-no-fetch-event-handler.https.html | 56 + .../service-worker/credentials.https.html | 100 + .../service-worker/data-iframe.html | 25 + .../service-worker/data-transfer-files.https.html | 41 + ...d-worker-service-worker-interception.https.html | 40 + .../service-worker/detached-context.https.html | 124 + ...embed-and-object-are-not-intercepted.https.html | 104 + .../extendable-event-async-waituntil.https.html | 120 + .../extendable-event-waituntil.https.html | 140 + .../service-worker/fetch-audio-tainting.https.html | 47 + .../fetch-canvas-tainting-double-write.https.html | 57 + .../fetch-canvas-tainting-image-cache.https.html | 16 + .../fetch-canvas-tainting-image.https.html | 16 + .../fetch-canvas-tainting-video-cache.https.html | 17 + ...as-tainting-video-with-range-request.https.html | 92 + .../fetch-canvas-tainting-video.https.html | 17 + .../fetch-cors-exposed-header-names.https.html | 30 + .../service-worker/fetch-cors-xhr.https.html | 49 + .../service-worker/fetch-csp.https.html | 138 + .../service-worker/fetch-error.https.html | 29 + .../fetch-event-add-async.https.html | 11 + ...h-event-after-navigation-within-page.https.html | 71 + .../fetch-event-async-respond-with.https.html | 73 + .../service-worker/fetch-event-handled.https.html | 86 + ...s-history-backward-navigation-manual.https.html | 8 + ...is-history-forward-navigation-manual.https.html | 8 + ...t-is-reload-iframe-navigation-manual.https.html | 31 + ...ch-event-is-reload-navigation-manual.https.html | 8 + .../fetch-event-network-error.https.html | 44 + .../service-worker/fetch-event-redirect.https.html | 1038 ++++ .../fetch-event-referrer-policy.https.html | 274 ++ .../fetch-event-respond-with-argument.https.html | 44 + ...nt-respond-with-body-loaded-in-chunk.https.html | 24 + ...h-event-respond-with-custom-response.https.html | 82 + ...ch-event-respond-with-partial-stream.https.html | 62 + ...t-respond-with-readable-stream-chunk.https.html | 23 + ...h-event-respond-with-readable-stream.https.html | 88 + ...ith-response-body-with-invalid-chunk.https.html | 46 + ...event-respond-with-stops-propagation.https.html | 37 + ...etch-event-throws-after-respond-with.https.html | 37 + .../fetch-event-within-sw-manual.https.html | 122 + .../fetch-event-within-sw.https.html | 53 + .../service-worker/fetch-event.https.h2.html | 112 + .../service-worker/fetch-event.https.html | 1000 ++++ .../service-worker/fetch-frame-resource.https.html | 236 + .../fetch-header-visibility.https.html | 54 + .../fetch-mixed-content-to-inscope.https.html | 21 + .../fetch-mixed-content-to-outscope.https.html | 21 + .../fetch-request-css-base-url.https.html | 87 + .../fetch-request-css-cross-origin.https.html | 81 + .../fetch-request-css-images.https.html | 214 + .../fetch-request-fallback.https.html | 282 ++ .../fetch-request-no-freshness-headers.https.html | 55 + .../fetch-request-redirect.https.html | 385 ++ .../fetch-request-resources.https.html | 302 ++ .../fetch-request-xhr-sync-error.https.window.js | 19 + .../fetch-request-xhr-sync-on-worker.https.html | 41 + .../fetch-request-xhr-sync.https.html | 53 + .../service-worker/fetch-request-xhr.https.html | 75 + .../service-worker/fetch-response-taint.https.html | 223 + .../service-worker/fetch-response-xhr.https.html | 50 + .../fetch-waits-for-activate.https.html | 128 + .../service-worker/getregistration.https.html | 108 + .../service-worker/getregistrations.https.html | 134 + .../global-serviceworker.https.any.js | 53 + .../service-worker/historical.https.any.js | 5 + .../http-to-https-redirect-and-register.https.html | 49 + .../immutable-prototype-serviceworker.https.html | 23 + .../import-scripts-cross-origin.https.html | 18 + .../import-scripts-data-url.https.html | 18 + .../import-scripts-mime-types.https.html | 30 + .../import-scripts-redirect.https.html | 55 + .../import-scripts-resource-map.https.html | 34 + .../import-scripts-updated-flag.https.html | 83 + .../service-worker/indexeddb.https.html | 78 + .../service-worker/install-event-type.https.html | 30 + .../service-worker/installing.https.html | 48 + .../interface-requirements-sw.https.html | 16 + .../service-worker/invalid-blobtype.https.html | 40 + .../service-worker/invalid-header.https.html | 39 + .../service-worker/iso-latin1-header.https.html | 40 + .../local-url-inherit-controller.https.html | 115 + .../service-worker/mime-sniffing.https.html | 24 + .../multi-globals/current/current.https.html | 2 + .../multi-globals/current/test-sw.js | 1 + .../multi-globals/incumbent/incumbent.https.html | 20 + .../multi-globals/incumbent/test-sw.js | 1 + .../multi-globals/relevant/relevant.https.html | 2 + .../multi-globals/relevant/test-sw.js | 1 + .../service-worker/multi-globals/test-sw.js | 1 + .../multi-globals/url-parsing.https.html | 73 + .../service-worker/multipart-image.https.html | 68 + .../service-worker/multiple-register.https.html | 117 + .../service-worker/multiple-update.https.html | 94 + .../service-worker/navigate-window.https.html | 151 + .../service-worker/navigation-headers.https.html | 819 ++++ .../broken-chunked-encoding.https.html | 42 + .../navigation-preload/chunked-encoding.https.html | 25 + .../empty-preload-response-body.https.html | 25 + .../navigation-preload/get-state.https.html | 217 + .../navigationPreload.https.html | 20 + .../navigation-preload/redirect.https.html | 93 + .../navigation-preload/request-headers.https.html | 41 + .../navigation-preload/resource-timing.https.html | 92 + .../resources/broken-chunked-encoding-scope.asis | 6 + .../resources/broken-chunked-encoding-worker.js | 11 + .../resources/chunked-encoding-scope.py | 19 + .../resources/chunked-encoding-worker.js | 8 + .../navigation-preload/resources/cookie.py | 20 + .../empty-preload-response-body-scope.html | 0 .../empty-preload-response-body-worker.js | 15 + .../resources/get-state-worker.js | 21 + .../navigation-preload/resources/helpers.js | 5 + .../resources/navigation-preload-worker.js | 3 + .../resources/redirect-redirected.html | 3 + .../navigation-preload/resources/redirect-scope.py | 38 + .../resources/redirect-worker.js | 35 + .../resources/request-headers-scope.py | 14 + .../resources/request-headers-worker.js | 10 + .../resources/resource-timing-scope.py | 19 + .../resources/resource-timing-worker.js | 37 + .../resources/samesite-iframe.html | 10 + .../resources/samesite-sw-helper.html | 34 + .../resources/samesite-worker.js | 8 + .../resources/wait-for-activate-worker.js | 40 + .../navigation-preload/samesite-cookies.https.html | 61 + .../navigation-preload/samesite-iframe.https.html | 67 + .../navigation-redirect-body.https.html | 53 + .../navigation-redirect-resolution.https.html | 58 + .../navigation-redirect-to-http.https.html | 25 + .../service-worker/navigation-redirect.https.html | 846 ++++ .../navigation-sets-cookie.https.html | 133 + .../navigation-timing-extended.https.html | 55 + .../service-worker/navigation-timing.https.html | 77 + .../nested-blob-url-workers.https.html | 42 + .../service-worker/next-hop-protocol.https.html | 49 + .../no-dynamic-import-in-module.any.js | 7 + .../service-worker/no-dynamic-import.any.js | 3 + .../onactivate-script-error.https.html | 74 + .../oninstall-script-error.https.html | 72 + .../opaque-response-preloaded.https.html | 50 + .../service-worker/opaque-script.https.html | 71 + .../partitioned-claim.tentative.https.html | 74 + .../partitioned-cookies.tentative.https.html | 119 + ...rtitioned-getRegistrations.tentative.https.html | 99 + .../partitioned-matchAll.tentative.https.html | 65 + .../partitioned.tentative.https.html | 188 + .../service-worker/performance-timeline.https.html | 49 + .../service-worker/postMessage-client-worker.js | 23 + .../service-worker/postmessage-blob-url.https.html | 33 + ...stmessage-from-waiting-serviceworker.https.html | 50 + .../postmessage-msgport-to-client.https.html | 43 + .../postmessage-to-client-message-queue.https.html | 212 + .../postmessage-to-client.https.html | 42 + .../service-worker/postmessage.https.html | 202 + .../service-worker/ready.https.window.js | 223 + .../service-worker/redirected-response.https.html | 471 ++ .../service-worker/referer.https.html | 40 + .../referrer-policy-header.https.html | 67 + .../referrer-toplevel-script-fetch.https.html | 64 + .../register-closed-window.https.html | 35 + .../register-default-scope.https.html | 69 + ...ster-same-scope-different-script-url.https.html | 233 + ...ister-wait-forever-in-install-worker.https.html | 57 + .../service-worker/registration-basic.https.html | 39 + .../registration-end-to-end.https.html | 88 + .../service-worker/registration-events.https.html | 42 + .../service-worker/registration-iframe.https.html | 116 + .../registration-mime-types.https.html | 10 + .../registration-schedule-job.https.html | 107 + ...istration-scope-module-static-import.https.html | 41 + .../service-worker/registration-scope.https.html | 9 + .../registration-script-module.https.html | 13 + .../registration-script-url.https.html | 9 + .../service-worker/registration-script.https.html | 12 + .../registration-security-error.https.html | 9 + ...gistration-service-worker-attributes.https.html | 72 + .../registration-updateviacache.https.html | 204 + .../service-worker/rejections.https.html | 21 + .../service-worker/request-end-to-end.https.html | 40 + .../resource-timing-bodySize.https.html | 55 + .../resource-timing-cross-origin.https.html | 46 + .../resource-timing-fetch-variants.https.html | 121 + .../service-worker/resource-timing.sub.https.html | 150 + .../service-worker/resources/404.py | 5 + ...ank-replacement-blank-dynamic-nested-frame.html | 21 + ...about-blank-replacement-blank-nested-frame.html | 21 + .../resources/about-blank-replacement-frame.py | 31 + .../about-blank-replacement-ping-frame.py | 49 + .../about-blank-replacement-popup-frame.py | 32 + ...bout-blank-replacement-srcdoc-nested-frame.html | 22 + ...lank-replacement-uncontrolled-nested-frame.html | 22 + .../resources/about-blank-replacement-worker.js | 95 + .../service-worker/resources/basic-module-2.js | 1 + .../service-worker/resources/basic-module.js | 1 + .../service-worker/resources/blank.html | 2 + .../resources/bytecheck-worker-imported-script.py | 20 + .../service-worker/resources/bytecheck-worker.py | 38 + .../claim-blob-url-worker-fetch-iframe.html | 21 + .../claim-nested-worker-fetch-iframe.html | 16 + .../claim-nested-worker-fetch-parent-worker.js | 12 + .../claim-shared-worker-fetch-iframe.html | 13 + .../resources/claim-shared-worker-fetch-worker.js | 8 + .../resources/claim-with-redirect-iframe.html | 48 + .../resources/claim-worker-fetch-iframe.html | 13 + .../resources/claim-worker-fetch-worker.js | 5 + .../service-worker/resources/claim-worker.js | 19 + .../service-worker/resources/classic-worker.js | 1 + .../service-worker/resources/client-id-worker.js | 27 + .../resources/client-navigate-frame.html | 12 + .../resources/client-navigate-worker.js | 92 + .../resources/client-navigated-frame.html | 3 + .../resources/client-url-of-blob-url-worker.html | 26 + .../resources/client-url-of-blob-url-worker.js | 10 + .../resources/clients-frame-freeze.html | 15 + .../clients-get-client-types-frame-worker.js | 11 + .../resources/clients-get-client-types-frame.html | 17 + .../clients-get-client-types-shared-worker.js | 10 + .../resources/clients-get-client-types-worker.js | 11 + .../resources/clients-get-cross-origin-frame.html | 50 + .../resources/clients-get-frame.html | 12 + .../resources/clients-get-other-origin.html | 64 + .../clients-get-resultingClientId-worker.js | 60 + .../service-worker/resources/clients-get-worker.js | 41 + .../clients-matchall-blob-url-worker.html | 20 + ...ients-matchall-client-types-dedicated-worker.js | 3 + .../clients-matchall-client-types-iframe.html | 8 + .../clients-matchall-client-types-shared-worker.js | 4 + .../clients-matchall-on-evaluation-worker.js | 11 + .../resources/clients-matchall-worker.js | 40 + .../resources/controlled-frame-postMessage.html | 39 + .../controlled-worker-late-postMessage.js | 6 + .../resources/controlled-worker-postMessage.js | 4 + .../service-worker/resources/cors-approved.txt | 1 + .../resources/cors-approved.txt.headers | 3 + .../service-worker/resources/cors-denied.txt | 2 + .../resources/create-blob-url-worker.js | 22 + .../resources/create-out-of-scope-worker.html | 19 + .../service-worker/resources/echo-content.py | 16 + .../service-worker/resources/echo-cookie-worker.py | 24 + .../resources/echo-message-to-source-worker.js | 3 + .../embed-and-object-are-not-intercepted-worker.js | 14 + .../embed-image-is-not-intercepted-iframe.html | 21 + .../resources/embed-is-not-intercepted-iframe.html | 17 + ...embed-navigation-is-not-intercepted-iframe.html | 23 + .../resources/embedded-content-from-server.html | 6 + .../embedded-content-from-service-worker.html | 7 + .../resources/empty-but-slow-worker.js | 8 + .../service-worker/resources/empty-worker.js | 1 + .../service-worker/resources/empty.h2.js | 0 .../service-worker/resources/empty.html | 6 + .../service-worker/resources/empty.js | 0 .../resources/enable-client-message-queue.html | 39 + .../service-worker/resources/end-to-end-worker.js | 7 + .../service-worker/resources/events-worker.js | 12 + .../resources/extendable-event-async-waituntil.js | 210 + .../resources/extendable-event-waituntil.js | 87 + .../resources/fail-on-fetch-worker.js | 5 + .../resources/fetch-access-control-login.html | 16 + .../resources/fetch-access-control.py | 114 + .../fetch-canvas-tainting-double-write-worker.js | 7 + .../resources/fetch-canvas-tainting-iframe.html | 70 + .../resources/fetch-canvas-tainting-tests.js | 241 + .../fetch-cors-exposed-header-names-worker.js | 3 + .../resources/fetch-cors-xhr-iframe.html | 170 + .../service-worker/resources/fetch-csp-iframe.html | 16 + .../resources/fetch-csp-iframe.html.sub.headers | 1 + .../service-worker/resources/fetch-error-worker.js | 22 + .../resources/fetch-event-add-async-worker.js | 6 + ...-event-after-navigation-within-page-iframe.html | 22 + .../fetch-event-async-respond-with-worker.js | 66 + .../resources/fetch-event-handled-worker.js | 37 + ...etch-event-network-error-controllee-iframe.html | 60 + .../resources/fetch-event-network-error-worker.js | 49 + .../fetch-event-network-fallback-worker.js | 3 + .../fetch-event-respond-with-argument-iframe.html | 55 + .../fetch-event-respond-with-argument-worker.js | 14 + ...ent-respond-with-body-loaded-in-chunk-worker.js | 7 + ...ch-event-respond-with-custom-response-worker.js | 45 + ...tch-event-respond-with-partial-stream-worker.js | 28 + ...nt-respond-with-readable-stream-chunk-worker.js | 40 + ...ch-event-respond-with-readable-stream-worker.js | 81 + ...th-response-body-with-invalid-chunk-iframe.html | 15 + ...with-response-body-with-invalid-chunk-worker.js | 12 + ...-event-respond-with-stops-propagation-worker.js | 15 + .../resources/fetch-event-test-worker.js | 224 + .../resources/fetch-event-within-sw-worker.js | 48 + .../resources/fetch-header-visibility-iframe.html | 66 + ...ch-mixed-content-iframe-inscope-to-inscope.html | 71 + ...h-mixed-content-iframe-inscope-to-outscope.html | 80 + .../resources/fetch-mixed-content-iframe.html | 71 + .../fetch-request-css-base-url-iframe.html | 20 + .../resources/fetch-request-css-base-url-style.css | 1 + .../resources/fetch-request-css-base-url-worker.js | 45 + ...h-request-css-cross-origin-mime-check-cross.css | 1 + ...-request-css-cross-origin-mime-check-cross.html | 1 + ...request-css-cross-origin-mime-check-iframe.html | 17 + ...ch-request-css-cross-origin-mime-check-same.css | 1 + ...h-request-css-cross-origin-mime-check-same.html | 1 + ...tch-request-css-cross-origin-read-contents.html | 15 + .../fetch-request-css-cross-origin-worker.js | 65 + .../resources/fetch-request-fallback-iframe.html | 32 + .../resources/fetch-request-fallback-worker.js | 13 + .../fetch-request-html-imports-iframe.html | 13 + .../resources/fetch-request-html-imports-worker.js | 30 + .../fetch-request-no-freshness-headers-iframe.html | 1 + .../fetch-request-no-freshness-headers-script.py | 6 + .../fetch-request-no-freshness-headers-worker.js | 18 + .../resources/fetch-request-redirect-iframe.html | 35 + .../fetch-request-resources-iframe.https.html | 87 + .../resources/fetch-request-resources-worker.js | 26 + .../resources/fetch-request-xhr-iframe.https.html | 208 + .../fetch-request-xhr-sync-error-worker.js | 19 + .../resources/fetch-request-xhr-sync-iframe.html | 13 + .../fetch-request-xhr-sync-on-worker-worker.js | 41 + .../resources/fetch-request-xhr-sync-worker.js | 7 + .../resources/fetch-request-xhr-worker.js | 22 + .../resources/fetch-response-taint-iframe.html | 2 + .../resources/fetch-response-xhr-iframe.https.html | 53 + .../resources/fetch-response-xhr-worker.js | 12 + .../service-worker/resources/fetch-response.html | 29 + .../service-worker/resources/fetch-response.js | 35 + .../fetch-rewrite-worker-referrer-policy.js | 4 + ...fetch-rewrite-worker-referrer-policy.js.headers | 2 + .../resources/fetch-rewrite-worker.js | 166 + .../resources/fetch-rewrite-worker.js.headers | 2 + .../resources/fetch-variants-worker.js | 35 + .../resources/fetch-waits-for-activate-worker.js | 31 + .../service-worker/resources/form-poster.html | 13 + .../resources/frame-for-getregistrations.html | 19 + .../resources/get-resultingClientId-worker.js | 107 + ...http-to-https-redirect-and-register-iframe.html | 25 + .../resources/iframe-with-fetch-variants.html | 14 + .../resources/iframe-with-image.html | 2 + .../resources/immutable-prototype-serviceworker.js | 19 + .../resources/import-echo-cookie-worker-module.py | 6 + .../resources/import-echo-cookie-worker.js | 1 + .../resources/import-mime-type-worker.py | 10 + .../service-worker/resources/import-relative.xsl | 5 + ...-scripts-404-after-update-plus-update-worker.js | 8 + .../resources/import-scripts-404-after-update.js | 6 + .../service-worker/resources/import-scripts-404.js | 1 + .../import-scripts-cross-origin-worker.sub.js | 1 + .../resources/import-scripts-data-url-worker.js | 1 + .../import-scripts-diff-resource-map-worker.js | 10 + .../resources/import-scripts-echo.py | 6 + .../service-worker/resources/import-scripts-get.py | 6 + .../resources/import-scripts-mime-types-worker.js | 49 + .../resources/import-scripts-redirect-import.js | 1 + ...mport-scripts-redirect-on-second-time-worker.js | 7 + .../resources/import-scripts-redirect-worker.js | 1 + .../import-scripts-resource-map-worker.js | 15 + .../import-scripts-updated-flag-worker.js | 31 + .../resources/import-scripts-version.py | 17 + .../resources/imported-classic-script.js | 1 + .../resources/imported-module-script.js | 1 + .../service-worker/resources/indexeddb-worker.js | 57 + .../resources/install-event-type-worker.js | 9 + .../service-worker/resources/install-worker.html | 22 + .../resources/interface-requirements-worker.sub.js | 59 + .../resources/invalid-blobtype-iframe.https.html | 28 + .../resources/invalid-blobtype-worker.js | 10 + .../invalid-chunked-encoding-with-flush.py | 9 + .../resources/invalid-chunked-encoding.py | 2 + .../resources/invalid-header-iframe.https.html | 25 + .../resources/invalid-header-worker.js | 12 + .../resources/iso-latin1-header-iframe.html | 23 + .../resources/iso-latin1-header-worker.js | 12 + .../service-worker/resources/load_worker.js | 29 + .../service-worker/resources/loaded.html | 9 + .../local-url-inherit-controller-frame.html | 130 + .../local-url-inherit-controller-worker.js | 5 + .../service-worker/resources/location-setter.html | 10 + .../resources/malformed-http-response.asis | 1 + .../service-worker/resources/malformed-worker.py | 14 + .../resources/message-vs-microtask.html | 18 + .../resources/mime-sniffing-worker.js | 9 + .../service-worker/resources/mime-type-worker.py | 4 + .../service-worker/resources/mint-new-worker.py | 27 + .../service-worker/resources/missing.asis | 4 + .../service-worker/resources/module-worker.js | 1 + .../resources/multipart-image-iframe.html | 19 + .../resources/multipart-image-worker.js | 21 + .../service-worker/resources/multipart-image.py | 23 + .../resources/navigate-window-worker.js | 21 + .../resources/navigation-headers-server.py | 19 + .../resources/navigation-redirect-body-worker.js | 11 + .../resources/navigation-redirect-body.py | 11 + .../navigation-redirect-other-origin.html | 89 + .../resources/navigation-redirect-out-scope.py | 22 + .../resources/navigation-redirect-scope1.py | 22 + .../resources/navigation-redirect-scope2.py | 22 + .../navigation-redirect-to-http-iframe.html | 42 + .../navigation-redirect-to-http-worker.js | 22 + .../resources/navigation-timing-worker-extended.js | 22 + .../resources/navigation-timing-worker.js | 15 + ...nested-blob-url-worker-created-from-worker.html | 16 + .../resources/nested-blob-url-workers.html | 38 + .../resources/nested-iframe-parent.html | 5 + .../service-worker/resources/nested-parent.html | 18 + ...nested-worker-created-from-blob-url-worker.html | 33 + .../service-worker/resources/nested_load_worker.js | 23 + .../service-worker/resources/no-dynamic-import.js | 18 + .../service-worker/resources/notification_icon.py | 11 + .../object-image-is-not-intercepted-iframe.html | 21 + .../object-is-not-intercepted-iframe.html | 18 + ...bject-navigation-is-not-intercepted-iframe.html | 24 + ...ctivate-throw-error-from-nested-event-worker.js | 13 + .../onactivate-throw-error-then-cancel-worker.js | 3 + ...vate-throw-error-then-prevent-default-worker.js | 7 + ...tivate-throw-error-with-empty-onerror-worker.js | 2 + .../resources/onactivate-throw-error-worker.js | 7 + .../resources/onactivate-waituntil-forever.js | 8 + .../resources/onfetch-waituntil-forever.js | 10 + ...install-throw-error-from-nested-event-worker.js | 12 + .../oninstall-throw-error-then-cancel-worker.js | 3 + ...tall-throw-error-then-prevent-default-worker.js | 7 + ...nstall-throw-error-with-empty-onerror-worker.js | 2 + .../resources/oninstall-throw-error-worker.js | 7 + .../resources/oninstall-waituntil-forever.js | 8 + .../oninstall-waituntil-throw-error-worker.js | 5 + .../resources/onparse-infiniteloop-worker.js | 8 + .../opaque-response-being-preloaded-xhr.html | 33 + .../resources/opaque-response-preloaded-worker.js | 12 + .../resources/opaque-response-preloaded-xhr.html | 35 + .../resources/opaque-script-frame.html | 21 + .../resources/opaque-script-large.js | 41 + .../resources/opaque-script-small.js | 3 + .../service-worker/resources/opaque-script-sw.js | 37 + .../service-worker/resources/other.html | 3 + .../resources/override_assert_object_equals.js | 58 + ...artitioned-cookies-3p-credentialless-frame.html | 114 + .../resources/partitioned-cookies-3p-frame.html | 108 + .../resources/partitioned-cookies-3p-sw.js | 53 + .../resources/partitioned-cookies-3p-window.html | 35 + .../resources/partitioned-cookies-sw.js | 53 + .../partitioned-service-worker-iframe-claim.html | 59 + ...itioned-service-worker-nested-iframe-child.html | 44 + ...tioned-service-worker-nested-iframe-parent.html | 30 + ...worker-third-party-iframe-getRegistrations.html | 40 + ...service-worker-third-party-iframe-matchAll.html | 27 + ...titioned-service-worker-third-party-iframe.html | 36 + ...titioned-service-worker-third-party-window.html | 41 + .../resources/partitioned-storage-sw.js | 81 + .../service-worker/resources/partitioned-utils.js | 110 + .../resources/pass-through-worker.js | 3 + .../service-worker/resources/pass.txt | 1 + .../resources/performance-timeline-worker.js | 62 + .../resources/postmessage-blob-url.js | 5 + .../postmessage-dictionary-transferables-worker.js | 24 + .../resources/postmessage-echo-worker.js | 3 + .../resources/postmessage-fetched-text.js | 5 + .../postmessage-msgport-to-client-worker.js | 19 + .../resources/postmessage-on-load-worker.js | 9 + .../resources/postmessage-to-client-worker.js | 10 + .../resources/postmessage-transferables-worker.js | 24 + .../service-worker/resources/postmessage-worker.js | 19 + .../range-request-to-different-origins-worker.js | 40 + ...nge-request-with-different-cors-modes-worker.js | 60 + .../service-worker/resources/redirect-worker.js | 145 + .../service-worker/resources/redirect.py | 27 + .../service-worker/resources/referer-iframe.html | 39 + .../resources/referrer-policy-iframe.html | 32 + .../resources/register-closed-window-iframe.html | 19 + .../service-worker/resources/register-iframe.html | 4 + .../resources/register-rewrite-worker.html | 32 + .../resources/registration-tests-mime-types.js | 96 + .../resources/registration-tests-scope.js | 120 + .../resources/registration-tests-script-url.js | 82 + .../resources/registration-tests-script.js | 121 + .../resources/registration-tests-security-error.js | 78 + .../resources/registration-worker.js | 1 + .../resources/reject-install-worker.js | 3 + .../service-worker/resources/reply-to-message.html | 7 + .../resources/request-end-to-end-worker.js | 34 + .../service-worker/resources/request-headers.py | 8 + .../resources/resource-timing-iframe.sub.html | 10 + .../resources/resource-timing-worker.js | 12 + .../resources/respond-then-throw-worker.js | 40 + ...respond-with-body-accessed-response-iframe.html | 20 + .../respond-with-body-accessed-response-worker.js | 93 + .../respond-with-body-accessed-response.jsonp | 1 + .../resources/sample-worker-interceptor.js | 62 + .../service-worker/resources/sample.html | 2 + .../service-worker/resources/sample.js | 1 + .../service-worker/resources/sample.txt | 1 + .../sandboxed-iframe-fetch-event-iframe.html | 63 + .../sandboxed-iframe-fetch-event-iframe.py | 18 + .../sandboxed-iframe-fetch-event-worker.js | 20 + ...oxed-iframe-navigator-serviceworker-iframe.html | 25 + .../module-worker-importing-redirect-to-scope2.js | 1 + .../scope1/module-worker-importing-scope2.js | 1 + .../service-worker/resources/scope1/redirect.py | 6 + .../resources/scope2/import-scripts-echo.py | 6 + .../resources/scope2/imported-module-script.js | 4 + .../service-worker/resources/scope2/simple.txt | 1 + .../worker_interception_redirect_webworker.py | 6 + .../resources/secure-context-service-worker.js | 21 + .../resources/secure-context/sender.html | 1 + .../resources/secure-context/window.html | 15 + .../resources/service-worker-csp-worker.py | 183 + .../resources/service-worker-header.py | 20 + ...ce-worker-interception-dynamic-import-worker.js | 1 + .../service-worker-interception-network-worker.js | 1 + .../service-worker-interception-service-worker.js | 9 + ...ice-worker-interception-static-import-worker.js | 1 + .../service-worker/resources/silence.oga | Bin 0 -> 12983 bytes .../resources/simple-intercept-worker.js | 5 + .../resources/simple-intercept-worker.js.headers | 1 + .../service-worker/resources/simple.html | 3 + .../service-worker/resources/simple.txt | 1 + .../resources/skip-waiting-installed-worker.js | 33 + .../resources/skip-waiting-worker.js | 21 + .../service-worker/resources/square.png | Bin 0 -> 18299 bytes .../resources/square.png.sub.headers | 2 + .../resources/stalling-service-worker.js | 54 + .../service-worker/resources/subdir/blank.html | 2 + .../resources/subdir/import-scripts-echo.py | 6 + .../service-worker/resources/subdir/simple.txt | 1 + .../worker_interception_redirect_webworker.py | 6 + .../service-worker/resources/success.py | 8 + .../resources/svg-target-reftest-001-frame.html | 3 + .../resources/svg-target-reftest-001.html | 5 + .../resources/svg-target-reftest-frame.html | 2 + .../service-worker/resources/test-helpers.sub.js | 300 ++ .../resources/test-request-headers-worker.js | 10 + .../resources/test-request-headers-worker.py | 21 + .../resources/test-request-mode-worker.js | 10 + .../resources/test-request-mode-worker.py | 22 + .../resources/testharness-helpers.js | 136 + .../service-worker/resources/trickle.py | 14 + .../service-worker/resources/type-check-worker.js | 10 + .../resources/unregister-controller-page.html | 16 + .../resources/unregister-immediately-helpers.js | 19 + .../resources/unregister-rewrite-worker.html | 18 + .../resources/update-claim-worker.py | 24 + .../resources/update-during-installation-worker.js | 61 + .../resources/update-during-installation-worker.py | 11 + .../resources/update-fetch-worker.py | 18 + .../update-max-aged-worker-imported-script.py | 14 + .../resources/update-max-aged-worker.py | 30 + ...pdate-missing-import-scripts-imported-worker.py | 9 + .../update-missing-import-scripts-main-worker.py | 15 + .../resources/update-nocookie-worker.py | 14 + .../resources/update-recovery-worker.py | 25 + .../resources/update-registration-with-type.py | 33 + .../update-smaller-body-after-update-worker.js | 1 + .../update-smaller-body-before-update-worker.js | 2 + .../resources/update-worker-from-file.py | 33 + .../service-worker/resources/update-worker.py | 62 + .../update/update-after-oneday.https.html | 8 + .../service-worker/resources/update_shell.py | 32 + .../service-worker/resources/vtt-frame.html | 6 + .../resources/wait-forever-in-install-worker.js | 12 + .../service-worker/resources/websocket-worker.js | 35 + .../service-worker/resources/websocket.js | 7 + .../service-worker/resources/window-opener.html | 17 + .../resources/windowclient-navigate-worker.js | 75 + .../resources/worker-client-id-worker.js | 25 + .../resources/worker-fetching-cross-origin.js | 12 + .../worker-interception-redirect-serviceworker.js | 53 + .../worker-interception-redirect-webworker.js | 56 + .../resources/worker-load-interceptor.js | 16 + .../service-worker/resources/worker-testharness.js | 49 + .../worker_interception_redirect_webworker.py | 20 + .../resources/xhr-content-length-worker.js | 22 + .../service-worker/resources/xhr-iframe.html | 23 + .../resources/xhr-response-url-worker.js | 32 + .../resources/xsl-base-url-iframe.xml | 5 + .../resources/xsl-base-url-worker.js | 12 + .../service-worker/resources/xslt-pass.xsl | 11 + .../respond-with-body-accessed-response.https.html | 54 + .../service-worker/same-site-cookies.https.html | 496 ++ .../sandboxed-iframe-fetch-event.https.html | 536 +++ ...boxed-iframe-navigator-serviceworker.https.html | 120 + .../service-worker/secure-context.https.html | 57 + .../service-worker-csp-connect.https.html | 10 + .../service-worker-csp-default.https.html | 10 + .../service-worker-csp-script.https.html | 10 + .../service-worker-header.https.html | 23 + ...rviceworker-message-event-historical.https.html | 45 + .../serviceworkerobject-scripturl.https.html | 26 + .../skip-waiting-installed.https.html | 70 + .../skip-waiting-using-registration.https.html | 66 + .../skip-waiting-without-client.https.html | 12 + ...p-waiting-without-using-registration.https.html | 44 + .../service-worker/skip-waiting.https.html | 58 + .../service-worker/state.https.html | 74 + .../service-worker/svg-target-reftest.https.html | 28 + .../service-worker/synced-state.https.html | 93 + .../tentative/static-router/README.md | 4 + .../tentative/static-router/resources/direct.txt | 1 + .../simple-test-for-condition-main-resource.html | 3 + .../tentative/static-router/resources/simple.html | 3 + .../static-router/resources/static-router-sw.js | 35 + .../static-router/resources/test-helpers.sub.js | 303 ++ .../static-router-main-resource.https.html | 58 + .../static-router-subresource.https.html | 48 + .../service-worker/uncontrolled-page.https.html | 39 + .../unregister-controller.https.html | 108 + ...egister-immediately-before-installed.https.html | 57 + ...immediately-during-extendable-events.https.html | 50 + .../unregister-immediately.https.html | 134 + .../unregister-then-register-new-script.https.html | 136 + .../unregister-then-register.https.html | 107 + .../service-worker/unregister.https.html | 40 + .../update-after-navigation-fetch-event.https.html | 91 + .../update-after-navigation-redirect.https.html | 74 + .../service-worker/update-after-oneday.https.html | 51 + .../update-bytecheck-cors-import.https.html | 92 + .../service-worker/update-bytecheck.https.html | 92 + .../update-import-scripts.https.html | 135 + .../update-missing-import-scripts.https.html | 33 + .../update-module-request-mode.https.html | 45 + .../update-no-cache-request-headers.https.html | 48 + .../service-worker/update-not-allowed.https.html | 140 + .../service-worker/update-on-navigation.https.html | 20 + .../service-worker/update-recovery.https.html | 73 + .../update-registration-with-type.https.html | 208 + .../service-worker/update-result.https.html | 23 + .../service-worker/update.https.html | 164 + .../service-worker/waiting.https.html | 47 + .../websocket-in-service-worker.https.html | 27 + .../service-worker/websocket.https.html | 45 + .../service-worker/webvtt-cross-origin.https.html | 175 + .../windowclient-navigate.https.html | 190 + .../service-worker/worker-client-id.https.html | 58 + ...-sandboxed-iframe-by-csp-fetch-event.https.html | 132 + .../worker-interception-redirect.https.html | 212 + .../service-worker/worker-interception.https.html | 244 + .../xhr-content-length.https.window.js | 55 + .../service-worker/xhr-response-url.https.html | 103 + .../service-worker/xsl-base-url.https.html | 32 + test/wpt/tests/storage/META.yml | 4 + test/wpt/tests/storage/README.md | 7 + test/wpt/tests/storage/buckets/META.yml | 5 + .../bucket-quota-indexeddb.tentative.https.any.js | 35 + .../bucket-storage-policy.tentative.https.any.js | 21 + .../storage/buckets/resources/cached-resource.txt | 1 + test/wpt/tests/storage/buckets/resources/util.js | 57 + .../tests/storage/estimate-indexeddb.https.any.js | 61 + .../tests/storage/estimate-parallel.https.any.js | 13 + ...ate-usage-details-caches.https.tentative.any.js | 20 + ...-usage-details-indexeddb.https.tentative.any.js | 59 + ...tails-service-workers.https.tentative.window.js | 38 + .../estimate-usage-details.https.tentative.any.js | 12 + test/wpt/tests/storage/helpers.js | 46 + test/wpt/tests/storage/idlharness.https.any.js | 18 + .../tests/storage/opaque-origin.https.window.js | 80 + ...e-usage-details-caches.tentative.https.sub.html | 74 + ...sage-details-indexeddb.tentative.https.sub.html | 84 + ...etails-service-workers.tentative.https.sub.html | 88 + .../tests/storage/permission-query.https.any.js | 10 + .../storage/persist-permission-manual.https.html | 27 + test/wpt/tests/storage/persisted.https.any.js | 14 + ...achange-in-detached-iframe.tentative.https.html | 21 + ...estimate-usage-details-caches-helper-frame.html | 30 + ...imate-usage-details-indexeddb-helper-frame.html | 28 + ...usage-details-service-workers-helper-frame.html | 30 + test/wpt/tests/storage/resources/worker.js | 3 + .../storage/storagemanager-estimate.https.any.js | 60 + ...agemanager-persist-persisted-match.https.any.js | 9 + .../storage/storagemanager-persist.https.window.js | 10 + .../storage/storagemanager-persist.https.worker.js | 8 + .../storage/storagemanager-persisted.https.any.js | 10 + test/wpt/tests/websockets/Close-1000-reason.any.js | 21 + .../tests/websockets/Close-1000-verify-code.any.js | 21 + test/wpt/tests/websockets/Close-1000.any.js | 21 + .../tests/websockets/Close-1005-verify-code.any.js | 21 + test/wpt/tests/websockets/Close-1005.any.js | 18 + test/wpt/tests/websockets/Close-2999-reason.any.js | 17 + test/wpt/tests/websockets/Close-3000-reason.any.js | 21 + .../tests/websockets/Close-3000-verify-code.any.js | 20 + test/wpt/tests/websockets/Close-4999-reason.any.js | 21 + .../tests/websockets/Close-Reason-124Bytes.any.js | 20 + test/wpt/tests/websockets/Close-delayed.any.js | 27 + test/wpt/tests/websockets/Close-onlyReason.any.js | 17 + .../websockets/Close-readyState-Closed.any.js | 21 + .../websockets/Close-readyState-Closing.any.js | 20 + .../Close-reason-unpaired-surrogates.any.js | 22 + .../websockets/Close-server-initiated-close.any.js | 21 + test/wpt/tests/websockets/Close-undefined.any.js | 19 + .../Create-asciiSep-protocol-string.any.js | 12 + .../tests/websockets/Create-blocked-port.any.js | 97 + .../websockets/Create-extensions-empty.any.js | 20 + test/wpt/tests/websockets/Create-http-urls.any.js | 19 + .../tests/websockets/Create-invalid-urls.any.js | 14 + .../websockets/Create-non-absolute-url.any.js | 14 + .../Create-nonAscii-protocol-string.any.js | 12 + .../websockets/Create-on-worker-shutdown.any.js | 26 + .../websockets/Create-protocol-with-space.any.js | 11 + ...eate-protocols-repeated-case-insensitive.any.js | 11 + .../websockets/Create-protocols-repeated.any.js | 11 + .../tests/websockets/Create-url-with-space.any.js | 12 + .../Create-url-with-windows-1252-encoding.html | 20 + .../Create-valid-url-array-protocols.any.js | 21 + .../Create-valid-url-binaryType-blob.any.js | 21 + .../Create-valid-url-protocol-empty.any.js | 10 + .../Create-valid-url-protocol-setCorrectly.any.js | 21 + .../Create-valid-url-protocol-string.any.js | 21 + .../websockets/Create-valid-url-protocol.any.js | 21 + test/wpt/tests/websockets/Create-valid-url.any.js | 21 + test/wpt/tests/websockets/META.yml | 6 + test/wpt/tests/websockets/README.md | 1 + test/wpt/tests/websockets/Send-0byte-data.any.js | 30 + test/wpt/tests/websockets/Send-65K-data.any.js | 33 + test/wpt/tests/websockets/Send-before-open.any.js | 11 + .../websockets/Send-binary-65K-arraybuffer.any.js | 33 + .../websockets/Send-binary-arraybuffer.any.js | 33 + .../Send-binary-arraybufferview-float32.any.js | 40 + .../Send-binary-arraybufferview-float64.any.js | 40 + ...Send-binary-arraybufferview-int16-offset.any.js | 40 + .../Send-binary-arraybufferview-int32.any.js | 40 + .../Send-binary-arraybufferview-int8.any.js | 40 + ...ary-arraybufferview-uint16-offset-length.any.js | 40 + ...end-binary-arraybufferview-uint32-offset.any.js | 40 + ...nary-arraybufferview-uint8-offset-length.any.js | 40 + ...Send-binary-arraybufferview-uint8-offset.any.js | 40 + test/wpt/tests/websockets/Send-binary-blob.any.js | 36 + test/wpt/tests/websockets/Send-data.any.js | 30 + test/wpt/tests/websockets/Send-data.worker.js | 26 + test/wpt/tests/websockets/Send-null.any.js | 32 + .../tests/websockets/Send-paired-surrogates.any.js | 30 + test/wpt/tests/websockets/Send-unicode-data.any.js | 30 + .../websockets/Send-unpaired-surrogates.any.js | 30 + ...d-websocket-connection-ccns.tentative.window.js | 31 + ...ache-with-closed-websocket-connection.window.js | 20 + ...n-websocket-connection-ccns.tentative.window.js | 32 + ...-cache-with-open-websocket-connection.window.js | 21 + test/wpt/tests/websockets/basic-auth.any.js | 17 + test/wpt/tests/websockets/binary/001.html | 27 + test/wpt/tests/websockets/binary/002.html | 28 + test/wpt/tests/websockets/binary/004.html | 27 + test/wpt/tests/websockets/binary/005.html | 26 + .../tests/websockets/binaryType-wrong-value.any.js | 23 + .../bufferedAmount-unchanged-by-sync-xhr.any.js | 25 + test/wpt/tests/websockets/close-invalid.any.js | 21 + .../tests/websockets/closing-handshake/002.html | 23 + .../tests/websockets/closing-handshake/003.html | 24 + .../tests/websockets/closing-handshake/004.html | 25 + test/wpt/tests/websockets/constants.sub.js | 94 + test/wpt/tests/websockets/constructor.any.js | 10 + test/wpt/tests/websockets/constructor/001.html | 14 + test/wpt/tests/websockets/constructor/004.html | 36 + test/wpt/tests/websockets/constructor/005.html | 14 + test/wpt/tests/websockets/constructor/006.html | 29 + test/wpt/tests/websockets/constructor/007.html | 17 + test/wpt/tests/websockets/constructor/008.html | 15 + test/wpt/tests/websockets/constructor/009.html | 24 + test/wpt/tests/websockets/constructor/010.html | 22 + test/wpt/tests/websockets/constructor/011.html | 28 + test/wpt/tests/websockets/constructor/012.html | 20 + test/wpt/tests/websockets/constructor/013.html | 42 + test/wpt/tests/websockets/constructor/014.html | 39 + test/wpt/tests/websockets/constructor/016.html | 20 + test/wpt/tests/websockets/constructor/017.html | 19 + test/wpt/tests/websockets/constructor/018.html | 20 + test/wpt/tests/websockets/constructor/019.html | 21 + test/wpt/tests/websockets/constructor/020.html | 21 + test/wpt/tests/websockets/constructor/021.html | 12 + test/wpt/tests/websockets/constructor/022.html | 23 + test/wpt/tests/websockets/cookies/001.html | 28 + test/wpt/tests/websockets/cookies/002.html | 26 + test/wpt/tests/websockets/cookies/003.html | 34 + test/wpt/tests/websockets/cookies/004.html | 31 + test/wpt/tests/websockets/cookies/005.html | 35 + test/wpt/tests/websockets/cookies/006.html | 35 + test/wpt/tests/websockets/cookies/007.html | 36 + .../tests/websockets/cookies/support/set-cookie.py | 7 + .../support/websocket-cookies-helper.sub.js | 57 + .../cookies/third-party-cookie-accepted.https.html | 25 + test/wpt/tests/websockets/eventhandlers.any.js | 15 + .../tests/websockets/extended-payload-length.html | 72 + .../tests/websockets/handlers/basic_auth_wsh.py | 26 + .../handlers/delayed-passive-close_wsh.py | 27 + .../tests/websockets/handlers/echo-cookie_wsh.py | 12 + .../websockets/handlers/echo-query_v13_wsh.py | 11 + .../tests/websockets/handlers/echo-query_wsh.py | 9 + .../websockets/handlers/echo_close_data_wsh.py | 20 + .../wpt/tests/websockets/handlers/echo_exit_wsh.py | 19 + test/wpt/tests/websockets/handlers/echo_raw_wsh.py | 16 + test/wpt/tests/websockets/handlers/echo_wsh.py | 36 + .../tests/websockets/handlers/empty-message_wsh.py | 13 + .../handlers/handshake_no_extensions_wsh.py | 9 + .../handlers/handshake_no_protocol_wsh.py | 8 + .../websockets/handlers/handshake_protocol_wsh.py | 7 + .../websockets/handlers/handshake_sleep_2_wsh.py | 9 + test/wpt/tests/websockets/handlers/invalid_wsh.py | 8 + .../tests/websockets/handlers/msg_channel_wsh.py | 234 + test/wpt/tests/websockets/handlers/origin_wsh.py | 11 + .../websockets/handlers/protocol_array_wsh.py | 14 + test/wpt/tests/websockets/handlers/protocol_wsh.py | 12 + .../handlers/receive-backpressure_wsh.py | 14 + .../handlers/receive-many-with-backpressure_wsh.py | 23 + test/wpt/tests/websockets/handlers/referrer_wsh.py | 12 + .../websockets/handlers/send-backpressure_wsh.py | 39 + .../websockets/handlers/set-cookie-secure_wsh.py | 11 + .../websockets/handlers/set-cookie_http_wsh.py | 11 + .../tests/websockets/handlers/set-cookie_wsh.py | 11 + .../handlers/set-cookies-samesite_wsh.py | 25 + .../websockets/handlers/simple_handshake_wsh.py | 35 + .../tests/websockets/handlers/sleep_10_v13_wsh.py | 24 + .../handlers/stash_responder_blocking_wsh.py | 45 + .../websockets/handlers/stash_responder_wsh.py | 45 + .../websockets/handlers/wrong_accept_key_wsh.py | 19 + test/wpt/tests/websockets/idlharness.any.js | 17 + .../interfaces/CloseEvent/clean-close.html | 24 + .../interfaces/CloseEvent/constructor.html | 35 + .../interfaces/CloseEvent/historical.html | 12 + .../bufferedAmount/bufferedAmount-arraybuffer.html | 27 + .../bufferedAmount/bufferedAmount-blob.html | 28 + .../bufferedAmount-defineProperty-getter.html | 18 + .../bufferedAmount-defineProperty-setter.html | 20 + .../bufferedAmount/bufferedAmount-deleting.html | 23 + .../bufferedAmount/bufferedAmount-getting.html | 54 + .../bufferedAmount/bufferedAmount-initial.html | 15 + .../bufferedAmount/bufferedAmount-large.html | 29 + .../bufferedAmount/bufferedAmount-readonly.html | 16 + .../bufferedAmount/bufferedAmount-unicode.html | 25 + .../interfaces/WebSocket/close/close-basic.html | 26 + .../WebSocket/close/close-connecting.html | 25 + .../interfaces/WebSocket/close/close-multiple.html | 29 + .../interfaces/WebSocket/close/close-nested.html | 28 + .../interfaces/WebSocket/close/close-replace.html | 15 + .../interfaces/WebSocket/close/close-return.html | 14 + .../interfaces/WebSocket/constants/001.html | 17 + .../interfaces/WebSocket/constants/002.html | 24 + .../interfaces/WebSocket/constants/003.html | 22 + .../interfaces/WebSocket/constants/004.html | 21 + .../interfaces/WebSocket/constants/005.html | 20 + .../interfaces/WebSocket/constants/006.html | 20 + .../interfaces/WebSocket/events/001.html | 18 + .../interfaces/WebSocket/events/002.html | 20 + .../interfaces/WebSocket/events/003.html | 21 + .../interfaces/WebSocket/events/004.html | 16 + .../interfaces/WebSocket/events/006.html | 17 + .../interfaces/WebSocket/events/007.html | 22 + .../interfaces/WebSocket/events/008.html | 24 + .../interfaces/WebSocket/events/009.html | 21 + .../interfaces/WebSocket/events/010.html | 21 + .../interfaces/WebSocket/events/011.html | 18 + .../interfaces/WebSocket/events/012.html | 18 + .../interfaces/WebSocket/events/013.html | 20 + .../interfaces/WebSocket/events/014.html | 21 + .../interfaces/WebSocket/events/015.html | 36 + .../interfaces/WebSocket/events/016.html | 39 + .../interfaces/WebSocket/events/017.html | 56 + .../interfaces/WebSocket/events/018.html | 52 + .../interfaces/WebSocket/events/019.html | 31 + .../interfaces/WebSocket/events/020.html | 17 + .../interfaces/WebSocket/extensions/001.html | 14 + .../WebSocket/protocol/protocol-initial.html | 14 + .../interfaces/WebSocket/readyState/001.html | 13 + .../interfaces/WebSocket/readyState/002.html | 15 + .../interfaces/WebSocket/readyState/003.html | 18 + .../interfaces/WebSocket/readyState/004.html | 17 + .../interfaces/WebSocket/readyState/005.html | 19 + .../interfaces/WebSocket/readyState/006.html | 19 + .../interfaces/WebSocket/readyState/007.html | 19 + .../interfaces/WebSocket/readyState/008.html | 21 + .../websockets/interfaces/WebSocket/send/001.html | 15 + .../websockets/interfaces/WebSocket/send/002.html | 15 + .../websockets/interfaces/WebSocket/send/003.html | 15 + .../websockets/interfaces/WebSocket/send/004.html | 25 + .../websockets/interfaces/WebSocket/send/005.html | 19 + .../websockets/interfaces/WebSocket/send/006.html | 28 + .../websockets/interfaces/WebSocket/send/007.html | 27 + .../websockets/interfaces/WebSocket/send/008.html | 25 + .../websockets/interfaces/WebSocket/send/009.html | 27 + .../websockets/interfaces/WebSocket/send/010.html | 42 + .../websockets/interfaces/WebSocket/send/011.html | 28 + .../websockets/interfaces/WebSocket/send/012.html | 28 + .../websockets/interfaces/WebSocket/url/001.html | 13 + .../websockets/interfaces/WebSocket/url/002.html | 15 + .../websockets/interfaces/WebSocket/url/003.html | 17 + .../websockets/interfaces/WebSocket/url/004.html | 17 + .../websockets/interfaces/WebSocket/url/005.html | 17 + .../websockets/interfaces/WebSocket/url/006.html | 19 + .../interfaces/WebSocket/url/resolve.html | 14 + .../websockets/keeping-connection-open/001.html | 29 + .../tests/websockets/mixed-content.https.any.js | 7 + .../websockets/multi-globals/message-received.html | 33 + .../multi-globals/support/incumbent.sub.html | 24 + .../websockets/multi-globals/support/relevant.html | 2 + .../multi-globals/url-parsing/current/current.html | 2 + .../url-parsing/incumbent/incumbent.html | 13 + .../multi-globals/url-parsing/url-parsing.html | 22 + .../tests/websockets/opening-handshake/001.html | 20 + .../tests/websockets/opening-handshake/002.html | 24 + .../opening-handshake/003-sets-origin.worker.js | 17 + .../tests/websockets/opening-handshake/003.html | 27 + .../tests/websockets/opening-handshake/005.html | 25 + test/wpt/tests/websockets/referrer.any.js | 13 + .../remove-own-iframe-during-onerror.window.js | 23 + .../resources/websockets-test-helpers.sub.js | 25 + test/wpt/tests/websockets/security/001.html | 16 + test/wpt/tests/websockets/security/002.html | 20 + test/wpt/tests/websockets/security/check.py | 2 + ...send-many-64K-messages-with-backpressure.any.js | 49 + .../tests/websockets/stream/tentative/README.md | 9 + .../tests/websockets/stream/tentative/abort.any.js | 50 + .../stream/tentative/backpressure-receive.any.js | 40 + .../stream/tentative/backpressure-send.any.js | 25 + .../tests/websockets/stream/tentative/close.any.js | 187 + .../websockets/stream/tentative/constructor.any.js | 67 + .../stream/tentative/resources/url-constants.js | 8 + .../tests/websockets/unload-a-document/001-1.html | 25 + .../tests/websockets/unload-a-document/001-2.html | 4 + .../tests/websockets/unload-a-document/001.html | 26 + .../tests/websockets/unload-a-document/002-1.html | 32 + .../tests/websockets/unload-a-document/002-2.html | 4 + .../tests/websockets/unload-a-document/002.html | 27 + .../tests/websockets/unload-a-document/003.html | 14 + .../tests/websockets/unload-a-document/004.html | 16 + .../tests/websockets/unload-a-document/005-1.html | 22 + .../tests/websockets/unload-a-document/005.html | 21 + test/wpt/tests/wpt | 10 + test/wpt/tests/wpt.py | 7 + test/wpt/tests/xhr/META.yml | 7 + test/wpt/tests/xhr/README.md | 7 + .../xhr/XMLHttpRequest-withCredentials.any.js | 40 + test/wpt/tests/xhr/abort-after-receive.any.js | 30 + test/wpt/tests/xhr/abort-after-send.any.js | 29 + test/wpt/tests/xhr/abort-after-stop.window.js | 22 + test/wpt/tests/xhr/abort-after-timeout.any.js | 43 + test/wpt/tests/xhr/abort-during-done.window.js | 78 + .../xhr/abort-during-headers-received.window.js | 41 + test/wpt/tests/xhr/abort-during-loading.window.js | 41 + test/wpt/tests/xhr/abort-during-open.any.js | 18 + .../tests/xhr/abort-during-readystatechange.any.js | 19 + test/wpt/tests/xhr/abort-during-unsent.any.js | 19 + test/wpt/tests/xhr/abort-during-upload.any.js | 17 + test/wpt/tests/xhr/abort-event-abort.any.js | 32 + test/wpt/tests/xhr/abort-event-listeners.any.js | 13 + test/wpt/tests/xhr/abort-event-loadend.any.js | 30 + test/wpt/tests/xhr/abort-event-order.htm | 52 + test/wpt/tests/xhr/abort-upload-event-abort.any.js | 31 + .../tests/xhr/abort-upload-event-loadend.any.js | 31 + ...-control-and-redirects-async-same-origin.any.js | 61 + .../xhr/access-control-and-redirects-async.any.js | 79 + .../tests/xhr/access-control-and-redirects.any.js | 50 + ...allow-access-control-origin-header-data-url.htm | 43 + ...basic-allow-access-control-origin-header.any.js | 13 + .../xhr/access-control-basic-allow-async.any.js | 19 + ...c-allow-non-cors-safelisted-method-async.any.js | 17 + ...l-basic-allow-non-cors-safelisted-method.any.js | 14 + ...w-preflight-cache-invalidation-by-header.any.js | 38 + ...w-preflight-cache-invalidation-by-method.any.js | 37 + ...trol-basic-allow-preflight-cache-timeout.any.js | 37 + ...cess-control-basic-allow-preflight-cache.any.js | 35 + .../xhr/access-control-basic-allow-star.any.js | 12 + .../tests/xhr/access-control-basic-allow.any.js | 12 + ...ntrol-basic-cors-safelisted-request-headers.htm | 31 + ...trol-basic-cors-safelisted-response-headers.htm | 32 + test/wpt/tests/xhr/access-control-basic-denied.htm | 30 + .../access-control-basic-get-fail-non-simple.htm | 26 + ...trol-basic-non-cors-safelisted-content-type.htm | 30 + ...-control-basic-post-success-no-content-type.htm | 26 + ...-post-with-non-cors-safelisted-content-type.htm | 37 + .../xhr/access-control-basic-preflight-denied.htm | 31 + .../access-control-expose-headers-on-redirect.html | 33 + ...ccess-control-preflight-async-header-denied.htm | 39 + ...ccess-control-preflight-async-method-denied.htm | 38 + ...ccess-control-preflight-async-not-supported.htm | 37 + .../access-control-preflight-credential-async.htm | 29 + .../access-control-preflight-credential-sync.htm | 24 + .../xhr/access-control-preflight-headers-async.htm | 35 + .../xhr/access-control-preflight-headers-sync.htm | 29 + ...light-request-allow-headers-returns-star.any.js | 26 + ...-control-preflight-request-header-lowercase.htm | 29 + ...-preflight-request-header-returns-origin.any.js | 26 + ...ess-control-preflight-request-header-sorted.htm | 28 + ...ss-control-preflight-request-headers-origin.htm | 29 + ...ontrol-preflight-request-invalid-status-301.htm | 28 + ...ontrol-preflight-request-invalid-status-400.htm | 28 + ...ontrol-preflight-request-invalid-status-501.htm | 28 + ...l-preflight-request-must-not-contain-cookie.htm | 57 + ...access-control-preflight-sync-header-denied.htm | 34 + ...access-control-preflight-sync-method-denied.htm | 33 + ...access-control-preflight-sync-not-supported.htm | 33 + .../access-control-recursive-failed-request.htm | 38 + .../xhr/access-control-response-with-body-sync.htm | 25 + .../xhr/access-control-response-with-body.htm | 29 + ...ccess-control-response-with-exposed-headers.htm | 38 + ...-control-sandboxed-iframe-allow-origin-null.htm | 32 + .../xhr/access-control-sandboxed-iframe-allow.htm | 32 + ...ol-sandboxed-iframe-denied-without-wildcard.htm | 43 + .../xhr/access-control-sandboxed-iframe-denied.htm | 41 + .../tests/xhr/allow-lists-starting-with-comma.htm | 33 + test/wpt/tests/xhr/anonymous-mode-unsupported.htm | 40 + test/wpt/tests/xhr/blob-range.any.js | 246 + .../xhr/close-worker-with-xhr-in-progress.html | 26 + test/wpt/tests/xhr/content-type-unmodified.any.js | 16 + test/wpt/tests/xhr/cookies.http.html | 41 + test/wpt/tests/xhr/cors-expose-star.sub.any.js | 52 + test/wpt/tests/xhr/cors-upload.any.js | 59 + test/wpt/tests/xhr/data-uri.htm | 41 + test/wpt/tests/xhr/event-abort.any.js | 15 + test/wpt/tests/xhr/event-error-order.sub.html | 35 + test/wpt/tests/xhr/event-error.sub.any.js | 28 + test/wpt/tests/xhr/event-load.any.js | 21 + test/wpt/tests/xhr/event-loadend.any.js | 19 + test/wpt/tests/xhr/event-loadstart-upload.any.js | 19 + test/wpt/tests/xhr/event-loadstart.any.js | 17 + test/wpt/tests/xhr/event-progress.any.js | 18 + .../tests/xhr/event-readystate-sync-open.any.js | 23 + .../tests/xhr/event-readystatechange-loaded.any.js | 23 + test/wpt/tests/xhr/event-timeout-order.any.js | 21 + test/wpt/tests/xhr/event-timeout.any.js | 18 + .../xhr/event-upload-progress-crossorigin.any.js | 26 + test/wpt/tests/xhr/event-upload-progress.any.js | 30 + .../xhr/firing-events-http-content-length.html | 32 + .../xhr/firing-events-http-no-content-length.html | 35 + test/wpt/tests/xhr/folder.txt | 1 + test/wpt/tests/xhr/formdata.html | 90 + .../wpt/tests/xhr/formdata/append-formelement.html | 52 + test/wpt/tests/xhr/formdata/append.any.js | 37 + .../xhr/formdata/constructor-formelement.html | 150 + .../tests/xhr/formdata/constructor-submitter.html | 100 + test/wpt/tests/xhr/formdata/constructor.any.js | 6 + .../wpt/tests/xhr/formdata/delete-formelement.html | 41 + test/wpt/tests/xhr/formdata/delete.any.js | 26 + test/wpt/tests/xhr/formdata/foreach.any.js | 56 + test/wpt/tests/xhr/formdata/get-formelement.html | 34 + test/wpt/tests/xhr/formdata/get.any.js | 28 + test/wpt/tests/xhr/formdata/has-formelement.html | 25 + test/wpt/tests/xhr/formdata/has.any.js | 19 + test/wpt/tests/xhr/formdata/iteration.any.js | 65 + test/wpt/tests/xhr/formdata/set-blob.any.js | 61 + test/wpt/tests/xhr/formdata/set-formelement.html | 51 + test/wpt/tests/xhr/formdata/set.any.js | 36 + .../tests/xhr/getallresponseheaders-cookies.htm | 38 + .../wpt/tests/xhr/getallresponseheaders-status.htm | 33 + test/wpt/tests/xhr/getallresponseheaders.htm | 35 + .../xhr/getresponseheader-case-insensitive.htm | 34 + .../xhr/getresponseheader-chunked-trailer.htm | 32 + .../xhr/getresponseheader-cookies-and-more.htm | 36 + .../tests/xhr/getresponseheader-error-state.htm | 36 + .../tests/xhr/getresponseheader-server-date.htm | 29 + .../xhr/getresponseheader-special-characters.htm | 34 + .../xhr/getresponseheader-unsent-opened-state.htm | 32 + test/wpt/tests/xhr/getresponseheader.any.js | 18 + test/wpt/tests/xhr/header-user-agent-async.htm | 26 + test/wpt/tests/xhr/header-user-agent-sync.htm | 20 + test/wpt/tests/xhr/headers-normalize-response.htm | 43 + test/wpt/tests/xhr/historical.html | 15 + test/wpt/tests/xhr/idlharness.any.js | 28 + test/wpt/tests/xhr/json.any.js | 23 + test/wpt/tests/xhr/loadstart-and-state.html | 40 + test/wpt/tests/xhr/open-after-abort.htm | 77 + test/wpt/tests/xhr/open-after-setrequestheader.htm | 33 + test/wpt/tests/xhr/open-after-stop.window.js | 43 + test/wpt/tests/xhr/open-during-abort-event.htm | 56 + .../wpt/tests/xhr/open-during-abort-processing.htm | 62 + test/wpt/tests/xhr/open-during-abort.htm | 33 + test/wpt/tests/xhr/open-method-bogus.htm | 28 + .../wpt/tests/xhr/open-method-case-insensitive.htm | 29 + test/wpt/tests/xhr/open-method-case-sensitive.htm | 31 + test/wpt/tests/xhr/open-method-insecure.htm | 29 + .../xhr/open-method-responsetype-set-sync.htm | 32 + test/wpt/tests/xhr/open-open-send.htm | 33 + test/wpt/tests/xhr/open-open-sync-send.htm | 31 + test/wpt/tests/xhr/open-parameters-toString.htm | 54 + test/wpt/tests/xhr/open-referer.htm | 20 + test/wpt/tests/xhr/open-send-during-abort.htm | 27 + test/wpt/tests/xhr/open-send-open.htm | 33 + test/wpt/tests/xhr/open-sync-open-send.htm | 41 + test/wpt/tests/xhr/open-url-about-blank-window.htm | 23 + .../xhr/open-url-base-inserted-after-open.htm | 24 + test/wpt/tests/xhr/open-url-base-inserted.htm | 24 + test/wpt/tests/xhr/open-url-base.htm | 22 + test/wpt/tests/xhr/open-url-encoding.htm | 26 + test/wpt/tests/xhr/open-url-fragment.htm | 38 + .../wpt/tests/xhr/open-url-javascript-window-2.htm | 19 + test/wpt/tests/xhr/open-url-javascript-window.htm | 28 + test/wpt/tests/xhr/open-url-multi-window-2.htm | 25 + test/wpt/tests/xhr/open-url-multi-window-3.htm | 25 + test/wpt/tests/xhr/open-url-multi-window-4.htm | 50 + test/wpt/tests/xhr/open-url-multi-window-5.htm | 32 + test/wpt/tests/xhr/open-url-multi-window-6.htm | 41 + test/wpt/tests/xhr/open-url-multi-window.htm | 31 + .../open-url-redirected-sharedworker-origin.htm | 11 + .../xhr/open-url-redirected-worker-origin.htm | 11 + test/wpt/tests/xhr/open-url-worker-origin.htm | 9 + test/wpt/tests/xhr/open-url-worker-simple.htm | 25 + .../xhr/open-user-password-non-same-origin.htm | 25 + test/wpt/tests/xhr/over-1-meg.any.js | 16 + test/wpt/tests/xhr/overridemimetype-blob.html | 57 + .../tests/xhr/overridemimetype-done-state.any.js | 20 + .../xhr/overridemimetype-edge-cases.window.js | 50 + ...etype-headers-received-state-force-shiftjis.htm | 34 + .../xhr/overridemimetype-invalid-mime-type.htm | 41 + .../tests/xhr/overridemimetype-loading-state.htm | 32 + .../overridemimetype-open-state-force-utf-8.htm | 27 + .../xhr/overridemimetype-open-state-force-xml.htm | 34 + ...ridemimetype-unsent-state-force-shiftjis.any.js | 12 + .../tests/xhr/preserve-ua-header-on-redirect.htm | 43 + .../xhr/progress-events-response-data-gzip.htm | 83 + test/wpt/tests/xhr/progressevent-constructor.html | 47 + test/wpt/tests/xhr/progressevent-interface.html | 49 + test/wpt/tests/xhr/request-content-length.any.js | 31 + test/wpt/tests/xhr/resources/accept-language.py | 3 + test/wpt/tests/xhr/resources/accept.py | 2 + .../xhr/resources/access-control-allow-lists.py | 26 + .../resources/access-control-allow-with-body.py | 15 + .../xhr/resources/access-control-auth-basic.py | 17 + .../access-control-basic-allow-no-credentials.py | 5 + .../resources/access-control-basic-allow-star.py | 5 + .../xhr/resources/access-control-basic-allow.py | 6 + ...ontrol-basic-cors-safelisted-request-headers.py | 16 + ...ntrol-basic-cors-safelisted-response-headers.py | 19 + .../xhr/resources/access-control-basic-denied.py | 5 + .../access-control-basic-options-not-supported.py | 12 + ...s-control-basic-preflight-cache-invalidation.py | 49 + ...access-control-basic-preflight-cache-timeout.py | 50 + .../access-control-basic-preflight-cache.py | 50 + .../resources/access-control-basic-put-allow.py | 22 + .../tests/xhr/resources/access-control-cookie.py | 16 + .../xhr/resources/access-control-origin-header.py | 8 + .../resources/access-control-preflight-denied.py | 49 + ...preflight-request-allow-headers-returns-star.py | 12 + ...s-control-preflight-request-header-lowercase.py | 16 + ...trol-preflight-request-header-returns-origin.py | 12 + ...cess-control-preflight-request-header-sorted.py | 18 + ...ess-control-preflight-request-headers-origin.py | 12 + ...ess-control-preflight-request-invalid-status.py | 16 + ...ol-preflight-request-must-not-contain-cookie.py | 12 + .../resources/access-control-sandboxed-iframe.html | 24 + test/wpt/tests/xhr/resources/auth1/auth.py | 12 + test/wpt/tests/xhr/resources/auth10/auth.py | 12 + test/wpt/tests/xhr/resources/auth11/auth.py | 12 + test/wpt/tests/xhr/resources/auth2/auth.py | 12 + test/wpt/tests/xhr/resources/auth2/corsenabled.py | 18 + test/wpt/tests/xhr/resources/auth3/auth.py | 12 + test/wpt/tests/xhr/resources/auth4/auth.py | 12 + test/wpt/tests/xhr/resources/auth5/auth.py | 15 + test/wpt/tests/xhr/resources/auth6/auth.py | 15 + test/wpt/tests/xhr/resources/auth7/corsenabled.py | 20 + .../resources/auth8/corsenabled-no-authorize.py | 20 + test/wpt/tests/xhr/resources/auth9/auth.py | 12 + test/wpt/tests/xhr/resources/authentication.py | 24 + test/wpt/tests/xhr/resources/bad-chunk-encoding.py | 17 + test/wpt/tests/xhr/resources/base.xml | 1 + test/wpt/tests/xhr/resources/chunked.py | 17 + test/wpt/tests/xhr/resources/conditional.py | 29 + test/wpt/tests/xhr/resources/content.py | 20 + test/wpt/tests/xhr/resources/corsenabled.py | 25 + test/wpt/tests/xhr/resources/delay.py | 7 + test/wpt/tests/xhr/resources/echo-content-cors.py | 23 + test/wpt/tests/xhr/resources/echo-content-type.py | 6 + test/wpt/tests/xhr/resources/echo-headers.py | 7 + test/wpt/tests/xhr/resources/echo-method.py | 16 + .../wpt/tests/xhr/resources/empty-div-utf8-html.py | 5 + test/wpt/tests/xhr/resources/folder.txt | 1 + test/wpt/tests/xhr/resources/form.py | 2 + test/wpt/tests/xhr/resources/get-set-cookie.py | 18 + test/wpt/tests/xhr/resources/gzip.py | 24 + .../xhr/resources/header-content-length-twice.asis | 3 + .../tests/xhr/resources/header-content-length.asis | 2 + test/wpt/tests/xhr/resources/header-user-agent.py | 15 + test/wpt/tests/xhr/resources/headers-basic.asis | 4 + .../tests/xhr/resources/headers-double-empty.asis | 3 + .../xhr/resources/headers-some-are-empty.asis | 7 + .../xhr/resources/headers-www-authenticate.asis | 4 + test/wpt/tests/xhr/resources/headers.asis | 6 + test/wpt/tests/xhr/resources/headers.py | 12 + test/wpt/tests/xhr/resources/image.gif | Bin 0 -> 167145 bytes test/wpt/tests/xhr/resources/img-utf8-html.py | 5 + test/wpt/tests/xhr/resources/img.jpg | Bin 0 -> 108761 bytes test/wpt/tests/xhr/resources/infinite-redirects.py | 24 + test/wpt/tests/xhr/resources/init.htm | 20 + test/wpt/tests/xhr/resources/inspect-headers.py | 36 + test/wpt/tests/xhr/resources/invalid-utf8-html.py | 5 + test/wpt/tests/xhr/resources/last-modified.py | 9 + .../xhr/resources/no-custom-header-on-preflight.py | 27 + test/wpt/tests/xhr/resources/nocors/folder.txt | 1 + test/wpt/tests/xhr/resources/over-1-meg.txt | 1 + test/wpt/tests/xhr/resources/parse-headers.py | 6 + test/wpt/tests/xhr/resources/pass.txt | 1 + test/wpt/tests/xhr/resources/redirect-cors.py | 20 + test/wpt/tests/xhr/resources/redirect.py | 16 + test/wpt/tests/xhr/resources/requri.py | 5 + test/wpt/tests/xhr/resources/reset-token.py | 5 + .../resources/responseType-document-in-worker.js | 9 + .../resources/responseXML-unavailable-in-worker.js | 9 + ...send-after-setting-document-domain-window-1.htm | 23 + ...send-after-setting-document-domain-window-2.htm | 20 + ...-after-setting-document-domain-window-helper.js | 32 + test/wpt/tests/xhr/resources/shift-jis-html.py | 6 + test/wpt/tests/xhr/resources/status.py | 11 + test/wpt/tests/xhr/resources/top.txt | 1 + test/wpt/tests/xhr/resources/trickle.py | 15 + test/wpt/tests/xhr/resources/upload.py | 17 + test/wpt/tests/xhr/resources/utf16-bom.json | Bin 0 -> 30 bytes test/wpt/tests/xhr/resources/utf16.txt | Bin 0 -> 18 bytes test/wpt/tests/xhr/resources/well-formed.xml | 4 + test/wpt/tests/xhr/resources/win-1252-html.py | 5 + test/wpt/tests/xhr/resources/win-1252-xml.py | 5 + .../xhr/resources/workerxhr-origin-referrer.js | 63 + test/wpt/tests/xhr/resources/workerxhr-simple.js | 9 + .../xhr/resources/xmlhttprequest-event-order.js | 83 + .../resources/xmlhttprequest-timeout-aborted.js | 15 + .../xmlhttprequest-timeout-abortedonmain.js | 8 + .../resources/xmlhttprequest-timeout-overrides.js | 12 + .../xmlhttprequest-timeout-overridesexpires.js | 12 + .../xhr/resources/xmlhttprequest-timeout-runner.js | 21 + .../xhr/resources/xmlhttprequest-timeout-simple.js | 6 + .../resources/xmlhttprequest-timeout-synconmain.js | 2 + .../xmlhttprequest-timeout-synconworker.js | 11 + .../xhr/resources/xmlhttprequest-timeout-twice.js | 6 + .../tests/xhr/resources/xmlhttprequest-timeout.js | 333 ++ test/wpt/tests/xhr/resources/zlib.py | 19 + test/wpt/tests/xhr/response-body-errors.any.js | 23 + test/wpt/tests/xhr/response-data-arraybuffer.htm | 54 + test/wpt/tests/xhr/response-data-blob.htm | 55 + test/wpt/tests/xhr/response-data-deflate.htm | 42 + test/wpt/tests/xhr/response-data-gzip.htm | 42 + test/wpt/tests/xhr/response-data-progress.htm | 52 + .../tests/xhr/response-invalid-responsetype.htm | 38 + test/wpt/tests/xhr/response-json.htm | 61 + test/wpt/tests/xhr/response-method.htm | 21 + test/wpt/tests/xhr/responseText-status.html | 33 + .../tests/xhr/responseType-document-in-worker.html | 13 + .../xhr/responseXML-unavailable-in-worker.html | 13 + test/wpt/tests/xhr/responsedocument-decoding.htm | 39 + test/wpt/tests/xhr/responsetext-decoding.htm | 93 + test/wpt/tests/xhr/responsetype.any.js | 135 + test/wpt/tests/xhr/responseurl.html | 37 + test/wpt/tests/xhr/responsexml-basic.htm | 33 + .../tests/xhr/responsexml-document-properties.htm | 123 + test/wpt/tests/xhr/responsexml-get-twice.htm | 66 + test/wpt/tests/xhr/responsexml-invalid-type.html | 21 + test/wpt/tests/xhr/responsexml-media-type.htm | 41 + .../tests/xhr/responsexml-non-document-types.htm | 45 + test/wpt/tests/xhr/responsexml-non-well-formed.htm | 30 + test/wpt/tests/xhr/security-consideration.sub.html | 36 + test/wpt/tests/xhr/send-accept-language.htm | 27 + test/wpt/tests/xhr/send-accept.htm | 24 + .../xhr/send-after-setting-document-domain.htm | 39 + .../send-authentication-basic-cors-not-enabled.htm | 29 + .../tests/xhr/send-authentication-basic-cors.htm | 35 + .../send-authentication-basic-repeat-no-args.htm | 33 + ...cation-basic-setrequestheader-and-arguments.htm | 36 + ...ion-basic-setrequestheader-existing-session.htm | 53 + .../send-authentication-basic-setrequestheader.htm | 36 + test/wpt/tests/xhr/send-authentication-basic.htm | 27 + ...nd-authentication-competing-names-passwords.htm | 50 + ...-authentication-cors-basic-setrequestheader.htm | 31 + ...uthentication-cors-setrequestheader-no-cred.htm | 62 + ...send-authentication-existing-session-manual.htm | 33 + .../xhr/send-authentication-prompt-2-manual.htm | 25 + .../xhr/send-authentication-prompt-manual.htm | 25 + .../wpt/tests/xhr/send-blob-with-no-mime-type.html | 61 + test/wpt/tests/xhr/send-conditional-cors.htm | 42 + test/wpt/tests/xhr/send-conditional.htm | 34 + test/wpt/tests/xhr/send-content-type-charset.htm | 115 + test/wpt/tests/xhr/send-content-type-string.htm | 26 + test/wpt/tests/xhr/send-data-arraybuffer.any.js | 31 + .../wpt/tests/xhr/send-data-arraybufferview.any.js | 18 + test/wpt/tests/xhr/send-data-blob.htm | 62 + test/wpt/tests/xhr/send-data-es-object.any.js | 58 + test/wpt/tests/xhr/send-data-formdata.any.js | 21 + .../tests/xhr/send-data-sharedarraybuffer.any.js | 27 + .../xhr/send-data-string-invalid-unicode.any.js | 46 + .../tests/xhr/send-data-unexpected-tostring.htm | 56 + test/wpt/tests/xhr/send-entity-body-basic.htm | 28 + .../tests/xhr/send-entity-body-document-bogus.htm | 26 + test/wpt/tests/xhr/send-entity-body-document.htm | 92 + test/wpt/tests/xhr/send-entity-body-empty.htm | 26 + .../tests/xhr/send-entity-body-get-head-async.htm | 39 + test/wpt/tests/xhr/send-entity-body-get-head.htm | 36 + test/wpt/tests/xhr/send-entity-body-none.htm | 40 + .../xhr/send-network-error-async-events.sub.htm | 47 + .../xhr/send-network-error-sync-events.sub.htm | 45 + .../tests/xhr/send-no-response-event-loadend.htm | 48 + .../tests/xhr/send-no-response-event-loadstart.htm | 48 + .../wpt/tests/xhr/send-no-response-event-order.htm | 45 + test/wpt/tests/xhr/send-non-same-origin.htm | 33 + test/wpt/tests/xhr/send-receive-utf16.htm | 37 + test/wpt/tests/xhr/send-redirect-bogus-sync.htm | 26 + test/wpt/tests/xhr/send-redirect-bogus.htm | 36 + test/wpt/tests/xhr/send-redirect-infinite-sync.htm | 24 + test/wpt/tests/xhr/send-redirect-infinite.htm | 35 + test/wpt/tests/xhr/send-redirect-no-location.htm | 40 + test/wpt/tests/xhr/send-redirect-post-upload.htm | 140 + test/wpt/tests/xhr/send-redirect-to-cors.htm | 92 + test/wpt/tests/xhr/send-redirect-to-non-cors.htm | 37 + test/wpt/tests/xhr/send-redirect.htm | 36 + test/wpt/tests/xhr/send-response-event-order.htm | 40 + .../xhr/send-response-upload-event-loadend.htm | 40 + .../xhr/send-response-upload-event-loadstart.htm | 39 + .../xhr/send-response-upload-event-progress.htm | 39 + test/wpt/tests/xhr/send-send.any.js | 7 + test/wpt/tests/xhr/send-sync-blocks-async.htm | 53 + .../tests/xhr/send-sync-no-response-event-load.htm | 38 + .../xhr/send-sync-no-response-event-loadend.htm | 38 + .../xhr/send-sync-no-response-event-order.htm | 51 + .../tests/xhr/send-sync-response-event-order.htm | 35 + test/wpt/tests/xhr/send-sync-timeout.htm | 29 + test/wpt/tests/xhr/send-timeout-events.htm | 62 + test/wpt/tests/xhr/send-usp.any.js | 46 + test/wpt/tests/xhr/setrequestheader-after-send.htm | 27 + .../xhr/setrequestheader-allow-empty-value.htm | 26 + .../setrequestheader-allow-whitespace-in-value.htm | 27 + .../wpt/tests/xhr/setrequestheader-before-open.htm | 18 + test/wpt/tests/xhr/setrequestheader-bogus-name.htm | 59 + .../wpt/tests/xhr/setrequestheader-bogus-value.htm | 36 + .../xhr/setrequestheader-case-insensitive.htm | 34 + .../tests/xhr/setrequestheader-combining.window.js | 12 + .../tests/xhr/setrequestheader-content-type.htm | 220 + .../tests/xhr/setrequestheader-header-allowed.htm | 34 + .../xhr/setrequestheader-header-forbidden.htm | 95 + .../xhr/setrequestheader-open-setrequestheader.htm | 53 + test/wpt/tests/xhr/status-async.htm | 62 + test/wpt/tests/xhr/status-basic.htm | 51 + test/wpt/tests/xhr/status-error.htm | 87 + test/wpt/tests/xhr/status.h2.window.js | 21 + test/wpt/tests/xhr/sync-no-progress.any.js | 13 + test/wpt/tests/xhr/sync-no-timeout.any.js | 16 + test/wpt/tests/xhr/sync-xhr-and-window-onload.html | 25 + .../xhr/sync-xhr-supported-by-feature-policy.html | 11 + test/wpt/tests/xhr/template-element.html | 36 + test/wpt/tests/xhr/thrown-error-in-events.html | 60 + test/wpt/tests/xhr/timeout-cors-async.htm | 43 + test/wpt/tests/xhr/timeout-multiple-fetches.html | 32 + test/wpt/tests/xhr/timeout-sync.htm | 25 + .../tests/xhr/xhr-authorization-redirect.any.js | 28 + test/wpt/tests/xhr/xhr-timeout-longtask.any.js | 14 + test/wpt/tests/xhr/xmlhttprequest-basic.htm | 45 + test/wpt/tests/xhr/xmlhttprequest-eventtarget.htm | 48 + .../xhr/xmlhttprequest-network-error-sync.htm | 34 + .../wpt/tests/xhr/xmlhttprequest-network-error.htm | 39 + ...prequest-sync-block-defer-scripts-subframe.html | 17 + .../xmlhttprequest-sync-block-defer-scripts.html | 15 + .../xhr/xmlhttprequest-sync-block-scripts.html | 22 + ...ttprequest-sync-default-feature-policy.sub.html | 32 + ...equest-sync-not-hang-scriptloader-subframe.html | 17 + .../xmlhttprequest-sync-not-hang-scriptloader.html | 16 + .../tests/xhr/xmlhttprequest-timeout-aborted.html | 29 + .../xhr/xmlhttprequest-timeout-abortedonmain.html | 25 + .../xhr/xmlhttprequest-timeout-overrides.html | 26 + .../xmlhttprequest-timeout-overridesexpires.html | 26 + .../tests/xhr/xmlhttprequest-timeout-reused.html | 49 + .../tests/xhr/xmlhttprequest-timeout-simple.html | 27 + .../xhr/xmlhttprequest-timeout-synconmain.html | 23 + .../tests/xhr/xmlhttprequest-timeout-twice.html | 28 + .../xhr/xmlhttprequest-timeout-worker-aborted.html | 31 + .../xmlhttprequest-timeout-worker-overrides.html | 27 + ...ttprequest-timeout-worker-overridesexpires.html | 28 + .../xhr/xmlhttprequest-timeout-worker-simple.html | 29 + ...xmlhttprequest-timeout-worker-synconworker.html | 28 + .../xhr/xmlhttprequest-timeout-worker-twice.html | 29 + test/wpt/tests/xhr/xmlhttprequest-unsent.htm | 36 + 2863 files changed, 196436 insertions(+) create mode 100644 test/wpt/runner/runner.mjs create mode 100644 test/wpt/runner/util.mjs create mode 100644 test/wpt/runner/worker.mjs create mode 100644 test/wpt/server/routes/network-partition-key.mjs create mode 100644 test/wpt/server/routes/redirect.mjs create mode 100644 test/wpt/server/server.mjs create mode 100644 test/wpt/server/websocket.mjs create mode 100644 test/wpt/start-FileAPI.mjs create mode 100644 test/wpt/start-cacheStorage.mjs create mode 100644 test/wpt/start-fetch.mjs create mode 100644 test/wpt/start-mimesniff.mjs create mode 100644 test/wpt/start-websockets.mjs create mode 100644 test/wpt/start-xhr.mjs create mode 100644 test/wpt/status/FileAPI.status.json create mode 100644 test/wpt/status/fetch.status.json create mode 100644 test/wpt/status/mimesniff.status.json create mode 100644 test/wpt/status/service-workers/cache-storage.status.json create mode 100644 test/wpt/status/websockets.status.json create mode 100644 test/wpt/status/xhr/formdata.status.json create mode 100644 test/wpt/tests/.azure-pipelines.yml create mode 100644 test/wpt/tests/.gitattributes create mode 100644 test/wpt/tests/.gitignore create mode 100644 test/wpt/tests/.mailmap create mode 100644 test/wpt/tests/.taskcluster.yml create mode 100644 test/wpt/tests/CODEOWNERS create mode 100644 test/wpt/tests/CODE_OF_CONDUCT.md create mode 100644 test/wpt/tests/CONTRIBUTING.md create mode 100644 test/wpt/tests/FileAPI/Blob-methods-from-detached-frame.html create mode 100644 test/wpt/tests/FileAPI/BlobURL/cross-partition.tentative.https.html create mode 100644 test/wpt/tests/FileAPI/BlobURL/support/file_test2.txt create mode 100644 test/wpt/tests/FileAPI/BlobURL/test2-manual.html create mode 100644 test/wpt/tests/FileAPI/FileReader/progress_event_bubbles_cancelable.html create mode 100644 test/wpt/tests/FileAPI/FileReader/support/file_test1.txt create mode 100644 test/wpt/tests/FileAPI/FileReader/test_errors-manual.html create mode 100644 test/wpt/tests/FileAPI/FileReader/test_notreadableerrors-manual.html create mode 100644 test/wpt/tests/FileAPI/FileReader/test_securityerrors-manual.html create mode 100644 test/wpt/tests/FileAPI/FileReader/workers.html create mode 100644 test/wpt/tests/FileAPI/FileReaderSync.worker.js create mode 100644 test/wpt/tests/FileAPI/META.yml create mode 100644 test/wpt/tests/FileAPI/blob/Blob-array-buffer.any.js create mode 100644 test/wpt/tests/FileAPI/blob/Blob-constructor-dom.window.js create mode 100644 test/wpt/tests/FileAPI/blob/Blob-constructor-endings.html create mode 100644 test/wpt/tests/FileAPI/blob/Blob-constructor.any.js create mode 100644 test/wpt/tests/FileAPI/blob/Blob-in-worker.worker.js create mode 100644 test/wpt/tests/FileAPI/blob/Blob-slice-overflow.any.js create mode 100644 test/wpt/tests/FileAPI/blob/Blob-slice.any.js create mode 100644 test/wpt/tests/FileAPI/blob/Blob-stream-byob-crash.html create mode 100644 test/wpt/tests/FileAPI/blob/Blob-stream-sync-xhr-crash.html create mode 100644 test/wpt/tests/FileAPI/blob/Blob-stream.any.js create mode 100644 test/wpt/tests/FileAPI/blob/Blob-text.any.js create mode 100644 test/wpt/tests/FileAPI/file/File-constructor-endings.html create mode 100644 test/wpt/tests/FileAPI/file/File-constructor.any.js create mode 100644 test/wpt/tests/FileAPI/file/Worker-read-file-constructor.worker.js create mode 100644 test/wpt/tests/FileAPI/file/resources/echo-content-escaped.py create mode 100644 test/wpt/tests/FileAPI/file/send-file-form-controls.html create mode 100644 test/wpt/tests/FileAPI/file/send-file-form-iso-2022-jp.html create mode 100644 test/wpt/tests/FileAPI/file/send-file-form-punctuation.html create mode 100644 test/wpt/tests/FileAPI/file/send-file-form-utf-8.html create mode 100644 test/wpt/tests/FileAPI/file/send-file-form-windows-1252.html create mode 100644 test/wpt/tests/FileAPI/file/send-file-form-x-user-defined.html create mode 100644 test/wpt/tests/FileAPI/file/send-file-form.html create mode 100644 test/wpt/tests/FileAPI/file/send-file-formdata-controls.any.js create mode 100644 test/wpt/tests/FileAPI/file/send-file-formdata-punctuation.any.js create mode 100644 test/wpt/tests/FileAPI/file/send-file-formdata-utf-8.any.js create mode 100644 test/wpt/tests/FileAPI/file/send-file-formdata.any.js create mode 100644 test/wpt/tests/FileAPI/fileReader.any.js create mode 100644 test/wpt/tests/FileAPI/filelist-section/filelist.html create mode 100644 test/wpt/tests/FileAPI/filelist-section/filelist_multiple_selected_files-manual.html create mode 100644 test/wpt/tests/FileAPI/filelist-section/filelist_selected_file-manual.html create mode 100644 test/wpt/tests/FileAPI/filelist-section/support/upload.txt create mode 100644 test/wpt/tests/FileAPI/filelist-section/support/upload.zip create mode 100644 test/wpt/tests/FileAPI/historical.https.html create mode 100644 test/wpt/tests/FileAPI/idlharness-manual.html create mode 100644 test/wpt/tests/FileAPI/idlharness.any.js create mode 100644 test/wpt/tests/FileAPI/idlharness.html create mode 100644 test/wpt/tests/FileAPI/idlharness.worker.js create mode 100644 test/wpt/tests/FileAPI/progress-manual.html create mode 100644 test/wpt/tests/FileAPI/reading-data-section/Determining-Encoding.any.js create mode 100644 test/wpt/tests/FileAPI/reading-data-section/FileReader-event-handler-attributes.any.js create mode 100644 test/wpt/tests/FileAPI/reading-data-section/FileReader-multiple-reads.any.js create mode 100644 test/wpt/tests/FileAPI/reading-data-section/filereader_abort.any.js create mode 100644 test/wpt/tests/FileAPI/reading-data-section/filereader_error.any.js create mode 100644 test/wpt/tests/FileAPI/reading-data-section/filereader_events.any.js create mode 100644 test/wpt/tests/FileAPI/reading-data-section/filereader_file-manual.html create mode 100644 test/wpt/tests/FileAPI/reading-data-section/filereader_file_img-manual.html create mode 100644 test/wpt/tests/FileAPI/reading-data-section/filereader_readAsArrayBuffer.any.js create mode 100644 test/wpt/tests/FileAPI/reading-data-section/filereader_readAsBinaryString.any.js create mode 100644 test/wpt/tests/FileAPI/reading-data-section/filereader_readAsDataURL.any.js create mode 100644 test/wpt/tests/FileAPI/reading-data-section/filereader_readAsText.any.js create mode 100644 test/wpt/tests/FileAPI/reading-data-section/filereader_readystate.any.js create mode 100644 test/wpt/tests/FileAPI/reading-data-section/filereader_result.any.js create mode 100644 test/wpt/tests/FileAPI/reading-data-section/support/blue-100x100.png create mode 100644 test/wpt/tests/FileAPI/support/Blob.js create mode 100644 test/wpt/tests/FileAPI/support/document-domain-setter.sub.html create mode 100644 test/wpt/tests/FileAPI/support/empty-document.html create mode 100644 test/wpt/tests/FileAPI/support/historical-serviceworker.js create mode 100644 test/wpt/tests/FileAPI/support/incumbent.sub.html create mode 100644 test/wpt/tests/FileAPI/support/send-file-form-helper.js create mode 100644 test/wpt/tests/FileAPI/support/send-file-formdata-helper.js create mode 100644 test/wpt/tests/FileAPI/support/upload.txt create mode 100644 test/wpt/tests/FileAPI/support/url-origin.html create mode 100644 test/wpt/tests/FileAPI/unicode.html create mode 100644 test/wpt/tests/FileAPI/url/cross-global-revoke.sub.html create mode 100644 test/wpt/tests/FileAPI/url/multi-global-origin-serialization.sub.html create mode 100644 test/wpt/tests/FileAPI/url/resources/create-helper.html create mode 100644 test/wpt/tests/FileAPI/url/resources/create-helper.js create mode 100644 test/wpt/tests/FileAPI/url/resources/fetch-tests.js create mode 100644 test/wpt/tests/FileAPI/url/resources/revoke-helper.html create mode 100644 test/wpt/tests/FileAPI/url/resources/revoke-helper.js create mode 100644 test/wpt/tests/FileAPI/url/sandboxed-iframe.html create mode 100644 test/wpt/tests/FileAPI/url/unicode-origin.sub.html create mode 100644 test/wpt/tests/FileAPI/url/url-charset.window.js create mode 100644 test/wpt/tests/FileAPI/url/url-format.any.js create mode 100644 test/wpt/tests/FileAPI/url/url-in-tags-revoke.window.js create mode 100644 test/wpt/tests/FileAPI/url/url-in-tags.window.js create mode 100644 test/wpt/tests/FileAPI/url/url-lifetime.html create mode 100644 test/wpt/tests/FileAPI/url/url-reload.window.js create mode 100644 test/wpt/tests/FileAPI/url/url-with-fetch.any.js create mode 100644 test/wpt/tests/FileAPI/url/url-with-xhr.any.js create mode 100644 test/wpt/tests/FileAPI/url/url_createobjecturl_file-manual.html create mode 100644 test/wpt/tests/FileAPI/url/url_createobjecturl_file_img-manual.html create mode 100644 test/wpt/tests/FileAPI/url/url_xmlhttprequest_img-ref.html create mode 100644 test/wpt/tests/FileAPI/url/url_xmlhttprequest_img.html create mode 100644 test/wpt/tests/LICENSE.md create mode 100644 test/wpt/tests/README.md create mode 100644 test/wpt/tests/common/CustomCorsResponse.py create mode 100644 test/wpt/tests/common/META.yml create mode 100644 test/wpt/tests/common/PrefixedLocalStorage.js create mode 100644 test/wpt/tests/common/PrefixedLocalStorage.js.headers create mode 100644 test/wpt/tests/common/PrefixedPostMessage.js create mode 100644 test/wpt/tests/common/PrefixedPostMessage.js.headers create mode 100644 test/wpt/tests/common/README.md create mode 100644 test/wpt/tests/common/__init__.py create mode 100644 test/wpt/tests/common/arrays.js create mode 100644 test/wpt/tests/common/blank-with-cors.html create mode 100644 test/wpt/tests/common/blank-with-cors.html.headers create mode 100644 test/wpt/tests/common/blank.html create mode 100644 test/wpt/tests/common/custom-cors-response.js create mode 100644 test/wpt/tests/common/dispatcher/README.md create mode 100644 test/wpt/tests/common/dispatcher/dispatcher.js create mode 100644 test/wpt/tests/common/dispatcher/dispatcher.py create mode 100644 test/wpt/tests/common/dispatcher/executor-service-worker.js create mode 100644 test/wpt/tests/common/dispatcher/executor-worker.js create mode 100644 test/wpt/tests/common/dispatcher/executor.html create mode 100644 test/wpt/tests/common/dispatcher/remote-executor.html create mode 100644 test/wpt/tests/common/domain-setter.sub.html create mode 100644 test/wpt/tests/common/dummy.xhtml create mode 100644 test/wpt/tests/common/dummy.xml create mode 100644 test/wpt/tests/common/echo.py create mode 100644 test/wpt/tests/common/gc.js create mode 100644 test/wpt/tests/common/get-host-info.sub.js create mode 100644 test/wpt/tests/common/get-host-info.sub.js.headers create mode 100644 test/wpt/tests/common/media.js create mode 100644 test/wpt/tests/common/media.js.headers create mode 100644 test/wpt/tests/common/object-association.js create mode 100644 test/wpt/tests/common/object-association.js.headers create mode 100644 test/wpt/tests/common/performance-timeline-utils.js create mode 100644 test/wpt/tests/common/performance-timeline-utils.js.headers create mode 100644 test/wpt/tests/common/proxy-all.sub.pac create mode 100644 test/wpt/tests/common/redirect-opt-in.py create mode 100644 test/wpt/tests/common/redirect.py create mode 100644 test/wpt/tests/common/refresh.py create mode 100644 test/wpt/tests/common/reftest-wait.js create mode 100644 test/wpt/tests/common/reftest-wait.js.headers create mode 100644 test/wpt/tests/common/rendering-utils.js create mode 100644 test/wpt/tests/common/sab.js create mode 100644 test/wpt/tests/common/security-features/README.md create mode 100644 test/wpt/tests/common/security-features/__init__.py create mode 100644 test/wpt/tests/common/security-features/resources/common.sub.js create mode 100644 test/wpt/tests/common/security-features/resources/common.sub.js.headers create mode 100644 test/wpt/tests/common/security-features/scope/__init__.py create mode 100644 test/wpt/tests/common/security-features/scope/document.py create mode 100644 test/wpt/tests/common/security-features/scope/template/document.html.template create mode 100644 test/wpt/tests/common/security-features/scope/template/worker.js.template create mode 100644 test/wpt/tests/common/security-features/scope/util.py create mode 100644 test/wpt/tests/common/security-features/scope/worker.py create mode 100644 test/wpt/tests/common/security-features/subresource/__init__.py create mode 100644 test/wpt/tests/common/security-features/subresource/audio.py create mode 100644 test/wpt/tests/common/security-features/subresource/document.py create mode 100644 test/wpt/tests/common/security-features/subresource/empty.py create mode 100644 test/wpt/tests/common/security-features/subresource/font.py create mode 100644 test/wpt/tests/common/security-features/subresource/image.py create mode 100644 test/wpt/tests/common/security-features/subresource/referrer.py create mode 100644 test/wpt/tests/common/security-features/subresource/script.py create mode 100644 test/wpt/tests/common/security-features/subresource/shared-worker.py create mode 100644 test/wpt/tests/common/security-features/subresource/static-import.py create mode 100644 test/wpt/tests/common/security-features/subresource/stylesheet.py create mode 100644 test/wpt/tests/common/security-features/subresource/subresource.py create mode 100644 test/wpt/tests/common/security-features/subresource/svg.py create mode 100644 test/wpt/tests/common/security-features/subresource/template/document.html.template create mode 100644 test/wpt/tests/common/security-features/subresource/template/font.css.template create mode 100644 test/wpt/tests/common/security-features/subresource/template/image.css.template create mode 100644 test/wpt/tests/common/security-features/subresource/template/script.js.template create mode 100644 test/wpt/tests/common/security-features/subresource/template/shared-worker.js.template create mode 100644 test/wpt/tests/common/security-features/subresource/template/static-import.js.template create mode 100644 test/wpt/tests/common/security-features/subresource/template/svg.css.template create mode 100644 test/wpt/tests/common/security-features/subresource/template/svg.embedded.template create mode 100644 test/wpt/tests/common/security-features/subresource/template/worker.js.template create mode 100644 test/wpt/tests/common/security-features/subresource/video.py create mode 100644 test/wpt/tests/common/security-features/subresource/worker.py create mode 100644 test/wpt/tests/common/security-features/subresource/xhr.py create mode 100644 test/wpt/tests/common/security-features/tools/format_spec_src_json.py create mode 100644 test/wpt/tests/common/security-features/tools/generate.py create mode 100644 test/wpt/tests/common/security-features/tools/spec.src.json create mode 100644 test/wpt/tests/common/security-features/tools/spec_validator.py create mode 100644 test/wpt/tests/common/security-features/tools/template/disclaimer.template create mode 100644 test/wpt/tests/common/security-features/tools/template/spec_json.js.template create mode 100644 test/wpt/tests/common/security-features/tools/template/test.debug.html.template create mode 100644 test/wpt/tests/common/security-features/tools/template/test.release.html.template create mode 100644 test/wpt/tests/common/security-features/tools/util.py create mode 100644 test/wpt/tests/common/security-features/types.md create mode 100644 test/wpt/tests/common/slow-redirect.py create mode 100644 test/wpt/tests/common/slow.py create mode 100644 test/wpt/tests/common/square.png create mode 100644 test/wpt/tests/common/stringifiers.js create mode 100644 test/wpt/tests/common/stringifiers.js.headers create mode 100644 test/wpt/tests/common/subset-tests-by-key.js create mode 100644 test/wpt/tests/common/subset-tests.js create mode 100644 test/wpt/tests/common/test-setting-immutable-prototype.js create mode 100644 test/wpt/tests/common/test-setting-immutable-prototype.js.headers create mode 100644 test/wpt/tests/common/text-plain.txt create mode 100644 test/wpt/tests/common/third_party/reftest-analyzer.xhtml create mode 100644 test/wpt/tests/common/utils.js create mode 100644 test/wpt/tests/common/utils.js.headers create mode 100644 test/wpt/tests/common/window-name-setter.html create mode 100644 test/wpt/tests/common/worklet-reftest.js create mode 100644 test/wpt/tests/common/worklet-reftest.js.headers create mode 100644 test/wpt/tests/fetch/META.yml create mode 100644 test/wpt/tests/fetch/README.md create mode 100644 test/wpt/tests/fetch/api/abort/cache.https.any.js create mode 100644 test/wpt/tests/fetch/api/abort/destroyed-context.html create mode 100644 test/wpt/tests/fetch/api/abort/general.any.js create mode 100644 test/wpt/tests/fetch/api/abort/keepalive.html create mode 100644 test/wpt/tests/fetch/api/abort/request.any.js create mode 100644 test/wpt/tests/fetch/api/abort/serviceworker-intercepted.https.html create mode 100644 test/wpt/tests/fetch/api/basic/accept-header.any.js create mode 100644 test/wpt/tests/fetch/api/basic/block-mime-as-script.html create mode 100644 test/wpt/tests/fetch/api/basic/conditional-get.any.js create mode 100644 test/wpt/tests/fetch/api/basic/error-after-response.any.js create mode 100644 test/wpt/tests/fetch/api/basic/header-value-combining.any.js create mode 100644 test/wpt/tests/fetch/api/basic/header-value-null-byte.any.js create mode 100644 test/wpt/tests/fetch/api/basic/historical.any.js create mode 100644 test/wpt/tests/fetch/api/basic/http-response-code.any.js create mode 100644 test/wpt/tests/fetch/api/basic/integrity.sub.any.js create mode 100644 test/wpt/tests/fetch/api/basic/keepalive.any.js create mode 100644 test/wpt/tests/fetch/api/basic/mediasource.window.js create mode 100644 test/wpt/tests/fetch/api/basic/mode-no-cors.sub.any.js create mode 100644 test/wpt/tests/fetch/api/basic/mode-same-origin.any.js create mode 100644 test/wpt/tests/fetch/api/basic/referrer.any.js create mode 100644 test/wpt/tests/fetch/api/basic/request-forbidden-headers.any.js create mode 100644 test/wpt/tests/fetch/api/basic/request-head.any.js create mode 100644 test/wpt/tests/fetch/api/basic/request-headers-case.any.js create mode 100644 test/wpt/tests/fetch/api/basic/request-headers-nonascii.any.js create mode 100644 test/wpt/tests/fetch/api/basic/request-headers.any.js create mode 100644 test/wpt/tests/fetch/api/basic/request-referrer-redirected-worker.html create mode 100644 test/wpt/tests/fetch/api/basic/request-referrer.any.js create mode 100644 test/wpt/tests/fetch/api/basic/request-upload.any.js create mode 100644 test/wpt/tests/fetch/api/basic/request-upload.h2.any.js create mode 100644 test/wpt/tests/fetch/api/basic/response-null-body.any.js create mode 100644 test/wpt/tests/fetch/api/basic/response-url.sub.any.js create mode 100644 test/wpt/tests/fetch/api/basic/scheme-about.any.js create mode 100644 test/wpt/tests/fetch/api/basic/scheme-blob.sub.any.js create mode 100644 test/wpt/tests/fetch/api/basic/scheme-data.any.js create mode 100644 test/wpt/tests/fetch/api/basic/scheme-others.sub.any.js create mode 100644 test/wpt/tests/fetch/api/basic/status.h2.any.js create mode 100644 test/wpt/tests/fetch/api/basic/stream-response.any.js create mode 100644 test/wpt/tests/fetch/api/basic/stream-safe-creation.any.js create mode 100644 test/wpt/tests/fetch/api/basic/text-utf8.any.js create mode 100644 test/wpt/tests/fetch/api/body/cloned-any.js create mode 100644 test/wpt/tests/fetch/api/body/formdata.any.js create mode 100644 test/wpt/tests/fetch/api/body/mime-type.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-basic.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-cookies-redirect.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-cookies.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-expose-star.sub.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-filtering.sub.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-keepalive.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-multiple-origins.sub.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-no-preflight.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-origin.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-preflight-cache.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-preflight-not-cors-safelisted.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-preflight-redirect.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-preflight-referrer.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-preflight-response-validation.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-preflight-star.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-preflight-status.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-preflight.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-redirect-credentials.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-redirect-preflight.any.js create mode 100644 test/wpt/tests/fetch/api/cors/cors-redirect.any.js create mode 100644 test/wpt/tests/fetch/api/cors/data-url-iframe.html create mode 100644 test/wpt/tests/fetch/api/cors/data-url-shared-worker.html create mode 100644 test/wpt/tests/fetch/api/cors/data-url-worker.html create mode 100644 test/wpt/tests/fetch/api/cors/resources/corspreflight.js create mode 100644 test/wpt/tests/fetch/api/cors/resources/not-cors-safelisted.json create mode 100644 test/wpt/tests/fetch/api/cors/sandboxed-iframe.html create mode 100644 test/wpt/tests/fetch/api/crashtests/body-window-destroy.html create mode 100644 test/wpt/tests/fetch/api/crashtests/request.html create mode 100644 test/wpt/tests/fetch/api/credentials/authentication-basic.any.js create mode 100644 test/wpt/tests/fetch/api/credentials/authentication-redirection.any.js create mode 100644 test/wpt/tests/fetch/api/credentials/cookies.any.js create mode 100644 test/wpt/tests/fetch/api/headers/header-setcookie.any.js create mode 100644 test/wpt/tests/fetch/api/headers/header-values-normalize.any.js create mode 100644 test/wpt/tests/fetch/api/headers/header-values.any.js create mode 100644 test/wpt/tests/fetch/api/headers/headers-basic.any.js create mode 100644 test/wpt/tests/fetch/api/headers/headers-casing.any.js create mode 100644 test/wpt/tests/fetch/api/headers/headers-combine.any.js create mode 100644 test/wpt/tests/fetch/api/headers/headers-errors.any.js create mode 100644 test/wpt/tests/fetch/api/headers/headers-no-cors.any.js create mode 100644 test/wpt/tests/fetch/api/headers/headers-normalize.any.js create mode 100644 test/wpt/tests/fetch/api/headers/headers-record.any.js create mode 100644 test/wpt/tests/fetch/api/headers/headers-structure.any.js create mode 100644 test/wpt/tests/fetch/api/idlharness.any.js create mode 100644 test/wpt/tests/fetch/api/policies/csp-blocked-worker.html create mode 100644 test/wpt/tests/fetch/api/policies/csp-blocked.html create mode 100644 test/wpt/tests/fetch/api/policies/csp-blocked.html.headers create mode 100644 test/wpt/tests/fetch/api/policies/csp-blocked.js create mode 100644 test/wpt/tests/fetch/api/policies/csp-blocked.js.headers create mode 100644 test/wpt/tests/fetch/api/policies/nested-policy.js create mode 100644 test/wpt/tests/fetch/api/policies/nested-policy.js.headers create mode 100644 test/wpt/tests/fetch/api/policies/referrer-no-referrer-service-worker.https.html create mode 100644 test/wpt/tests/fetch/api/policies/referrer-no-referrer-worker.html create mode 100644 test/wpt/tests/fetch/api/policies/referrer-no-referrer.html create mode 100644 test/wpt/tests/fetch/api/policies/referrer-no-referrer.html.headers create mode 100644 test/wpt/tests/fetch/api/policies/referrer-no-referrer.js create mode 100644 test/wpt/tests/fetch/api/policies/referrer-no-referrer.js.headers create mode 100644 test/wpt/tests/fetch/api/policies/referrer-origin-service-worker.https.html create mode 100644 test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin-service-worker.https.html create mode 100644 test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin-worker.html create mode 100644 test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.html create mode 100644 test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.html.headers create mode 100644 test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.js create mode 100644 test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.js.headers create mode 100644 test/wpt/tests/fetch/api/policies/referrer-origin-worker.html create mode 100644 test/wpt/tests/fetch/api/policies/referrer-origin.html create mode 100644 test/wpt/tests/fetch/api/policies/referrer-origin.html.headers create mode 100644 test/wpt/tests/fetch/api/policies/referrer-origin.js create mode 100644 test/wpt/tests/fetch/api/policies/referrer-origin.js.headers create mode 100644 test/wpt/tests/fetch/api/policies/referrer-unsafe-url-service-worker.https.html create mode 100644 test/wpt/tests/fetch/api/policies/referrer-unsafe-url-worker.html create mode 100644 test/wpt/tests/fetch/api/policies/referrer-unsafe-url.html create mode 100644 test/wpt/tests/fetch/api/policies/referrer-unsafe-url.html.headers create mode 100644 test/wpt/tests/fetch/api/policies/referrer-unsafe-url.js create mode 100644 test/wpt/tests/fetch/api/policies/referrer-unsafe-url.js.headers create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-back-to-original-origin.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-count.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-empty-location.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-keepalive.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-location-escape.tentative.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-location.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-method.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-mode.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-origin.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-referrer-override.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-referrer.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-schemes.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-to-dataurl.any.js create mode 100644 test/wpt/tests/fetch/api/redirect/redirect-upload.h2.any.js create mode 100644 test/wpt/tests/fetch/api/request/destination/fetch-destination-frame.https.html create mode 100644 test/wpt/tests/fetch/api/request/destination/fetch-destination-iframe.https.html create mode 100644 test/wpt/tests/fetch/api/request/destination/fetch-destination-no-load-event.https.html create mode 100644 test/wpt/tests/fetch/api/request/destination/fetch-destination-prefetch.https.html create mode 100644 test/wpt/tests/fetch/api/request/destination/fetch-destination-worker.https.html create mode 100644 test/wpt/tests/fetch/api/request/destination/fetch-destination.https.html create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/dummy create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/dummy.es create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/dummy.es.headers create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/dummy.html create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/dummy.png create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/dummy.ttf create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/dummy_audio.mp3 create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/dummy_audio.oga create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/dummy_video.mp4 create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/dummy_video.ogv create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/dummy_video.webm create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/empty.https.html create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker-frame.js create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker-iframe.js create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker-no-load-event.js create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker.js create mode 100644 test/wpt/tests/fetch/api/request/destination/resources/importer.js create mode 100644 test/wpt/tests/fetch/api/request/forbidden-method.any.js create mode 100644 test/wpt/tests/fetch/api/request/multi-globals/construct-in-detached-frame.window.js create mode 100644 test/wpt/tests/fetch/api/request/multi-globals/current/current.html create mode 100644 test/wpt/tests/fetch/api/request/multi-globals/incumbent/incumbent.html create mode 100644 test/wpt/tests/fetch/api/request/multi-globals/url-parsing.html create mode 100644 test/wpt/tests/fetch/api/request/request-bad-port.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-cache-default-conditional.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-cache-default.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-cache-force-cache.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-cache-no-cache.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-cache-no-store.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-cache-only-if-cached.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-cache-reload.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-cache.js create mode 100644 test/wpt/tests/fetch/api/request/request-clone.sub.html create mode 100644 test/wpt/tests/fetch/api/request/request-consume-empty.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-consume.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-disturbed.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-error.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-error.js create mode 100644 test/wpt/tests/fetch/api/request/request-headers.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-init-001.sub.html create mode 100644 test/wpt/tests/fetch/api/request/request-init-002.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-init-003.sub.html create mode 100644 test/wpt/tests/fetch/api/request/request-init-contenttype.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-init-priority.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-init-stream.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-keepalive-quota.html create mode 100644 test/wpt/tests/fetch/api/request/request-keepalive.any.js create mode 100644 test/wpt/tests/fetch/api/request/request-reset-attributes.https.html create mode 100644 test/wpt/tests/fetch/api/request/request-structure.any.js create mode 100644 test/wpt/tests/fetch/api/request/resources/cache.py create mode 100644 test/wpt/tests/fetch/api/request/resources/hello.txt create mode 100644 test/wpt/tests/fetch/api/request/resources/request-reset-attributes-worker.js create mode 100644 test/wpt/tests/fetch/api/request/url-encoding.html create mode 100644 test/wpt/tests/fetch/api/resources/authentication.py create mode 100644 test/wpt/tests/fetch/api/resources/bad-chunk-encoding.py create mode 100644 test/wpt/tests/fetch/api/resources/basic.html create mode 100644 test/wpt/tests/fetch/api/resources/cache.py create mode 100644 test/wpt/tests/fetch/api/resources/clean-stash.py create mode 100644 test/wpt/tests/fetch/api/resources/cors-top.txt create mode 100644 test/wpt/tests/fetch/api/resources/cors-top.txt.headers create mode 100644 test/wpt/tests/fetch/api/resources/data.json create mode 100644 test/wpt/tests/fetch/api/resources/dump-authorization-header.py create mode 100644 test/wpt/tests/fetch/api/resources/echo-content.h2.py create mode 100644 test/wpt/tests/fetch/api/resources/echo-content.py create mode 100644 test/wpt/tests/fetch/api/resources/empty.txt create mode 100644 test/wpt/tests/fetch/api/resources/infinite-slow-response.py create mode 100644 test/wpt/tests/fetch/api/resources/inspect-headers.py create mode 100644 test/wpt/tests/fetch/api/resources/keepalive-helper.js create mode 100644 test/wpt/tests/fetch/api/resources/keepalive-iframe.html create mode 100644 test/wpt/tests/fetch/api/resources/keepalive-redirect-iframe.html create mode 100644 test/wpt/tests/fetch/api/resources/keepalive-redirect-window.html create mode 100644 test/wpt/tests/fetch/api/resources/method.py create mode 100644 test/wpt/tests/fetch/api/resources/preflight.py create mode 100644 test/wpt/tests/fetch/api/resources/redirect-empty-location.py create mode 100644 test/wpt/tests/fetch/api/resources/redirect.h2.py create mode 100644 test/wpt/tests/fetch/api/resources/redirect.py create mode 100644 test/wpt/tests/fetch/api/resources/sandboxed-iframe.html create mode 100644 test/wpt/tests/fetch/api/resources/script-with-header.py create mode 100644 test/wpt/tests/fetch/api/resources/stash-put.py create mode 100644 test/wpt/tests/fetch/api/resources/stash-take.py create mode 100644 test/wpt/tests/fetch/api/resources/status.py create mode 100644 test/wpt/tests/fetch/api/resources/sw-intercept-abort.js create mode 100644 test/wpt/tests/fetch/api/resources/sw-intercept.js create mode 100644 test/wpt/tests/fetch/api/resources/top.txt create mode 100644 test/wpt/tests/fetch/api/resources/trickle.py create mode 100644 test/wpt/tests/fetch/api/resources/utils.js create mode 100644 test/wpt/tests/fetch/api/response/json.any.js create mode 100644 test/wpt/tests/fetch/api/response/many-empty-chunks-crash.html create mode 100644 test/wpt/tests/fetch/api/response/multi-globals/current/current.html create mode 100644 test/wpt/tests/fetch/api/response/multi-globals/incumbent/incumbent.html create mode 100644 test/wpt/tests/fetch/api/response/multi-globals/relevant/relevant.html create mode 100644 test/wpt/tests/fetch/api/response/multi-globals/url-parsing.html create mode 100644 test/wpt/tests/fetch/api/response/response-body-read-task-handling.html create mode 100644 test/wpt/tests/fetch/api/response/response-cancel-stream.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-clone-iframe.window.js create mode 100644 test/wpt/tests/fetch/api/response/response-clone.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-consume-empty.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-consume-stream.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-consume.html create mode 100644 test/wpt/tests/fetch/api/response/response-error-from-stream.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-error.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-from-stream.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-init-001.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-init-002.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-init-contenttype.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-static-error.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-static-json.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-static-redirect.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-stream-bad-chunk.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-stream-disturbed-1.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-stream-disturbed-2.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-stream-disturbed-3.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-stream-disturbed-4.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-stream-disturbed-5.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-stream-disturbed-6.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-stream-disturbed-by-pipe.any.js create mode 100644 test/wpt/tests/fetch/api/response/response-stream-disturbed-util.js create mode 100644 test/wpt/tests/fetch/api/response/response-stream-with-broken-then.any.js create mode 100644 test/wpt/tests/fetch/connection-pool/network-partition-key.html create mode 100644 test/wpt/tests/fetch/connection-pool/resources/network-partition-about-blank-checker.html create mode 100644 test/wpt/tests/fetch/connection-pool/resources/network-partition-checker.html create mode 100644 test/wpt/tests/fetch/connection-pool/resources/network-partition-iframe-checker.html create mode 100644 test/wpt/tests/fetch/connection-pool/resources/network-partition-key.js create mode 100644 test/wpt/tests/fetch/connection-pool/resources/network-partition-key.py create mode 100644 test/wpt/tests/fetch/connection-pool/resources/network-partition-worker-checker.html create mode 100644 test/wpt/tests/fetch/connection-pool/resources/network-partition-worker.js create mode 100644 test/wpt/tests/fetch/content-encoding/bad-gzip-body.any.js create mode 100644 test/wpt/tests/fetch/content-encoding/gzip-body.any.js create mode 100644 test/wpt/tests/fetch/content-encoding/resources/bad-gzip-body.py create mode 100644 test/wpt/tests/fetch/content-encoding/resources/foo.octetstream.gz create mode 100644 test/wpt/tests/fetch/content-encoding/resources/foo.octetstream.gz.headers create mode 100644 test/wpt/tests/fetch/content-encoding/resources/foo.text.gz create mode 100644 test/wpt/tests/fetch/content-encoding/resources/foo.text.gz.headers create mode 100644 test/wpt/tests/fetch/content-length/api-and-duplicate-headers.any.js create mode 100644 test/wpt/tests/fetch/content-length/content-length.html create mode 100644 test/wpt/tests/fetch/content-length/content-length.html.headers create mode 100644 test/wpt/tests/fetch/content-length/parsing.window.js create mode 100644 test/wpt/tests/fetch/content-length/resources/content-length.py create mode 100644 test/wpt/tests/fetch/content-length/resources/content-lengths.json create mode 100644 test/wpt/tests/fetch/content-length/resources/identical-duplicates.asis create mode 100644 test/wpt/tests/fetch/content-length/too-long.window.js create mode 100644 test/wpt/tests/fetch/content-type/README.md create mode 100644 test/wpt/tests/fetch/content-type/multipart-malformed.any.js create mode 100644 test/wpt/tests/fetch/content-type/multipart.window.js create mode 100644 test/wpt/tests/fetch/content-type/resources/content-type.py create mode 100644 test/wpt/tests/fetch/content-type/resources/content-types.json create mode 100644 test/wpt/tests/fetch/content-type/resources/script-content-types.json create mode 100644 test/wpt/tests/fetch/content-type/response.window.js create mode 100644 test/wpt/tests/fetch/content-type/script.window.js create mode 100644 test/wpt/tests/fetch/corb/README.md create mode 100644 test/wpt/tests/fetch/corb/img-html-correctly-labeled.sub-ref.html create mode 100644 test/wpt/tests/fetch/corb/img-html-correctly-labeled.sub.html create mode 100644 test/wpt/tests/fetch/corb/img-mime-types-coverage.tentative.sub.html create mode 100644 test/wpt/tests/fetch/corb/img-png-mislabeled-as-html-nosniff.tentative.sub-ref.html create mode 100644 test/wpt/tests/fetch/corb/img-png-mislabeled-as-html-nosniff.tentative.sub.html create mode 100644 test/wpt/tests/fetch/corb/img-png-mislabeled-as-html.sub-ref.html create mode 100644 test/wpt/tests/fetch/corb/img-png-mislabeled-as-html.sub.html create mode 100644 test/wpt/tests/fetch/corb/img-svg-doctype-html-mimetype-empty.sub.html create mode 100644 test/wpt/tests/fetch/corb/img-svg-doctype-html-mimetype-svg.sub.html create mode 100644 test/wpt/tests/fetch/corb/img-svg-invalid.sub-ref.html create mode 100644 test/wpt/tests/fetch/corb/img-svg-labeled-as-dash.sub.html create mode 100644 test/wpt/tests/fetch/corb/img-svg-labeled-as-svg-xml.sub.html create mode 100644 test/wpt/tests/fetch/corb/img-svg-xml-decl.sub.html create mode 100644 test/wpt/tests/fetch/corb/img-svg.sub-ref.html create mode 100644 test/wpt/tests/fetch/corb/preload-image-png-mislabeled-as-html-nosniff.tentative.sub.html create mode 100644 test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html-nosniff.css create mode 100644 test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html-nosniff.css.headers create mode 100644 test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html.css create mode 100644 test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html.css.headers create mode 100644 test/wpt/tests/fetch/corb/resources/css-with-json-parser-breaker.css create mode 100644 test/wpt/tests/fetch/corb/resources/empty-labeled-as-png.png create mode 100644 test/wpt/tests/fetch/corb/resources/empty-labeled-as-png.png.headers create mode 100644 test/wpt/tests/fetch/corb/resources/html-correctly-labeled.html create mode 100644 test/wpt/tests/fetch/corb/resources/html-correctly-labeled.html.headers create mode 100644 test/wpt/tests/fetch/corb/resources/html-js-polyglot.js create mode 100644 test/wpt/tests/fetch/corb/resources/html-js-polyglot.js.headers create mode 100644 test/wpt/tests/fetch/corb/resources/html-js-polyglot2.js create mode 100644 test/wpt/tests/fetch/corb/resources/html-js-polyglot2.js.headers create mode 100644 test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html-nosniff.js create mode 100644 test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html-nosniff.js.headers create mode 100644 test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html.js create mode 100644 test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html.js.headers create mode 100644 test/wpt/tests/fetch/corb/resources/png-correctly-labeled.png create mode 100644 test/wpt/tests/fetch/corb/resources/png-correctly-labeled.png.headers create mode 100644 test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html-nosniff.png create mode 100644 test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html-nosniff.png.headers create mode 100644 test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html.png create mode 100644 test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html.png.headers create mode 100644 test/wpt/tests/fetch/corb/resources/response_block_probe.js create mode 100644 test/wpt/tests/fetch/corb/resources/response_block_probe.js.headers create mode 100644 test/wpt/tests/fetch/corb/resources/sniffable-resource.py create mode 100644 test/wpt/tests/fetch/corb/resources/subframe-that-posts-html-containing-blob-url-to-parent.html create mode 100644 test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-empty.svg create mode 100644 test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-empty.svg.headers create mode 100644 test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-svg.svg create mode 100644 test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-svg.svg.headers create mode 100644 test/wpt/tests/fetch/corb/resources/svg-labeled-as-dash.svg create mode 100644 test/wpt/tests/fetch/corb/resources/svg-labeled-as-dash.svg.headers create mode 100644 test/wpt/tests/fetch/corb/resources/svg-labeled-as-svg-xml.svg create mode 100644 test/wpt/tests/fetch/corb/resources/svg-labeled-as-svg-xml.svg.headers create mode 100644 test/wpt/tests/fetch/corb/resources/svg-xml-decl.svg create mode 100644 test/wpt/tests/fetch/corb/resources/svg.svg create mode 100644 test/wpt/tests/fetch/corb/resources/svg.svg.headers create mode 100644 test/wpt/tests/fetch/corb/response_block.tentative.https.html create mode 100644 test/wpt/tests/fetch/corb/script-html-correctly-labeled.tentative.sub.html create mode 100644 test/wpt/tests/fetch/corb/script-html-js-polyglot.sub.html create mode 100644 test/wpt/tests/fetch/corb/script-html-via-cross-origin-blob-url.sub.html create mode 100644 test/wpt/tests/fetch/corb/script-js-mislabeled-as-html-nosniff.sub.html create mode 100644 test/wpt/tests/fetch/corb/script-js-mislabeled-as-html.sub.html create mode 100644 test/wpt/tests/fetch/corb/script-resource-with-json-parser-breaker.tentative.sub.html create mode 100644 test/wpt/tests/fetch/corb/script-resource-with-nonsniffable-types.tentative.sub.html create mode 100644 test/wpt/tests/fetch/corb/style-css-mislabeled-as-html-nosniff.sub.html create mode 100644 test/wpt/tests/fetch/corb/style-css-mislabeled-as-html.sub.html create mode 100644 test/wpt/tests/fetch/corb/style-css-with-json-parser-breaker.sub.html create mode 100644 test/wpt/tests/fetch/corb/style-html-correctly-labeled.sub.html create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/fetch-in-iframe.html create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/fetch.any.js create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/fetch.https.any.js create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/iframe-loads.html create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/image-loads.html create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/resources/green.png create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/resources/hello.py create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/resources/iframe.py create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/resources/iframeFetch.html create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/resources/image.py create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/resources/redirect.py create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/resources/script.py create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/scheme-restriction.any.js create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/scheme-restriction.https.window.js create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/script-loads.html create mode 100644 test/wpt/tests/fetch/cross-origin-resource-policy/syntax.any.js create mode 100644 test/wpt/tests/fetch/data-urls/README.md create mode 100644 test/wpt/tests/fetch/data-urls/base64.any.js create mode 100644 test/wpt/tests/fetch/data-urls/navigate.window.js create mode 100644 test/wpt/tests/fetch/data-urls/processing.any.js create mode 100644 test/wpt/tests/fetch/data-urls/resources/base64.json create mode 100644 test/wpt/tests/fetch/data-urls/resources/data-urls.json create mode 100644 test/wpt/tests/fetch/fetch-later/META.yml create mode 100644 test/wpt/tests/fetch/fetch-later/README.md create mode 100644 test/wpt/tests/fetch/fetch-later/basic.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/fetch-later/non-secure.window.js create mode 100644 test/wpt/tests/fetch/fetch-later/sendondiscard.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/h1-parsing/README.md create mode 100644 test/wpt/tests/fetch/h1-parsing/lone-cr.window.js create mode 100644 test/wpt/tests/fetch/h1-parsing/resources-with-0x00-in-header.window.js create mode 100644 test/wpt/tests/fetch/h1-parsing/resources/README.md create mode 100644 test/wpt/tests/fetch/h1-parsing/resources/blue-with-0x00-in-a-header.asis create mode 100644 test/wpt/tests/fetch/h1-parsing/resources/document-with-0x00-in-header.py create mode 100644 test/wpt/tests/fetch/h1-parsing/resources/message.py create mode 100644 test/wpt/tests/fetch/h1-parsing/resources/script-with-0x00-in-header.py create mode 100644 test/wpt/tests/fetch/h1-parsing/resources/status-code.py create mode 100644 test/wpt/tests/fetch/h1-parsing/status-code.window.js create mode 100644 test/wpt/tests/fetch/http-cache/304-update.any.js create mode 100644 test/wpt/tests/fetch/http-cache/README.md create mode 100644 test/wpt/tests/fetch/http-cache/basic-auth-cache-test-ref.html create mode 100644 test/wpt/tests/fetch/http-cache/basic-auth-cache-test.html create mode 100644 test/wpt/tests/fetch/http-cache/cache-mode.any.js create mode 100644 test/wpt/tests/fetch/http-cache/cc-request.any.js create mode 100644 test/wpt/tests/fetch/http-cache/credentials.tentative.any.js create mode 100644 test/wpt/tests/fetch/http-cache/freshness.any.js create mode 100644 test/wpt/tests/fetch/http-cache/heuristic.any.js create mode 100644 test/wpt/tests/fetch/http-cache/http-cache.js create mode 100644 test/wpt/tests/fetch/http-cache/invalidate.any.js create mode 100644 test/wpt/tests/fetch/http-cache/partial.any.js create mode 100644 test/wpt/tests/fetch/http-cache/post-patch.any.js create mode 100644 test/wpt/tests/fetch/http-cache/resources/http-cache.py create mode 100644 test/wpt/tests/fetch/http-cache/resources/securedimage.py create mode 100644 test/wpt/tests/fetch/http-cache/resources/split-cache-popup-with-iframe.html create mode 100644 test/wpt/tests/fetch/http-cache/resources/split-cache-popup.html create mode 100644 test/wpt/tests/fetch/http-cache/split-cache.html create mode 100644 test/wpt/tests/fetch/http-cache/status.any.js create mode 100644 test/wpt/tests/fetch/http-cache/vary.any.js create mode 100644 test/wpt/tests/fetch/images/canvas-remote-read-remote-image-redirect.html create mode 100644 test/wpt/tests/fetch/metadata/META.yml create mode 100644 test/wpt/tests/fetch/metadata/README.md create mode 100644 test/wpt/tests/fetch/metadata/audio-worklet.https.html create mode 100644 test/wpt/tests/fetch/metadata/embed.https.sub.tentative.html create mode 100644 test/wpt/tests/fetch/metadata/fetch-preflight.https.sub.any.js create mode 100644 test/wpt/tests/fetch/metadata/fetch.https.sub.any.js create mode 100644 test/wpt/tests/fetch/metadata/generated/appcache-manifest.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/audioworklet.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/css-font-face.https.sub.tentative.html create mode 100644 test/wpt/tests/fetch/metadata/generated/css-font-face.sub.tentative.html create mode 100644 test/wpt/tests/fetch/metadata/generated/css-images.https.sub.tentative.html create mode 100644 test/wpt/tests/fetch/metadata/generated/css-images.sub.tentative.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-a.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-a.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-area.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-area.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-audio.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-audio.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-embed.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-embed.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-frame.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-frame.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-iframe.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-iframe.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-img-environment-change.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-img-environment-change.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-img.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-img.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-input-image.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-input-image.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-link-icon.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-link-icon.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-link-prefetch.https.optional.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-link-prefetch.optional.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-meta-refresh.https.optional.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-meta-refresh.optional.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-picture.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-picture.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-script.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-script.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-video-poster.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-video-poster.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-video.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/element-video.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/fetch-via-serviceworker.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/fetch.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/fetch.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/form-submission.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/form-submission.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/header-link.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/header-link.https.sub.tentative.html create mode 100644 test/wpt/tests/fetch/metadata/generated/header-link.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/header-refresh.https.optional.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/header-refresh.optional.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/script-module-import-dynamic.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/script-module-import-dynamic.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/script-module-import-static.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/script-module-import-static.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/serviceworker.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/svg-image.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/svg-image.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/window-history.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/window-history.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/window-location.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/window-location.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/worker-dedicated-constructor.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/worker-dedicated-constructor.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/worker-dedicated-importscripts.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/generated/worker-dedicated-importscripts.sub.html create mode 100644 test/wpt/tests/fetch/metadata/navigation.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/object.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/paint-worklet.https.html create mode 100644 test/wpt/tests/fetch/metadata/portal.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/preload.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/redirect/multiple-redirect-https-downgrade-upgrade.sub.html create mode 100644 test/wpt/tests/fetch/metadata/redirect/redirect-http-upgrade.sub.html create mode 100644 test/wpt/tests/fetch/metadata/redirect/redirect-https-downgrade.sub.html create mode 100644 test/wpt/tests/fetch/metadata/report.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/report.https.sub.html.sub.headers create mode 100644 test/wpt/tests/fetch/metadata/resources/appcache-iframe.sub.html create mode 100644 test/wpt/tests/fetch/metadata/resources/dedicatedWorker.js create mode 100644 test/wpt/tests/fetch/metadata/resources/echo-as-json.py create mode 100644 test/wpt/tests/fetch/metadata/resources/echo-as-script.py create mode 100644 test/wpt/tests/fetch/metadata/resources/es-module.sub.js create mode 100644 test/wpt/tests/fetch/metadata/resources/fetch-via-serviceworker--fallback--sw.js create mode 100644 test/wpt/tests/fetch/metadata/resources/fetch-via-serviceworker--respondWith--sw.js create mode 100644 test/wpt/tests/fetch/metadata/resources/fetch-via-serviceworker-frame.html create mode 100644 test/wpt/tests/fetch/metadata/resources/header-link.py create mode 100644 test/wpt/tests/fetch/metadata/resources/helper.js create mode 100644 test/wpt/tests/fetch/metadata/resources/helper.sub.js create mode 100644 test/wpt/tests/fetch/metadata/resources/message-opener.html create mode 100644 test/wpt/tests/fetch/metadata/resources/post-to-owner.py create mode 100644 test/wpt/tests/fetch/metadata/resources/record-header.py create mode 100644 test/wpt/tests/fetch/metadata/resources/record-headers.py create mode 100644 test/wpt/tests/fetch/metadata/resources/redirectTestHelper.sub.js create mode 100644 test/wpt/tests/fetch/metadata/resources/serviceworker-accessors-frame.html create mode 100644 test/wpt/tests/fetch/metadata/resources/serviceworker-accessors.sw.js create mode 100644 test/wpt/tests/fetch/metadata/resources/sharedWorker.js create mode 100644 test/wpt/tests/fetch/metadata/resources/unload-with-beacon.html create mode 100644 test/wpt/tests/fetch/metadata/resources/xslt-test.sub.xml create mode 100644 test/wpt/tests/fetch/metadata/serviceworker-accessors.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/sharedworker.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/style.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/README.md create mode 100644 test/wpt/tests/fetch/metadata/tools/fetch-metadata.conf.yml create mode 100644 test/wpt/tests/fetch/metadata/tools/generate.py create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/appcache-manifest.sub.https.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/audioworklet.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/css-font-face.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/css-images.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-a.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-area.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-audio.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-embed.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-frame.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-iframe.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-img-environment-change.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-img.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-input-image.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-link-icon.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-link-prefetch.optional.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-meta-refresh.optional.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-picture.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-script.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-video-poster.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/element-video.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/fetch-via-serviceworker.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/fetch.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/form-submission.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/header-link.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/header-refresh.optional.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/script-module-import-dynamic.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/script-module-import-static.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/serviceworker.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/svg-image.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/window-history.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/window-location.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/worker-dedicated-constructor.sub.html create mode 100644 test/wpt/tests/fetch/metadata/tools/templates/worker-dedicated-importscripts.sub.html create mode 100644 test/wpt/tests/fetch/metadata/track.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/trailing-dot.https.sub.any.js create mode 100644 test/wpt/tests/fetch/metadata/unload.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/window-open.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/worker.https.sub.html create mode 100644 test/wpt/tests/fetch/metadata/xslt.https.sub.html create mode 100644 test/wpt/tests/fetch/nosniff/image.html create mode 100644 test/wpt/tests/fetch/nosniff/importscripts.html create mode 100644 test/wpt/tests/fetch/nosniff/importscripts.js create mode 100644 test/wpt/tests/fetch/nosniff/parsing-nosniff.window.js create mode 100644 test/wpt/tests/fetch/nosniff/resources/css.py create mode 100644 test/wpt/tests/fetch/nosniff/resources/image.py create mode 100644 test/wpt/tests/fetch/nosniff/resources/js.py create mode 100644 test/wpt/tests/fetch/nosniff/resources/nosniff.py create mode 100644 test/wpt/tests/fetch/nosniff/resources/worker.py create mode 100644 test/wpt/tests/fetch/nosniff/resources/x-content-type-options.json create mode 100644 test/wpt/tests/fetch/nosniff/script.html create mode 100644 test/wpt/tests/fetch/nosniff/stylesheet.html create mode 100644 test/wpt/tests/fetch/nosniff/worker.html create mode 100644 test/wpt/tests/fetch/orb/resources/data.json create mode 100644 test/wpt/tests/fetch/orb/resources/data_non_ascii.json create mode 100644 test/wpt/tests/fetch/orb/resources/empty.json create mode 100644 test/wpt/tests/fetch/orb/resources/font.ttf create mode 100644 test/wpt/tests/fetch/orb/resources/image.png create mode 100644 test/wpt/tests/fetch/orb/resources/js-unlabeled-utf16-without-bom.json create mode 100644 test/wpt/tests/fetch/orb/resources/js-unlabeled.js create mode 100644 test/wpt/tests/fetch/orb/resources/png-mislabeled-as-html.png create mode 100644 test/wpt/tests/fetch/orb/resources/png-mislabeled-as-html.png.headers create mode 100644 test/wpt/tests/fetch/orb/resources/png-unlabeled.png create mode 100644 test/wpt/tests/fetch/orb/resources/script-asm-js-invalid.js create mode 100644 test/wpt/tests/fetch/orb/resources/script-asm-js-valid.js create mode 100644 test/wpt/tests/fetch/orb/resources/script-iso-8559-1.js create mode 100644 test/wpt/tests/fetch/orb/resources/script-utf16-bom.js create mode 100644 test/wpt/tests/fetch/orb/resources/script-utf16-without-bom.js create mode 100644 test/wpt/tests/fetch/orb/resources/script.js create mode 100644 test/wpt/tests/fetch/orb/resources/sound.mp3 create mode 100644 test/wpt/tests/fetch/orb/resources/text.txt create mode 100644 test/wpt/tests/fetch/orb/resources/utils.js create mode 100644 test/wpt/tests/fetch/orb/tentative/compressed-image-sniffing.sub.html create mode 100644 test/wpt/tests/fetch/orb/tentative/content-range.sub.any.js create mode 100644 test/wpt/tests/fetch/orb/tentative/img-mime-types-coverage.tentative.sub.html create mode 100644 test/wpt/tests/fetch/orb/tentative/img-png-mislabeled-as-html.sub-ref.html create mode 100644 test/wpt/tests/fetch/orb/tentative/img-png-mislabeled-as-html.sub.html create mode 100644 test/wpt/tests/fetch/orb/tentative/img-png-unlabeled.sub-ref.html create mode 100644 test/wpt/tests/fetch/orb/tentative/img-png-unlabeled.sub.html create mode 100644 test/wpt/tests/fetch/orb/tentative/known-mime-type.sub.any.js create mode 100644 test/wpt/tests/fetch/orb/tentative/nosniff.sub.any.js create mode 100644 test/wpt/tests/fetch/orb/tentative/script-js-unlabeled-gziped.sub.html create mode 100644 test/wpt/tests/fetch/orb/tentative/script-unlabeled.sub.html create mode 100644 test/wpt/tests/fetch/orb/tentative/script-utf16-without-bom-hint-charset.sub.html create mode 100644 test/wpt/tests/fetch/orb/tentative/status.sub.any.js create mode 100644 test/wpt/tests/fetch/orb/tentative/status.sub.html create mode 100644 test/wpt/tests/fetch/orb/tentative/unknown-mime-type.sub.any.js create mode 100644 test/wpt/tests/fetch/origin/assorted.window.js create mode 100644 test/wpt/tests/fetch/origin/resources/redirect-and-stash.py create mode 100644 test/wpt/tests/fetch/origin/resources/referrer-policy.py create mode 100644 test/wpt/tests/fetch/private-network-access/META.yml create mode 100644 test/wpt/tests/fetch/private-network-access/README.md create mode 100644 test/wpt/tests/fetch/private-network-access/fenced-frame-no-preflight-required.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/fenced-frame-subresource-fetch.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/fenced-frame.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/fetch-from-treat-as-public.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/fetch.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/fetch.tentative.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/iframe.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/iframe.tentative.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/mixed-content-fetch.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/nested-worker.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/nested-worker.tentative.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/preflight-cache.https.tentative.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/redirect.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/resources/executor.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/fenced-frame-fetcher.https.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/fenced-frame-fetcher.https.html.headers create mode 100644 test/wpt/tests/fetch/private-network-access/resources/fenced-frame-local-network-access-target.https.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/fenced-frame-local-network-access.https.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/fenced-frame-local-network-access.https.html.headers create mode 100644 test/wpt/tests/fetch/private-network-access/resources/fetcher.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/fetcher.js create mode 100644 test/wpt/tests/fetch/private-network-access/resources/iframed.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/iframer.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/preflight.py create mode 100644 test/wpt/tests/fetch/private-network-access/resources/service-worker-bridge.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/service-worker.js create mode 100644 test/wpt/tests/fetch/private-network-access/resources/shared-fetcher.js create mode 100644 test/wpt/tests/fetch/private-network-access/resources/shared-worker-blob-fetcher.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/shared-worker-fetcher.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/socket-opener.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/support.sub.js create mode 100644 test/wpt/tests/fetch/private-network-access/resources/worker-blob-fetcher.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/worker-fetcher.html create mode 100644 test/wpt/tests/fetch/private-network-access/resources/worker-fetcher.js create mode 100644 test/wpt/tests/fetch/private-network-access/resources/xhr-sender.html create mode 100644 test/wpt/tests/fetch/private-network-access/service-worker-background-fetch.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/service-worker-fetch.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/service-worker-update.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/service-worker.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/shared-worker-blob-fetch.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/shared-worker-blob-fetch.tentative.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/shared-worker-fetch.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/shared-worker-fetch.tentative.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/shared-worker.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/shared-worker.tentative.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/websocket.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/websocket.tentative.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/worker-blob-fetch.tentative.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/worker-fetch.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/worker-fetch.tentative.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/worker.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/worker.tentative.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/xhr-from-treat-as-public.tentative.https.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/xhr.https.tentative.window.js create mode 100644 test/wpt/tests/fetch/private-network-access/xhr.tentative.window.js create mode 100644 test/wpt/tests/fetch/range/blob.any.js create mode 100644 test/wpt/tests/fetch/range/data.any.js create mode 100644 test/wpt/tests/fetch/range/general.any.js create mode 100644 test/wpt/tests/fetch/range/general.window.js create mode 100644 test/wpt/tests/fetch/range/non-matching-range-response.html create mode 100644 test/wpt/tests/fetch/range/resources/basic.html create mode 100644 test/wpt/tests/fetch/range/resources/long-wav.py create mode 100644 test/wpt/tests/fetch/range/resources/partial-script.py create mode 100644 test/wpt/tests/fetch/range/resources/partial-text.py create mode 100644 test/wpt/tests/fetch/range/resources/range-sw.js create mode 100644 test/wpt/tests/fetch/range/resources/stash-take.py create mode 100644 test/wpt/tests/fetch/range/resources/utils.js create mode 100644 test/wpt/tests/fetch/range/resources/video-with-range.py create mode 100644 test/wpt/tests/fetch/range/sw.https.window.js create mode 100644 test/wpt/tests/fetch/redirect-navigate/302-found-post-handler.py create mode 100644 test/wpt/tests/fetch/redirect-navigate/302-found-post.html create mode 100644 test/wpt/tests/fetch/redirect-navigate/preserve-fragment.html create mode 100644 test/wpt/tests/fetch/redirect-navigate/resources/destination.html create mode 100644 test/wpt/tests/fetch/redirects/data.window.js create mode 100644 test/wpt/tests/fetch/redirects/subresource-fragments.html create mode 100644 test/wpt/tests/fetch/security/1xx-response.any.js create mode 100644 test/wpt/tests/fetch/security/dangling-markup-mitigation-data-url.tentative.sub.html create mode 100644 test/wpt/tests/fetch/security/dangling-markup-mitigation.tentative.html create mode 100644 test/wpt/tests/fetch/security/embedded-credentials.tentative.sub.html create mode 100644 test/wpt/tests/fetch/security/redirect-to-url-with-credentials.https.html create mode 100644 test/wpt/tests/fetch/security/support/embedded-credential-window.sub.html create mode 100644 test/wpt/tests/fetch/stale-while-revalidate/fetch-sw.https.html create mode 100644 test/wpt/tests/fetch/stale-while-revalidate/fetch.any.js create mode 100644 test/wpt/tests/fetch/stale-while-revalidate/resources/stale-css.py create mode 100644 test/wpt/tests/fetch/stale-while-revalidate/resources/stale-image.py create mode 100644 test/wpt/tests/fetch/stale-while-revalidate/resources/stale-script.py create mode 100644 test/wpt/tests/fetch/stale-while-revalidate/revalidate-not-blocked-by-csp.html create mode 100644 test/wpt/tests/fetch/stale-while-revalidate/stale-css.html create mode 100644 test/wpt/tests/fetch/stale-while-revalidate/stale-image.html create mode 100644 test/wpt/tests/fetch/stale-while-revalidate/stale-script.html create mode 100644 test/wpt/tests/fetch/stale-while-revalidate/sw-intercept.js create mode 100644 test/wpt/tests/interfaces/ANGLE_instanced_arrays.idl create mode 100644 test/wpt/tests/interfaces/CSP.idl create mode 100644 test/wpt/tests/interfaces/DOM-Parsing.idl create mode 100644 test/wpt/tests/interfaces/EXT_blend_minmax.idl create mode 100644 test/wpt/tests/interfaces/EXT_color_buffer_float.idl create mode 100644 test/wpt/tests/interfaces/EXT_color_buffer_half_float.idl create mode 100644 test/wpt/tests/interfaces/EXT_disjoint_timer_query.idl create mode 100644 test/wpt/tests/interfaces/EXT_disjoint_timer_query_webgl2.idl create mode 100644 test/wpt/tests/interfaces/EXT_float_blend.idl create mode 100644 test/wpt/tests/interfaces/EXT_frag_depth.idl create mode 100644 test/wpt/tests/interfaces/EXT_sRGB.idl create mode 100644 test/wpt/tests/interfaces/EXT_shader_texture_lod.idl create mode 100644 test/wpt/tests/interfaces/EXT_texture_compression_bptc.idl create mode 100644 test/wpt/tests/interfaces/EXT_texture_compression_rgtc.idl create mode 100644 test/wpt/tests/interfaces/EXT_texture_filter_anisotropic.idl create mode 100644 test/wpt/tests/interfaces/EXT_texture_norm16.idl create mode 100644 test/wpt/tests/interfaces/FedCM.idl create mode 100644 test/wpt/tests/interfaces/FileAPI.idl create mode 100644 test/wpt/tests/interfaces/IndexedDB.idl create mode 100644 test/wpt/tests/interfaces/KHR_parallel_shader_compile.idl create mode 100644 test/wpt/tests/interfaces/META.yml create mode 100644 test/wpt/tests/interfaces/OES_draw_buffers_indexed.idl create mode 100644 test/wpt/tests/interfaces/OES_element_index_uint.idl create mode 100644 test/wpt/tests/interfaces/OES_fbo_render_mipmap.idl create mode 100644 test/wpt/tests/interfaces/OES_standard_derivatives.idl create mode 100644 test/wpt/tests/interfaces/OES_texture_float.idl create mode 100644 test/wpt/tests/interfaces/OES_texture_float_linear.idl create mode 100644 test/wpt/tests/interfaces/OES_texture_half_float.idl create mode 100644 test/wpt/tests/interfaces/OES_texture_half_float_linear.idl create mode 100644 test/wpt/tests/interfaces/OES_vertex_array_object.idl create mode 100644 test/wpt/tests/interfaces/OVR_multiview2.idl create mode 100644 test/wpt/tests/interfaces/README.md create mode 100644 test/wpt/tests/interfaces/SVG.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_blend_equation_advanced_coherent.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_clip_cull_distance.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_color_buffer_float.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_compressed_texture_astc.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_compressed_texture_etc.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_compressed_texture_etc1.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_compressed_texture_pvrtc.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_compressed_texture_s3tc.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_compressed_texture_s3tc_srgb.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_debug_renderer_info.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_debug_shaders.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_depth_texture.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_draw_buffers.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_draw_instanced_base_vertex_base_instance.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_lose_context.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_multi_draw.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_multi_draw_instanced_base_vertex_base_instance.idl create mode 100644 test/wpt/tests/interfaces/WEBGL_provoking_vertex.idl create mode 100644 test/wpt/tests/interfaces/WebCryptoAPI.idl create mode 100644 test/wpt/tests/interfaces/accelerometer.idl create mode 100644 test/wpt/tests/interfaces/ambient-light.idl create mode 100644 test/wpt/tests/interfaces/anchors.idl create mode 100644 test/wpt/tests/interfaces/attribution-reporting-api.idl create mode 100644 test/wpt/tests/interfaces/audio-output.idl create mode 100644 test/wpt/tests/interfaces/autoplay-detection.idl create mode 100644 test/wpt/tests/interfaces/background-fetch.idl create mode 100644 test/wpt/tests/interfaces/background-sync.idl create mode 100644 test/wpt/tests/interfaces/badging.idl create mode 100644 test/wpt/tests/interfaces/battery-status.idl create mode 100644 test/wpt/tests/interfaces/beacon.idl create mode 100644 test/wpt/tests/interfaces/capture-handle-identity.idl create mode 100644 test/wpt/tests/interfaces/captured-mouse-events.tentative.idl create mode 100644 test/wpt/tests/interfaces/clipboard-apis.idl create mode 100644 test/wpt/tests/interfaces/close-watcher.idl create mode 100644 test/wpt/tests/interfaces/compat.idl create mode 100644 test/wpt/tests/interfaces/compression.idl create mode 100644 test/wpt/tests/interfaces/compute-pressure.idl create mode 100644 test/wpt/tests/interfaces/console.idl create mode 100644 test/wpt/tests/interfaces/contact-picker.idl create mode 100644 test/wpt/tests/interfaces/content-index.idl create mode 100644 test/wpt/tests/interfaces/cookie-store.idl create mode 100644 test/wpt/tests/interfaces/credential-management.idl create mode 100644 test/wpt/tests/interfaces/csp-embedded-enforcement.idl create mode 100644 test/wpt/tests/interfaces/csp-next.idl create mode 100644 test/wpt/tests/interfaces/css-anchor-position.idl create mode 100644 test/wpt/tests/interfaces/css-animation-worklet.idl create mode 100644 test/wpt/tests/interfaces/css-animations-2.idl create mode 100644 test/wpt/tests/interfaces/css-animations.idl create mode 100644 test/wpt/tests/interfaces/css-cascade-6.idl create mode 100644 test/wpt/tests/interfaces/css-cascade.idl create mode 100644 test/wpt/tests/interfaces/css-color-5.idl create mode 100644 test/wpt/tests/interfaces/css-conditional.idl create mode 100644 test/wpt/tests/interfaces/css-contain-3.idl create mode 100644 test/wpt/tests/interfaces/css-contain.idl create mode 100644 test/wpt/tests/interfaces/css-counter-styles.idl create mode 100644 test/wpt/tests/interfaces/css-font-loading.idl create mode 100644 test/wpt/tests/interfaces/css-fonts.idl create mode 100644 test/wpt/tests/interfaces/css-highlight-api.idl create mode 100644 test/wpt/tests/interfaces/css-images-4.idl create mode 100644 test/wpt/tests/interfaces/css-layout-api.idl create mode 100644 test/wpt/tests/interfaces/css-masking.idl create mode 100644 test/wpt/tests/interfaces/css-nav.idl create mode 100644 test/wpt/tests/interfaces/css-nesting.idl create mode 100644 test/wpt/tests/interfaces/css-paint-api.idl create mode 100644 test/wpt/tests/interfaces/css-parser-api.idl create mode 100644 test/wpt/tests/interfaces/css-properties-values-api.idl create mode 100644 test/wpt/tests/interfaces/css-pseudo.idl create mode 100644 test/wpt/tests/interfaces/css-regions.idl create mode 100644 test/wpt/tests/interfaces/css-shadow-parts.idl create mode 100644 test/wpt/tests/interfaces/css-toggle.tentative.idl create mode 100644 test/wpt/tests/interfaces/css-transitions-2.idl create mode 100644 test/wpt/tests/interfaces/css-transitions.idl create mode 100644 test/wpt/tests/interfaces/css-typed-om.idl create mode 100644 test/wpt/tests/interfaces/css-view-transitions.idl create mode 100644 test/wpt/tests/interfaces/cssom-view.idl create mode 100644 test/wpt/tests/interfaces/cssom.idl create mode 100644 test/wpt/tests/interfaces/custom-state-pseudo-class.idl create mode 100644 test/wpt/tests/interfaces/datacue.idl create mode 100644 test/wpt/tests/interfaces/deprecation-reporting.idl create mode 100644 test/wpt/tests/interfaces/device-memory.idl create mode 100644 test/wpt/tests/interfaces/device-posture.idl create mode 100644 test/wpt/tests/interfaces/digital-goods.idl create mode 100644 test/wpt/tests/interfaces/document-picture-in-picture.idl create mode 100644 test/wpt/tests/interfaces/dom.idl create mode 100644 test/wpt/tests/interfaces/edit-context.idl create mode 100644 test/wpt/tests/interfaces/element-timing.idl create mode 100644 test/wpt/tests/interfaces/encoding.idl create mode 100644 test/wpt/tests/interfaces/encrypted-media.idl create mode 100644 test/wpt/tests/interfaces/entries-api.idl create mode 100644 test/wpt/tests/interfaces/event-timing.idl create mode 100644 test/wpt/tests/interfaces/eyedropper-api.idl create mode 100644 test/wpt/tests/interfaces/fenced-frame.idl create mode 100644 test/wpt/tests/interfaces/fetch.idl create mode 100644 test/wpt/tests/interfaces/fido.idl create mode 100644 test/wpt/tests/interfaces/file-system-access.idl create mode 100644 test/wpt/tests/interfaces/filter-effects.idl create mode 100644 test/wpt/tests/interfaces/font-metrics-api.idl create mode 100644 test/wpt/tests/interfaces/fs.idl create mode 100644 test/wpt/tests/interfaces/fullscreen.idl create mode 100644 test/wpt/tests/interfaces/gamepad-extensions.idl create mode 100644 test/wpt/tests/interfaces/gamepad.idl create mode 100644 test/wpt/tests/interfaces/generic-sensor.idl create mode 100644 test/wpt/tests/interfaces/geolocation-sensor.idl create mode 100644 test/wpt/tests/interfaces/geolocation.idl create mode 100644 test/wpt/tests/interfaces/geometry.idl create mode 100644 test/wpt/tests/interfaces/get-installed-related-apps.idl create mode 100644 test/wpt/tests/interfaces/gpc-spec.idl create mode 100644 test/wpt/tests/interfaces/gyroscope.idl create mode 100644 test/wpt/tests/interfaces/hr-time.idl create mode 100644 test/wpt/tests/interfaces/html-media-capture.idl create mode 100644 test/wpt/tests/interfaces/html.idl create mode 100644 test/wpt/tests/interfaces/idle-detection.idl create mode 100644 test/wpt/tests/interfaces/image-capture.idl create mode 100644 test/wpt/tests/interfaces/image-resource.idl create mode 100644 test/wpt/tests/interfaces/ink-enhancement.idl create mode 100644 test/wpt/tests/interfaces/input-device-capabilities.idl create mode 100644 test/wpt/tests/interfaces/input-events.idl create mode 100644 test/wpt/tests/interfaces/intersection-observer.idl create mode 100644 test/wpt/tests/interfaces/intervention-reporting.idl create mode 100644 test/wpt/tests/interfaces/is-input-pending.idl create mode 100644 test/wpt/tests/interfaces/js-self-profiling.idl create mode 100644 test/wpt/tests/interfaces/keyboard-lock.idl create mode 100644 test/wpt/tests/interfaces/keyboard-map.idl create mode 100644 test/wpt/tests/interfaces/largest-contentful-paint.idl create mode 100644 test/wpt/tests/interfaces/layout-instability.idl create mode 100644 test/wpt/tests/interfaces/local-font-access.idl create mode 100644 test/wpt/tests/interfaces/longtasks.idl create mode 100644 test/wpt/tests/interfaces/magnetometer.idl create mode 100644 test/wpt/tests/interfaces/manifest-incubations.idl create mode 100644 test/wpt/tests/interfaces/mathml-core.idl create mode 100644 test/wpt/tests/interfaces/media-capabilities.idl create mode 100644 test/wpt/tests/interfaces/media-playback-quality.idl create mode 100644 test/wpt/tests/interfaces/media-source.idl create mode 100644 test/wpt/tests/interfaces/mediacapture-automation.idl create mode 100644 test/wpt/tests/interfaces/mediacapture-fromelement.idl create mode 100644 test/wpt/tests/interfaces/mediacapture-handle-actions.idl create mode 100644 test/wpt/tests/interfaces/mediacapture-region.idl create mode 100644 test/wpt/tests/interfaces/mediacapture-streams.idl create mode 100644 test/wpt/tests/interfaces/mediacapture-transform.idl create mode 100644 test/wpt/tests/interfaces/mediacapture-viewport.idl create mode 100644 test/wpt/tests/interfaces/mediasession.idl create mode 100644 test/wpt/tests/interfaces/mediastream-recording.idl create mode 100644 test/wpt/tests/interfaces/model-element.idl create mode 100644 test/wpt/tests/interfaces/mst-content-hint.idl create mode 100644 test/wpt/tests/interfaces/navigation-timing.idl create mode 100644 test/wpt/tests/interfaces/netinfo.idl create mode 100644 test/wpt/tests/interfaces/notifications.idl create mode 100644 test/wpt/tests/interfaces/orientation-event.idl create mode 100644 test/wpt/tests/interfaces/orientation-sensor.idl create mode 100644 test/wpt/tests/interfaces/page-lifecycle.idl create mode 100644 test/wpt/tests/interfaces/paint-timing.idl create mode 100644 test/wpt/tests/interfaces/parakeet.tentative.idl create mode 100644 test/wpt/tests/interfaces/payment-handler.idl create mode 100644 test/wpt/tests/interfaces/payment-request.idl create mode 100644 test/wpt/tests/interfaces/performance-measure-memory.idl create mode 100644 test/wpt/tests/interfaces/performance-timeline.idl create mode 100644 test/wpt/tests/interfaces/periodic-background-sync.idl create mode 100644 test/wpt/tests/interfaces/permissions-policy.idl create mode 100644 test/wpt/tests/interfaces/permissions-request.idl create mode 100644 test/wpt/tests/interfaces/permissions-revoke.idl create mode 100644 test/wpt/tests/interfaces/permissions.idl create mode 100644 test/wpt/tests/interfaces/picture-in-picture.idl create mode 100644 test/wpt/tests/interfaces/pointerevents.idl create mode 100644 test/wpt/tests/interfaces/pointerlock.idl create mode 100644 test/wpt/tests/interfaces/portals.idl create mode 100644 test/wpt/tests/interfaces/prefer-current-tab.idl create mode 100644 test/wpt/tests/interfaces/prerendering-revamped.idl create mode 100644 test/wpt/tests/interfaces/presentation-api.idl create mode 100644 test/wpt/tests/interfaces/private-click-measurement.idl create mode 100644 test/wpt/tests/interfaces/proximity.idl create mode 100644 test/wpt/tests/interfaces/push-api.idl create mode 100644 test/wpt/tests/interfaces/raw-camera-access.idl create mode 100644 test/wpt/tests/interfaces/real-world-meshing.idl create mode 100644 test/wpt/tests/interfaces/referrer-policy.idl create mode 100644 test/wpt/tests/interfaces/remote-playback.idl create mode 100644 test/wpt/tests/interfaces/reporting.idl create mode 100644 test/wpt/tests/interfaces/requestStorageAccessFor.idl create mode 100644 test/wpt/tests/interfaces/requestidlecallback.idl create mode 100644 test/wpt/tests/interfaces/resize-observer.idl create mode 100644 test/wpt/tests/interfaces/resource-timing.idl create mode 100644 test/wpt/tests/interfaces/sanitizer-api.idl create mode 100644 test/wpt/tests/interfaces/sanitizer-api.tentative.idl create mode 100644 test/wpt/tests/interfaces/savedata.idl create mode 100644 test/wpt/tests/interfaces/scheduling-apis.idl create mode 100644 test/wpt/tests/interfaces/screen-capture.idl create mode 100644 test/wpt/tests/interfaces/screen-orientation.idl create mode 100644 test/wpt/tests/interfaces/screen-wake-lock.idl create mode 100644 test/wpt/tests/interfaces/scroll-animations.idl create mode 100644 test/wpt/tests/interfaces/scroll-to-text-fragment.idl create mode 100644 test/wpt/tests/interfaces/secure-payment-confirmation.idl create mode 100644 test/wpt/tests/interfaces/selection-api.idl create mode 100644 test/wpt/tests/interfaces/serial.idl create mode 100644 test/wpt/tests/interfaces/server-timing.idl create mode 100644 test/wpt/tests/interfaces/service-workers.idl create mode 100644 test/wpt/tests/interfaces/shape-detection-api.idl create mode 100644 test/wpt/tests/interfaces/shared-storage.idl create mode 100644 test/wpt/tests/interfaces/speech-api.idl create mode 100644 test/wpt/tests/interfaces/storage-access.idl create mode 100644 test/wpt/tests/interfaces/storage-buckets.idl create mode 100644 test/wpt/tests/interfaces/storage-buckets.tentative.idl create mode 100644 test/wpt/tests/interfaces/storage.idl create mode 100644 test/wpt/tests/interfaces/streams.idl create mode 100644 test/wpt/tests/interfaces/sub-apps.tentative.idl create mode 100644 test/wpt/tests/interfaces/svg-animations.idl create mode 100644 test/wpt/tests/interfaces/testutils.idl create mode 100644 test/wpt/tests/interfaces/text-detection-api.idl create mode 100644 test/wpt/tests/interfaces/touch-events.idl create mode 100644 test/wpt/tests/interfaces/trust-token-api.idl create mode 100644 test/wpt/tests/interfaces/trusted-types.idl create mode 100644 test/wpt/tests/interfaces/turtledove.idl create mode 100644 test/wpt/tests/interfaces/ua-client-hints.idl create mode 100644 test/wpt/tests/interfaces/uievents.idl create mode 100644 test/wpt/tests/interfaces/url.idl create mode 100644 test/wpt/tests/interfaces/urlpattern.idl create mode 100644 test/wpt/tests/interfaces/user-timing.idl create mode 100644 test/wpt/tests/interfaces/vibration.idl create mode 100644 test/wpt/tests/interfaces/video-rvfc.idl create mode 100644 test/wpt/tests/interfaces/virtual-keyboard.idl create mode 100644 test/wpt/tests/interfaces/virtual-keyboard.tentative.idl create mode 100644 test/wpt/tests/interfaces/wai-aria.idl create mode 100644 test/wpt/tests/interfaces/wasm-js-api.idl create mode 100644 test/wpt/tests/interfaces/wasm-web-api.idl create mode 100644 test/wpt/tests/interfaces/web-animations-2.idl create mode 100644 test/wpt/tests/interfaces/web-animations.idl create mode 100644 test/wpt/tests/interfaces/web-app-launch.idl create mode 100644 test/wpt/tests/interfaces/web-bluetooth.idl create mode 100644 test/wpt/tests/interfaces/web-locks.idl create mode 100644 test/wpt/tests/interfaces/web-nfc.idl create mode 100644 test/wpt/tests/interfaces/web-otp.idl create mode 100644 test/wpt/tests/interfaces/web-share.idl create mode 100644 test/wpt/tests/interfaces/webaudio.idl create mode 100644 test/wpt/tests/interfaces/webauthn.idl create mode 100644 test/wpt/tests/interfaces/webcodecs-aac-codec-registration.idl create mode 100644 test/wpt/tests/interfaces/webcodecs-av1-codec-registration.idl create mode 100644 test/wpt/tests/interfaces/webcodecs-avc-codec-registration.idl create mode 100644 test/wpt/tests/interfaces/webcodecs-flac-codec-registration.idl create mode 100644 test/wpt/tests/interfaces/webcodecs-hevc-codec-registration.idl create mode 100644 test/wpt/tests/interfaces/webcodecs-opus-codec-registration.idl create mode 100644 test/wpt/tests/interfaces/webcodecs-vp9-codec-registration.idl create mode 100644 test/wpt/tests/interfaces/webcodecs.idl create mode 100644 test/wpt/tests/interfaces/webcrypto-secure-curves.idl create mode 100644 test/wpt/tests/interfaces/webdriver.idl create mode 100644 test/wpt/tests/interfaces/webgl1.idl create mode 100644 test/wpt/tests/interfaces/webgl2.idl create mode 100644 test/wpt/tests/interfaces/webgpu.idl create mode 100644 test/wpt/tests/interfaces/webhid.idl create mode 100644 test/wpt/tests/interfaces/webidl.idl create mode 100644 test/wpt/tests/interfaces/webmidi.idl create mode 100644 test/wpt/tests/interfaces/webnn.idl create mode 100644 test/wpt/tests/interfaces/webrtc-encoded-transform.idl create mode 100644 test/wpt/tests/interfaces/webrtc-ice.idl create mode 100644 test/wpt/tests/interfaces/webrtc-identity.idl create mode 100644 test/wpt/tests/interfaces/webrtc-priority.idl create mode 100644 test/wpt/tests/interfaces/webrtc-stats.idl create mode 100644 test/wpt/tests/interfaces/webrtc-svc.idl create mode 100644 test/wpt/tests/interfaces/webrtc.idl create mode 100644 test/wpt/tests/interfaces/websockets.idl create mode 100644 test/wpt/tests/interfaces/webtransport.idl create mode 100644 test/wpt/tests/interfaces/webusb.idl create mode 100644 test/wpt/tests/interfaces/webvr.tentative.idl create mode 100644 test/wpt/tests/interfaces/webvtt.idl create mode 100644 test/wpt/tests/interfaces/webxr-ar-module.idl create mode 100644 test/wpt/tests/interfaces/webxr-depth-sensing.idl create mode 100644 test/wpt/tests/interfaces/webxr-dom-overlays.idl create mode 100644 test/wpt/tests/interfaces/webxr-gamepads-module.idl create mode 100644 test/wpt/tests/interfaces/webxr-hand-input.idl create mode 100644 test/wpt/tests/interfaces/webxr-hit-test.idl create mode 100644 test/wpt/tests/interfaces/webxr-lighting-estimation.idl create mode 100644 test/wpt/tests/interfaces/webxr.idl create mode 100644 test/wpt/tests/interfaces/webxrlayers.idl create mode 100644 test/wpt/tests/interfaces/window-controls-overlay.idl create mode 100644 test/wpt/tests/interfaces/window-management.idl create mode 100644 test/wpt/tests/interfaces/xhr.idl create mode 100644 test/wpt/tests/lint.ignore create mode 100644 test/wpt/tests/mimesniff/META.yml create mode 100644 test/wpt/tests/mimesniff/README.md create mode 100644 test/wpt/tests/mimesniff/media/media-sniff.window.js create mode 100644 test/wpt/tests/mimesniff/media/resources/flac.flac create mode 100644 test/wpt/tests/mimesniff/media/resources/make-vectors.sh create mode 100644 test/wpt/tests/mimesniff/media/resources/mp3-raw.mp3 create mode 100644 test/wpt/tests/mimesniff/media/resources/mp3-with-id3.mp3 create mode 100644 test/wpt/tests/mimesniff/media/resources/mp4.mp4 create mode 100644 test/wpt/tests/mimesniff/media/resources/ogg.ogg create mode 100644 test/wpt/tests/mimesniff/media/resources/wav.wav create mode 100644 test/wpt/tests/mimesniff/media/resources/webm.webm create mode 100644 test/wpt/tests/mimesniff/mime-types/README.md create mode 100644 test/wpt/tests/mimesniff/mime-types/charset-parameter.window.js create mode 100644 test/wpt/tests/mimesniff/mime-types/parsing.any.js create mode 100644 test/wpt/tests/mimesniff/mime-types/resources/generated-mime-types.json create mode 100644 test/wpt/tests/mimesniff/mime-types/resources/generated-mime-types.py create mode 100644 test/wpt/tests/mimesniff/mime-types/resources/mime-charset.py create mode 100644 test/wpt/tests/mimesniff/mime-types/resources/mime-groups.json create mode 100644 test/wpt/tests/mimesniff/mime-types/resources/mime-types.json create mode 100644 test/wpt/tests/resources/.htaccess create mode 100644 test/wpt/tests/resources/META.yml create mode 100644 test/wpt/tests/resources/SVGAnimationTestCase-testharness.js create mode 100644 test/wpt/tests/resources/accesskey.js create mode 100644 test/wpt/tests/resources/blank.html create mode 100644 test/wpt/tests/resources/channel.sub.js create mode 100644 test/wpt/tests/resources/check-layout-th.js create mode 100644 test/wpt/tests/resources/check-layout.js create mode 100644 test/wpt/tests/resources/chromium/README.md create mode 100644 test/wpt/tests/resources/chromium/contacts_manager_mock.js create mode 100644 test/wpt/tests/resources/chromium/content-index-helpers.js create mode 100644 test/wpt/tests/resources/chromium/enable-hyperlink-auditing.js create mode 100644 test/wpt/tests/resources/chromium/fake-hid.js create mode 100644 test/wpt/tests/resources/chromium/fake-serial.js create mode 100644 test/wpt/tests/resources/chromium/generic_sensor_mocks.js create mode 100644 test/wpt/tests/resources/chromium/generic_sensor_mocks.js.headers create mode 100644 test/wpt/tests/resources/chromium/mock-barcodedetection.js create mode 100644 test/wpt/tests/resources/chromium/mock-barcodedetection.js.headers create mode 100644 test/wpt/tests/resources/chromium/mock-battery-monitor.headers create mode 100644 test/wpt/tests/resources/chromium/mock-battery-monitor.js create mode 100644 test/wpt/tests/resources/chromium/mock-direct-sockets.js create mode 100644 test/wpt/tests/resources/chromium/mock-facedetection.js create mode 100644 test/wpt/tests/resources/chromium/mock-facedetection.js.headers create mode 100644 test/wpt/tests/resources/chromium/mock-idle-detection.js create mode 100644 test/wpt/tests/resources/chromium/mock-imagecapture.js create mode 100644 test/wpt/tests/resources/chromium/mock-managed-config.js create mode 100644 test/wpt/tests/resources/chromium/mock-pressure-service.js create mode 100644 test/wpt/tests/resources/chromium/mock-pressure-service.js.headers create mode 100644 test/wpt/tests/resources/chromium/mock-subapps.js create mode 100644 test/wpt/tests/resources/chromium/mock-textdetection.js create mode 100644 test/wpt/tests/resources/chromium/mock-textdetection.js.headers create mode 100644 test/wpt/tests/resources/chromium/nfc-mock.js create mode 100644 test/wpt/tests/resources/chromium/web-bluetooth-test.js create mode 100644 test/wpt/tests/resources/chromium/web-bluetooth-test.js.headers create mode 100644 test/wpt/tests/resources/chromium/webusb-child-test.js create mode 100644 test/wpt/tests/resources/chromium/webusb-child-test.js.headers create mode 100644 test/wpt/tests/resources/chromium/webusb-test.js create mode 100644 test/wpt/tests/resources/chromium/webusb-test.js.headers create mode 100644 test/wpt/tests/resources/chromium/webxr-test-math-helper.js create mode 100644 test/wpt/tests/resources/chromium/webxr-test-math-helper.js.headers create mode 100644 test/wpt/tests/resources/chromium/webxr-test.js create mode 100644 test/wpt/tests/resources/chromium/webxr-test.js.headers create mode 100644 test/wpt/tests/resources/declarative-shadow-dom-polyfill.js create mode 100644 test/wpt/tests/resources/idlharness-shadowrealm.js create mode 100644 test/wpt/tests/resources/idlharness.js create mode 100644 test/wpt/tests/resources/idlharness.js.headers create mode 100644 test/wpt/tests/resources/readme.md create mode 100644 test/wpt/tests/resources/sriharness.js create mode 100644 test/wpt/tests/resources/test-only-api.js create mode 100644 test/wpt/tests/resources/test-only-api.js.headers create mode 100644 test/wpt/tests/resources/test-only-api.m.js create mode 100644 test/wpt/tests/resources/test-only-api.m.js.headers create mode 100644 test/wpt/tests/resources/test/README.md create mode 100644 test/wpt/tests/resources/test/conftest.py create mode 100644 test/wpt/tests/resources/test/harness.html create mode 100644 test/wpt/tests/resources/test/idl-helper.js create mode 100644 test/wpt/tests/resources/test/nested-testharness.js create mode 100644 test/wpt/tests/resources/test/requirements.txt create mode 100644 test/wpt/tests/resources/test/tests/functional/abortsignal.html create mode 100644 test/wpt/tests/resources/test/tests/functional/add_cleanup.html create mode 100644 test/wpt/tests/resources/test/tests/functional/add_cleanup_async.html create mode 100644 test/wpt/tests/resources/test/tests/functional/add_cleanup_async_bad_return.html create mode 100644 test/wpt/tests/resources/test/tests/functional/add_cleanup_async_rejection.html create mode 100644 test/wpt/tests/resources/test/tests/functional/add_cleanup_async_rejection_after_load.html create mode 100644 test/wpt/tests/resources/test/tests/functional/add_cleanup_async_timeout.html create mode 100644 test/wpt/tests/resources/test/tests/functional/add_cleanup_bad_return.html create mode 100644 test/wpt/tests/resources/test/tests/functional/add_cleanup_count.html create mode 100644 test/wpt/tests/resources/test/tests/functional/add_cleanup_err.html create mode 100644 test/wpt/tests/resources/test/tests/functional/add_cleanup_err_multi.html create mode 100644 test/wpt/tests/resources/test/tests/functional/add_cleanup_sync_queue.html create mode 100644 test/wpt/tests/resources/test/tests/functional/api-tests-1.html create mode 100644 test/wpt/tests/resources/test/tests/functional/api-tests-2.html create mode 100644 test/wpt/tests/resources/test/tests/functional/api-tests-3.html create mode 100644 test/wpt/tests/resources/test/tests/functional/assert-array-equals.html create mode 100644 test/wpt/tests/resources/test/tests/functional/assert-throws-dom.html create mode 100644 test/wpt/tests/resources/test/tests/functional/force_timeout.html create mode 100644 test/wpt/tests/resources/test/tests/functional/generate-callback.html create mode 100644 test/wpt/tests/resources/test/tests/functional/idlharness/IdlDictionary/test_partial_interface_of.html create mode 100644 test/wpt/tests/resources/test/tests/functional/idlharness/IdlInterface/test_exposed_wildcard.html create mode 100644 test/wpt/tests/resources/test/tests/functional/idlharness/IdlInterface/test_immutable_prototype.html create mode 100644 test/wpt/tests/resources/test/tests/functional/idlharness/IdlInterface/test_interface_mixin.html create mode 100644 test/wpt/tests/resources/test/tests/functional/idlharness/IdlInterface/test_partial_interface_of.html create mode 100644 test/wpt/tests/resources/test/tests/functional/idlharness/IdlInterface/test_primary_interface_of.html create mode 100644 test/wpt/tests/resources/test/tests/functional/idlharness/IdlInterface/test_to_json_operation.html create mode 100644 test/wpt/tests/resources/test/tests/functional/idlharness/IdlNamespace/test_attribute.html create mode 100644 test/wpt/tests/resources/test/tests/functional/idlharness/IdlNamespace/test_operation.html create mode 100644 test/wpt/tests/resources/test/tests/functional/idlharness/IdlNamespace/test_partial_namespace.html create mode 100644 test/wpt/tests/resources/test/tests/functional/iframe-callback.html create mode 100644 test/wpt/tests/resources/test/tests/functional/iframe-consolidate-errors.html create mode 100644 test/wpt/tests/resources/test/tests/functional/iframe-consolidate-tests.html create mode 100644 test/wpt/tests/resources/test/tests/functional/iframe-msg.html create mode 100644 test/wpt/tests/resources/test/tests/functional/log-insertion.html create mode 100644 test/wpt/tests/resources/test/tests/functional/no-title.html create mode 100644 test/wpt/tests/resources/test/tests/functional/order.html create mode 100644 test/wpt/tests/resources/test/tests/functional/promise-async.html create mode 100644 test/wpt/tests/resources/test/tests/functional/promise-with-sync.html create mode 100644 test/wpt/tests/resources/test/tests/functional/promise.html create mode 100644 test/wpt/tests/resources/test/tests/functional/queue.html create mode 100644 test/wpt/tests/resources/test/tests/functional/setup-function-worker.js create mode 100644 test/wpt/tests/resources/test/tests/functional/setup-worker-service.html create mode 100644 test/wpt/tests/resources/test/tests/functional/single-page-test-fail.html create mode 100644 test/wpt/tests/resources/test/tests/functional/single-page-test-no-assertions.html create mode 100644 test/wpt/tests/resources/test/tests/functional/single-page-test-no-body.html create mode 100644 test/wpt/tests/resources/test/tests/functional/single-page-test-pass.html create mode 100644 test/wpt/tests/resources/test/tests/functional/step_wait.html create mode 100644 test/wpt/tests/resources/test/tests/functional/step_wait_func.html create mode 100644 test/wpt/tests/resources/test/tests/functional/task-scheduling-promise-test.html create mode 100644 test/wpt/tests/resources/test/tests/functional/task-scheduling-test.html create mode 100644 test/wpt/tests/resources/test/tests/functional/uncaught-exception-handle.html create mode 100644 test/wpt/tests/resources/test/tests/functional/uncaught-exception-ignore.html create mode 100644 test/wpt/tests/resources/test/tests/functional/worker-dedicated-uncaught-allow.html create mode 100644 test/wpt/tests/resources/test/tests/functional/worker-dedicated-uncaught-single.html create mode 100644 test/wpt/tests/resources/test/tests/functional/worker-dedicated.sub.html create mode 100644 test/wpt/tests/resources/test/tests/functional/worker-error.js create mode 100644 test/wpt/tests/resources/test/tests/functional/worker-service.html create mode 100644 test/wpt/tests/resources/test/tests/functional/worker-shared.html create mode 100644 test/wpt/tests/resources/test/tests/functional/worker-uncaught-allow.js create mode 100644 test/wpt/tests/resources/test/tests/functional/worker-uncaught-single.js create mode 100644 test/wpt/tests/resources/test/tests/functional/worker.js create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlArray/is_json_type.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlDictionary/get_reverse_inheritance_stack.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlDictionary/test_partial_dictionary.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterface/constructors.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterface/default_to_json_operation.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterface/do_member_unscopable_asserts.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterface/get_interface_object.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterface/get_interface_object_owner.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterface/get_legacy_namespace.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterface/get_qualified_name.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterface/get_reverse_inheritance_stack.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterface/has_default_to_json_regular_operation.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterface/has_to_json_regular_operation.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterface/should_have_interface_object.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterface/test_primary_interface_of_undefined.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterfaceMember/is_to_json_regular_operation.html create mode 100644 test/wpt/tests/resources/test/tests/unit/IdlInterfaceMember/toString.html create mode 100644 test/wpt/tests/resources/test/tests/unit/assert_implements.html create mode 100644 test/wpt/tests/resources/test/tests/unit/assert_implements_optional.html create mode 100644 test/wpt/tests/resources/test/tests/unit/assert_object_equals.html create mode 100644 test/wpt/tests/resources/test/tests/unit/async-test-return-restrictions.html create mode 100644 test/wpt/tests/resources/test/tests/unit/basic.html create mode 100644 test/wpt/tests/resources/test/tests/unit/exceptional-cases-timeouts.html create mode 100644 test/wpt/tests/resources/test/tests/unit/exceptional-cases.html create mode 100644 test/wpt/tests/resources/test/tests/unit/format-value.html create mode 100644 test/wpt/tests/resources/test/tests/unit/helpers.js create mode 100644 test/wpt/tests/resources/test/tests/unit/late-test.html create mode 100644 test/wpt/tests/resources/test/tests/unit/promise_setup-timeout.html create mode 100644 test/wpt/tests/resources/test/tests/unit/promise_setup.html create mode 100644 test/wpt/tests/resources/test/tests/unit/single_test.html create mode 100644 test/wpt/tests/resources/test/tests/unit/test-return-restrictions.html create mode 100644 test/wpt/tests/resources/test/tests/unit/throwing-assertions.html create mode 100644 test/wpt/tests/resources/test/tests/unit/unpaired-surrogates.html create mode 100644 test/wpt/tests/resources/test/tox.ini create mode 100644 test/wpt/tests/resources/test/wptserver.py create mode 100644 test/wpt/tests/resources/testdriver-actions.js create mode 100644 test/wpt/tests/resources/testdriver-vendor.js create mode 100644 test/wpt/tests/resources/testdriver-vendor.js.headers create mode 100644 test/wpt/tests/resources/testdriver.js create mode 100644 test/wpt/tests/resources/testdriver.js.headers create mode 100644 test/wpt/tests/resources/testharness.js create mode 100644 test/wpt/tests/resources/testharness.js.headers create mode 100644 test/wpt/tests/resources/testharnessreport.js create mode 100644 test/wpt/tests/resources/testharnessreport.js.headers create mode 100644 test/wpt/tests/resources/webidl2/build.sh create mode 100644 test/wpt/tests/resources/webidl2/lib/README.md create mode 100644 test/wpt/tests/resources/webidl2/lib/VERSION.md create mode 100644 test/wpt/tests/resources/webidl2/lib/webidl2.js create mode 100644 test/wpt/tests/resources/webidl2/lib/webidl2.js.headers create mode 100644 test/wpt/tests/service-workers/META.yml create mode 100644 test/wpt/tests/service-workers/cache-storage/META.yml create mode 100644 test/wpt/tests/service-workers/cache-storage/cache-abort.https.any.js create mode 100644 test/wpt/tests/service-workers/cache-storage/cache-add.https.any.js create mode 100644 test/wpt/tests/service-workers/cache-storage/cache-delete.https.any.js create mode 100644 test/wpt/tests/service-workers/cache-storage/cache-keys-attributes-for-service-worker.https.html create mode 100644 test/wpt/tests/service-workers/cache-storage/cache-keys.https.any.js create mode 100644 test/wpt/tests/service-workers/cache-storage/cache-match.https.any.js create mode 100644 test/wpt/tests/service-workers/cache-storage/cache-matchAll.https.any.js create mode 100644 test/wpt/tests/service-workers/cache-storage/cache-put.https.any.js create mode 100644 test/wpt/tests/service-workers/cache-storage/cache-storage-buckets.https.any.js create mode 100644 test/wpt/tests/service-workers/cache-storage/cache-storage-keys.https.any.js create mode 100644 test/wpt/tests/service-workers/cache-storage/cache-storage-match.https.any.js create mode 100644 test/wpt/tests/service-workers/cache-storage/cache-storage.https.any.js create mode 100644 test/wpt/tests/service-workers/cache-storage/common.https.window.js create mode 100644 test/wpt/tests/service-workers/cache-storage/crashtests/cache-response-clone.https.html create mode 100644 test/wpt/tests/service-workers/cache-storage/credentials.https.html create mode 100644 test/wpt/tests/service-workers/cache-storage/cross-partition.https.tentative.html create mode 100644 test/wpt/tests/service-workers/cache-storage/resources/blank.html create mode 100644 test/wpt/tests/service-workers/cache-storage/resources/cache-keys-attributes-for-service-worker.js create mode 100644 test/wpt/tests/service-workers/cache-storage/resources/common-worker.js create mode 100644 test/wpt/tests/service-workers/cache-storage/resources/credentials-iframe.html create mode 100644 test/wpt/tests/service-workers/cache-storage/resources/credentials-worker.js create mode 100644 test/wpt/tests/service-workers/cache-storage/resources/fetch-status.py create mode 100644 test/wpt/tests/service-workers/cache-storage/resources/iframe.html create mode 100644 test/wpt/tests/service-workers/cache-storage/resources/simple.txt create mode 100644 test/wpt/tests/service-workers/cache-storage/resources/test-helpers.js create mode 100644 test/wpt/tests/service-workers/cache-storage/resources/vary.py create mode 100644 test/wpt/tests/service-workers/cache-storage/sandboxed-iframes.https.html create mode 100644 test/wpt/tests/service-workers/idlharness.https.any.js create mode 100644 test/wpt/tests/service-workers/service-worker/Service-Worker-Allowed-header.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/close.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/extendable-message-event-constructor.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/extendable-message-event.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/fetch-on-the-right-interface.https.any.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/isSecureContext.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/isSecureContext.serviceworker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/postmessage.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/registration-attribute.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/close-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/error-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/extendable-message-event-constructor-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/extendable-message-event-loopback-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/extendable-message-event-ping-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/extendable-message-event-pong-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/extendable-message-event-utils.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/extendable-message-event-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/postmessage-loopback-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/postmessage-ping-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/postmessage-pong-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/registration-attribute-newer-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/registration-attribute-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/unregister-controlling-worker.html create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/unregister-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/update-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/resources/update-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/service-worker-error-event.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/unregister.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/ServiceWorkerGlobalScope/update.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/about-blank-replacement.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/activate-event-after-install-state-change.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/activation-after-registration.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/activation.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/active.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/claim-affect-other-registration.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/claim-fetch.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/claim-not-using-registration.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/claim-shared-worker-fetch.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/claim-using-registration.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/claim-with-redirect.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/claim-worker-fetch.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/client-id.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/client-navigate.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/client-url-of-blob-url-worker.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/clients-get-client-types.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/clients-get-cross-origin.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/clients-get-resultingClientId.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/clients-get.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/clients-matchall-blob-url-worker.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/clients-matchall-client-types.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/clients-matchall-exact-controller.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/clients-matchall-frozen.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/clients-matchall-include-uncontrolled.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/clients-matchall-on-evaluation.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/clients-matchall-order.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/clients-matchall.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/controlled-dedicatedworker-postMessage.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/controlled-iframe-postMessage.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/controller-on-disconnect.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/controller-on-load.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/controller-on-reload.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/controller-with-no-fetch-event-handler.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/credentials.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/data-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/data-transfer-files.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/dedicated-worker-service-worker-interception.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/detached-context.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/embed-and-object-are-not-intercepted.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/extendable-event-async-waituntil.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/extendable-event-waituntil.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-audio-tainting.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-canvas-tainting-double-write.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-canvas-tainting-image-cache.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-canvas-tainting-image.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-canvas-tainting-video-cache.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-canvas-tainting-video-with-range-request.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-canvas-tainting-video.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-cors-exposed-header-names.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-cors-xhr.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-csp.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-error.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-add-async.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-after-navigation-within-page.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-async-respond-with.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-handled.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-is-history-backward-navigation-manual.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-is-history-forward-navigation-manual.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-is-reload-iframe-navigation-manual.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-is-reload-navigation-manual.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-network-error.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-redirect.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-referrer-policy.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-respond-with-argument.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-respond-with-body-loaded-in-chunk.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-respond-with-custom-response.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-respond-with-partial-stream.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-respond-with-readable-stream-chunk.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-respond-with-readable-stream.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-respond-with-response-body-with-invalid-chunk.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-respond-with-stops-propagation.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-throws-after-respond-with.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-within-sw-manual.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event-within-sw.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event.https.h2.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-event.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-frame-resource.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-header-visibility.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-mixed-content-to-inscope.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-mixed-content-to-outscope.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-request-css-base-url.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-request-css-cross-origin.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-request-css-images.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-request-fallback.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-request-no-freshness-headers.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-request-redirect.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-request-resources.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-request-xhr-sync-error.https.window.js create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-request-xhr-sync-on-worker.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-request-xhr-sync.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-request-xhr.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-response-taint.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-response-xhr.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/fetch-waits-for-activate.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/getregistration.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/getregistrations.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/global-serviceworker.https.any.js create mode 100644 test/wpt/tests/service-workers/service-worker/historical.https.any.js create mode 100644 test/wpt/tests/service-workers/service-worker/http-to-https-redirect-and-register.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/immutable-prototype-serviceworker.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/import-scripts-cross-origin.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/import-scripts-data-url.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/import-scripts-mime-types.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/import-scripts-redirect.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/import-scripts-resource-map.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/import-scripts-updated-flag.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/indexeddb.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/install-event-type.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/installing.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/interface-requirements-sw.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/invalid-blobtype.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/invalid-header.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/iso-latin1-header.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/local-url-inherit-controller.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/mime-sniffing.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/multi-globals/current/current.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/multi-globals/current/test-sw.js create mode 100644 test/wpt/tests/service-workers/service-worker/multi-globals/incumbent/incumbent.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/multi-globals/incumbent/test-sw.js create mode 100644 test/wpt/tests/service-workers/service-worker/multi-globals/relevant/relevant.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/multi-globals/relevant/test-sw.js create mode 100644 test/wpt/tests/service-workers/service-worker/multi-globals/test-sw.js create mode 100644 test/wpt/tests/service-workers/service-worker/multi-globals/url-parsing.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/multipart-image.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/multiple-register.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/multiple-update.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigate-window.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-headers.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/broken-chunked-encoding.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/chunked-encoding.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/empty-preload-response-body.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/get-state.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/navigationPreload.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/redirect.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/request-headers.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resource-timing.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/broken-chunked-encoding-scope.asis create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/broken-chunked-encoding-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/chunked-encoding-scope.py create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/chunked-encoding-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/cookie.py create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/empty-preload-response-body-scope.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/empty-preload-response-body-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/get-state-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/helpers.js create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/navigation-preload-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/redirect-redirected.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/redirect-scope.py create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/redirect-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/request-headers-scope.py create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/request-headers-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/resource-timing-scope.py create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/resource-timing-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/samesite-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/samesite-sw-helper.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/samesite-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/resources/wait-for-activate-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/samesite-cookies.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-preload/samesite-iframe.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-redirect-body.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-redirect-resolution.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-redirect-to-http.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-redirect.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-sets-cookie.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-timing-extended.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/navigation-timing.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/nested-blob-url-workers.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/next-hop-protocol.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/no-dynamic-import-in-module.any.js create mode 100644 test/wpt/tests/service-workers/service-worker/no-dynamic-import.any.js create mode 100644 test/wpt/tests/service-workers/service-worker/onactivate-script-error.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/oninstall-script-error.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/opaque-response-preloaded.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/opaque-script.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/partitioned-claim.tentative.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/partitioned-cookies.tentative.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/partitioned-getRegistrations.tentative.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/partitioned-matchAll.tentative.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/partitioned.tentative.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/performance-timeline.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/postMessage-client-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/postmessage-blob-url.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/postmessage-from-waiting-serviceworker.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/postmessage-msgport-to-client.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/postmessage-to-client-message-queue.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/postmessage-to-client.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/postmessage.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/ready.https.window.js create mode 100644 test/wpt/tests/service-workers/service-worker/redirected-response.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/referer.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/referrer-policy-header.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/referrer-toplevel-script-fetch.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/register-closed-window.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/register-default-scope.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/register-same-scope-different-script-url.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/register-wait-forever-in-install-worker.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-basic.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-end-to-end.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-events.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-iframe.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-mime-types.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-schedule-job.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-scope-module-static-import.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-scope.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-script-module.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-script-url.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-script.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-security-error.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-service-worker-attributes.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/registration-updateviacache.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/rejections.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/request-end-to-end.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/resource-timing-bodySize.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/resource-timing-cross-origin.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/resource-timing-fetch-variants.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/resource-timing.sub.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/404.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/about-blank-replacement-blank-dynamic-nested-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/about-blank-replacement-blank-nested-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/about-blank-replacement-frame.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/about-blank-replacement-ping-frame.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/about-blank-replacement-popup-frame.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/about-blank-replacement-srcdoc-nested-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/about-blank-replacement-uncontrolled-nested-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/about-blank-replacement-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/basic-module-2.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/basic-module.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/blank.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/bytecheck-worker-imported-script.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/bytecheck-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/claim-blob-url-worker-fetch-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/claim-nested-worker-fetch-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/claim-nested-worker-fetch-parent-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/claim-shared-worker-fetch-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/claim-shared-worker-fetch-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/claim-with-redirect-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/claim-worker-fetch-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/claim-worker-fetch-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/claim-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/classic-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/client-id-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/client-navigate-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/client-navigate-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/client-navigated-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/client-url-of-blob-url-worker.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/client-url-of-blob-url-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-frame-freeze.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-get-client-types-frame-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-get-client-types-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-get-client-types-shared-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-get-client-types-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-get-cross-origin-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-get-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-get-other-origin.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-get-resultingClientId-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-get-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-matchall-blob-url-worker.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-matchall-client-types-dedicated-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-matchall-client-types-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-matchall-client-types-shared-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-matchall-on-evaluation-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/clients-matchall-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/controlled-frame-postMessage.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/controlled-worker-late-postMessage.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/controlled-worker-postMessage.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/cors-approved.txt create mode 100644 test/wpt/tests/service-workers/service-worker/resources/cors-approved.txt.headers create mode 100644 test/wpt/tests/service-workers/service-worker/resources/cors-denied.txt create mode 100644 test/wpt/tests/service-workers/service-worker/resources/create-blob-url-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/create-out-of-scope-worker.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/echo-content.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/echo-cookie-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/echo-message-to-source-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/embed-and-object-are-not-intercepted-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/embed-image-is-not-intercepted-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/embed-is-not-intercepted-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/embed-navigation-is-not-intercepted-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/embedded-content-from-server.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/embedded-content-from-service-worker.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/empty-but-slow-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/empty-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/empty.h2.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/empty.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/empty.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/enable-client-message-queue.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/end-to-end-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/events-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/extendable-event-async-waituntil.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/extendable-event-waituntil.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fail-on-fetch-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-access-control-login.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-access-control.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-canvas-tainting-double-write-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-canvas-tainting-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-canvas-tainting-tests.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-cors-exposed-header-names-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-cors-xhr-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-csp-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-csp-iframe.html.sub.headers create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-error-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-add-async-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-after-navigation-within-page-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-async-respond-with-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-handled-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-network-error-controllee-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-network-error-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-network-fallback-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-respond-with-argument-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-respond-with-argument-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-respond-with-body-loaded-in-chunk-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-respond-with-custom-response-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-respond-with-partial-stream-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-respond-with-readable-stream-chunk-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-respond-with-readable-stream-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-respond-with-response-body-with-invalid-chunk-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-respond-with-response-body-with-invalid-chunk-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-respond-with-stops-propagation-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-test-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-event-within-sw-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-header-visibility-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-mixed-content-iframe-inscope-to-inscope.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-mixed-content-iframe-inscope-to-outscope.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-mixed-content-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-css-base-url-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-css-base-url-style.css create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-css-base-url-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-cross.css create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-cross.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-same.css create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-css-cross-origin-mime-check-same.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-css-cross-origin-read-contents.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-css-cross-origin-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-fallback-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-fallback-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-html-imports-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-html-imports-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-no-freshness-headers-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-no-freshness-headers-script.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-no-freshness-headers-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-redirect-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-resources-iframe.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-resources-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-xhr-iframe.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-xhr-sync-error-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-xhr-sync-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-xhr-sync-on-worker-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-xhr-sync-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-request-xhr-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-response-taint-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-response-xhr-iframe.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-response-xhr-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-response.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-response.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-rewrite-worker-referrer-policy.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-rewrite-worker-referrer-policy.js.headers create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-rewrite-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-rewrite-worker.js.headers create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-variants-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/fetch-waits-for-activate-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/form-poster.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/frame-for-getregistrations.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/get-resultingClientId-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/http-to-https-redirect-and-register-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/iframe-with-fetch-variants.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/iframe-with-image.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/immutable-prototype-serviceworker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-echo-cookie-worker-module.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-echo-cookie-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-mime-type-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-relative.xsl create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-404-after-update-plus-update-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-404-after-update.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-404.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-cross-origin-worker.sub.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-data-url-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-diff-resource-map-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-echo.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-get.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-mime-types-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-redirect-import.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-redirect-on-second-time-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-redirect-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-resource-map-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-updated-flag-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/import-scripts-version.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/imported-classic-script.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/imported-module-script.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/indexeddb-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/install-event-type-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/install-worker.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/interface-requirements-worker.sub.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/invalid-blobtype-iframe.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/invalid-blobtype-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/invalid-chunked-encoding-with-flush.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/invalid-chunked-encoding.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/invalid-header-iframe.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/invalid-header-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/iso-latin1-header-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/iso-latin1-header-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/load_worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/loaded.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/local-url-inherit-controller-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/local-url-inherit-controller-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/location-setter.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/malformed-http-response.asis create mode 100644 test/wpt/tests/service-workers/service-worker/resources/malformed-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/message-vs-microtask.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/mime-sniffing-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/mime-type-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/mint-new-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/missing.asis create mode 100644 test/wpt/tests/service-workers/service-worker/resources/module-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/multipart-image-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/multipart-image-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/multipart-image.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/navigate-window-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/navigation-headers-server.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/navigation-redirect-body-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/navigation-redirect-body.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/navigation-redirect-other-origin.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/navigation-redirect-out-scope.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/navigation-redirect-scope1.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/navigation-redirect-scope2.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/navigation-redirect-to-http-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/navigation-redirect-to-http-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/navigation-timing-worker-extended.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/navigation-timing-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/nested-blob-url-worker-created-from-worker.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/nested-blob-url-workers.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/nested-iframe-parent.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/nested-parent.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/nested-worker-created-from-blob-url-worker.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/nested_load_worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/no-dynamic-import.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/notification_icon.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/object-image-is-not-intercepted-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/object-is-not-intercepted-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/object-navigation-is-not-intercepted-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/onactivate-throw-error-from-nested-event-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/onactivate-throw-error-then-cancel-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/onactivate-throw-error-then-prevent-default-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/onactivate-throw-error-with-empty-onerror-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/onactivate-throw-error-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/onactivate-waituntil-forever.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/onfetch-waituntil-forever.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/oninstall-throw-error-from-nested-event-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/oninstall-throw-error-then-cancel-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/oninstall-throw-error-then-prevent-default-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/oninstall-throw-error-with-empty-onerror-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/oninstall-throw-error-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/oninstall-waituntil-forever.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/oninstall-waituntil-throw-error-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/onparse-infiniteloop-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/opaque-response-being-preloaded-xhr.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/opaque-response-preloaded-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/opaque-response-preloaded-xhr.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/opaque-script-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/opaque-script-large.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/opaque-script-small.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/opaque-script-sw.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/other.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/override_assert_object_equals.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-cookies-3p-credentialless-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-cookies-3p-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-cookies-3p-sw.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-cookies-3p-window.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-cookies-sw.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-service-worker-iframe-claim.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-service-worker-nested-iframe-child.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-service-worker-nested-iframe-parent.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-service-worker-third-party-iframe-getRegistrations.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-service-worker-third-party-iframe-matchAll.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-service-worker-third-party-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-service-worker-third-party-window.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-storage-sw.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/partitioned-utils.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/pass-through-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/pass.txt create mode 100644 test/wpt/tests/service-workers/service-worker/resources/performance-timeline-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/postmessage-blob-url.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/postmessage-dictionary-transferables-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/postmessage-echo-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/postmessage-fetched-text.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/postmessage-msgport-to-client-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/postmessage-on-load-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/postmessage-to-client-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/postmessage-transferables-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/postmessage-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/range-request-to-different-origins-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/range-request-with-different-cors-modes-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/redirect-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/redirect.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/referer-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/referrer-policy-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/register-closed-window-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/register-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/register-rewrite-worker.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/registration-tests-mime-types.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/registration-tests-scope.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/registration-tests-script-url.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/registration-tests-script.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/registration-tests-security-error.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/registration-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/reject-install-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/reply-to-message.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/request-end-to-end-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/request-headers.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/resource-timing-iframe.sub.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/resource-timing-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/respond-then-throw-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/respond-with-body-accessed-response-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/respond-with-body-accessed-response-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/respond-with-body-accessed-response.jsonp create mode 100644 test/wpt/tests/service-workers/service-worker/resources/sample-worker-interceptor.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/sample.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/sample.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/sample.txt create mode 100644 test/wpt/tests/service-workers/service-worker/resources/sandboxed-iframe-fetch-event-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/sandboxed-iframe-fetch-event-iframe.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/sandboxed-iframe-fetch-event-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/sandboxed-iframe-navigator-serviceworker-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/scope1/module-worker-importing-redirect-to-scope2.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/scope1/module-worker-importing-scope2.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/scope1/redirect.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/scope2/import-scripts-echo.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/scope2/imported-module-script.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/scope2/simple.txt create mode 100644 test/wpt/tests/service-workers/service-worker/resources/scope2/worker_interception_redirect_webworker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/secure-context-service-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/secure-context/sender.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/secure-context/window.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/service-worker-csp-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/service-worker-header.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/service-worker-interception-dynamic-import-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/service-worker-interception-network-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/service-worker-interception-service-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/service-worker-interception-static-import-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/silence.oga create mode 100644 test/wpt/tests/service-workers/service-worker/resources/simple-intercept-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/simple-intercept-worker.js.headers create mode 100644 test/wpt/tests/service-workers/service-worker/resources/simple.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/simple.txt create mode 100644 test/wpt/tests/service-workers/service-worker/resources/skip-waiting-installed-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/skip-waiting-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/square.png create mode 100644 test/wpt/tests/service-workers/service-worker/resources/square.png.sub.headers create mode 100644 test/wpt/tests/service-workers/service-worker/resources/stalling-service-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/subdir/blank.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/subdir/import-scripts-echo.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/subdir/simple.txt create mode 100644 test/wpt/tests/service-workers/service-worker/resources/subdir/worker_interception_redirect_webworker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/success.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/svg-target-reftest-001-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/svg-target-reftest-001.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/svg-target-reftest-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/test-helpers.sub.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/test-request-headers-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/test-request-headers-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/test-request-mode-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/test-request-mode-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/testharness-helpers.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/trickle.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/type-check-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/unregister-controller-page.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/unregister-immediately-helpers.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/unregister-rewrite-worker.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-claim-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-during-installation-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-during-installation-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-fetch-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-max-aged-worker-imported-script.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-max-aged-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-missing-import-scripts-imported-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-missing-import-scripts-main-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-nocookie-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-recovery-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-registration-with-type.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-smaller-body-after-update-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-smaller-body-before-update-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-worker-from-file.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update-worker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update/update-after-oneday.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/update_shell.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/vtt-frame.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/wait-forever-in-install-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/websocket-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/websocket.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/window-opener.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/windowclient-navigate-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/worker-client-id-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/worker-fetching-cross-origin.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/worker-interception-redirect-serviceworker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/worker-interception-redirect-webworker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/worker-load-interceptor.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/worker-testharness.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/worker_interception_redirect_webworker.py create mode 100644 test/wpt/tests/service-workers/service-worker/resources/xhr-content-length-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/xhr-iframe.html create mode 100644 test/wpt/tests/service-workers/service-worker/resources/xhr-response-url-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/xsl-base-url-iframe.xml create mode 100644 test/wpt/tests/service-workers/service-worker/resources/xsl-base-url-worker.js create mode 100644 test/wpt/tests/service-workers/service-worker/resources/xslt-pass.xsl create mode 100644 test/wpt/tests/service-workers/service-worker/respond-with-body-accessed-response.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/same-site-cookies.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/sandboxed-iframe-fetch-event.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/sandboxed-iframe-navigator-serviceworker.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/secure-context.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/service-worker-csp-connect.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/service-worker-csp-default.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/service-worker-csp-script.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/service-worker-header.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/serviceworker-message-event-historical.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/serviceworkerobject-scripturl.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/skip-waiting-installed.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/skip-waiting-using-registration.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/skip-waiting-without-client.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/skip-waiting-without-using-registration.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/skip-waiting.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/state.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/svg-target-reftest.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/synced-state.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/tentative/static-router/README.md create mode 100644 test/wpt/tests/service-workers/service-worker/tentative/static-router/resources/direct.txt create mode 100644 test/wpt/tests/service-workers/service-worker/tentative/static-router/resources/simple-test-for-condition-main-resource.html create mode 100644 test/wpt/tests/service-workers/service-worker/tentative/static-router/resources/simple.html create mode 100644 test/wpt/tests/service-workers/service-worker/tentative/static-router/resources/static-router-sw.js create mode 100644 test/wpt/tests/service-workers/service-worker/tentative/static-router/resources/test-helpers.sub.js create mode 100644 test/wpt/tests/service-workers/service-worker/tentative/static-router/static-router-main-resource.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/tentative/static-router/static-router-subresource.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/uncontrolled-page.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/unregister-controller.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/unregister-immediately-before-installed.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/unregister-immediately-during-extendable-events.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/unregister-immediately.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/unregister-then-register-new-script.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/unregister-then-register.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/unregister.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-after-navigation-fetch-event.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-after-navigation-redirect.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-after-oneday.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-bytecheck-cors-import.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-bytecheck.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-import-scripts.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-missing-import-scripts.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-module-request-mode.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-no-cache-request-headers.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-not-allowed.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-on-navigation.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-recovery.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-registration-with-type.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update-result.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/update.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/waiting.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/websocket-in-service-worker.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/websocket.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/webvtt-cross-origin.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/windowclient-navigate.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/worker-client-id.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/worker-in-sandboxed-iframe-by-csp-fetch-event.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/worker-interception-redirect.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/worker-interception.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/xhr-content-length.https.window.js create mode 100644 test/wpt/tests/service-workers/service-worker/xhr-response-url.https.html create mode 100644 test/wpt/tests/service-workers/service-worker/xsl-base-url.https.html create mode 100644 test/wpt/tests/storage/META.yml create mode 100644 test/wpt/tests/storage/README.md create mode 100644 test/wpt/tests/storage/buckets/META.yml create mode 100644 test/wpt/tests/storage/buckets/bucket-quota-indexeddb.tentative.https.any.js create mode 100644 test/wpt/tests/storage/buckets/bucket-storage-policy.tentative.https.any.js create mode 100644 test/wpt/tests/storage/buckets/resources/cached-resource.txt create mode 100644 test/wpt/tests/storage/buckets/resources/util.js create mode 100644 test/wpt/tests/storage/estimate-indexeddb.https.any.js create mode 100644 test/wpt/tests/storage/estimate-parallel.https.any.js create mode 100644 test/wpt/tests/storage/estimate-usage-details-caches.https.tentative.any.js create mode 100644 test/wpt/tests/storage/estimate-usage-details-indexeddb.https.tentative.any.js create mode 100644 test/wpt/tests/storage/estimate-usage-details-service-workers.https.tentative.window.js create mode 100644 test/wpt/tests/storage/estimate-usage-details.https.tentative.any.js create mode 100644 test/wpt/tests/storage/helpers.js create mode 100644 test/wpt/tests/storage/idlharness.https.any.js create mode 100644 test/wpt/tests/storage/opaque-origin.https.window.js create mode 100644 test/wpt/tests/storage/partitioned-estimate-usage-details-caches.tentative.https.sub.html create mode 100644 test/wpt/tests/storage/partitioned-estimate-usage-details-indexeddb.tentative.https.sub.html create mode 100644 test/wpt/tests/storage/partitioned-estimate-usage-details-service-workers.tentative.https.sub.html create mode 100644 test/wpt/tests/storage/permission-query.https.any.js create mode 100644 test/wpt/tests/storage/persist-permission-manual.https.html create mode 100644 test/wpt/tests/storage/persisted.https.any.js create mode 100644 test/wpt/tests/storage/quotachange-in-detached-iframe.tentative.https.html create mode 100644 test/wpt/tests/storage/resources/partitioned-estimate-usage-details-caches-helper-frame.html create mode 100644 test/wpt/tests/storage/resources/partitioned-estimate-usage-details-indexeddb-helper-frame.html create mode 100644 test/wpt/tests/storage/resources/partitioned-estimate-usage-details-service-workers-helper-frame.html create mode 100644 test/wpt/tests/storage/resources/worker.js create mode 100644 test/wpt/tests/storage/storagemanager-estimate.https.any.js create mode 100644 test/wpt/tests/storage/storagemanager-persist-persisted-match.https.any.js create mode 100644 test/wpt/tests/storage/storagemanager-persist.https.window.js create mode 100644 test/wpt/tests/storage/storagemanager-persist.https.worker.js create mode 100644 test/wpt/tests/storage/storagemanager-persisted.https.any.js create mode 100644 test/wpt/tests/websockets/Close-1000-reason.any.js create mode 100644 test/wpt/tests/websockets/Close-1000-verify-code.any.js create mode 100644 test/wpt/tests/websockets/Close-1000.any.js create mode 100644 test/wpt/tests/websockets/Close-1005-verify-code.any.js create mode 100644 test/wpt/tests/websockets/Close-1005.any.js create mode 100644 test/wpt/tests/websockets/Close-2999-reason.any.js create mode 100644 test/wpt/tests/websockets/Close-3000-reason.any.js create mode 100644 test/wpt/tests/websockets/Close-3000-verify-code.any.js create mode 100644 test/wpt/tests/websockets/Close-4999-reason.any.js create mode 100644 test/wpt/tests/websockets/Close-Reason-124Bytes.any.js create mode 100644 test/wpt/tests/websockets/Close-delayed.any.js create mode 100644 test/wpt/tests/websockets/Close-onlyReason.any.js create mode 100644 test/wpt/tests/websockets/Close-readyState-Closed.any.js create mode 100644 test/wpt/tests/websockets/Close-readyState-Closing.any.js create mode 100644 test/wpt/tests/websockets/Close-reason-unpaired-surrogates.any.js create mode 100644 test/wpt/tests/websockets/Close-server-initiated-close.any.js create mode 100644 test/wpt/tests/websockets/Close-undefined.any.js create mode 100644 test/wpt/tests/websockets/Create-asciiSep-protocol-string.any.js create mode 100644 test/wpt/tests/websockets/Create-blocked-port.any.js create mode 100644 test/wpt/tests/websockets/Create-extensions-empty.any.js create mode 100644 test/wpt/tests/websockets/Create-http-urls.any.js create mode 100644 test/wpt/tests/websockets/Create-invalid-urls.any.js create mode 100644 test/wpt/tests/websockets/Create-non-absolute-url.any.js create mode 100644 test/wpt/tests/websockets/Create-nonAscii-protocol-string.any.js create mode 100644 test/wpt/tests/websockets/Create-on-worker-shutdown.any.js create mode 100644 test/wpt/tests/websockets/Create-protocol-with-space.any.js create mode 100644 test/wpt/tests/websockets/Create-protocols-repeated-case-insensitive.any.js create mode 100644 test/wpt/tests/websockets/Create-protocols-repeated.any.js create mode 100644 test/wpt/tests/websockets/Create-url-with-space.any.js create mode 100644 test/wpt/tests/websockets/Create-url-with-windows-1252-encoding.html create mode 100644 test/wpt/tests/websockets/Create-valid-url-array-protocols.any.js create mode 100644 test/wpt/tests/websockets/Create-valid-url-binaryType-blob.any.js create mode 100644 test/wpt/tests/websockets/Create-valid-url-protocol-empty.any.js create mode 100644 test/wpt/tests/websockets/Create-valid-url-protocol-setCorrectly.any.js create mode 100644 test/wpt/tests/websockets/Create-valid-url-protocol-string.any.js create mode 100644 test/wpt/tests/websockets/Create-valid-url-protocol.any.js create mode 100644 test/wpt/tests/websockets/Create-valid-url.any.js create mode 100644 test/wpt/tests/websockets/META.yml create mode 100644 test/wpt/tests/websockets/README.md create mode 100644 test/wpt/tests/websockets/Send-0byte-data.any.js create mode 100644 test/wpt/tests/websockets/Send-65K-data.any.js create mode 100644 test/wpt/tests/websockets/Send-before-open.any.js create mode 100644 test/wpt/tests/websockets/Send-binary-65K-arraybuffer.any.js create mode 100644 test/wpt/tests/websockets/Send-binary-arraybuffer.any.js create mode 100644 test/wpt/tests/websockets/Send-binary-arraybufferview-float32.any.js create mode 100644 test/wpt/tests/websockets/Send-binary-arraybufferview-float64.any.js create mode 100644 test/wpt/tests/websockets/Send-binary-arraybufferview-int16-offset.any.js create mode 100644 test/wpt/tests/websockets/Send-binary-arraybufferview-int32.any.js create mode 100644 test/wpt/tests/websockets/Send-binary-arraybufferview-int8.any.js create mode 100644 test/wpt/tests/websockets/Send-binary-arraybufferview-uint16-offset-length.any.js create mode 100644 test/wpt/tests/websockets/Send-binary-arraybufferview-uint32-offset.any.js create mode 100644 test/wpt/tests/websockets/Send-binary-arraybufferview-uint8-offset-length.any.js create mode 100644 test/wpt/tests/websockets/Send-binary-arraybufferview-uint8-offset.any.js create mode 100644 test/wpt/tests/websockets/Send-binary-blob.any.js create mode 100644 test/wpt/tests/websockets/Send-data.any.js create mode 100644 test/wpt/tests/websockets/Send-data.worker.js create mode 100644 test/wpt/tests/websockets/Send-null.any.js create mode 100644 test/wpt/tests/websockets/Send-paired-surrogates.any.js create mode 100644 test/wpt/tests/websockets/Send-unicode-data.any.js create mode 100644 test/wpt/tests/websockets/Send-unpaired-surrogates.any.js create mode 100644 test/wpt/tests/websockets/back-forward-cache-with-closed-websocket-connection-ccns.tentative.window.js create mode 100644 test/wpt/tests/websockets/back-forward-cache-with-closed-websocket-connection.window.js create mode 100644 test/wpt/tests/websockets/back-forward-cache-with-open-websocket-connection-ccns.tentative.window.js create mode 100644 test/wpt/tests/websockets/back-forward-cache-with-open-websocket-connection.window.js create mode 100644 test/wpt/tests/websockets/basic-auth.any.js create mode 100644 test/wpt/tests/websockets/binary/001.html create mode 100644 test/wpt/tests/websockets/binary/002.html create mode 100644 test/wpt/tests/websockets/binary/004.html create mode 100644 test/wpt/tests/websockets/binary/005.html create mode 100644 test/wpt/tests/websockets/binaryType-wrong-value.any.js create mode 100644 test/wpt/tests/websockets/bufferedAmount-unchanged-by-sync-xhr.any.js create mode 100644 test/wpt/tests/websockets/close-invalid.any.js create mode 100644 test/wpt/tests/websockets/closing-handshake/002.html create mode 100644 test/wpt/tests/websockets/closing-handshake/003.html create mode 100644 test/wpt/tests/websockets/closing-handshake/004.html create mode 100644 test/wpt/tests/websockets/constants.sub.js create mode 100644 test/wpt/tests/websockets/constructor.any.js create mode 100644 test/wpt/tests/websockets/constructor/001.html create mode 100644 test/wpt/tests/websockets/constructor/004.html create mode 100644 test/wpt/tests/websockets/constructor/005.html create mode 100644 test/wpt/tests/websockets/constructor/006.html create mode 100644 test/wpt/tests/websockets/constructor/007.html create mode 100644 test/wpt/tests/websockets/constructor/008.html create mode 100644 test/wpt/tests/websockets/constructor/009.html create mode 100644 test/wpt/tests/websockets/constructor/010.html create mode 100644 test/wpt/tests/websockets/constructor/011.html create mode 100644 test/wpt/tests/websockets/constructor/012.html create mode 100644 test/wpt/tests/websockets/constructor/013.html create mode 100644 test/wpt/tests/websockets/constructor/014.html create mode 100644 test/wpt/tests/websockets/constructor/016.html create mode 100644 test/wpt/tests/websockets/constructor/017.html create mode 100644 test/wpt/tests/websockets/constructor/018.html create mode 100644 test/wpt/tests/websockets/constructor/019.html create mode 100644 test/wpt/tests/websockets/constructor/020.html create mode 100644 test/wpt/tests/websockets/constructor/021.html create mode 100644 test/wpt/tests/websockets/constructor/022.html create mode 100644 test/wpt/tests/websockets/cookies/001.html create mode 100644 test/wpt/tests/websockets/cookies/002.html create mode 100644 test/wpt/tests/websockets/cookies/003.html create mode 100644 test/wpt/tests/websockets/cookies/004.html create mode 100644 test/wpt/tests/websockets/cookies/005.html create mode 100644 test/wpt/tests/websockets/cookies/006.html create mode 100644 test/wpt/tests/websockets/cookies/007.html create mode 100644 test/wpt/tests/websockets/cookies/support/set-cookie.py create mode 100644 test/wpt/tests/websockets/cookies/support/websocket-cookies-helper.sub.js create mode 100644 test/wpt/tests/websockets/cookies/third-party-cookie-accepted.https.html create mode 100644 test/wpt/tests/websockets/eventhandlers.any.js create mode 100644 test/wpt/tests/websockets/extended-payload-length.html create mode 100644 test/wpt/tests/websockets/handlers/basic_auth_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/delayed-passive-close_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/echo-cookie_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/echo-query_v13_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/echo-query_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/echo_close_data_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/echo_exit_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/echo_raw_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/echo_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/empty-message_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/handshake_no_extensions_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/handshake_no_protocol_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/handshake_protocol_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/handshake_sleep_2_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/invalid_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/msg_channel_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/origin_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/protocol_array_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/protocol_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/receive-backpressure_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/receive-many-with-backpressure_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/referrer_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/send-backpressure_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/set-cookie-secure_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/set-cookie_http_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/set-cookie_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/set-cookies-samesite_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/simple_handshake_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/sleep_10_v13_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/stash_responder_blocking_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/stash_responder_wsh.py create mode 100644 test/wpt/tests/websockets/handlers/wrong_accept_key_wsh.py create mode 100644 test/wpt/tests/websockets/idlharness.any.js create mode 100644 test/wpt/tests/websockets/interfaces/CloseEvent/clean-close.html create mode 100644 test/wpt/tests/websockets/interfaces/CloseEvent/constructor.html create mode 100644 test/wpt/tests/websockets/interfaces/CloseEvent/historical.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/bufferedAmount/bufferedAmount-arraybuffer.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/bufferedAmount/bufferedAmount-blob.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/bufferedAmount/bufferedAmount-defineProperty-getter.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/bufferedAmount/bufferedAmount-defineProperty-setter.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/bufferedAmount/bufferedAmount-deleting.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/bufferedAmount/bufferedAmount-getting.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/bufferedAmount/bufferedAmount-initial.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/bufferedAmount/bufferedAmount-large.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/bufferedAmount/bufferedAmount-readonly.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/bufferedAmount/bufferedAmount-unicode.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/close/close-basic.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/close/close-connecting.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/close/close-multiple.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/close/close-nested.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/close/close-replace.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/close/close-return.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/constants/001.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/constants/002.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/constants/003.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/constants/004.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/constants/005.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/constants/006.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/001.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/002.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/003.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/004.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/006.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/007.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/008.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/009.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/010.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/011.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/012.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/013.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/014.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/015.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/016.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/017.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/018.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/019.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/events/020.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/extensions/001.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/protocol/protocol-initial.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/readyState/001.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/readyState/002.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/readyState/003.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/readyState/004.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/readyState/005.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/readyState/006.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/readyState/007.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/readyState/008.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/send/001.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/send/002.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/send/003.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/send/004.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/send/005.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/send/006.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/send/007.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/send/008.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/send/009.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/send/010.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/send/011.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/send/012.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/url/001.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/url/002.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/url/003.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/url/004.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/url/005.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/url/006.html create mode 100644 test/wpt/tests/websockets/interfaces/WebSocket/url/resolve.html create mode 100644 test/wpt/tests/websockets/keeping-connection-open/001.html create mode 100644 test/wpt/tests/websockets/mixed-content.https.any.js create mode 100644 test/wpt/tests/websockets/multi-globals/message-received.html create mode 100644 test/wpt/tests/websockets/multi-globals/support/incumbent.sub.html create mode 100644 test/wpt/tests/websockets/multi-globals/support/relevant.html create mode 100644 test/wpt/tests/websockets/multi-globals/url-parsing/current/current.html create mode 100644 test/wpt/tests/websockets/multi-globals/url-parsing/incumbent/incumbent.html create mode 100644 test/wpt/tests/websockets/multi-globals/url-parsing/url-parsing.html create mode 100644 test/wpt/tests/websockets/opening-handshake/001.html create mode 100644 test/wpt/tests/websockets/opening-handshake/002.html create mode 100644 test/wpt/tests/websockets/opening-handshake/003-sets-origin.worker.js create mode 100644 test/wpt/tests/websockets/opening-handshake/003.html create mode 100644 test/wpt/tests/websockets/opening-handshake/005.html create mode 100644 test/wpt/tests/websockets/referrer.any.js create mode 100644 test/wpt/tests/websockets/remove-own-iframe-during-onerror.window.js create mode 100644 test/wpt/tests/websockets/resources/websockets-test-helpers.sub.js create mode 100644 test/wpt/tests/websockets/security/001.html create mode 100644 test/wpt/tests/websockets/security/002.html create mode 100644 test/wpt/tests/websockets/security/check.py create mode 100644 test/wpt/tests/websockets/send-many-64K-messages-with-backpressure.any.js create mode 100644 test/wpt/tests/websockets/stream/tentative/README.md create mode 100644 test/wpt/tests/websockets/stream/tentative/abort.any.js create mode 100644 test/wpt/tests/websockets/stream/tentative/backpressure-receive.any.js create mode 100644 test/wpt/tests/websockets/stream/tentative/backpressure-send.any.js create mode 100644 test/wpt/tests/websockets/stream/tentative/close.any.js create mode 100644 test/wpt/tests/websockets/stream/tentative/constructor.any.js create mode 100644 test/wpt/tests/websockets/stream/tentative/resources/url-constants.js create mode 100644 test/wpt/tests/websockets/unload-a-document/001-1.html create mode 100644 test/wpt/tests/websockets/unload-a-document/001-2.html create mode 100644 test/wpt/tests/websockets/unload-a-document/001.html create mode 100644 test/wpt/tests/websockets/unload-a-document/002-1.html create mode 100644 test/wpt/tests/websockets/unload-a-document/002-2.html create mode 100644 test/wpt/tests/websockets/unload-a-document/002.html create mode 100644 test/wpt/tests/websockets/unload-a-document/003.html create mode 100644 test/wpt/tests/websockets/unload-a-document/004.html create mode 100644 test/wpt/tests/websockets/unload-a-document/005-1.html create mode 100644 test/wpt/tests/websockets/unload-a-document/005.html create mode 100644 test/wpt/tests/wpt create mode 100644 test/wpt/tests/wpt.py create mode 100644 test/wpt/tests/xhr/META.yml create mode 100644 test/wpt/tests/xhr/README.md create mode 100644 test/wpt/tests/xhr/XMLHttpRequest-withCredentials.any.js create mode 100644 test/wpt/tests/xhr/abort-after-receive.any.js create mode 100644 test/wpt/tests/xhr/abort-after-send.any.js create mode 100644 test/wpt/tests/xhr/abort-after-stop.window.js create mode 100644 test/wpt/tests/xhr/abort-after-timeout.any.js create mode 100644 test/wpt/tests/xhr/abort-during-done.window.js create mode 100644 test/wpt/tests/xhr/abort-during-headers-received.window.js create mode 100644 test/wpt/tests/xhr/abort-during-loading.window.js create mode 100644 test/wpt/tests/xhr/abort-during-open.any.js create mode 100644 test/wpt/tests/xhr/abort-during-readystatechange.any.js create mode 100644 test/wpt/tests/xhr/abort-during-unsent.any.js create mode 100644 test/wpt/tests/xhr/abort-during-upload.any.js create mode 100644 test/wpt/tests/xhr/abort-event-abort.any.js create mode 100644 test/wpt/tests/xhr/abort-event-listeners.any.js create mode 100644 test/wpt/tests/xhr/abort-event-loadend.any.js create mode 100644 test/wpt/tests/xhr/abort-event-order.htm create mode 100644 test/wpt/tests/xhr/abort-upload-event-abort.any.js create mode 100644 test/wpt/tests/xhr/abort-upload-event-loadend.any.js create mode 100644 test/wpt/tests/xhr/access-control-and-redirects-async-same-origin.any.js create mode 100644 test/wpt/tests/xhr/access-control-and-redirects-async.any.js create mode 100644 test/wpt/tests/xhr/access-control-and-redirects.any.js create mode 100644 test/wpt/tests/xhr/access-control-basic-allow-access-control-origin-header-data-url.htm create mode 100644 test/wpt/tests/xhr/access-control-basic-allow-access-control-origin-header.any.js create mode 100644 test/wpt/tests/xhr/access-control-basic-allow-async.any.js create mode 100644 test/wpt/tests/xhr/access-control-basic-allow-non-cors-safelisted-method-async.any.js create mode 100644 test/wpt/tests/xhr/access-control-basic-allow-non-cors-safelisted-method.any.js create mode 100644 test/wpt/tests/xhr/access-control-basic-allow-preflight-cache-invalidation-by-header.any.js create mode 100644 test/wpt/tests/xhr/access-control-basic-allow-preflight-cache-invalidation-by-method.any.js create mode 100644 test/wpt/tests/xhr/access-control-basic-allow-preflight-cache-timeout.any.js create mode 100644 test/wpt/tests/xhr/access-control-basic-allow-preflight-cache.any.js create mode 100644 test/wpt/tests/xhr/access-control-basic-allow-star.any.js create mode 100644 test/wpt/tests/xhr/access-control-basic-allow.any.js create mode 100644 test/wpt/tests/xhr/access-control-basic-cors-safelisted-request-headers.htm create mode 100644 test/wpt/tests/xhr/access-control-basic-cors-safelisted-response-headers.htm create mode 100644 test/wpt/tests/xhr/access-control-basic-denied.htm create mode 100644 test/wpt/tests/xhr/access-control-basic-get-fail-non-simple.htm create mode 100644 test/wpt/tests/xhr/access-control-basic-non-cors-safelisted-content-type.htm create mode 100644 test/wpt/tests/xhr/access-control-basic-post-success-no-content-type.htm create mode 100644 test/wpt/tests/xhr/access-control-basic-post-with-non-cors-safelisted-content-type.htm create mode 100644 test/wpt/tests/xhr/access-control-basic-preflight-denied.htm create mode 100644 test/wpt/tests/xhr/access-control-expose-headers-on-redirect.html create mode 100644 test/wpt/tests/xhr/access-control-preflight-async-header-denied.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-async-method-denied.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-async-not-supported.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-credential-async.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-credential-sync.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-headers-async.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-headers-sync.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-request-allow-headers-returns-star.any.js create mode 100644 test/wpt/tests/xhr/access-control-preflight-request-header-lowercase.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-request-header-returns-origin.any.js create mode 100644 test/wpt/tests/xhr/access-control-preflight-request-header-sorted.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-request-headers-origin.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-request-invalid-status-301.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-request-invalid-status-400.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-request-invalid-status-501.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-request-must-not-contain-cookie.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-sync-header-denied.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-sync-method-denied.htm create mode 100644 test/wpt/tests/xhr/access-control-preflight-sync-not-supported.htm create mode 100644 test/wpt/tests/xhr/access-control-recursive-failed-request.htm create mode 100644 test/wpt/tests/xhr/access-control-response-with-body-sync.htm create mode 100644 test/wpt/tests/xhr/access-control-response-with-body.htm create mode 100644 test/wpt/tests/xhr/access-control-response-with-exposed-headers.htm create mode 100644 test/wpt/tests/xhr/access-control-sandboxed-iframe-allow-origin-null.htm create mode 100644 test/wpt/tests/xhr/access-control-sandboxed-iframe-allow.htm create mode 100644 test/wpt/tests/xhr/access-control-sandboxed-iframe-denied-without-wildcard.htm create mode 100644 test/wpt/tests/xhr/access-control-sandboxed-iframe-denied.htm create mode 100644 test/wpt/tests/xhr/allow-lists-starting-with-comma.htm create mode 100644 test/wpt/tests/xhr/anonymous-mode-unsupported.htm create mode 100644 test/wpt/tests/xhr/blob-range.any.js create mode 100644 test/wpt/tests/xhr/close-worker-with-xhr-in-progress.html create mode 100644 test/wpt/tests/xhr/content-type-unmodified.any.js create mode 100644 test/wpt/tests/xhr/cookies.http.html create mode 100644 test/wpt/tests/xhr/cors-expose-star.sub.any.js create mode 100644 test/wpt/tests/xhr/cors-upload.any.js create mode 100644 test/wpt/tests/xhr/data-uri.htm create mode 100644 test/wpt/tests/xhr/event-abort.any.js create mode 100644 test/wpt/tests/xhr/event-error-order.sub.html create mode 100644 test/wpt/tests/xhr/event-error.sub.any.js create mode 100644 test/wpt/tests/xhr/event-load.any.js create mode 100644 test/wpt/tests/xhr/event-loadend.any.js create mode 100644 test/wpt/tests/xhr/event-loadstart-upload.any.js create mode 100644 test/wpt/tests/xhr/event-loadstart.any.js create mode 100644 test/wpt/tests/xhr/event-progress.any.js create mode 100644 test/wpt/tests/xhr/event-readystate-sync-open.any.js create mode 100644 test/wpt/tests/xhr/event-readystatechange-loaded.any.js create mode 100644 test/wpt/tests/xhr/event-timeout-order.any.js create mode 100644 test/wpt/tests/xhr/event-timeout.any.js create mode 100644 test/wpt/tests/xhr/event-upload-progress-crossorigin.any.js create mode 100644 test/wpt/tests/xhr/event-upload-progress.any.js create mode 100644 test/wpt/tests/xhr/firing-events-http-content-length.html create mode 100644 test/wpt/tests/xhr/firing-events-http-no-content-length.html create mode 100644 test/wpt/tests/xhr/folder.txt create mode 100644 test/wpt/tests/xhr/formdata.html create mode 100644 test/wpt/tests/xhr/formdata/append-formelement.html create mode 100644 test/wpt/tests/xhr/formdata/append.any.js create mode 100644 test/wpt/tests/xhr/formdata/constructor-formelement.html create mode 100644 test/wpt/tests/xhr/formdata/constructor-submitter.html create mode 100644 test/wpt/tests/xhr/formdata/constructor.any.js create mode 100644 test/wpt/tests/xhr/formdata/delete-formelement.html create mode 100644 test/wpt/tests/xhr/formdata/delete.any.js create mode 100644 test/wpt/tests/xhr/formdata/foreach.any.js create mode 100644 test/wpt/tests/xhr/formdata/get-formelement.html create mode 100644 test/wpt/tests/xhr/formdata/get.any.js create mode 100644 test/wpt/tests/xhr/formdata/has-formelement.html create mode 100644 test/wpt/tests/xhr/formdata/has.any.js create mode 100644 test/wpt/tests/xhr/formdata/iteration.any.js create mode 100644 test/wpt/tests/xhr/formdata/set-blob.any.js create mode 100644 test/wpt/tests/xhr/formdata/set-formelement.html create mode 100644 test/wpt/tests/xhr/formdata/set.any.js create mode 100644 test/wpt/tests/xhr/getallresponseheaders-cookies.htm create mode 100644 test/wpt/tests/xhr/getallresponseheaders-status.htm create mode 100644 test/wpt/tests/xhr/getallresponseheaders.htm create mode 100644 test/wpt/tests/xhr/getresponseheader-case-insensitive.htm create mode 100644 test/wpt/tests/xhr/getresponseheader-chunked-trailer.htm create mode 100644 test/wpt/tests/xhr/getresponseheader-cookies-and-more.htm create mode 100644 test/wpt/tests/xhr/getresponseheader-error-state.htm create mode 100644 test/wpt/tests/xhr/getresponseheader-server-date.htm create mode 100644 test/wpt/tests/xhr/getresponseheader-special-characters.htm create mode 100644 test/wpt/tests/xhr/getresponseheader-unsent-opened-state.htm create mode 100644 test/wpt/tests/xhr/getresponseheader.any.js create mode 100644 test/wpt/tests/xhr/header-user-agent-async.htm create mode 100644 test/wpt/tests/xhr/header-user-agent-sync.htm create mode 100644 test/wpt/tests/xhr/headers-normalize-response.htm create mode 100644 test/wpt/tests/xhr/historical.html create mode 100644 test/wpt/tests/xhr/idlharness.any.js create mode 100644 test/wpt/tests/xhr/json.any.js create mode 100644 test/wpt/tests/xhr/loadstart-and-state.html create mode 100644 test/wpt/tests/xhr/open-after-abort.htm create mode 100644 test/wpt/tests/xhr/open-after-setrequestheader.htm create mode 100644 test/wpt/tests/xhr/open-after-stop.window.js create mode 100644 test/wpt/tests/xhr/open-during-abort-event.htm create mode 100644 test/wpt/tests/xhr/open-during-abort-processing.htm create mode 100644 test/wpt/tests/xhr/open-during-abort.htm create mode 100644 test/wpt/tests/xhr/open-method-bogus.htm create mode 100644 test/wpt/tests/xhr/open-method-case-insensitive.htm create mode 100644 test/wpt/tests/xhr/open-method-case-sensitive.htm create mode 100644 test/wpt/tests/xhr/open-method-insecure.htm create mode 100644 test/wpt/tests/xhr/open-method-responsetype-set-sync.htm create mode 100644 test/wpt/tests/xhr/open-open-send.htm create mode 100644 test/wpt/tests/xhr/open-open-sync-send.htm create mode 100644 test/wpt/tests/xhr/open-parameters-toString.htm create mode 100644 test/wpt/tests/xhr/open-referer.htm create mode 100644 test/wpt/tests/xhr/open-send-during-abort.htm create mode 100644 test/wpt/tests/xhr/open-send-open.htm create mode 100644 test/wpt/tests/xhr/open-sync-open-send.htm create mode 100644 test/wpt/tests/xhr/open-url-about-blank-window.htm create mode 100644 test/wpt/tests/xhr/open-url-base-inserted-after-open.htm create mode 100644 test/wpt/tests/xhr/open-url-base-inserted.htm create mode 100644 test/wpt/tests/xhr/open-url-base.htm create mode 100644 test/wpt/tests/xhr/open-url-encoding.htm create mode 100644 test/wpt/tests/xhr/open-url-fragment.htm create mode 100644 test/wpt/tests/xhr/open-url-javascript-window-2.htm create mode 100644 test/wpt/tests/xhr/open-url-javascript-window.htm create mode 100644 test/wpt/tests/xhr/open-url-multi-window-2.htm create mode 100644 test/wpt/tests/xhr/open-url-multi-window-3.htm create mode 100644 test/wpt/tests/xhr/open-url-multi-window-4.htm create mode 100644 test/wpt/tests/xhr/open-url-multi-window-5.htm create mode 100644 test/wpt/tests/xhr/open-url-multi-window-6.htm create mode 100644 test/wpt/tests/xhr/open-url-multi-window.htm create mode 100644 test/wpt/tests/xhr/open-url-redirected-sharedworker-origin.htm create mode 100644 test/wpt/tests/xhr/open-url-redirected-worker-origin.htm create mode 100644 test/wpt/tests/xhr/open-url-worker-origin.htm create mode 100644 test/wpt/tests/xhr/open-url-worker-simple.htm create mode 100644 test/wpt/tests/xhr/open-user-password-non-same-origin.htm create mode 100644 test/wpt/tests/xhr/over-1-meg.any.js create mode 100644 test/wpt/tests/xhr/overridemimetype-blob.html create mode 100644 test/wpt/tests/xhr/overridemimetype-done-state.any.js create mode 100644 test/wpt/tests/xhr/overridemimetype-edge-cases.window.js create mode 100644 test/wpt/tests/xhr/overridemimetype-headers-received-state-force-shiftjis.htm create mode 100644 test/wpt/tests/xhr/overridemimetype-invalid-mime-type.htm create mode 100644 test/wpt/tests/xhr/overridemimetype-loading-state.htm create mode 100644 test/wpt/tests/xhr/overridemimetype-open-state-force-utf-8.htm create mode 100644 test/wpt/tests/xhr/overridemimetype-open-state-force-xml.htm create mode 100644 test/wpt/tests/xhr/overridemimetype-unsent-state-force-shiftjis.any.js create mode 100644 test/wpt/tests/xhr/preserve-ua-header-on-redirect.htm create mode 100644 test/wpt/tests/xhr/progress-events-response-data-gzip.htm create mode 100644 test/wpt/tests/xhr/progressevent-constructor.html create mode 100644 test/wpt/tests/xhr/progressevent-interface.html create mode 100644 test/wpt/tests/xhr/request-content-length.any.js create mode 100644 test/wpt/tests/xhr/resources/accept-language.py create mode 100644 test/wpt/tests/xhr/resources/accept.py create mode 100644 test/wpt/tests/xhr/resources/access-control-allow-lists.py create mode 100644 test/wpt/tests/xhr/resources/access-control-allow-with-body.py create mode 100644 test/wpt/tests/xhr/resources/access-control-auth-basic.py create mode 100644 test/wpt/tests/xhr/resources/access-control-basic-allow-no-credentials.py create mode 100644 test/wpt/tests/xhr/resources/access-control-basic-allow-star.py create mode 100644 test/wpt/tests/xhr/resources/access-control-basic-allow.py create mode 100644 test/wpt/tests/xhr/resources/access-control-basic-cors-safelisted-request-headers.py create mode 100644 test/wpt/tests/xhr/resources/access-control-basic-cors-safelisted-response-headers.py create mode 100644 test/wpt/tests/xhr/resources/access-control-basic-denied.py create mode 100644 test/wpt/tests/xhr/resources/access-control-basic-options-not-supported.py create mode 100644 test/wpt/tests/xhr/resources/access-control-basic-preflight-cache-invalidation.py create mode 100644 test/wpt/tests/xhr/resources/access-control-basic-preflight-cache-timeout.py create mode 100644 test/wpt/tests/xhr/resources/access-control-basic-preflight-cache.py create mode 100644 test/wpt/tests/xhr/resources/access-control-basic-put-allow.py create mode 100644 test/wpt/tests/xhr/resources/access-control-cookie.py create mode 100644 test/wpt/tests/xhr/resources/access-control-origin-header.py create mode 100644 test/wpt/tests/xhr/resources/access-control-preflight-denied.py create mode 100644 test/wpt/tests/xhr/resources/access-control-preflight-request-allow-headers-returns-star.py create mode 100644 test/wpt/tests/xhr/resources/access-control-preflight-request-header-lowercase.py create mode 100644 test/wpt/tests/xhr/resources/access-control-preflight-request-header-returns-origin.py create mode 100644 test/wpt/tests/xhr/resources/access-control-preflight-request-header-sorted.py create mode 100644 test/wpt/tests/xhr/resources/access-control-preflight-request-headers-origin.py create mode 100644 test/wpt/tests/xhr/resources/access-control-preflight-request-invalid-status.py create mode 100644 test/wpt/tests/xhr/resources/access-control-preflight-request-must-not-contain-cookie.py create mode 100644 test/wpt/tests/xhr/resources/access-control-sandboxed-iframe.html create mode 100644 test/wpt/tests/xhr/resources/auth1/auth.py create mode 100644 test/wpt/tests/xhr/resources/auth10/auth.py create mode 100644 test/wpt/tests/xhr/resources/auth11/auth.py create mode 100644 test/wpt/tests/xhr/resources/auth2/auth.py create mode 100644 test/wpt/tests/xhr/resources/auth2/corsenabled.py create mode 100644 test/wpt/tests/xhr/resources/auth3/auth.py create mode 100644 test/wpt/tests/xhr/resources/auth4/auth.py create mode 100644 test/wpt/tests/xhr/resources/auth5/auth.py create mode 100644 test/wpt/tests/xhr/resources/auth6/auth.py create mode 100644 test/wpt/tests/xhr/resources/auth7/corsenabled.py create mode 100644 test/wpt/tests/xhr/resources/auth8/corsenabled-no-authorize.py create mode 100644 test/wpt/tests/xhr/resources/auth9/auth.py create mode 100644 test/wpt/tests/xhr/resources/authentication.py create mode 100644 test/wpt/tests/xhr/resources/bad-chunk-encoding.py create mode 100644 test/wpt/tests/xhr/resources/base.xml create mode 100644 test/wpt/tests/xhr/resources/chunked.py create mode 100644 test/wpt/tests/xhr/resources/conditional.py create mode 100644 test/wpt/tests/xhr/resources/content.py create mode 100644 test/wpt/tests/xhr/resources/corsenabled.py create mode 100644 test/wpt/tests/xhr/resources/delay.py create mode 100644 test/wpt/tests/xhr/resources/echo-content-cors.py create mode 100644 test/wpt/tests/xhr/resources/echo-content-type.py create mode 100644 test/wpt/tests/xhr/resources/echo-headers.py create mode 100644 test/wpt/tests/xhr/resources/echo-method.py create mode 100644 test/wpt/tests/xhr/resources/empty-div-utf8-html.py create mode 100644 test/wpt/tests/xhr/resources/folder.txt create mode 100644 test/wpt/tests/xhr/resources/form.py create mode 100644 test/wpt/tests/xhr/resources/get-set-cookie.py create mode 100644 test/wpt/tests/xhr/resources/gzip.py create mode 100644 test/wpt/tests/xhr/resources/header-content-length-twice.asis create mode 100644 test/wpt/tests/xhr/resources/header-content-length.asis create mode 100644 test/wpt/tests/xhr/resources/header-user-agent.py create mode 100644 test/wpt/tests/xhr/resources/headers-basic.asis create mode 100644 test/wpt/tests/xhr/resources/headers-double-empty.asis create mode 100644 test/wpt/tests/xhr/resources/headers-some-are-empty.asis create mode 100644 test/wpt/tests/xhr/resources/headers-www-authenticate.asis create mode 100644 test/wpt/tests/xhr/resources/headers.asis create mode 100644 test/wpt/tests/xhr/resources/headers.py create mode 100644 test/wpt/tests/xhr/resources/image.gif create mode 100644 test/wpt/tests/xhr/resources/img-utf8-html.py create mode 100644 test/wpt/tests/xhr/resources/img.jpg create mode 100644 test/wpt/tests/xhr/resources/infinite-redirects.py create mode 100644 test/wpt/tests/xhr/resources/init.htm create mode 100644 test/wpt/tests/xhr/resources/inspect-headers.py create mode 100644 test/wpt/tests/xhr/resources/invalid-utf8-html.py create mode 100644 test/wpt/tests/xhr/resources/last-modified.py create mode 100644 test/wpt/tests/xhr/resources/no-custom-header-on-preflight.py create mode 100644 test/wpt/tests/xhr/resources/nocors/folder.txt create mode 100644 test/wpt/tests/xhr/resources/over-1-meg.txt create mode 100644 test/wpt/tests/xhr/resources/parse-headers.py create mode 100644 test/wpt/tests/xhr/resources/pass.txt create mode 100644 test/wpt/tests/xhr/resources/redirect-cors.py create mode 100644 test/wpt/tests/xhr/resources/redirect.py create mode 100644 test/wpt/tests/xhr/resources/requri.py create mode 100644 test/wpt/tests/xhr/resources/reset-token.py create mode 100644 test/wpt/tests/xhr/resources/responseType-document-in-worker.js create mode 100644 test/wpt/tests/xhr/resources/responseXML-unavailable-in-worker.js create mode 100644 test/wpt/tests/xhr/resources/send-after-setting-document-domain-window-1.htm create mode 100644 test/wpt/tests/xhr/resources/send-after-setting-document-domain-window-2.htm create mode 100644 test/wpt/tests/xhr/resources/send-after-setting-document-domain-window-helper.js create mode 100644 test/wpt/tests/xhr/resources/shift-jis-html.py create mode 100644 test/wpt/tests/xhr/resources/status.py create mode 100644 test/wpt/tests/xhr/resources/top.txt create mode 100644 test/wpt/tests/xhr/resources/trickle.py create mode 100644 test/wpt/tests/xhr/resources/upload.py create mode 100644 test/wpt/tests/xhr/resources/utf16-bom.json create mode 100644 test/wpt/tests/xhr/resources/utf16.txt create mode 100644 test/wpt/tests/xhr/resources/well-formed.xml create mode 100644 test/wpt/tests/xhr/resources/win-1252-html.py create mode 100644 test/wpt/tests/xhr/resources/win-1252-xml.py create mode 100644 test/wpt/tests/xhr/resources/workerxhr-origin-referrer.js create mode 100644 test/wpt/tests/xhr/resources/workerxhr-simple.js create mode 100644 test/wpt/tests/xhr/resources/xmlhttprequest-event-order.js create mode 100644 test/wpt/tests/xhr/resources/xmlhttprequest-timeout-aborted.js create mode 100644 test/wpt/tests/xhr/resources/xmlhttprequest-timeout-abortedonmain.js create mode 100644 test/wpt/tests/xhr/resources/xmlhttprequest-timeout-overrides.js create mode 100644 test/wpt/tests/xhr/resources/xmlhttprequest-timeout-overridesexpires.js create mode 100644 test/wpt/tests/xhr/resources/xmlhttprequest-timeout-runner.js create mode 100644 test/wpt/tests/xhr/resources/xmlhttprequest-timeout-simple.js create mode 100644 test/wpt/tests/xhr/resources/xmlhttprequest-timeout-synconmain.js create mode 100644 test/wpt/tests/xhr/resources/xmlhttprequest-timeout-synconworker.js create mode 100644 test/wpt/tests/xhr/resources/xmlhttprequest-timeout-twice.js create mode 100644 test/wpt/tests/xhr/resources/xmlhttprequest-timeout.js create mode 100644 test/wpt/tests/xhr/resources/zlib.py create mode 100644 test/wpt/tests/xhr/response-body-errors.any.js create mode 100644 test/wpt/tests/xhr/response-data-arraybuffer.htm create mode 100644 test/wpt/tests/xhr/response-data-blob.htm create mode 100644 test/wpt/tests/xhr/response-data-deflate.htm create mode 100644 test/wpt/tests/xhr/response-data-gzip.htm create mode 100644 test/wpt/tests/xhr/response-data-progress.htm create mode 100644 test/wpt/tests/xhr/response-invalid-responsetype.htm create mode 100644 test/wpt/tests/xhr/response-json.htm create mode 100644 test/wpt/tests/xhr/response-method.htm create mode 100644 test/wpt/tests/xhr/responseText-status.html create mode 100644 test/wpt/tests/xhr/responseType-document-in-worker.html create mode 100644 test/wpt/tests/xhr/responseXML-unavailable-in-worker.html create mode 100644 test/wpt/tests/xhr/responsedocument-decoding.htm create mode 100644 test/wpt/tests/xhr/responsetext-decoding.htm create mode 100644 test/wpt/tests/xhr/responsetype.any.js create mode 100644 test/wpt/tests/xhr/responseurl.html create mode 100644 test/wpt/tests/xhr/responsexml-basic.htm create mode 100644 test/wpt/tests/xhr/responsexml-document-properties.htm create mode 100644 test/wpt/tests/xhr/responsexml-get-twice.htm create mode 100644 test/wpt/tests/xhr/responsexml-invalid-type.html create mode 100644 test/wpt/tests/xhr/responsexml-media-type.htm create mode 100644 test/wpt/tests/xhr/responsexml-non-document-types.htm create mode 100644 test/wpt/tests/xhr/responsexml-non-well-formed.htm create mode 100644 test/wpt/tests/xhr/security-consideration.sub.html create mode 100644 test/wpt/tests/xhr/send-accept-language.htm create mode 100644 test/wpt/tests/xhr/send-accept.htm create mode 100644 test/wpt/tests/xhr/send-after-setting-document-domain.htm create mode 100644 test/wpt/tests/xhr/send-authentication-basic-cors-not-enabled.htm create mode 100644 test/wpt/tests/xhr/send-authentication-basic-cors.htm create mode 100644 test/wpt/tests/xhr/send-authentication-basic-repeat-no-args.htm create mode 100644 test/wpt/tests/xhr/send-authentication-basic-setrequestheader-and-arguments.htm create mode 100644 test/wpt/tests/xhr/send-authentication-basic-setrequestheader-existing-session.htm create mode 100644 test/wpt/tests/xhr/send-authentication-basic-setrequestheader.htm create mode 100644 test/wpt/tests/xhr/send-authentication-basic.htm create mode 100644 test/wpt/tests/xhr/send-authentication-competing-names-passwords.htm create mode 100644 test/wpt/tests/xhr/send-authentication-cors-basic-setrequestheader.htm create mode 100644 test/wpt/tests/xhr/send-authentication-cors-setrequestheader-no-cred.htm create mode 100644 test/wpt/tests/xhr/send-authentication-existing-session-manual.htm create mode 100644 test/wpt/tests/xhr/send-authentication-prompt-2-manual.htm create mode 100644 test/wpt/tests/xhr/send-authentication-prompt-manual.htm create mode 100644 test/wpt/tests/xhr/send-blob-with-no-mime-type.html create mode 100644 test/wpt/tests/xhr/send-conditional-cors.htm create mode 100644 test/wpt/tests/xhr/send-conditional.htm create mode 100644 test/wpt/tests/xhr/send-content-type-charset.htm create mode 100644 test/wpt/tests/xhr/send-content-type-string.htm create mode 100644 test/wpt/tests/xhr/send-data-arraybuffer.any.js create mode 100644 test/wpt/tests/xhr/send-data-arraybufferview.any.js create mode 100644 test/wpt/tests/xhr/send-data-blob.htm create mode 100644 test/wpt/tests/xhr/send-data-es-object.any.js create mode 100644 test/wpt/tests/xhr/send-data-formdata.any.js create mode 100644 test/wpt/tests/xhr/send-data-sharedarraybuffer.any.js create mode 100644 test/wpt/tests/xhr/send-data-string-invalid-unicode.any.js create mode 100644 test/wpt/tests/xhr/send-data-unexpected-tostring.htm create mode 100644 test/wpt/tests/xhr/send-entity-body-basic.htm create mode 100644 test/wpt/tests/xhr/send-entity-body-document-bogus.htm create mode 100644 test/wpt/tests/xhr/send-entity-body-document.htm create mode 100644 test/wpt/tests/xhr/send-entity-body-empty.htm create mode 100644 test/wpt/tests/xhr/send-entity-body-get-head-async.htm create mode 100644 test/wpt/tests/xhr/send-entity-body-get-head.htm create mode 100644 test/wpt/tests/xhr/send-entity-body-none.htm create mode 100644 test/wpt/tests/xhr/send-network-error-async-events.sub.htm create mode 100644 test/wpt/tests/xhr/send-network-error-sync-events.sub.htm create mode 100644 test/wpt/tests/xhr/send-no-response-event-loadend.htm create mode 100644 test/wpt/tests/xhr/send-no-response-event-loadstart.htm create mode 100644 test/wpt/tests/xhr/send-no-response-event-order.htm create mode 100644 test/wpt/tests/xhr/send-non-same-origin.htm create mode 100644 test/wpt/tests/xhr/send-receive-utf16.htm create mode 100644 test/wpt/tests/xhr/send-redirect-bogus-sync.htm create mode 100644 test/wpt/tests/xhr/send-redirect-bogus.htm create mode 100644 test/wpt/tests/xhr/send-redirect-infinite-sync.htm create mode 100644 test/wpt/tests/xhr/send-redirect-infinite.htm create mode 100644 test/wpt/tests/xhr/send-redirect-no-location.htm create mode 100644 test/wpt/tests/xhr/send-redirect-post-upload.htm create mode 100644 test/wpt/tests/xhr/send-redirect-to-cors.htm create mode 100644 test/wpt/tests/xhr/send-redirect-to-non-cors.htm create mode 100644 test/wpt/tests/xhr/send-redirect.htm create mode 100644 test/wpt/tests/xhr/send-response-event-order.htm create mode 100644 test/wpt/tests/xhr/send-response-upload-event-loadend.htm create mode 100644 test/wpt/tests/xhr/send-response-upload-event-loadstart.htm create mode 100644 test/wpt/tests/xhr/send-response-upload-event-progress.htm create mode 100644 test/wpt/tests/xhr/send-send.any.js create mode 100644 test/wpt/tests/xhr/send-sync-blocks-async.htm create mode 100644 test/wpt/tests/xhr/send-sync-no-response-event-load.htm create mode 100644 test/wpt/tests/xhr/send-sync-no-response-event-loadend.htm create mode 100644 test/wpt/tests/xhr/send-sync-no-response-event-order.htm create mode 100644 test/wpt/tests/xhr/send-sync-response-event-order.htm create mode 100644 test/wpt/tests/xhr/send-sync-timeout.htm create mode 100644 test/wpt/tests/xhr/send-timeout-events.htm create mode 100644 test/wpt/tests/xhr/send-usp.any.js create mode 100644 test/wpt/tests/xhr/setrequestheader-after-send.htm create mode 100644 test/wpt/tests/xhr/setrequestheader-allow-empty-value.htm create mode 100644 test/wpt/tests/xhr/setrequestheader-allow-whitespace-in-value.htm create mode 100644 test/wpt/tests/xhr/setrequestheader-before-open.htm create mode 100644 test/wpt/tests/xhr/setrequestheader-bogus-name.htm create mode 100644 test/wpt/tests/xhr/setrequestheader-bogus-value.htm create mode 100644 test/wpt/tests/xhr/setrequestheader-case-insensitive.htm create mode 100644 test/wpt/tests/xhr/setrequestheader-combining.window.js create mode 100644 test/wpt/tests/xhr/setrequestheader-content-type.htm create mode 100644 test/wpt/tests/xhr/setrequestheader-header-allowed.htm create mode 100644 test/wpt/tests/xhr/setrequestheader-header-forbidden.htm create mode 100644 test/wpt/tests/xhr/setrequestheader-open-setrequestheader.htm create mode 100644 test/wpt/tests/xhr/status-async.htm create mode 100644 test/wpt/tests/xhr/status-basic.htm create mode 100644 test/wpt/tests/xhr/status-error.htm create mode 100644 test/wpt/tests/xhr/status.h2.window.js create mode 100644 test/wpt/tests/xhr/sync-no-progress.any.js create mode 100644 test/wpt/tests/xhr/sync-no-timeout.any.js create mode 100644 test/wpt/tests/xhr/sync-xhr-and-window-onload.html create mode 100644 test/wpt/tests/xhr/sync-xhr-supported-by-feature-policy.html create mode 100644 test/wpt/tests/xhr/template-element.html create mode 100644 test/wpt/tests/xhr/thrown-error-in-events.html create mode 100644 test/wpt/tests/xhr/timeout-cors-async.htm create mode 100644 test/wpt/tests/xhr/timeout-multiple-fetches.html create mode 100644 test/wpt/tests/xhr/timeout-sync.htm create mode 100644 test/wpt/tests/xhr/xhr-authorization-redirect.any.js create mode 100644 test/wpt/tests/xhr/xhr-timeout-longtask.any.js create mode 100644 test/wpt/tests/xhr/xmlhttprequest-basic.htm create mode 100644 test/wpt/tests/xhr/xmlhttprequest-eventtarget.htm create mode 100644 test/wpt/tests/xhr/xmlhttprequest-network-error-sync.htm create mode 100644 test/wpt/tests/xhr/xmlhttprequest-network-error.htm create mode 100644 test/wpt/tests/xhr/xmlhttprequest-sync-block-defer-scripts-subframe.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-sync-block-defer-scripts.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-sync-block-scripts.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-sync-default-feature-policy.sub.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-sync-not-hang-scriptloader-subframe.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-sync-not-hang-scriptloader.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-aborted.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-abortedonmain.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-overrides.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-overridesexpires.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-reused.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-simple.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-synconmain.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-twice.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-worker-aborted.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-worker-overrides.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-worker-overridesexpires.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-worker-simple.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-worker-synconworker.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-timeout-worker-twice.html create mode 100644 test/wpt/tests/xhr/xmlhttprequest-unsent.htm (limited to 'test/wpt') diff --git a/test/wpt/runner/runner.mjs b/test/wpt/runner/runner.mjs new file mode 100644 index 0000000..5bec326 --- /dev/null +++ b/test/wpt/runner/runner.mjs @@ -0,0 +1,356 @@ +import { EventEmitter, once } from 'node:events' +import { isAbsolute, join, resolve } from 'node:path' +import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { Worker } from 'node:worker_threads' +import { colors, handlePipes, normalizeName, parseMeta, resolveStatusPath } from './util.mjs' + +const basePath = fileURLToPath(join(import.meta.url, '../..')) +const testPath = join(basePath, 'tests') +const statusPath = join(basePath, 'status') + +// https://github.com/web-platform-tests/wpt/blob/b24eedd/resources/testharness.js#L3705 +function sanitizeUnpairedSurrogates (str) { + return str.replace( + /([\ud800-\udbff]+)(?![\udc00-\udfff])|(^|[^\ud800-\udbff])([\udc00-\udfff]+)/g, + function (_, low, prefix, high) { + let output = prefix || '' // Prefix may be undefined + const string = low || high // Only one of these alternates can match + for (let i = 0; i < string.length; i++) { + output += codeUnitStr(string[i]) + } + return output + }) +} + +function codeUnitStr (char) { + return 'U+' + char.charCodeAt(0).toString(16) +} + +export class WPTRunner extends EventEmitter { + /** @type {string} */ + #folderName + + /** @type {string} */ + #folderPath + + /** @type {string[]} */ + #files = [] + + /** @type {string[]} */ + #initScripts = [] + + /** @type {string} */ + #url + + /** @type {import('../../status/fetch.status.json')} */ + #status + + /** Tests that have expectedly failed mapped by file name */ + #statusOutput = {} + + #uncaughtExceptions = [] + + /** @type {boolean} */ + #appendReport + + /** @type {string} */ + #reportPath + + #stats = { + completed: 0, + failed: 0, + success: 0, + expectedFailures: 0, + skipped: 0 + } + + constructor (folder, url, { appendReport = false, reportPath } = {}) { + super() + + this.#folderName = folder + this.#folderPath = join(testPath, folder) + this.#files.push( + ...WPTRunner.walk( + this.#folderPath, + (file) => file.endsWith('.any.js') + ) + ) + + if (appendReport) { + if (!reportPath) { + throw new TypeError('reportPath must be provided when appendReport is true') + } + if (!existsSync(reportPath)) { + throw new TypeError('reportPath is invalid') + } + } + + this.#appendReport = appendReport + this.#reportPath = reportPath + + this.#status = JSON.parse(readFileSync(join(statusPath, `${folder}.status.json`))) + this.#url = url + + if (this.#files.length === 0) { + queueMicrotask(() => { + this.emit('completion') + }) + } + + this.once('completion', () => { + for (const { error, test } of this.#uncaughtExceptions) { + console.log(colors(`Uncaught exception in "${test}":`, 'red')) + console.log(colors(`${error.stack}`, 'red')) + console.log('='.repeat(96)) + } + }) + } + + static walk (dir, fn) { + const ini = new Set(readdirSync(dir)) + const files = new Set() + + while (ini.size !== 0) { + for (const d of ini) { + const path = resolve(dir, d) + ini.delete(d) // remove from set + const stats = statSync(path) + + if (stats.isDirectory()) { + for (const f of readdirSync(path)) { + ini.add(resolve(path, f)) + } + } else if (stats.isFile() && fn(d)) { + files.add(path) + } + } + } + + return [...files].sort() + } + + async run () { + const workerPath = fileURLToPath(join(import.meta.url, '../worker.mjs')) + /** @type {Set} */ + const activeWorkers = new Set() + let finishedFiles = 1 + let total = this.#files.length + + const files = this.#files.map((test) => { + const code = test.includes('.sub.') + ? handlePipes(readFileSync(test, 'utf-8'), this.#url) + : readFileSync(test, 'utf-8') + const meta = this.resolveMeta(code, test) + + if (meta.variant.length) { + total += meta.variant.length - 1 + } + + return [test, code, meta] + }) + + console.log('='.repeat(96)) + + for (const [test, code, meta] of files) { + console.log(`Started ${test}`) + + const status = resolveStatusPath(test, this.#status) + + if (status.file.skip || status.topLevel.skip) { + this.#stats.skipped += 1 + + console.log(colors(`[${finishedFiles}/${total}] SKIPPED - ${test}`, 'yellow')) + console.log('='.repeat(96)) + + finishedFiles++ + continue + } + + const start = performance.now() + + for (const variant of meta.variant.length ? meta.variant : ['']) { + const url = new URL(this.#url) + if (variant) { + url.search = variant + } + const worker = new Worker(workerPath, { + workerData: { + // Code to load before the test harness and tests. + initScripts: this.#initScripts, + // The test file. + test: code, + // Parsed META tag information + meta, + url: url.href, + path: test + } + }) + + let result, report + if (this.#appendReport) { + report = JSON.parse(readFileSync(this.#reportPath)) + + const fileUrl = new URL(`/${this.#folderName}${test.slice(this.#folderPath.length)}`, 'http://wpt') + fileUrl.pathname = fileUrl.pathname.replace(/\.js$/, '.html') + fileUrl.search = variant + + result = { + test: fileUrl.href.slice(fileUrl.origin.length), + subtests: [], + status: 'OK' + } + report.results.push(result) + } + + activeWorkers.add(worker) + // These values come directly from the web-platform-tests + const timeout = meta.timeout === 'long' ? 60_000 : 10_000 + + worker.on('message', (message) => { + if (message.type === 'result') { + this.handleIndividualTestCompletion(message, status, test, meta, result) + } else if (message.type === 'completion') { + this.handleTestCompletion(worker) + } else if (message.type === 'error') { + this.#uncaughtExceptions.push({ error: message.error, test }) + this.#stats.failed += 1 + this.#stats.success -= 1 + } + }) + + try { + await once(worker, 'exit', { + signal: AbortSignal.timeout(timeout) + }) + + console.log(colors(`[${finishedFiles}/${total}] PASSED - ${test}`, 'green')) + if (variant) console.log('Variant:', variant) + console.log(`Test took ${(performance.now() - start).toFixed(2)}ms`) + console.log('='.repeat(96)) + } catch (e) { + console.log(`${test} timed out after ${timeout}ms`) + } finally { + if (result?.subtests.length > 0) { + writeFileSync(this.#reportPath, JSON.stringify(report)) + } + + finishedFiles++ + activeWorkers.delete(worker) + } + } + } + + this.handleRunnerCompletion() + } + + /** + * Called after a test has succeeded or failed. + */ + handleIndividualTestCompletion (message, status, path, meta, wptResult) { + const { file, topLevel } = status + + if (message.type === 'result') { + this.#stats.completed += 1 + + if (message.result.status === 1) { + this.#stats.failed += 1 + + wptResult?.subtests.push({ + status: 'FAIL', + name: sanitizeUnpairedSurrogates(message.result.name), + message: sanitizeUnpairedSurrogates(message.result.message) + }) + + const name = normalizeName(message.result.name) + + if (file.flaky?.includes(name)) { + this.#stats.expectedFailures += 1 + } else if (file.allowUnexpectedFailures || topLevel.allowUnexpectedFailures || file.fail?.includes(name)) { + if (!file.allowUnexpectedFailures && !topLevel.allowUnexpectedFailures) { + if (Array.isArray(file.fail)) { + this.#statusOutput[path] ??= [] + this.#statusOutput[path].push(name) + } + } + + this.#stats.expectedFailures += 1 + } else { + process.exitCode = 1 + console.error(message.result) + } + } else { + wptResult?.subtests.push({ + status: 'PASS', + name: sanitizeUnpairedSurrogates(message.result.name) + }) + this.#stats.success += 1 + } + } + } + + /** + * Called after all the tests in a worker are completed. + * @param {Worker} worker + */ + handleTestCompletion (worker) { + worker.terminate() + } + + /** + * Called after every test has completed. + */ + handleRunnerCompletion () { + console.log(this.#statusOutput) // tests that failed + + this.emit('completion') + const { completed, failed, success, expectedFailures, skipped } = this.#stats + console.log( + `[${this.#folderName}]: ` + + `Completed: ${completed}, failed: ${failed}, success: ${success}, ` + + `expected failures: ${expectedFailures}, ` + + `unexpected failures: ${failed - expectedFailures}, ` + + `skipped: ${skipped}` + ) + + process.exit(0) + } + + addInitScript (code) { + this.#initScripts.push(code) + } + + /** + * Parses META tags and resolves any script file paths. + * @param {string} code + * @param {string} path The absolute path of the test + */ + resolveMeta (code, path) { + const meta = parseMeta(code) + const scripts = meta.scripts.map((filePath) => { + let content = '' + + if (filePath === '/resources/WebIDLParser.js') { + // See https://github.com/web-platform-tests/wpt/pull/731 + return readFileSync(join(testPath, '/resources/webidl2/lib/webidl2.js'), 'utf-8') + } else if (isAbsolute(filePath)) { + content = readFileSync(join(testPath, filePath), 'utf-8') + } else { + content = readFileSync(resolve(path, '..', filePath), 'utf-8') + } + + // If the file has any built-in pipes. + if (filePath.includes('.sub.')) { + content = handlePipes(content, this.#url) + } + + return content + }) + + return { + ...meta, + resourcePaths: meta.scripts, + scripts + } + } +} diff --git a/test/wpt/runner/util.mjs b/test/wpt/runner/util.mjs new file mode 100644 index 0000000..ec284df --- /dev/null +++ b/test/wpt/runner/util.mjs @@ -0,0 +1,172 @@ +import assert from 'node:assert' +import { exit } from 'node:process' +import { inspect } from 'node:util' +import tty from 'node:tty' +import { sep } from 'node:path' + +/** + * Parse the `Meta:` tags sometimes included in tests. + * These can include resources to inject, how long it should + * take to timeout, and which globals to expose. + * @example + * // META: timeout=long + * // META: global=window,worker + * // META: script=/common/utils.js + * // META: script=/common/get-host-info.sub.js + * // META: script=../request/request-error.js + * @see https://nodejs.org/api/readline.html#readline_example_read_file_stream_line_by_line + * @param {string} fileContents + */ +export function parseMeta (fileContents) { + const lines = fileContents.split(/\r?\n/g) + + const meta = { + /** @type {string|null} */ + timeout: null, + /** @type {string[]} */ + global: [], + /** @type {string[]} */ + scripts: [], + /** @type {string[]} */ + variant: [] + } + + for (const line of lines) { + if (!line.startsWith('// META: ')) { + break + } + + const groups = /^\/\/ META: (?.*?)=(?.*)$/.exec(line)?.groups + + if (!groups) { + console.log(`Failed to parse META tag: ${line}`) + exit(1) + } + + switch (groups.type) { + case 'variant': + meta[groups.type].push(groups.match) + break + case 'title': + case 'timeout': { + meta[groups.type] = groups.match + break + } + case 'global': { + // window,worker -> ['window', 'worker'] + meta.global.push(...groups.match.split(',')) + break + } + case 'script': { + // A relative or absolute file path to the resources + // needed for the current test. + meta.scripts.push(groups.match) + break + } + default: { + console.log(`Unknown META tag: ${groups.type}`) + exit(1) + } + } + } + + return meta +} + +/** + * @param {string} sub + */ +function parseSubBlock (sub) { + const subName = sub.includes('[') ? sub.slice(0, sub.indexOf('[')) : sub + const options = sub.matchAll(/\[(.*?)\]/gm) + + return { + sub: subName, + options: [...options].map(match => match[1]) + } +} + +/** + * @see https://web-platform-tests.org/writing-tests/server-pipes.html?highlight=sub#built-in-pipes + * @param {string} code + * @param {string} url + */ +export function handlePipes (code, url) { + const server = new URL(url) + + // "Substitutions are marked in a file using a block delimited by + // {{ and }}. Inside the block the following variables are available:" + return code.replace(/{{(.*?)}}/gm, (_, match) => { + const { sub } = parseSubBlock(match) + + switch (sub) { + // "The host name of the server excluding any subdomain part." + // eslint-disable-next-line no-fallthrough + case 'host': + // "The domain name of a particular subdomain e.g. + // {{domains[www]}} for the www subdomain." + // eslint-disable-next-line no-fallthrough + case 'domains': + // "The domain name of a particular subdomain for a particular host. + // The first key may be empty (designating the “default†host) or + // the value alt; i.e., {{hosts[alt][]}} (designating the alternate + // host)." + // eslint-disable-next-line no-fallthrough + case 'hosts': { + return 'localhost' + } + // "The port number of servers, by protocol e.g. {{ports[http][0]}} + // for the first (and, depending on setup, possibly only) http server" + case 'ports': { + return server.port + } + default: { + throw new TypeError(`Unknown substitute "${sub}".`) + } + } + }) +} + +/** + * Some test names may contain characters that JSON cannot handle. + * @param {string} name + */ +export function normalizeName (name) { + return name.replace(/(\v)/g, (_, match) => { + switch (inspect(match)) { + case '\'\\x0B\'': return '\\x0B' + default: return match + } + }) +} + +export function colors (str, color) { + assert(Object.hasOwn(inspect.colors, color), `Missing color ${color}`) + + if (!tty.WriteStream.prototype.hasColors()) { + return str + } + + const [start, end] = inspect.colors[color] + + return `\u001b[${start}m${str}\u001b[${end}m` +} + +/** @param {string} path */ +export function resolveStatusPath (path, status) { + const paths = path + .slice(process.cwd().length + sep.length) + .split(sep) + .slice(3) // [test, wpt, tests, fetch, b, c.js] -> [fetch, b, c.js] + + // skip the first folder name + for (let i = 1; i < paths.length - 1; i++) { + status = status[paths[i]] + + if (!status) { + break + } + } + + return { topLevel: status ?? {}, file: status?.[paths.at(-1)] ?? {} } +} diff --git a/test/wpt/runner/worker.mjs b/test/wpt/runner/worker.mjs new file mode 100644 index 0000000..90bfcf6 --- /dev/null +++ b/test/wpt/runner/worker.mjs @@ -0,0 +1,164 @@ +import buffer from 'node:buffer' +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { setFlagsFromString } from 'node:v8' +import { runInNewContext, runInThisContext } from 'node:vm' +import { parentPort, workerData } from 'node:worker_threads' +import { + fetch, File, FileReader, FormData, Headers, Request, Response, setGlobalOrigin +} from '../../../index.js' +import { CloseEvent } from '../../../lib/websocket/events.js' +import { WebSocket } from '../../../lib/websocket/websocket.js' +import { Cache } from '../../../lib/cache/cache.js' +import { CacheStorage } from '../../../lib/cache/cachestorage.js' +import { kConstruct } from '../../../lib/cache/symbols.js' + +const { initScripts, meta, test, url, path } = workerData + +process.on('uncaughtException', (err) => { + parentPort.postMessage({ + type: 'error', + error: { + message: err.message, + name: err.name, + stack: err.stack + } + }) +}) + +const basePath = join(process.cwd(), 'test/wpt/tests') +const urlPath = path.slice(basePath.length) + +const globalPropertyDescriptors = { + writable: true, + enumerable: false, + configurable: true +} + +Object.defineProperties(globalThis, { + fetch: { + ...globalPropertyDescriptors, + enumerable: true, + value: fetch + }, + File: { + ...globalPropertyDescriptors, + value: buffer.File ?? File + }, + FormData: { + ...globalPropertyDescriptors, + value: FormData + }, + Headers: { + ...globalPropertyDescriptors, + value: Headers + }, + Request: { + ...globalPropertyDescriptors, + value: Request + }, + Response: { + ...globalPropertyDescriptors, + value: Response + }, + FileReader: { + ...globalPropertyDescriptors, + value: FileReader + }, + WebSocket: { + ...globalPropertyDescriptors, + value: WebSocket + }, + CloseEvent: { + ...globalPropertyDescriptors, + value: CloseEvent + }, + Blob: { + ...globalPropertyDescriptors, + // See https://github.com/nodejs/node/pull/45659 + value: buffer.Blob + }, + caches: { + ...globalPropertyDescriptors, + value: new CacheStorage(kConstruct) + }, + Cache: { + ...globalPropertyDescriptors, + value: Cache + }, + CacheStorage: { + ...globalPropertyDescriptors, + value: CacheStorage + } +}) + +// self is required by testharness +// GLOBAL is required by self +runInThisContext(` + globalThis.self = globalThis + globalThis.GLOBAL = { + isWorker () { + return false + }, + isShadowRealm () { + return false + }, + isWindow () { + return false + } + } + globalThis.window = globalThis + globalThis.location = new URL('${urlPath.replace(/\\/g, '/')}', '${url}') + globalThis.Window = Object.getPrototypeOf(globalThis).constructor +`) + +if (meta.title) { + runInThisContext(`globalThis.META_TITLE = "${meta.title}"`) +} + +const harness = readFileSync(join(basePath, '/resources/testharness.js'), 'utf-8') +runInThisContext(harness) + +// add_*_callback comes from testharness +// stolen from node's wpt test runner +// eslint-disable-next-line no-undef +add_result_callback((result) => { + parentPort.postMessage({ + type: 'result', + result: { + status: result.status, + name: result.name, + message: result.message, + stack: result.stack + } + }) +}) + +// eslint-disable-next-line no-undef +add_completion_callback((_, status) => { + parentPort.postMessage({ + type: 'completion', + status + }) +}) + +setGlobalOrigin(globalThis.location) + +// Inject any script the user provided before +// running the tests. +for (const initScript of initScripts) { + runInThisContext(initScript) +} + +// Inject any files from the META tags +for (const script of meta.scripts) { + runInThisContext(script) +} + +// A few tests require gc, which can't be passed to a Worker. +// see https://github.com/nodejs/node/issues/16595#issuecomment-340288680 +setFlagsFromString('--expose-gc') +globalThis.gc = runInNewContext('gc') + +// Finally, run the test. +runInThisContext(test) diff --git a/test/wpt/server/routes/network-partition-key.mjs b/test/wpt/server/routes/network-partition-key.mjs new file mode 100644 index 0000000..f1203f7 --- /dev/null +++ b/test/wpt/server/routes/network-partition-key.mjs @@ -0,0 +1,111 @@ +const stash = new Map() + +/** + * @see https://github.com/web-platform-tests/wpt/blob/master/fetch/connection-pool/resources/network-partition-key.py + * @param {Parameters[0]} req + * @param {Parameters[1]} res + * @param {URL} url + */ +export function route (req, res, { searchParams, port }) { + res.setHeader('Cache-Control', 'no-store') + + const dispatch = searchParams.get('dispatch') + const uuid = searchParams.get('uuid') + const partitionId = searchParams.get('partition_id') + + if (!uuid || !dispatch || !partitionId) { + res.statusCode = 404 + res.end('Invalid query parameters') + return + } + + let testFailed = false + let requestCount = 0 + let connectionCount = 0 + + if (searchParams.get('nocheck_partition') !== 'True') { + const addressKey = `${req.socket.localAddress}|${port}` + const serverState = stash.get(uuid) ?? { + testFailed: false, + requestCount: 0, + connectionCount: 0 + } + + stash.delete(uuid) + requestCount = serverState.requestCount + 1 + serverState.requestCount = requestCount + + if (Object.hasOwn(serverState, addressKey)) { + if (serverState[addressKey] !== partitionId) { + serverState.testFailed = true + } + } else { + connectionCount = serverState.connectionCount + 1 + serverState.connectionCount = connectionCount + } + + serverState[addressKey] = partitionId + testFailed = serverState.testFailed + stash.set(uuid, serverState) + } + + const origin = req.headers.origin + if (origin) { + res.setHeader('Access-Control-Allow-Origin', origin) + res.setHeader('Access-Control-Allow-Credentials', 'true') + } + + if (req.method === 'OPTIONS') { + return handlePreflight(req, res) + } + + if (dispatch === 'fetch_file') { + res.end() + return + } + + if (dispatch === 'check_partition') { + const status = searchParams.get('status') ?? 200 + + if (testFailed) { + res.statusCode = status + res.end('Multiple partition IDs used on a socket') + return + } + + let body = 'ok' + if (searchParams.get('addcounter')) { + body += `. Request was sent ${requestCount} times. ${connectionCount} connections were created.` + res.statusCode = status + res.end(body) + return + } + } + + if (dispatch === 'clean_up') { + stash.delete(uuid) + res.statusCode = 200 + if (testFailed) { + res.end('Test failed, but cleanup completed.') + } else { + res.end('cleanup complete') + } + + return + } + + res.statusCode = 404 + res.end('Unrecognized dispatch parameter: ' + dispatch) +} + +/** + * @param {Parameters[0]} req + * @param {Parameters[1]} res + */ +function handlePreflight (req, res) { + res.statusCode = 200 + res.setHeader('Access-Control-Allow-Methods', 'GET') + res.setHeader('Access-Control-Allow-Headers', 'header-to-force-cors') + res.setHeader('Access-Control-Max-Age', '86400') + res.end('Preflight request') +} diff --git a/test/wpt/server/routes/redirect.mjs b/test/wpt/server/routes/redirect.mjs new file mode 100644 index 0000000..46770cf --- /dev/null +++ b/test/wpt/server/routes/redirect.mjs @@ -0,0 +1,104 @@ +import { setTimeout } from 'timers/promises' + +const stash = new Map() + +/** + * @see https://github.com/web-platform-tests/wpt/blob/master/fetch/connection-pool/resources/network-partition-key.py + * @param {Parameters[0]} req + * @param {Parameters[1]} res + * @param {URL} fullUrl + */ +export async function route (req, res, fullUrl) { + const { searchParams } = fullUrl + + let stashedData = { count: 0, preflight: 0 } + let status = 302 + res.setHeader('Content-Type', 'text/plain') + res.setHeader('Cache-Control', 'no-cache') + res.setHeader('Pragma', 'no-cache') + + if (Object.hasOwn(req.headers, 'origin')) { + res.setHeader('Access-Control-Allow-Origin', req.headers.origin ?? '') + res.setHeader('Access-Control-Allow-Credentials', 'true') + } else { + res.setHeader('Access-Control-Allow-Origin', '*') + } + + let token = null + if (searchParams.has('token')) { + token = searchParams.get('token') + const data = stash.get(token) + stash.delete(token) + if (data) { + stashedData = data + } + } + + if (req.method === 'OPTIONS') { + if (searchParams.has('allow_headers')) { + res.setHeader('Access-Control-Allow-Headers', searchParams.get('allow_headers')) + } + + stashedData.preflight = '1' + + if (!searchParams.has('redirect_preflight')) { + if (token) { + stash.set(searchParams.get('token'), stashedData) + } + + res.statusCode = 200 + res.end('') + return + } + } + + if (searchParams.has('redirect_status')) { + status = parseInt(searchParams.get('redirect_status')) + } + + stashedData.count += 1 + + if (searchParams.has('location')) { + let url = decodeURIComponent(searchParams.get('location')) + + if (!searchParams.has('simple')) { + const scheme = new URL(url, fullUrl).protocol + + if (scheme === 'http:' || scheme === 'https:') { + url += url.includes('?') ? '&' : '?' + + for (const [key, value] of searchParams) { + url += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(value) + } + + url += '&count=' + stashedData.count + } + } + + res.setHeader('location', url) + } + + if (searchParams.has('redirect_referrerpolicy')) { + res.setHeader('Referrer-Policy', searchParams.get('redirect_referrerpolicy')) + } + + if (searchParams.has('delay')) { + await setTimeout(parseFloat(searchParams.get('delay') ?? 0)) + } + + if (token) { + stash.set(searchParams.get('token'), stashedData) + + if (searchParams.has('max_count')) { + const maxCount = parseInt(searchParams.get('max_count')) + + if (stashedData.count > maxCount) { + res.end((stashedData.count - 1).toString()) + return + } + } + } + + res.statusCode = status + res.end('') +} diff --git a/test/wpt/server/server.mjs b/test/wpt/server/server.mjs new file mode 100644 index 0000000..82b9080 --- /dev/null +++ b/test/wpt/server/server.mjs @@ -0,0 +1,397 @@ +import { once } from 'node:events' +import { createServer } from 'node:http' +import { join } from 'node:path' +import process from 'node:process' +import { fileURLToPath } from 'node:url' +import { createReadStream, readFileSync, existsSync } from 'node:fs' +import { setTimeout as sleep } from 'node:timers/promises' +import { route as networkPartitionRoute } from './routes/network-partition-key.mjs' +import { route as redirectRoute } from './routes/redirect.mjs' + +const tests = fileURLToPath(join(import.meta.url, '../../tests')) + +// https://web-platform-tests.org/tools/wptserve/docs/stash.html +class Stash extends Map { + take (key) { + if (this.has(key)) { + const value = this.get(key) + + this.delete(key) + return value.value + } + } + + put (key, value, path) { + this.set(key, { value, path }) + } +} + +const stash = new Stash() + +const server = createServer(async (req, res) => { + const fullUrl = new URL(req.url, `http://localhost:${server.address().port}`) + + switch (fullUrl.pathname) { + case '/service-workers/cache-storage/resources/blank.html': { + res.setHeader('content-type', 'text/html') + // fall through + } + case '/service-workers/cache-storage/resources/simple.txt': + case '/fetch/content-encoding/resources/foo.octetstream.gz': + case '/fetch/content-encoding/resources/foo.text.gz': + case '/fetch/api/resources/cors-top.txt': + case '/fetch/api/resources/top.txt': + case '/mimesniff/mime-types/resources/generated-mime-types.json': + case '/mimesniff/mime-types/resources/mime-types.json': + case '/interfaces/dom.idl': + case '/interfaces/url.idl': + case '/interfaces/html.idl': + case '/interfaces/fetch.idl': + case '/interfaces/FileAPI.idl': + case '/interfaces/websockets.idl': + case '/interfaces/referrer-policy.idl': + case '/xhr/resources/utf16-bom.json': + case '/fetch/data-urls/resources/base64.json': + case '/fetch/data-urls/resources/data-urls.json': + case '/fetch/api/resources/empty.txt': + case '/fetch/api/resources/data.json': { + // If this specific resources requires custom headers + const customHeadersPath = join(tests, fullUrl.pathname + '.headers') + if (existsSync(customHeadersPath)) { + const headers = readFileSync(customHeadersPath, 'utf-8') + .trim() + .split(/\r?\n/g) + .map((h) => h.split(': ')) + + for (const [key, value] of headers) { + if (!key || !value) { + console.warn(`Skipping ${key}:${value} header pair`) + continue + } + res.setHeader(key, value) + } + } + + // https://github.com/web-platform-tests/wpt/blob/6ae3f702a332e8399fab778c831db6b7dca3f1c6/fetch/api/resources/data.json + return createReadStream(join(tests, fullUrl.pathname)) + .on('end', () => res.end()) + .pipe(res) + } + case '/fetch/api/resources/trickle.py': { + // Note: python's time.sleep(...) takes seconds, while setTimeout + // takes ms. + const delay = parseFloat(fullUrl.searchParams.get('ms') ?? 500) + const count = parseInt(fullUrl.searchParams.get('count') ?? 50) + + // eslint-disable-next-line no-unused-vars + for await (const chunk of req); // read request body + + await sleep(delay) + + if (!fullUrl.searchParams.has('notype')) { + res.setHeader('Content-type', 'text/plain') + } + + res.statusCode = 200 + await sleep(delay) + + for (let i = 0; i < count; i++) { + res.write('TEST_TRICKLE\n') + await sleep(delay) + } + + res.end() + break + } + case '/fetch/api/resources/infinite-slow-response.py': { + // https://github.com/web-platform-tests/wpt/blob/master/fetch/api/resources/infinite-slow-response.py + const stateKey = fullUrl.searchParams.get('stateKey') ?? '' + const abortKey = fullUrl.searchParams.get('abortKey') ?? '' + + if (stateKey) { + stash.put(stateKey, 'open', fullUrl.pathname) + } + + res.setHeader('Content-Type', 'text/plain') + res.statusCode = 200 + + res.write('.'.repeat(2048)) + + while (true) { + if (!res.write('.')) { + break + } else if (abortKey && stash.take(abortKey)) { + break + } + + await sleep(100) + } + + if (stateKey) { + stash.put(stateKey, 'closed', fullUrl.pathname) + } + + res.end() + return + } + case '/fetch/api/resources/stash-take.py': { + // https://github.com/web-platform-tests/wpt/blob/6ae3f702a332e8399fab778c831db6b7dca3f1c6/fetch/api/resources/stash-take.py + + const key = fullUrl.searchParams.get('key') + res.setHeader('Access-Control-Allow-Origin', '*') + + const took = stash.take(key, fullUrl.pathname) ?? null + + res.write(JSON.stringify(took)) + return res.end() + } + case '/fetch/api/resources/echo-content.py': { + res.setHeader('X-Request-Method', req.method) + res.setHeader('X-Request-Content-Length', req.headers['content-length'] ?? 'NO') + res.setHeader('X-Request-Content-Type', req.headers['content-type'] ?? 'NO') + res.setHeader('Content-Type', 'text/plain') + + for await (const chunk of req) { + res.write(chunk) + } + + res.end() + break + } + case '/fetch/api/resources/status.py': { + const code = parseInt(fullUrl.searchParams.get('code') ?? 200) + const text = fullUrl.searchParams.get('text') ?? 'OMG' + const content = fullUrl.searchParams.get('content') ?? '' + const type = fullUrl.searchParams.get('type') ?? '' + res.statusCode = code + res.statusMessage = text + res.setHeader('Content-Type', type) + res.setHeader('X-Request-Method', req.method) + res.end(content) + break + } + case '/fetch/api/resources/inspect-headers.py': { + const query = fullUrl.searchParams + const checkedHeaders = query.get('headers') + ?.split('|') + .map(h => h.toLowerCase()) ?? [] + + if (query.has('headers')) { + for (const header of checkedHeaders) { + if (Object.hasOwn(req.headers, header)) { + res.setHeader(`x-request-${header}`, req.headers[header] ?? '') + } + } + } + + if (query.has('cors')) { + if (Object.hasOwn(req.headers, 'origin')) { + res.setHeader('Access-Control-Allow-Origin', req.headers.origin ?? '') + } else { + res.setHeader('Access-Control-Allow-Origin', '*') + } + + res.setHeader('Access-Control-Allow-Credentials', 'true') + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, HEAD') + const exposedHeaders = checkedHeaders.map(h => `x-request-${h}`).join(', ') + res.setHeader('Access-Control-Expose-Headers', exposedHeaders) + if (query.has('allow_headers')) { + res.setHeader('Access-Control-Allow-Headers', query.get('allowed_headers')) + } else { + res.setHeader('Access-Control-Allow-Headers', Object.keys(req.headers).join(', ')) + } + } + + res.setHeader('content-type', 'text/plain') + res.end('') + break + } + case '/xhr/resources/parse-headers.py': { + if (fullUrl.searchParams.has('my-custom-header')) { + const val = fullUrl.searchParams.get('my-custom-header').toLowerCase() + // res.setHeader does validation which may prevent some tests from running. + res.socket.write( + `HTTP/1.1 200 OK\r\nmy-custom-header: ${val}\r\n\r\n` + ) + } + res.end('') + break + } + case '/fetch/api/resources/bad-chunk-encoding.py': { + const query = fullUrl.searchParams + + const delay = parseFloat(query.get('ms') ?? 1000) + const count = parseInt(query.get('count') ?? 50) + await sleep(delay) + res.socket.write( + 'HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n' + ) + await sleep(delay) + + for (let i = 0; i < count; i++) { + res.socket.write('a\r\nTEST_CHUNK\r\n') + await sleep(delay) + } + + res.end('garbage') + break + } + case '/xhr/resources/headers-www-authenticate.asis': + case '/xhr/resources/headers-some-are-empty.asis': + case '/xhr/resources/headers-basic': + case '/xhr/resources/headers-double-empty.asis': + case '/xhr/resources/header-content-length-twice.asis': + case '/xhr/resources/header-content-length.asis': { + let asis = readFileSync(join(tests, fullUrl.pathname), 'utf-8') + asis = asis.replace(/\n/g, '\r\n') + asis = `${asis}\r\n` + + res.socket.write(asis) + res.end() + break + } + case '/fetch/connection-pool/resources/network-partition-key.py': { + return networkPartitionRoute(req, res, fullUrl) + } + case '/resources/top.txt': { + return createReadStream(join(tests, 'fetch/api/', fullUrl.pathname)) + .on('end', () => res.end()) + .pipe(res) + } + case '/fetch/api/resources/redirect.py': { + return redirectRoute(req, res, fullUrl) + } + case '/fetch/api/resources/method.py': { + if (fullUrl.searchParams.has('cors')) { + res.setHeader('Access-Control-Allow-Origin', '*') + res.setHeader('Access-Control-Allow-Credentials', 'true') + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, FOO') + res.setHeader('Access-Control-Allow-Headers', 'x-test, x-foo') + res.setHeader('Access-Control-Expose-Headers', 'x-request-method') + } + + res.setHeader('x-request-method', req.method) + res.setHeader('x-request-content-type', req.headers['content-type'] ?? 'NO') + res.setHeader('x-request-content-length', req.headers['content-length'] ?? 'NO') + res.setHeader('x-request-content-encoding', req.headers['content-encoding'] ?? 'NO') + res.setHeader('x-request-content-language', req.headers['content-language'] ?? 'NO') + res.setHeader('x-request-content-location', req.headers['content-location'] ?? 'NO') + + for await (const chunk of req) { + res.write(chunk) + } + + res.end() + return + } + case '/fetch/api/resources/clean-stash.py': { + const token = fullUrl.searchParams.get('token') + const took = stash.take(token) + + if (took) { + res.end('1') + } else { + res.end('0') + } + + break + } + case '/fetch/content-encoding/resources/bad-gzip-body.py': { + res.setHeader('Content-Encoding', 'gzip') + res.end('not actually gzip') + break + } + case '/fetch/api/resources/dump-authorization-header.py': { + res.setHeader('Content-Type', 'text/html') + res.setHeader('Cache-Control', 'no-cache') + + if (req.headers.origin) { + res.setHeader('Access-Control-Allow-Origin', req.headers.origin) + res.setHeader('Access-Control-Allow-Credentials', 'true') + } else { + res.setHeader('Access-Control-Allow-Origin', '*') + } + + res.setHeader('Access-Control-Allow-Headers', 'Authorization') + res.statusCode = 200 + + if (req.headers.authorization) { + res.end(req.headers.authorization) + return + } + + res.end('none') + break + } + case '/xhr/resources/echo-headers.py': { + res.statusCode = 200 + res.setHeader('Content-Type', 'text/plain') + + // wpt runner sends this as 1 chunk + let body = '' + + for (let i = 0; i < req.rawHeaders.length; i += 2) { + const key = req.rawHeaders[i] + const value = req.rawHeaders[i + 1] + + body += `${key}: ${value}` + } + + res.end(body) + break + } + case '/fetch/api/resources/authentication.py': { + const auth = Buffer.from(req.headers.authorization.slice('Basic '.length), 'base64') + const [user, password] = auth.toString().split(':') + + if (user === 'user' && password === 'password') { + res.end('Authentication done') + return + } + + const realm = fullUrl.searchParams.get('realm') ?? 'test' + + res.statusCode = 401 + res.setHeader('WWW-Authenticate', `Basic realm="${realm}"`) + res.end('Please login with credentials \'user\' and \'password\'') + return + } + case '/fetch/api/resources/redirect-empty-location.py': { + res.setHeader('location', '') + res.statusCode = 302 + res.end('') + return + } + case '/service-workers/cache-storage/resources/fetch-status.py': { + const status = Number(fullUrl.searchParams.get('status')) + + res.statusCode = status + res.end() + return + } + default: { + res.statusCode = 200 + res.end(fullUrl.toString()) + } + } +}).listen(0) + +await once(server, 'listening') + +const send = (message) => { + if (typeof process.send === 'function') { + process.send(message) + } +} + +const url = `http://localhost:${server.address().port}` +console.log('server opened ' + url) +send({ server: url }) + +process.on('message', (message) => { + if (message === 'shutdown') { + server.close((err) => process.exit(err ? 1 : 0)) + } +}) + +export { server } diff --git a/test/wpt/server/websocket.mjs b/test/wpt/server/websocket.mjs new file mode 100644 index 0000000..cc8ce78 --- /dev/null +++ b/test/wpt/server/websocket.mjs @@ -0,0 +1,46 @@ +import { WebSocketServer } from 'ws' +import { server } from './server.mjs' + +// The file router server handles sending the url, closing, +// and sending messages back to the main process for us. +// The types for WebSocketServer don't include a `request` +// event, so I'm unsure if we can stop relying on server. + +const wss = new WebSocketServer({ + server, + handleProtocols: (protocols) => [...protocols].join(', ') +}) + +wss.on('connection', (ws, request) => { + ws.on('message', (data, isBinary) => { + const str = data.toString('utf-8') + + if (request.url === '/receive-many-with-backpressure') { + setTimeout(() => { + ws.send(str.length.toString(), { binary: false }) + }, 100) + return + } + + if (str === 'Goodbye') { + // Close-server-initiated-close.any.js sends a "Goodbye" message + // when it wants the server to close the connection. + ws.close(1000) + return + } + + ws.send(data, { binary: isBinary }) + }) + + // Some tests, such as `Create-blocked-port.any.js` do NOT + // close the connection automatically. + const timeout = setTimeout(() => { + if (ws.readyState !== ws.CLOSED && ws.readyState !== ws.CLOSING) { + ws.close() + } + }, 2500) + + ws.on('close', () => { + clearTimeout(timeout) + }) +}) diff --git a/test/wpt/start-FileAPI.mjs b/test/wpt/start-FileAPI.mjs new file mode 100644 index 0000000..5a92ab8 --- /dev/null +++ b/test/wpt/start-FileAPI.mjs @@ -0,0 +1,26 @@ +import { WPTRunner } from './runner/runner.mjs' +import { join } from 'path' +import { fileURLToPath } from 'url' +import { fork } from 'child_process' +import { on } from 'events' + +const serverPath = fileURLToPath(join(import.meta.url, '../server/server.mjs')) + +const child = fork(serverPath, [], { + stdio: ['pipe', 'pipe', 'pipe', 'ipc'] +}) + +child.on('exit', (code) => process.exit(code)) + +for await (const [message] of on(child, 'message')) { + if (message.server) { + const runner = new WPTRunner('FileAPI', message.server) + runner.run() + + runner.once('completion', () => { + if (child.connected) { + child.send('shutdown') + } + }) + } +} diff --git a/test/wpt/start-cacheStorage.mjs b/test/wpt/start-cacheStorage.mjs new file mode 100644 index 0000000..a630e05 --- /dev/null +++ b/test/wpt/start-cacheStorage.mjs @@ -0,0 +1,26 @@ +import { WPTRunner } from './runner/runner.mjs' +import { join } from 'path' +import { fileURLToPath } from 'url' +import { fork } from 'child_process' +import { on } from 'events' + +const serverPath = fileURLToPath(join(import.meta.url, '../server/server.mjs')) + +const child = fork(serverPath, [], { + stdio: ['pipe', 'pipe', 'pipe', 'ipc'] +}) + +child.on('exit', (code) => process.exit(code)) + +for await (const [message] of on(child, 'message')) { + if (message.server) { + const runner = new WPTRunner('service-workers/cache-storage', message.server) + runner.run() + + runner.once('completion', () => { + if (child.connected) { + child.send('shutdown') + } + }) + } +} diff --git a/test/wpt/start-fetch.mjs b/test/wpt/start-fetch.mjs new file mode 100644 index 0000000..59c9f83 --- /dev/null +++ b/test/wpt/start-fetch.mjs @@ -0,0 +1,31 @@ +import { WPTRunner } from './runner/runner.mjs' +import { join } from 'path' +import { fileURLToPath } from 'url' +import { fork } from 'child_process' +import { on } from 'events' + +const { WPT_REPORT } = process.env + +const serverPath = fileURLToPath(join(import.meta.url, '../server/server.mjs')) + +const child = fork(serverPath, [], { + stdio: ['pipe', 'pipe', 'pipe', 'ipc'] +}) + +child.on('exit', (code) => process.exit(code)) + +for await (const [message] of on(child, 'message')) { + if (message.server) { + const runner = new WPTRunner('fetch', message.server, { + appendReport: !!WPT_REPORT, + reportPath: WPT_REPORT + }) + runner.run() + + runner.once('completion', () => { + if (child.connected) { + child.send('shutdown') + } + }) + } +} diff --git a/test/wpt/start-mimesniff.mjs b/test/wpt/start-mimesniff.mjs new file mode 100644 index 0000000..fbdb9bf --- /dev/null +++ b/test/wpt/start-mimesniff.mjs @@ -0,0 +1,31 @@ +import { WPTRunner } from './runner/runner.mjs' +import { join } from 'path' +import { fileURLToPath } from 'url' +import { fork } from 'child_process' +import { on } from 'events' + +const { WPT_REPORT } = process.env + +const serverPath = fileURLToPath(join(import.meta.url, '../server/server.mjs')) + +const child = fork(serverPath, [], { + stdio: ['pipe', 'pipe', 'pipe', 'ipc'] +}) + +child.on('exit', (code) => process.exit(code)) + +for await (const [message] of on(child, 'message')) { + if (message.server) { + const runner = new WPTRunner('mimesniff', message.server, { + appendReport: !!WPT_REPORT, + reportPath: WPT_REPORT + }) + runner.run() + + runner.once('completion', () => { + if (child.connected) { + child.send('shutdown') + } + }) + } +} diff --git a/test/wpt/start-websockets.mjs b/test/wpt/start-websockets.mjs new file mode 100644 index 0000000..79aa297 --- /dev/null +++ b/test/wpt/start-websockets.mjs @@ -0,0 +1,47 @@ +import { WPTRunner } from './runner/runner.mjs' +import { join } from 'path' +import { fileURLToPath } from 'url' +import { fork } from 'child_process' +import { on } from 'events' + +const { WPT_REPORT } = process.env + +function isGlobalAvailable () { + if (typeof WebSocket !== 'undefined') { + return true + } + + const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) + + // TODO: keep this up to date when backports to earlier majors happen + return nodeMajor >= 21 || (nodeMajor === 20 && nodeMinor >= 10) +} + +if (process.env.CI) { + // TODO(@KhafraDev): figure out *why* these tests are flaky in the CI. + // process.exit(0) +} + +const serverPath = fileURLToPath(join(import.meta.url, '../server/websocket.mjs')) + +const child = fork(serverPath, [], { + stdio: ['pipe', 'pipe', 'pipe', 'ipc'] +}) + +child.on('exit', (code) => process.exit(code)) + +for await (const [message] of on(child, 'message')) { + if (message.server) { + const runner = new WPTRunner('websockets', message.server, { + appendReport: !!WPT_REPORT && isGlobalAvailable(), + reportPath: WPT_REPORT + }) + runner.run() + + runner.once('completion', () => { + if (child.connected) { + child.send('shutdown') + } + }) + } +} diff --git a/test/wpt/start-xhr.mjs b/test/wpt/start-xhr.mjs new file mode 100644 index 0000000..08f82eb --- /dev/null +++ b/test/wpt/start-xhr.mjs @@ -0,0 +1,12 @@ +import { WPTRunner } from './runner/runner.mjs' +import { once } from 'events' + +const { WPT_REPORT } = process.env + +const runner = new WPTRunner('xhr/formdata', 'http://localhost:3333', { + appendReport: !!WPT_REPORT, + reportPath: WPT_REPORT +}) +runner.run() + +await once(runner, 'completion') diff --git a/test/wpt/status/FileAPI.status.json b/test/wpt/status/FileAPI.status.json new file mode 100644 index 0000000..c64d255 --- /dev/null +++ b/test/wpt/status/FileAPI.status.json @@ -0,0 +1,75 @@ +{ + "file": { + "File-constructor.any.js": { + "flaky": [ + "Using type in File constructor: nonparsable" + ] + } + }, + "blob": { + "Blob-constructor.any.js": { + "skip": true + }, + "Blob-stream.any.js": { + "fail": [ + "Reading Blob.stream() with BYOB reader" + ] + } + }, + "url": { + "url-with-xhr.any.js": { + "skip": true + }, + "url-with-fetch.any.js": { + "note": "needs investigation", + "fail": [ + "Only exact matches should revoke URLs, using fetch", + "Revoke blob URL after creating Request, will fetch", + "Revoke blob URL after creating Request, then clone Request, will fetch" + ] + }, + "url-format.any.js": { + "fail": [ + "Origin of Blob URL matches our origin", + "Blob URL parses correctly", + "Origin of Blob URL matches our origin for Files" + ] + } + }, + "reading-data-section": { + "filereader_result.any.js": { + "note": "has to do with html microtask queue being different than queueMicrotask", + "skip": true + }, + "filereader_events.any.js": { + "note": "has to do with html microtask queue being different than queueMicrotask", + "fail": [ + "events are dispatched in the correct order for an empty blob", + "events are dispatched in the correct order for a non-empty blob" + ] + } + }, + "idlharness.any.js": { + "note": "These flaky tests only fail in < node v19; add in a way to mark them as such eventually", + "flaky": [ + "Blob interface: attribute size", + "Blob interface: attribute type", + "Blob interface: operation slice(optional long long, optional long long, optional DOMString)", + "Blob interface: operation stream()", + "Blob interface: operation text()", + "Blob interface: operation arrayBuffer()", + "URL interface: operation createObjectURL((Blob or MediaSource))", + "URL interface: operation revokeObjectURL(DOMString)" + ], + "fail": [ + "FileList interface: existence and properties of interface object", + "FileList interface object length", + "FileList interface object name", + "FileList interface: existence and properties of interface prototype object", + "FileList interface: existence and properties of interface prototype object's \"constructor\" property", + "FileList interface: existence and properties of interface prototype object's @@unscopables property", + "FileList interface: operation item(unsigned long)", + "FileList interface: attribute length" + ] + } +} diff --git a/test/wpt/status/fetch.status.json b/test/wpt/status/fetch.status.json new file mode 100644 index 0000000..5910bf3 --- /dev/null +++ b/test/wpt/status/fetch.status.json @@ -0,0 +1,457 @@ +{ + "api": { + "abort": { + "general.any.js": { + "note": "TODO(@KhafraDev): Clone aborts with original controller can probably be fixed", + "fail": [ + "Already aborted signal rejects immediately", + "Underlying connection is closed when aborting after receiving response - no-cors", + "Stream errors once aborted. Underlying connection closed.", + "Readable stream synchronously cancels with AbortError if aborted before reading", + "Clone aborts with original controller" + ] + }, + "cache.https.any.js": { + "note": "undici doesn't implement http caching", + "skip": true + } + }, + "basic": { + "conditional-get.any.js": { + "fail": [ + "Testing conditional GET with ETags" + ] + }, + "header-value-combining.any.js": { + "fail": [ + "response.headers.get('content-length') expects 0, 0", + "response.headers.get('foo-test') expects 1, 2, 3", + "response.headers.get('heya') expects , \\x0B\f, 1, , , 2" + ], + "flaky": [ + "response.headers.get('content-length') expects 0", + "response.headers.get('double-trouble') expects , ", + "response.headers.get('www-authenticate') expects 1, 2, 3, 4" + ] + }, + "integrity.sub.any.js": { + "fail": [ + "Empty string integrity for opaque response" + ] + }, + "keepalive.any.js": { + "note": "document is not defined", + "skip": true + }, + "mode-no-cors.sub.any.js": { + "note": "undici doesn't implement CORs", + "skip": true + }, + "mode-same-origin.any.js": { + "note": "undici doesn't respect RequestInit.mode", + "skip": true + }, + "referrer.any.js": { + "fail": [ + "origin-when-cross-origin policy on a cross-origin URL", + "origin-when-cross-origin policy on a cross-origin URL after same-origin redirection", + "origin-when-cross-origin policy on a same-origin URL after cross-origin redirection", + "origin-when-cross-origin policy on a same-origin URL" + ] + }, + "request-forbidden-headers.any.js": { + "note": "undici doesn't filter headers", + "skip": true + }, + "request-headers.any.js": { + "fail": [ + "Fetch with Chicken", + "Fetch with Chicken with body", + "Fetch with TacO and mode \"same-origin\" needs an Origin header", + "Fetch with TacO and mode \"cors\" needs an Origin header" + ] + }, + "request-referrer.any.js": { + "note": "TODO(@KhafraDev): url referrer test could probably be fixed", + "fail": [ + "about:client referrer", + "url referrer" + ] + }, + "request-upload.any.js": { + "fail": [ + "Fetch with POST with text body on 421 response should be retried once on new connection." + ] + }, + "request-upload.h2.any.js": { + "note": "undici doesn't support http/2", + "skip": true + }, + "status.h2.any.js": { + "note": "undici doesn't support http/2", + "skip": true + }, + "stream-safe-creation.any.js": { + "note": "tests are very finnicky", + "fail": [ + "throwing Object.prototype.type accessor should not affect stream creation by 'fetch'", + "Object.prototype.type accessor returning invalid value should not affect stream creation by 'fetch'", + "throwing Object.prototype.highWaterMark accessor should not affect stream creation by 'fetch'", + "Object.prototype.highWaterMark accessor returning invalid value should not affect stream creation by 'fetch'" + ] + } + }, + "body": { + "mime-type.any.js": { + "note": "fails on all platforms, https://wpt.fyi/results/fetch/api/body/mime-type.any.html?label=master&label=experimental&product=chrome&product=firefox&product=safari&product=node.js&product=deno&aligned", + "fail": [ + "Response: Extract a MIME type with clone" + ] + } + }, + "cors": { + "note": "undici doesn't implement CORs", + "skip": true + }, + "credentials": { + "authentication-redirection.any.js": { + "note": "connects to https server", + "fail": [ + "getAuthorizationHeaderValue - cross origin redirection", + "getAuthorizationHeaderValue - same origin redirection" + ] + }, + "cookies.any.js": { + "fail": [ + "Include mode: 1 cookie", + "Include mode: 2 cookies", + "Same-origin mode: 1 cookie", + "Same-origin mode: 2 cookies" + ] + } + }, + "fetch-later": { + "note": "this is not part of the spec, only a proposal", + "skip": true + }, + "headers": { + "header-setcookie.any.js": { + "note": "undici doesn't filter headers", + "fail": [ + "Set-Cookie is a forbidden response header" + ] + }, + "header-values-normalize.any.js": { + "note": "TODO(@KhafraDev): https://github.com/nodejs/undici/issues/1680", + "fail": [ + "XMLHttpRequest with value %00", + "XMLHttpRequest with value %01", + "XMLHttpRequest with value %02", + "XMLHttpRequest with value %03", + "XMLHttpRequest with value %04", + "XMLHttpRequest with value %05", + "XMLHttpRequest with value %06", + "XMLHttpRequest with value %07", + "XMLHttpRequest with value %08", + "XMLHttpRequest with value %09", + "XMLHttpRequest with value %0A", + "XMLHttpRequest with value %0D", + "XMLHttpRequest with value %0E", + "XMLHttpRequest with value %0F", + "XMLHttpRequest with value %10", + "XMLHttpRequest with value %11", + "XMLHttpRequest with value %12", + "XMLHttpRequest with value %13", + "XMLHttpRequest with value %14", + "XMLHttpRequest with value %15", + "XMLHttpRequest with value %16", + "XMLHttpRequest with value %17", + "XMLHttpRequest with value %18", + "XMLHttpRequest with value %19", + "XMLHttpRequest with value %1A", + "XMLHttpRequest with value %1B", + "XMLHttpRequest with value %1C", + "XMLHttpRequest with value %1D", + "XMLHttpRequest with value %1E", + "XMLHttpRequest with value %1F", + "XMLHttpRequest with value %20", + "fetch() with value %01", + "fetch() with value %02", + "fetch() with value %03", + "fetch() with value %04", + "fetch() with value %05", + "fetch() with value %06", + "fetch() with value %07", + "fetch() with value %08", + "fetch() with value %0E", + "fetch() with value %0F", + "fetch() with value %10", + "fetch() with value %11", + "fetch() with value %12", + "fetch() with value %13", + "fetch() with value %14", + "fetch() with value %15", + "fetch() with value %16", + "fetch() with value %17", + "fetch() with value %18", + "fetch() with value %19", + "fetch() with value %1A", + "fetch() with value %1B", + "fetch() with value %1C", + "fetch() with value %1D", + "fetch() with value %1E", + "fetch() with value %1F" + ] + }, + "header-values.any.js": { + "fail": [ + "XMLHttpRequest with value x%00x needs to throw", + "XMLHttpRequest with value x%0Ax needs to throw", + "XMLHttpRequest with value x%0Dx needs to throw", + "XMLHttpRequest with all valid values", + "fetch() with all valid values" + ] + }, + "headers-no-cors.any.js": { + "note": "undici doesn't implement CORs", + "skip": true + } + }, + "redirect": { + "redirect-empty-location.any.js": { + "note": "undici handles redirect: manual differently than browsers", + "fail": [ + "redirect response with empty Location, manual mode" + ] + }, + "redirect-keepalive.any.js": { + "note": "document is not defined", + "skip": true + }, + "redirect-location-escape.tentative.any.js": { + "note": "TODO(@KhafraDev): crashes runner", + "skip": true + }, + "redirect-location.any.js": { + "note": "undici handles redirect: manual differently than browsers", + "fail": [ + "Redirect 301 in \"manual\" mode without location", + "Redirect 301 in \"manual\" mode with invalid location", + "Redirect 301 in \"manual\" mode with data location", + "Redirect 302 in \"manual\" mode without location", + "Redirect 302 in \"manual\" mode with invalid location", + "Redirect 302 in \"manual\" mode with data location", + "Redirect 303 in \"manual\" mode without location", + "Redirect 303 in \"manual\" mode with invalid location", + "Redirect 303 in \"manual\" mode with data location", + "Redirect 307 in \"manual\" mode without location", + "Redirect 307 in \"manual\" mode with invalid location", + "Redirect 307 in \"manual\" mode with data location", + "Redirect 308 in \"manual\" mode without location", + "Redirect 308 in \"manual\" mode with invalid location", + "Redirect 308 in \"manual\" mode with data location", + "Redirect 301 in \"manual\" mode with valid location", + "Redirect 302 in \"manual\" mode with valid location", + "Redirect 303 in \"manual\" mode with valid location", + "Redirect 307 in \"manual\" mode with valid location", + "Redirect 308 in \"manual\" mode with valid location" + ] + }, + "redirect-method.any.js": { + "fail": [ + "Redirect 303 with TESTING" + ] + }, + "redirect-mode.any.js": { + "note": "mode isn't respected", + "skip": true + }, + "redirect-origin.any.js": { + "note": "TODO(@KhafraDev): investigate", + "skip": true + }, + "redirect-referrer-override.any.js": { + "note": "TODO(@KhafraDev): investigate", + "skip": true + }, + "redirect-referrer.any.js": { + "note": "TODO(@KhafraDev): investigate", + "skip": true + }, + "redirect-upload.h2.any.js": { + "note": "undici doesn't support http/2", + "skip": true + } + }, + "request": { + "request-cache-default-conditional.any.js": { + "note": "undici doesn't implement an http cache", + "skip": true + }, + "request-cache-default.any.js": { + "note": "undici doesn't implement an http cache", + "skip": true + }, + "request-cache-force-cache.any.js": { + "note": "undici doesn't implement an http cache", + "skip": true + }, + "request-cache-no-cache.any.js": { + "note": "undici doesn't implement an http cache", + "skip": true + }, + "request-cache-no-store.any.js": { + "note": "undici doesn't implement an http cache", + "skip": true + }, + "request-cache-only-if-cached.any.js": { + "note": "undici doesn't implement an http cache", + "skip": true + }, + "request-cache-reload.any.js": { + "note": "undici doesn't implement an http cache", + "skip": true + }, + "request-consume-empty.any.js": { + "note": "the semantics about this test are being discussed - https://github.com/web-platform-tests/wpt/pull/3950", + "fail": [ + "Consume empty FormData request body as text" + ] + }, + "request-disturbed.any.js": { + "note": "this test fails in all other platforms - https://wpt.fyi/results/fetch/api/request/request-disturbed.any.html?label=master&label=experimental&product=chrome&product=firefox&product=safari&product=deno&aligned&view=subtest", + "fail": [ + "Input request used for creating new request became disturbed even if body is not used" + ] + }, + "request-headers.any.js": { + "note": "undici doesn't filter headers", + "fail": [ + "Adding invalid request header \"Accept-Charset: KO\"", + "Adding invalid request header \"accept-charset: KO\"", + "Adding invalid request header \"ACCEPT-ENCODING: KO\"", + "Adding invalid request header \"Accept-Encoding: KO\"", + "Adding invalid request header \"Access-Control-Request-Headers: KO\"", + "Adding invalid request header \"Access-Control-Request-Method: KO\"", + "Adding invalid request header \"Access-Control-Request-Private-Network: KO\"", + "Adding invalid request header \"Connection: KO\"", + "Adding invalid request header \"Content-Length: KO\"", + "Adding invalid request header \"Cookie: KO\"", + "Adding invalid request header \"Cookie2: KO\"", + "Adding invalid request header \"Date: KO\"", + "Adding invalid request header \"DNT: KO\"", + "Adding invalid request header \"Expect: KO\"", + "Adding invalid request header \"Host: KO\"", + "Adding invalid request header \"Keep-Alive: KO\"", + "Adding invalid request header \"Origin: KO\"", + "Adding invalid request header \"Referer: KO\"", + "Adding invalid request header \"Set-Cookie: KO\"", + "Adding invalid request header \"TE: KO\"", + "Adding invalid request header \"Trailer: KO\"", + "Adding invalid request header \"Transfer-Encoding: KO\"", + "Adding invalid request header \"Upgrade: KO\"", + "Adding invalid request header \"Via: KO\"", + "Adding invalid request header \"Proxy-: KO\"", + "Adding invalid request header \"proxy-a: KO\"", + "Adding invalid request header \"Sec-: KO\"", + "Adding invalid request header \"sec-b: KO\"", + "Adding invalid no-cors request header \"Content-Type: KO\"", + "Adding invalid no-cors request header \"Potato: KO\"", + "Adding invalid no-cors request header \"proxy: KO\"", + "Adding invalid no-cors request header \"proxya: KO\"", + "Adding invalid no-cors request header \"sec: KO\"", + "Adding invalid no-cors request header \"secb: KO\"", + "Adding invalid no-cors request header \"Empty-Value: \"", + "Check that request constructor is filtering headers provided as init parameter", + "Check that no-cors request constructor is filtering headers provided as init parameter", + "Check that no-cors request constructor is filtering headers provided as part of request parameter" + ] + }, + "request-init-priority.any.js": { + "note": "undici doesn't implement priority hints, yet(?)", + "skip": true + } + }, + "response": { + "response-clone.any.js": { + "fail": [ + "Check response clone use structureClone for teed ReadableStreams (ArrayBufferchunk)", + "Check response clone use structureClone for teed ReadableStreams (DataViewchunk)" + ] + }, + "response-consume-empty.any.js": { + "fail": [ + "Consume empty FormData response body as text" + ] + }, + "response-consume-stream.any.js": { + "fail": [ + "Read blob response's body as readableStream with mode=byob", + "Read text response's body as readableStream with mode=byob", + "Read URLSearchParams response's body as readableStream with mode=byob", + "Read array buffer response's body as readableStream with mode=byob", + "Read form data response's body as readableStream with mode=byob" + ] + }, + "response-error-from-stream.any.js": { + "fail": [ + "ReadableStream start() Error propagates to Response.formData() Promise", + "ReadableStream pull() Error propagates to Response.formData() Promise" + ] + }, + "response-stream-with-broken-then.any.js": { + "note": "this is a bug in webstreams, see https://github.com/nodejs/node/issues/46786", + "skip": true + } + } + }, + "content-length": { + "api-and-duplicate-headers.any.js": { + "fail": [ + "XMLHttpRequest and duplicate Content-Length/Content-Type headers", + "fetch() and duplicate Content-Length/Content-Type headers" + ] + } + }, + "cross-origin-resource-policy": { + "note": "undici doesn't implement CORs", + "skip": true + }, + "http-cache": { + "note": "undici doesn't implement http caching", + "skip": true + }, + "metadata": { + "note": "undici doesn't respect RequestInit.mode", + "skip": true + }, + "orb": { + "tentative": { + "note": "undici doesn't implement orb", + "skip": true + } + }, + "range": { + "note": "undici doesn't respect range header", + "skip": true + }, + "security": { + "1xx-response.any.js": { + "fail": [ + "Status(100) should be ignored.", + "Status(101) should be accepted, with removing body.", + "Status(103) should be ignored.", + "Status(199) should be ignored." + ] + } + }, + "stale-while-revalidate": { + "note": "undici doesn't implement http caching", + "skip": true + }, + "idlharness.any.js": { + "flaky": [ + "Window interface: operation fetch(RequestInfo, optional RequestInit)" + ] + } +} diff --git a/test/wpt/status/mimesniff.status.json b/test/wpt/status/mimesniff.status.json new file mode 100644 index 0000000..ab9a3d3 --- /dev/null +++ b/test/wpt/status/mimesniff.status.json @@ -0,0 +1,7 @@ +{ + "mime-types": { + "parsing.any.js": { + "allowUnexpectedFailures": true + } + } +} diff --git a/test/wpt/status/service-workers/cache-storage.status.json b/test/wpt/status/service-workers/cache-storage.status.json new file mode 100644 index 0000000..09a291e --- /dev/null +++ b/test/wpt/status/service-workers/cache-storage.status.json @@ -0,0 +1,24 @@ +{ + "cache-storage": { + "cache-abort.https.any.js": { + "skip": true + }, + "cache-storage-buckets.https.any.js": { + "skip": true, + "note": "navigator is not defined" + }, + "cache-put.https.any.js": { + "note": "probably can be fixed", + "fail": [ + "Cache.put with a VARY:* opaque response should not reject", + "Cache.put with opaque-filtered HTTP 206 response" + ] + }, + "cache-match.https.any.js": { + "note": "requires https server", + "fail": [ + "cors-exposed header should be stored correctly." + ] + } + } +} diff --git a/test/wpt/status/websockets.status.json b/test/wpt/status/websockets.status.json new file mode 100644 index 0000000..68bc6e2 --- /dev/null +++ b/test/wpt/status/websockets.status.json @@ -0,0 +1,115 @@ +{ + "stream": { + "tentative": { + "skip": true + } + }, + "Create-blocked-port.any.js": { + "note": "TODO(@KhafraDev): investigate failure", + "fail": [ + "Basic check" + ] + }, + "Send-binary-arraybufferview-float32.any.js": { + "note": "TODO(@KhafraDev): investigate failure", + "fail": [ + "Send binary data on a WebSocket - ArrayBufferView - Float32Array - Connection should be closed" + ] + }, + "Send-binary-arraybufferview-float64.any.js": { + "note": "TODO(@KhafraDev): investigate failure", + "fail": [ + "Send binary data on a WebSocket - ArrayBufferView - Float64Array - Connection should be closed" + ] + }, + "Send-binary-arraybufferview-int16-offset.any.js": { + "note": "TODO(@KhafraDev): investigate failure", + "fail": [ + "Send binary data on a WebSocket - ArrayBufferView - Int16Array with offset - Connection should be closed" + ] + }, + "Send-binary-arraybufferview-int32.any.js": { + "note": "TODO(@KhafraDev): investigate failure", + "fail": [ + "Send binary data on a WebSocket - ArrayBufferView - Int32Array - Connection should be closed" + ] + }, + "Send-binary-arraybufferview-uint16-offset-length.any.js": { + "note": "TODO(@KhafraDev): investigate failure", + "fail": [ + "Send binary data on a WebSocket - ArrayBufferView - Uint16Array with offset and length - Connection should be closed" + ] + }, + "Send-binary-arraybufferview-uint32-offset.any.js": { + "note": "TODO(@KhafraDev): investigate failure", + "fail": [ + "Send binary data on a WebSocket - ArrayBufferView - Uint32Array with offset - Connection should be closed" + ] + }, + "basic-auth.any.js": { + "note": "TODO(@KhafraDev): investigate failure", + "fail": [ + "HTTP basic authentication should work with WebSockets" + ] + }, + "Create-on-worker-shutdown.any.js": { + "skip": true, + "//": "Node.js workers are different from web workers & don't work with blob: urls" + }, + "Close-delayed.any.js": { + "skip": true + }, + "bufferedAmount-unchanged-by-sync-xhr.any.js": { + "skip": true, + "//": "Node.js doesn't have XMLHttpRequest nor does this test make sense regardless" + }, + "referrer.any.js": { + "skip": true + }, + "Send-binary-blob.any.js": { + "flaky": [ + "Send binary data on a WebSocket - Blob - Connection should be closed" + ] + }, + "Send-65K-data.any.js": { + "flaky": [ + "Send 65K data on a WebSocket - Connection should be closed" + ] + }, + "Send-binary-65K-arraybuffer.any.js": { + "flaky": [ + "Send 65K binary data on a WebSocket - ArrayBuffer - Connection should be closed" + ] + }, + "Send-0byte-data.any.js": { + "flaky": [ + "Send 0 byte data on a WebSocket - Connection should be closed" + ] + }, + "send-many-64K-messages-with-backpressure.any.js": { + "note": "probably flaky based on other flaky tests.", + "flaky": [ + "sending 50 messages of size 65536 with backpressure applied should not hang" + ] + }, + "back-forward-cache-with-closed-websocket-connection-ccns.tentative.window.js": { + "skip": true, + "note": "browser-only test" + }, + "back-forward-cache-with-closed-websocket-connection.window.js": { + "skip": true, + "note": "browser-only test" + }, + "back-forward-cache-with-open-websocket-connection-ccns.tentative.window.js": { + "skip": true, + "note": "browser-only test" + }, + "back-forward-cache-with-open-websocket-connection.window.js": { + "skip": true, + "note": "browser-only test" + }, + "mixed-content.https.any.js": { + "note": "node has no concept of origin, thus there is no 'secure' or 'insecure' contexts", + "skip": true + } +} diff --git a/test/wpt/status/xhr/formdata.status.json b/test/wpt/status/xhr/formdata.status.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/test/wpt/status/xhr/formdata.status.json @@ -0,0 +1 @@ +{} diff --git a/test/wpt/tests/.azure-pipelines.yml b/test/wpt/tests/.azure-pipelines.yml new file mode 100644 index 0000000..75a87df --- /dev/null +++ b/test/wpt/tests/.azure-pipelines.yml @@ -0,0 +1,595 @@ +# This is the configuration file for Azure Pipelines, used to run tests on +# macOS and Windows. Documentation to help understand this setup: +# https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema +# https://docs.microsoft.com/en-us/azure/devops/pipelines/build/triggers +# https://docs.microsoft.com/en-us/azure/devops/pipelines/process/multiple-phases +# https://docs.microsoft.com/en-us/azure/devops/pipelines/process/templates +# https://docs.microsoft.com/en-us/azure/devops/pipelines/process/variables +# https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/index +# +# In addition to this configuration file, some setup in the Azure DevOps +# project is required: +# - The "Build pull requests from forks of this repository" setting must be +# enabled: https://docs.microsoft.com/en-us/azure/devops/pipelines/repos/github#validate-contributions-from-forks + +trigger: +# These are all the branches referenced in the jobs that follow. +- epochs/daily +- epochs/three_hourly +- triggers/edge_stable +- triggers/edge_dev +- triggers/edge_canary +- triggers/safari_stable +- triggers/safari_preview +- triggers/wktr_preview + +# Set safaridriver_diagnose to true to enable safaridriver diagnostics. The +# logs won't appear in `./wpt run` output but will be uploaded as an artifact. +variables: + safaridriver_diagnose: false + +jobs: +# The affected tests jobs are unconditional for speed, as most PRs have one or +# more affected tests: https://github.com/web-platform-tests/wpt/issues/13936. +- job: affected_safari_preview + displayName: 'affected tests: Safari Technology Preview' + condition: eq(variables['Build.Reason'], 'PullRequest') + pool: + vmImage: 'macOS-13' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/affected_tests.yml + parameters: + artifactName: 'safari-preview-affected-tests' +- template: tools/ci/azure/fyi_hook.yml + parameters: + dependsOn: affected_safari_preview + artifactName: safari-preview-affected-tests + +- job: affected_without_changes_safari_preview + displayName: 'affected tests without changes: Safari Technology Preview' + condition: eq(variables['Build.Reason'], 'PullRequest') + pool: + vmImage: 'macOS-13' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/affected_tests.yml + parameters: + checkoutCommit: 'HEAD^1' + affectedRange: 'HEAD@{1}' + artifactName: 'safari-preview-affected-tests-without-changes' +- template: tools/ci/azure/fyi_hook.yml + parameters: + dependsOn: affected_without_changes_safari_preview + artifactName: safari-preview-affected-tests-without-changes + +# The decision jobs runs `./wpt test-jobs` to determine which jobs to run, +# and all following jobs wait for it to finish and depend on its output. +- job: decision + displayName: './wpt test-jobs' + condition: eq(variables['Build.Reason'], 'PullRequest') + pool: + vmImage: 'ubuntu-20.04' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/checkout.yml + - script: | + set -eux -o pipefail + git fetch --depth 50 --quiet origin master + ./wpt test-jobs | while read job; do + echo "$job" + echo "##vso[task.setvariable variable=$job;isOutput=true]true"; + done + name: test_jobs + displayName: 'Run ./wpt test-jobs' + +- job: infrastructure_mac + displayName: 'infrastructure/ tests: macOS' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.wptrunner_infrastructure'] + pool: + vmImage: 'macOS-13' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/pip_install.yml + parameters: + packages: virtualenv + - template: tools/ci/azure/install_fonts.yml + - template: tools/ci/azure/install_certs.yml + - template: tools/ci/azure/color_profile.yml + - template: tools/ci/azure/install_chrome.yml + - template: tools/ci/azure/install_firefox.yml + - template: tools/ci/azure/install_safari.yml + - template: tools/ci/azure/update_hosts.yml + - template: tools/ci/azure/update_manifest.yml + - script: | + set -eux -o pipefail + ./wpt run --yes --no-manifest-update --manifest MANIFEST.json --metadata infrastructure/metadata/ --log-mach - --log-mach-level info --log-wptreport $(Build.ArtifactStagingDirectory)/wpt_report_macos_chrome.json --channel dev chrome infrastructure/ + condition: succeededOrFailed() + displayName: 'Run tests (Chrome Dev)' + - script: | + set -eux -o pipefail + ./wpt run --yes --no-manifest-update --manifest MANIFEST.json --metadata infrastructure/metadata/ --log-mach - --log-mach-level info --log-wptreport $(Build.ArtifactStagingDirectory)/wpt_report_macos_firefox.json --channel nightly firefox infrastructure/ + condition: succeededOrFailed() + displayName: 'Run tests (Firefox Nightly)' + - script: | + set -eux -o pipefail + export SYSTEM_VERSION_COMPAT=0 + ./wpt run --yes --no-manifest-update --manifest MANIFEST.json --metadata infrastructure/metadata/ --log-mach - --log-mach-level info --log-wptreport $(Build.ArtifactStagingDirectory)/wpt_report_macos_safari.json --channel preview safari infrastructure/ + condition: succeededOrFailed() + displayName: 'Run tests (Safari Technology Preview)' + - task: PublishBuildArtifacts@1 + condition: succeededOrFailed() + displayName: 'Publish results' + inputs: + artifactName: 'infrastructure-results' + - template: tools/ci/azure/publish_logs.yml + - template: tools/ci/azure/sysdiagnose.yml + +- job: tools_unittest_mac_py37 + displayName: 'tools/ unittests: macOS + Python 3.7' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.tools_unittest'] + pool: + vmImage: 'macOS-13' + steps: + - task: UsePythonVersion@0 + inputs: + # TODO(#40525): Revert back to 3.7 once the Mac agent's Python v3.7 contains bz2 again. + versionSpec: '3.7.16' + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/tox_pytest.yml + parameters: + directory: tools/ + toxenv: py37 + +- job: tools_unittest_mac_py311 + displayName: 'tools/ unittests: macOS + Python 3.11' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.tools_unittest'] + pool: + vmImage: 'macOS-13' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/tox_pytest.yml + parameters: + directory: tools/ + toxenv: py311 + +- job: wptrunner_unittest_mac_py37 + displayName: 'tools/wptrunner/ unittests: macOS + Python 3.7' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.wptrunner_unittest'] + pool: + vmImage: 'macOS-13' + steps: + - task: UsePythonVersion@0 + inputs: + # TODO(#40525): Revert back to 3.7 once the Mac agent's Python v3.7 contains bz2 again. + versionSpec: '3.7.16' + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/tox_pytest.yml + parameters: + directory: tools/wptrunner/ + toxenv: py37 + +- job: wptrunner_unittest_mac_py311 + displayName: 'tools/wptrunner/ unittests: macOS + Python 3.11' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.wptrunner_unittest'] + pool: + vmImage: 'macOS-13' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/tox_pytest.yml + parameters: + directory: tools/wptrunner/ + toxenv: py311 + +- job: wpt_integration_mac_py37 + displayName: 'tools/wpt/ tests: macOS + Python 3.7' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.wpt_integration'] + pool: + vmImage: 'macOS-13' + steps: + # full checkout required + - task: UsePythonVersion@0 + inputs: + # TODO(#40525): Revert back to 3.7 once the Mac agent's Python v3.7 contains bz2 again. + versionSpec: '3.7.16' + - template: tools/ci/azure/install_chrome.yml + - template: tools/ci/azure/install_firefox.yml + - template: tools/ci/azure/update_hosts.yml + - template: tools/ci/azure/update_manifest.yml + - template: tools/ci/azure/tox_pytest.yml + parameters: + directory: tools/wpt/ + toxenv: py37 + +- job: wpt_integration_mac_py311 + displayName: 'tools/wpt/ tests: macOS + Python 3.11' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.wpt_integration'] + pool: + vmImage: 'macOS-13' + steps: + # full checkout required + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/install_chrome.yml + - template: tools/ci/azure/install_firefox.yml + - template: tools/ci/azure/update_hosts.yml + - template: tools/ci/azure/update_manifest.yml + - template: tools/ci/azure/tox_pytest.yml + parameters: + directory: tools/wpt/ + toxenv: py311 + +- job: tools_unittest_win_py37 + displayName: 'tools/ unittests: Windows + Python 3.7' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.tools_unittest'] + pool: + vmImage: 'windows-2019' + variables: + HYPOTHESIS_PROFILE: ci + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.7' + addToPath: false + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/tox_pytest.yml + parameters: + directory: tools/ + toxenv: py37 + +- job: tools_unittest_win_py311 + displayName: 'tools/ unittests: Windows + Python 3.11' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.tools_unittest'] + pool: + vmImage: 'windows-2019' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + addToPath: false + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/tox_pytest.yml + parameters: + directory: tools/ + toxenv: py311 + +- job: wptrunner_unittest_win_py37 + displayName: 'tools/wptrunner/ unittests: Windows + Python 3.7' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.wptrunner_unittest'] + pool: + vmImage: 'windows-2019' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.7' + addToPath: false + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/tox_pytest.yml + parameters: + directory: tools/wptrunner/ + toxenv: py37 + +- job: wptrunner_unittest_win_py311 + displayName: 'tools/wptrunner/ unittests: Windows + Python 3.11' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.wptrunner_unittest'] + pool: + vmImage: 'windows-2019' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + addToPath: false + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/tox_pytest.yml + parameters: + directory: tools/wptrunner/ + toxenv: py311 + +- job: wpt_integration_win_py37 + displayName: 'tools/wpt/ tests: Windows + Python 3.7' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.wpt_integration'] + pool: + vmImage: 'windows-2019' + steps: + # full checkout required + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.7' + # currently just using the outdated Chrome/Firefox on the VM rather than + # figuring out how to install Chrome Dev channel on Windows + # - template: tools/ci/azure/install_chrome.yml + # - template: tools/ci/azure/install_firefox.yml + - template: tools/ci/azure/update_hosts.yml + - template: tools/ci/azure/update_manifest.yml + - template: tools/ci/azure/tox_pytest.yml + parameters: + directory: tools/wpt/ + toxenv: py37 + +- job: wpt_integration_win_py311 + displayName: 'tools/wpt/ tests: Windows + Python 3.11' + dependsOn: decision + condition: dependencies.decision.outputs['test_jobs.wpt_integration'] + pool: + vmImage: 'windows-2019' + steps: + # full checkout required + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + # currently just using the outdated Chrome/Firefox on the VM rather than + # figuring out how to install Chrome Dev channel on Windows + # - template: tools/ci/azure/install_chrome.yml + # - template: tools/ci/azure/install_firefox.yml + - template: tools/ci/azure/update_hosts.yml + - template: tools/ci/azure/update_manifest.yml + - template: tools/ci/azure/tox_pytest.yml + parameters: + directory: tools/wpt/ + toxenv: py311 + +- job: results_edge_stable + displayName: 'all tests: Edge Stable' + condition: | + or(eq(variables['Build.SourceBranch'], 'refs/heads/epochs/daily'), + eq(variables['Build.SourceBranch'], 'refs/heads/triggers/edge_stable'), + and(eq(variables['Build.Reason'], 'Manual'), variables['run_all_edge_stable'])) + strategy: + parallel: 8 # chosen to make runtime ~2h + timeoutInMinutes: 180 + pool: + vmImage: 'windows-2019' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/system_info.yml + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/pip_install.yml + parameters: + packages: virtualenv + - template: tools/ci/azure/install_certs.yml + - template: tools/ci/azure/install_edge.yml + parameters: + channel: stable + - template: tools/ci/azure/update_hosts.yml + - template: tools/ci/azure/update_manifest.yml + - script: python ./wpt run --yes --no-manifest-update --no-restart-on-unexpected --no-fail-on-unexpected --install-fonts --this-chunk $(System.JobPositionInPhase) --total-chunks $(System.TotalJobsInPhase) --chunk-type hash --log-wptreport $(Build.ArtifactStagingDirectory)/wpt_report_$(System.JobPositionInPhase).json --log-wptscreenshot $(Build.ArtifactStagingDirectory)/wpt_screenshot_$(System.JobPositionInPhase).txt --log-mach - --log-mach-level info --channel stable edgechromium + displayName: 'Run tests (Edge Stable)' + - task: PublishBuildArtifacts@1 + displayName: 'Publish results' + inputs: + artifactName: 'edge-stable-results' + - template: tools/ci/azure/publish_logs.yml + - template: tools/ci/azure/sysdiagnose.yml +- template: tools/ci/azure/fyi_hook.yml + parameters: + dependsOn: results_edge_stable + artifactName: edge-stable-results + +- job: results_edge_dev + displayName: 'all tests: Edge Dev' + condition: | + or(eq(variables['Build.SourceBranch'], 'refs/heads/epochs/three_hourly'), + eq(variables['Build.SourceBranch'], 'refs/heads/triggers/edge_dev'), + and(eq(variables['Build.Reason'], 'Manual'), variables['run_all_edge_dev'])) + strategy: + parallel: 8 # chosen to make runtime ~2h + timeoutInMinutes: 180 + pool: + vmImage: 'windows-2019' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/system_info.yml + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/pip_install.yml + parameters: + packages: virtualenv + - template: tools/ci/azure/install_certs.yml + - template: tools/ci/azure/install_edge.yml + parameters: + channel: dev + - template: tools/ci/azure/update_hosts.yml + - template: tools/ci/azure/update_manifest.yml + - script: python ./wpt run --yes --no-manifest-update --no-restart-on-unexpected --no-fail-on-unexpected --install-fonts --this-chunk $(System.JobPositionInPhase) --total-chunks $(System.TotalJobsInPhase) --chunk-type hash --log-wptreport $(Build.ArtifactStagingDirectory)/wpt_report_$(System.JobPositionInPhase).json --log-wptscreenshot $(Build.ArtifactStagingDirectory)/wpt_screenshot_$(System.JobPositionInPhase).txt --log-mach - --log-mach-level info --channel dev edgechromium + displayName: 'Run tests (Edge Dev)' + - task: PublishBuildArtifacts@1 + displayName: 'Publish results' + inputs: + artifactName: 'edge-dev-results' + - template: tools/ci/azure/publish_logs.yml + - template: tools/ci/azure/sysdiagnose.yml +- template: tools/ci/azure/fyi_hook.yml + parameters: + dependsOn: results_edge_dev + artifactName: edge-dev-results + +- job: results_edge_canary + displayName: 'all tests: Edge Canary' + condition: | + or(eq(variables['Build.SourceBranch'], 'refs/heads/epochs/weekly'), + eq(variables['Build.SourceBranch'], 'refs/heads/triggers/edge_canary'), + and(eq(variables['Build.Reason'], 'Manual'), variables['run_all_edge_canary'])) + strategy: + parallel: 8 # chosen to make runtime ~2h + timeoutInMinutes: 180 + pool: + vmImage: 'windows-2019' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/pip_install.yml + parameters: + packages: virtualenv + - template: tools/ci/azure/install_certs.yml + - template: tools/ci/azure/install_edge.yml + parameters: + channel: canary + - template: tools/ci/azure/update_hosts.yml + - template: tools/ci/azure/update_manifest.yml + - script: python ./wpt run --yes --no-manifest-update --no-restart-on-unexpected --no-fail-on-unexpected --install-fonts --this-chunk $(System.JobPositionInPhase) --total-chunks $(System.TotalJobsInPhase) --chunk-type hash --log-wptreport $(Build.ArtifactStagingDirectory)/wpt_report_$(System.JobPositionInPhase).json --log-wptscreenshot $(Build.ArtifactStagingDirectory)/wpt_screenshot_$(System.JobPositionInPhase).txt --log-mach - --log-mach-level info --channel canary edgechromium + displayName: 'Run tests (Edge Canary)' + - task: PublishBuildArtifacts@1 + displayName: 'Publish results' + inputs: + artifactName: 'edge-canary-results' + - template: tools/ci/azure/publish_logs.yml + - template: tools/ci/azure/sysdiagnose.yml +- template: tools/ci/azure/fyi_hook.yml + parameters: + dependsOn: results_edge_canary + artifactName: edge-canary-results + +- job: results_safari + displayName: 'all tests: Safari' + condition: | + or(eq(variables['Build.SourceBranch'], 'refs/heads/epochs/daily'), + eq(variables['Build.SourceBranch'], 'refs/heads/triggers/safari_stable'), + and(eq(variables['Build.Reason'], 'Manual'), variables['run_all_safari'])) + strategy: + parallel: 8 # chosen to make runtime ~2h + timeoutInMinutes: 180 + pool: + vmImage: 'macOS-13' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/pip_install.yml + parameters: + packages: virtualenv + - template: tools/ci/azure/install_certs.yml + - template: tools/ci/azure/color_profile.yml + - template: tools/ci/azure/install_safari.yml + parameters: + channel: stable + - template: tools/ci/azure/update_hosts.yml + - template: tools/ci/azure/update_manifest.yml + - script: | + set -eux -o pipefail + export SYSTEM_VERSION_COMPAT=0 + ./wpt run --no-manifest-update --no-restart-on-unexpected --no-fail-on-unexpected --this-chunk=$(System.JobPositionInPhase) --total-chunks=$(System.TotalJobsInPhase) --chunk-type hash --log-wptreport $(Build.ArtifactStagingDirectory)/wpt_report_$(System.JobPositionInPhase).json --log-wptscreenshot $(Build.ArtifactStagingDirectory)/wpt_screenshot_$(System.JobPositionInPhase).txt --log-mach - --log-mach-level info --channel stable --kill-safari --max-restarts 100 safari + displayName: 'Run tests' + retryCountOnTaskFailure: 2 + - task: PublishBuildArtifacts@1 + displayName: 'Publish results' + inputs: + artifactName: 'safari-results' + - template: tools/ci/azure/publish_logs.yml + - template: tools/ci/azure/sysdiagnose.yml +- template: tools/ci/azure/fyi_hook.yml + parameters: + dependsOn: results_safari + artifactName: safari-results + +- job: results_safari_preview + displayName: 'all tests: Safari Technology Preview' + condition: | + or(eq(variables['Build.SourceBranch'], 'refs/heads/epochs/three_hourly'), + eq(variables['Build.SourceBranch'], 'refs/heads/triggers/safari_preview'), + and(eq(variables['Build.Reason'], 'Manual'), variables['run_all_safari_preview'])) + strategy: + parallel: 8 # chosen to make runtime ~2h + timeoutInMinutes: 180 + pool: + vmImage: 'macOS-13' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/pip_install.yml + parameters: + packages: virtualenv + - template: tools/ci/azure/install_certs.yml + - template: tools/ci/azure/color_profile.yml + - template: tools/ci/azure/install_safari.yml + - template: tools/ci/azure/update_hosts.yml + - template: tools/ci/azure/update_manifest.yml + - script: | + set -eux -o pipefail + export SYSTEM_VERSION_COMPAT=0 + ./wpt run --no-manifest-update --no-restart-on-unexpected --no-fail-on-unexpected --this-chunk=$(System.JobPositionInPhase) --total-chunks=$(System.TotalJobsInPhase) --chunk-type hash --log-wptreport $(Build.ArtifactStagingDirectory)/wpt_report_$(System.JobPositionInPhase).json --log-wptscreenshot $(Build.ArtifactStagingDirectory)/wpt_screenshot_$(System.JobPositionInPhase).txt --log-mach - --log-mach-level info --channel preview --kill-safari --max-restarts 100 safari + displayName: 'Run tests' + retryCountOnTaskFailure: 2 + - task: PublishBuildArtifacts@1 + displayName: 'Publish results' + inputs: + artifactName: 'safari-preview-results' + - template: tools/ci/azure/publish_logs.yml + - template: tools/ci/azure/sysdiagnose.yml +- template: tools/ci/azure/fyi_hook.yml + parameters: + dependsOn: results_safari_preview + artifactName: safari-preview-results + +- job: results_wktr_preview + displayName: 'all tests: WebKitTestRunner' + condition: | + or(eq(variables['Build.SourceBranch'], 'refs/heads/triggers/wktr_preview'), + and(eq(variables['Build.Reason'], 'Manual'), variables['run_all_wktr_preview'])) + strategy: + parallel: 8 # chosen to make runtime ~2h + timeoutInMinutes: 180 + pool: + vmImage: 'macOS-13' + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: '3.11' + - template: tools/ci/azure/checkout.yml + - template: tools/ci/azure/pip_install.yml + parameters: + packages: virtualenv + - template: tools/ci/azure/install_certs.yml + - template: tools/ci/azure/color_profile.yml + - template: tools/ci/azure/update_hosts.yml + - template: tools/ci/azure/update_manifest.yml + - script: | + set -eux -o pipefail + export SYSTEM_VERSION_COMPAT=0 + ./wpt run --no-manifest-update --no-restart-on-unexpected --no-fail-on-unexpected --this-chunk=$(System.JobPositionInPhase) --total-chunks=$(System.TotalJobsInPhase) --chunk-type hash --log-wptreport $(Build.ArtifactStagingDirectory)/wpt_report_$(System.JobPositionInPhase).json --log-wptscreenshot $(Build.ArtifactStagingDirectory)/wpt_screenshot_$(System.JobPositionInPhase).txt --log-mach - --log-mach-level info --channel experimental --install-browser --yes wktr + displayName: 'Run tests' + - task: PublishBuildArtifacts@1 + displayName: 'Publish results' + inputs: + artifactName: 'wktr-preview-results' + - template: tools/ci/azure/publish_logs.yml + - template: tools/ci/azure/sysdiagnose.yml +- template: tools/ci/azure/fyi_hook.yml + parameters: + dependsOn: results_wktr_preview + artifactName: wktr-preview-results diff --git a/test/wpt/tests/.gitattributes b/test/wpt/tests/.gitattributes new file mode 100644 index 0000000..5c11e4e --- /dev/null +++ b/test/wpt/tests/.gitattributes @@ -0,0 +1 @@ +* -text diff --git a/test/wpt/tests/.gitignore b/test/wpt/tests/.gitignore new file mode 100644 index 0000000..061700a --- /dev/null +++ b/test/wpt/tests/.gitignore @@ -0,0 +1,52 @@ +# Python +*.py[co] +.cache/ +.coverage* +.mypy_cache/ +.pytest_cache/ +.tox/ +.virtualenv/ +_venv*/ +_virtualenv/ + +# Node +node_modules/ + +# WPT repo stuff +.wptcache/ +/MANIFEST.json +/_certs +/config.json + +# Files generated when regenerating pre-generated certs +/tools/certs/0*.pem +/tools/certs/index.txt* +/tools/certs/serial* + +# Various OS/editor specific files +*# +*.orig +*.rej +*.svn +*.sw[po] +*.xcodeproj +*Thumbs.db +*~ +.DS_Store +.directory* +.idea/ +.vscode/ +\#* +scratch + +# Testsuite-specific rules +/conformance-checkers/vnu.jar +/cors/resources/log.txt +/css/build-temp +/css/dist +/css/dist_last +/url/tools/IdnaTestV2.txt +/webaudio/idl/* + +# w3c-test.org PR-branch mirroring +/submissions/ diff --git a/test/wpt/tests/.mailmap b/test/wpt/tests/.mailmap new file mode 100644 index 0000000..5293948 --- /dev/null +++ b/test/wpt/tests/.mailmap @@ -0,0 +1,9 @@ +# People who've changed name: + +# Sam Sneddon: +Sam Sneddon +Sam Sneddon + +# Theresa O'Connor: +Theresa O'Connor +Theresa O'Connor diff --git a/test/wpt/tests/.taskcluster.yml b/test/wpt/tests/.taskcluster.yml new file mode 100644 index 0000000..c817999 --- /dev/null +++ b/test/wpt/tests/.taskcluster.yml @@ -0,0 +1,82 @@ +version: 1 +reporting: checks-v1 +policy: + pullRequests: public +tasks: + $let: + run_task: + $if: 'tasks_for == "github-push"' + then: + $if: 'event.ref in ["refs/heads/master", "refs/heads/epochs/daily", "refs/heads/epochs/weekly", "refs/heads/triggers/chrome_stable", "refs/heads/triggers/chrome_beta", "refs/heads/triggers/chrome_dev", "refs/heads/triggers/chrome_nightly", "refs/heads/triggers/firefox_stable", "refs/heads/triggers/firefox_beta", "refs/heads/triggers/firefox_nightly", "refs/heads/triggers/webkitgtk_minibrowser_stable", "refs/heads/triggers/webkitgtk_minibrowser_beta", "refs/heads/triggers/webkitgtk_minibrowser_nightly", "refs/heads/triggers/servo_nightly"]' + then: true + else: false + else: + $if: 'tasks_for == "github-pull-request"' + then: + $if: 'event.action in ["opened", "reopened", "synchronize"]' + then: true + else: false + else: false + in: + - $if: run_task + then: + $let: + event_str: {$json: {$eval: event}} + scopes: + $if: 'tasks_for == "github-push"' + then: + $let: + branch: + $if: "event.ref[:11] == 'refs/heads/'" + then: "${event.ref[11:]}" + else: "${event.ref}" + in: "assume:repo:github.com/${event.repository.full_name}:branch:${branch}" + else: "assume:repo:github.com/${event.repository.full_name}:pull-request" + rev: + $if: 'tasks_for == "github-pull-request"' + then: "refs/pull/${event.number}/merge" + else: "${event.after}" + owner: + $if: 'tasks_for == "github-push"' + then: + $if: 'event.pusher.email' + then: + $if: '"@" in event.pusher.email' + then: ${event.pusher.email} + else: web-platform-tests@users.noreply.github.com + else: web-platform-tests@users.noreply.github.com + else: web-platform-tests@users.noreply.github.com + in: + created: {$fromNow: ''} + deadline: {$fromNow: '24 hours'} + provisionerId: proj-wpt + workerType: ci + metadata: + name: "wpt-decision-task" + description: "The task that creates all of the other tasks in the task graph" + owner: ${owner} + source: ${event.repository.clone_url} + payload: + image: webplatformtests/wpt:0.54 + maxRunTime: 7200 + artifacts: + public/results: + path: /home/test/artifacts + type: directory + command: + - /bin/bash + - --login + - -c + - set -ex; + ~/start.sh + ${event.repository.clone_url} + ${rev}; + cd ~/web-platform-tests; + ./wpt tc-decision --tasks-path=/home/test/artifacts/tasks.json + features : + taskclusterProxy: true + scopes: + - ${scopes} + extra: + github_event: "${event_str}" + diff --git a/test/wpt/tests/CODEOWNERS b/test/wpt/tests/CODEOWNERS new file mode 100644 index 0000000..140e0c6 --- /dev/null +++ b/test/wpt/tests/CODEOWNERS @@ -0,0 +1,6 @@ +# Require review for changes that often need an RFC +/resources/testdriver* @web-platform-tests/wpt-core-team +/resources/testharness* @web-platform-tests/wpt-core-team + +# Prevent accidentally touching tools/third_party +/tools/third_party/ @web-platform-tests/wpt-core-team diff --git a/test/wpt/tests/CODE_OF_CONDUCT.md b/test/wpt/tests/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..dae98ee --- /dev/null +++ b/test/wpt/tests/CODE_OF_CONDUCT.md @@ -0,0 +1,138 @@ +# Code of Conduct + +Contact: a moderator ([see below](#moderators)), or a member of the WPT +community that you feel you can trust. + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, sexual identity and +orientation, or any other dimension of diversity. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Moderators are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Moderators have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +Moderators are held to a higher standard than other community members. If a +moderator creates an inappropriate situation, they should expect less leeway +than others. + +## Scope + +This Code of Conduct applies within all community spaces, and also +applies when an individual is officially representing the community in +public spaces. Examples of representing our community include +the official Matrix channel (wpt:matrix.org); GitHub repositories under +the web-platform-tests organization; and the public-test-infra@w3.org +mailing list. + +There may arise situations where both the WPT code of conduct and that of +another organization (such as the WHATWG or W3C) may apply. +For example, a WPT-focused meeting at +[TPAC](https://www.w3.org/2002/09/TPOverview.html) would involve both the WPT +code of conduct and the [W3C code of ethics and professional +conduct](https://www.w3.org/Consortium/cepc/). +In such situations we operate under all code of conducts involved. +If you are placed in a situation where you feel this is inappropriate (e.g. if +you believe the code of conducts involved contradict one another), please +contact a [moderator](#moderators). + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the [moderators](#moderators). +All complaints will be reviewed and investigated promptly and fairly. + +All moderators are obligated to respect the privacy and security of the +reporter of any incident. + +Moderators will recuse themselves if they are directly involved in a report of +a code of conduct violation. + +## Enforcement Guidelines + +Moderators will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct. +These are not a consecutive set of steps; a single incident may be sufficient +enough to proceed straight to a temporary ban, for example. + +### 1. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 3. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Moderators + +This section lists the current moderators and how to reach them. + +* Nina Satragno - [nso@google.com](mailto:nso@google.com). Languages: English, Spanish. +* Boaz Sender - [boaz@bocoup.com](mailto:boaz@bocoup.com). Languages: English, Hebrew. +* Jory Burson - [jory@bocoup.education](mailto:jory@bocoup.education). Languages: English (fluent), Spanish (conversational). + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. diff --git a/test/wpt/tests/CONTRIBUTING.md b/test/wpt/tests/CONTRIBUTING.md new file mode 100644 index 0000000..cb80d8d --- /dev/null +++ b/test/wpt/tests/CONTRIBUTING.md @@ -0,0 +1,11 @@ +All contributions are licensed under the terms of the [3-Clause BSD License](LICENSE.md). + +Documentation +------------- + +See [web-platform-tests.org](https://web-platform-tests.org/). + +Code of Conduct +--------------- + +See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md). diff --git a/test/wpt/tests/FileAPI/Blob-methods-from-detached-frame.html b/test/wpt/tests/FileAPI/Blob-methods-from-detached-frame.html new file mode 100644 index 0000000..37efd5e --- /dev/null +++ b/test/wpt/tests/FileAPI/Blob-methods-from-detached-frame.html @@ -0,0 +1,59 @@ + + +Blob methods from detached frame work as expected + + + + + + diff --git a/test/wpt/tests/FileAPI/BlobURL/cross-partition.tentative.https.html b/test/wpt/tests/FileAPI/BlobURL/cross-partition.tentative.https.html new file mode 100644 index 0000000..c75ce07 --- /dev/null +++ b/test/wpt/tests/FileAPI/BlobURL/cross-partition.tentative.https.html @@ -0,0 +1,276 @@ + + + + + + + + + + + + + + + diff --git a/test/wpt/tests/FileAPI/BlobURL/support/file_test2.txt b/test/wpt/tests/FileAPI/BlobURL/support/file_test2.txt new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/FileAPI/BlobURL/test2-manual.html b/test/wpt/tests/FileAPI/BlobURL/test2-manual.html new file mode 100644 index 0000000..07fb27e --- /dev/null +++ b/test/wpt/tests/FileAPI/BlobURL/test2-manual.html @@ -0,0 +1,62 @@ + + + + + Blob and File reference URL Test(2) + + + + + + +
+
+
+ +
+

Test steps:

+
    +
  1. Download the file.
  2. +
  3. Select the file in the file inputbox.
  4. +
  5. Delete the file.
  6. +
  7. Click the 'start' button.
  8. +
+
+ +
+ + + + diff --git a/test/wpt/tests/FileAPI/FileReader/progress_event_bubbles_cancelable.html b/test/wpt/tests/FileAPI/FileReader/progress_event_bubbles_cancelable.html new file mode 100644 index 0000000..6a03243 --- /dev/null +++ b/test/wpt/tests/FileAPI/FileReader/progress_event_bubbles_cancelable.html @@ -0,0 +1,33 @@ + + +File API Test: Progress Event - bubbles, cancelable + + + + +
+ + diff --git a/test/wpt/tests/FileAPI/FileReader/support/file_test1.txt b/test/wpt/tests/FileAPI/FileReader/support/file_test1.txt new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/FileAPI/FileReader/test_errors-manual.html b/test/wpt/tests/FileAPI/FileReader/test_errors-manual.html new file mode 100644 index 0000000..b8c3f84 --- /dev/null +++ b/test/wpt/tests/FileAPI/FileReader/test_errors-manual.html @@ -0,0 +1,72 @@ + + + + + FileReader Errors Test + + + + + + +
+
+
+ +
+

Test steps:

+
    +
  1. Download the file.
  2. +
  3. Select the file in the file inputbox.
  4. +
  5. Delete the file.
  6. +
  7. Click the 'start' button.
  8. +
+
+ +
+ + + + diff --git a/test/wpt/tests/FileAPI/FileReader/test_notreadableerrors-manual.html b/test/wpt/tests/FileAPI/FileReader/test_notreadableerrors-manual.html new file mode 100644 index 0000000..46d7359 --- /dev/null +++ b/test/wpt/tests/FileAPI/FileReader/test_notreadableerrors-manual.html @@ -0,0 +1,42 @@ + + +FileReader NotReadableError Test + + + + +
+
+
+ +
+

Test steps:

+
    +
  1. Download the file.
  2. +
  3. Select the file in the file inputbox.
  4. +
  5. Delete the file's readable permission.
  6. +
  7. Click the 'start' button.
  8. +
+
+ + + diff --git a/test/wpt/tests/FileAPI/FileReader/test_securityerrors-manual.html b/test/wpt/tests/FileAPI/FileReader/test_securityerrors-manual.html new file mode 100644 index 0000000..add93ed --- /dev/null +++ b/test/wpt/tests/FileAPI/FileReader/test_securityerrors-manual.html @@ -0,0 +1,40 @@ + + +FileReader SecurityError Test + + + + +
+
+
+ +
+

Test steps:

+
    +
  1. Select a system sensitive file (e.g. files in /usr/bin, password files, + and other native operating system executables) in the file inputbox.
  2. +
  3. Click the 'start' button.
  4. +
+
+ + diff --git a/test/wpt/tests/FileAPI/FileReader/workers.html b/test/wpt/tests/FileAPI/FileReader/workers.html new file mode 100644 index 0000000..8e114ee --- /dev/null +++ b/test/wpt/tests/FileAPI/FileReader/workers.html @@ -0,0 +1,27 @@ + + + + + diff --git a/test/wpt/tests/FileAPI/FileReaderSync.worker.js b/test/wpt/tests/FileAPI/FileReaderSync.worker.js new file mode 100644 index 0000000..3d7a022 --- /dev/null +++ b/test/wpt/tests/FileAPI/FileReaderSync.worker.js @@ -0,0 +1,56 @@ +importScripts("/resources/testharness.js"); + +var blob, empty_blob, readerSync; +setup(() => { + readerSync = new FileReaderSync(); + blob = new Blob(["test"]); + empty_blob = new Blob(); +}); + +test(() => { + assert_true(readerSync instanceof FileReaderSync); +}, "Interface"); + +test(() => { + var text = readerSync.readAsText(blob); + assert_equals(text, "test"); +}, "readAsText"); + +test(() => { + var text = readerSync.readAsText(empty_blob); + assert_equals(text, ""); +}, "readAsText with empty blob"); + +test(() => { + var data = readerSync.readAsDataURL(blob); + assert_equals(data.indexOf("data:"), 0); +}, "readAsDataURL"); + +test(() => { + var data = readerSync.readAsDataURL(empty_blob); + assert_equals(data.indexOf("data:"), 0); +}, "readAsDataURL with empty blob"); + +test(() => { + var data = readerSync.readAsBinaryString(blob); + assert_equals(data, "test"); +}, "readAsBinaryString"); + +test(() => { + var data = readerSync.readAsBinaryString(empty_blob); + assert_equals(data, ""); +}, "readAsBinaryString with empty blob"); + +test(() => { + var data = readerSync.readAsArrayBuffer(blob); + assert_true(data instanceof ArrayBuffer); + assert_equals(data.byteLength, "test".length); +}, "readAsArrayBuffer"); + +test(() => { + var data = readerSync.readAsArrayBuffer(empty_blob); + assert_true(data instanceof ArrayBuffer); + assert_equals(data.byteLength, 0); +}, "readAsArrayBuffer with empty blob"); + +done(); diff --git a/test/wpt/tests/FileAPI/META.yml b/test/wpt/tests/FileAPI/META.yml new file mode 100644 index 0000000..506a59f --- /dev/null +++ b/test/wpt/tests/FileAPI/META.yml @@ -0,0 +1,6 @@ +spec: https://w3c.github.io/FileAPI/ +suggested_reviewers: + - inexorabletash + - zqzhang + - jdm + - mkruisselbrink diff --git a/test/wpt/tests/FileAPI/blob/Blob-array-buffer.any.js b/test/wpt/tests/FileAPI/blob/Blob-array-buffer.any.js new file mode 100644 index 0000000..2310646 --- /dev/null +++ b/test/wpt/tests/FileAPI/blob/Blob-array-buffer.any.js @@ -0,0 +1,45 @@ +// META: title=Blob Array Buffer +// META: script=../support/Blob.js +'use strict'; + +promise_test(async () => { + const input_arr = new TextEncoder().encode("PASS"); + const blob = new Blob([input_arr]); + const array_buffer = await blob.arrayBuffer(); + assert_true(array_buffer instanceof ArrayBuffer); + assert_equals_typed_array(new Uint8Array(array_buffer), input_arr); +}, "Blob.arrayBuffer()") + +promise_test(async () => { + const input_arr = new TextEncoder().encode(""); + const blob = new Blob([input_arr]); + const array_buffer = await blob.arrayBuffer(); + assert_true(array_buffer instanceof ArrayBuffer); + assert_equals_typed_array(new Uint8Array(array_buffer), input_arr); +}, "Blob.arrayBuffer() empty Blob data") + +promise_test(async () => { + const input_arr = new TextEncoder().encode("\u08B8\u000a"); + const blob = new Blob([input_arr]); + const array_buffer = await blob.arrayBuffer(); + assert_equals_typed_array(new Uint8Array(array_buffer), input_arr); +}, "Blob.arrayBuffer() non-ascii input") + +promise_test(async () => { + const input_arr = [8, 241, 48, 123, 151]; + const typed_arr = new Uint8Array(input_arr); + const blob = new Blob([typed_arr]); + const array_buffer = await blob.arrayBuffer(); + assert_equals_typed_array(new Uint8Array(array_buffer), typed_arr); +}, "Blob.arrayBuffer() non-unicode input") + +promise_test(async () => { + const input_arr = new TextEncoder().encode("PASS"); + const blob = new Blob([input_arr]); + const array_buffer_results = await Promise.all([blob.arrayBuffer(), + blob.arrayBuffer(), blob.arrayBuffer()]); + for (let array_buffer of array_buffer_results) { + assert_true(array_buffer instanceof ArrayBuffer); + assert_equals_typed_array(new Uint8Array(array_buffer), input_arr); + } +}, "Blob.arrayBuffer() concurrent reads") diff --git a/test/wpt/tests/FileAPI/blob/Blob-constructor-dom.window.js b/test/wpt/tests/FileAPI/blob/Blob-constructor-dom.window.js new file mode 100644 index 0000000..4fd4a43 --- /dev/null +++ b/test/wpt/tests/FileAPI/blob/Blob-constructor-dom.window.js @@ -0,0 +1,53 @@ +// META: title=Blob constructor +// META: script=../support/Blob.js +'use strict'; + +var test_error = { + name: "test", + message: "test error", +}; + +test(function() { + var args = [ + document.createElement("div"), + window, + ]; + args.forEach(function(arg) { + assert_throws_js(TypeError, function() { + new Blob(arg); + }, "Should throw for argument " + format_value(arg) + "."); + }); +}, "Passing platform objects for blobParts should throw a TypeError."); + +test(function() { + var element = document.createElement("div"); + element.appendChild(document.createElement("div")); + element.appendChild(document.createElement("p")); + var list = element.children; + Object.defineProperty(list, "length", { + get: function() { throw test_error; } + }); + assert_throws_exactly(test_error, function() { + new Blob(list); + }); +}, "A platform object that supports indexed properties should be treated as a sequence for the blobParts argument (overwritten 'length'.)"); + +test_blob(function() { + var select = document.createElement("select"); + select.appendChild(document.createElement("option")); + return new Blob(select); +}, { + expected: "[object HTMLOptionElement]", + type: "", + desc: "Passing an platform object that supports indexed properties as the blobParts array should work (select)." +}); + +test_blob(function() { + var elm = document.createElement("div"); + elm.setAttribute("foo", "bar"); + return new Blob(elm.attributes); +}, { + expected: "[object Attr]", + type: "", + desc: "Passing an platform object that supports indexed properties as the blobParts array should work (attributes)." +}); \ No newline at end of file diff --git a/test/wpt/tests/FileAPI/blob/Blob-constructor-endings.html b/test/wpt/tests/FileAPI/blob/Blob-constructor-endings.html new file mode 100644 index 0000000..04edd2a --- /dev/null +++ b/test/wpt/tests/FileAPI/blob/Blob-constructor-endings.html @@ -0,0 +1,104 @@ + + +Blob constructor: endings option + + + + diff --git a/test/wpt/tests/FileAPI/blob/Blob-constructor.any.js b/test/wpt/tests/FileAPI/blob/Blob-constructor.any.js new file mode 100644 index 0000000..d16f760 --- /dev/null +++ b/test/wpt/tests/FileAPI/blob/Blob-constructor.any.js @@ -0,0 +1,468 @@ +// META: title=Blob constructor +// META: script=../support/Blob.js +'use strict'; + +test(function() { + assert_true("Blob" in globalThis, "globalThis should have a Blob property."); + assert_equals(Blob.length, 0, "Blob.length should be 0."); + assert_true(Blob instanceof Function, "Blob should be a function."); +}, "Blob interface object"); + +// Step 1. +test(function() { + var blob = new Blob(); + assert_true(blob instanceof Blob); + assert_equals(String(blob), '[object Blob]'); + assert_equals(blob.size, 0); + assert_equals(blob.type, ""); +}, "Blob constructor with no arguments"); +test(function() { + assert_throws_js(TypeError, function() { var blob = Blob(); }); +}, "Blob constructor with no arguments, without 'new'"); +test(function() { + var blob = new Blob; + assert_true(blob instanceof Blob); + assert_equals(blob.size, 0); + assert_equals(blob.type, ""); +}, "Blob constructor without brackets"); +test(function() { + var blob = new Blob(undefined); + assert_true(blob instanceof Blob); + assert_equals(String(blob), '[object Blob]'); + assert_equals(blob.size, 0); + assert_equals(blob.type, ""); +}, "Blob constructor with undefined as first argument"); + +// blobParts argument (WebIDL). +test(function() { + var args = [ + null, + true, + false, + 0, + 1, + 1.5, + "FAIL", + new Date(), + new RegExp(), + {}, + { 0: "FAIL", length: 1 }, + ]; + args.forEach(function(arg) { + assert_throws_js(TypeError, function() { + new Blob(arg); + }, "Should throw for argument " + format_value(arg) + "."); + }); +}, "Passing non-objects, Dates and RegExps for blobParts should throw a TypeError."); + +test_blob(function() { + return new Blob({ + [Symbol.iterator]: Array.prototype[Symbol.iterator], + }); +}, { + expected: "", + type: "", + desc: "A plain object with @@iterator should be treated as a sequence for the blobParts argument." +}); +test(t => { + const blob = new Blob({ + [Symbol.iterator]() { + var i = 0; + return {next: () => [ + {done:false, value:'ab'}, + {done:false, value:'cde'}, + {done:true} + ][i++] + }; + } + }); + assert_equals(blob.size, 5, 'Custom @@iterator should be treated as a sequence'); +}, "A plain object with custom @@iterator should be treated as a sequence for the blobParts argument."); +test_blob(function() { + return new Blob({ + [Symbol.iterator]: Array.prototype[Symbol.iterator], + 0: "PASS", + length: 1 + }); +}, { + expected: "PASS", + type: "", + desc: "A plain object with @@iterator and a length property should be treated as a sequence for the blobParts argument." +}); +test_blob(function() { + return new Blob(new String("xyz")); +}, { + expected: "xyz", + type: "", + desc: "A String object should be treated as a sequence for the blobParts argument." +}); +test_blob(function() { + return new Blob(new Uint8Array([1, 2, 3])); +}, { + expected: "123", + type: "", + desc: "A Uint8Array object should be treated as a sequence for the blobParts argument." +}); + +var test_error = { + name: "test", + message: "test error", +}; + +test(function() { + var obj = { + [Symbol.iterator]: Array.prototype[Symbol.iterator], + get length() { throw test_error; } + }; + assert_throws_exactly(test_error, function() { + new Blob(obj); + }); +}, "The length getter should be invoked and any exceptions should be propagated."); + +test(function() { + assert_throws_exactly(test_error, function() { + var obj = { + [Symbol.iterator]: Array.prototype[Symbol.iterator], + length: { + valueOf: null, + toString: function() { throw test_error; } + } + }; + new Blob(obj); + }); + assert_throws_exactly(test_error, function() { + var obj = { + [Symbol.iterator]: Array.prototype[Symbol.iterator], + length: { valueOf: function() { throw test_error; } } + }; + new Blob(obj); + }); +}, "ToUint32 should be applied to the length and any exceptions should be propagated."); + +test(function() { + var received = []; + var obj = { + get [Symbol.iterator]() { + received.push("Symbol.iterator"); + return Array.prototype[Symbol.iterator]; + }, + get length() { + received.push("length getter"); + return { + valueOf: function() { + received.push("length valueOf"); + return 3; + } + }; + }, + get 0() { + received.push("0 getter"); + return { + toString: function() { + received.push("0 toString"); + return "a"; + } + }; + }, + get 1() { + received.push("1 getter"); + throw test_error; + }, + get 2() { + received.push("2 getter"); + assert_unreached("Should not call the getter for 2 if the getter for 1 threw."); + } + }; + assert_throws_exactly(test_error, function() { + new Blob(obj); + }); + assert_array_equals(received, [ + "Symbol.iterator", + "length getter", + "length valueOf", + "0 getter", + "0 toString", + "length getter", + "length valueOf", + "1 getter", + ]); +}, "Getters and value conversions should happen in order until an exception is thrown."); + +// XXX should add tests edge cases of ToLength(length) + +test(function() { + assert_throws_exactly(test_error, function() { + new Blob([{ toString: function() { throw test_error; } }]); + }, "Throwing toString"); + assert_throws_exactly(test_error, function() { + new Blob([{ toString: undefined, valueOf: function() { throw test_error; } }]); + }, "Throwing valueOf"); + assert_throws_exactly(test_error, function() { + new Blob([{ + toString: function() { throw test_error; }, + valueOf: function() { assert_unreached("Should not call valueOf if toString is present."); } + }]); + }, "Throwing toString and valueOf"); + assert_throws_js(TypeError, function() { + new Blob([{toString: null, valueOf: null}]); + }, "Null toString and valueOf"); +}, "ToString should be called on elements of the blobParts array and any exceptions should be propagated."); + +test_blob(function() { + var arr = [ + { toString: function() { arr.pop(); return "PASS"; } }, + { toString: function() { assert_unreached("Should have removed the second element of the array rather than called toString() on it."); } } + ]; + return new Blob(arr); +}, { + expected: "PASS", + type: "", + desc: "Changes to the blobParts array should be reflected in the returned Blob (pop)." +}); + +test_blob(function() { + var arr = [ + { + toString: function() { + if (arr.length === 3) { + return "A"; + } + arr.unshift({ + toString: function() { + assert_unreached("Should only access index 0 once."); + } + }); + return "P"; + } + }, + { + toString: function() { + return "SS"; + } + } + ]; + return new Blob(arr); +}, { + expected: "PASS", + type: "", + desc: "Changes to the blobParts array should be reflected in the returned Blob (unshift)." +}); + +test_blob(function() { + // https://www.w3.org/Bugs/Public/show_bug.cgi?id=17652 + return new Blob([ + null, + undefined, + true, + false, + 0, + 1, + new String("stringobject"), + [], + ['x', 'y'], + {}, + { 0: "FAIL", length: 1 }, + { toString: function() { return "stringA"; } }, + { toString: undefined, valueOf: function() { return "stringB"; } }, + { valueOf: function() { assert_unreached("Should not call valueOf if toString is present on the prototype."); } } + ]); +}, { + expected: "nullundefinedtruefalse01stringobjectx,y[object Object][object Object]stringAstringB[object Object]", + type: "", + desc: "ToString should be called on elements of the blobParts array." +}); + +test_blob(function() { + return new Blob([ + new ArrayBuffer(8) + ]); +}, { + expected: "\0\0\0\0\0\0\0\0", + type: "", + desc: "ArrayBuffer elements of the blobParts array should be supported." +}); + +test_blob(function() { + return new Blob([ + new Uint8Array([0x50, 0x41, 0x53, 0x53]), + new Int8Array([0x50, 0x41, 0x53, 0x53]), + new Uint16Array([0x4150, 0x5353]), + new Int16Array([0x4150, 0x5353]), + new Uint32Array([0x53534150]), + new Int32Array([0x53534150]), + new Float32Array([0xD341500000]) + ]); +}, { + expected: "PASSPASSPASSPASSPASSPASSPASS", + type: "", + desc: "Passing typed arrays as elements of the blobParts array should work." +}); +test_blob(function() { + return new Blob([ + // 0x535 3415053534150 + // 0x535 = 0b010100110101 -> Sign = +, Exponent = 1333 - 1023 = 310 + // 0x13415053534150 * 2**(-52) + // ==> 0x13415053534150 * 2**258 = 2510297372767036725005267563121821874921913208671273727396467555337665343087229079989707079680 + new Float64Array([2510297372767036725005267563121821874921913208671273727396467555337665343087229079989707079680]) + ]); +}, { + expected: "PASSPASS", + type: "", + desc: "Passing a Float64Array as element of the blobParts array should work." +}); + +test_blob(function() { + return new Blob([ + new BigInt64Array([BigInt("0x5353415053534150")]), + new BigUint64Array([BigInt("0x5353415053534150")]) + ]); +}, { + expected: "PASSPASSPASSPASS", + type: "", + desc: "Passing BigInt typed arrays as elements of the blobParts array should work." +}); + +var t_ports = async_test("Passing a FrozenArray as the blobParts array should work (FrozenArray)."); +t_ports.step(function() { + var channel = new MessageChannel(); + channel.port2.onmessage = this.step_func(function(e) { + var b_ports = new Blob(e.ports); + assert_equals(b_ports.size, "[object MessagePort]".length); + this.done(); + }); + var channel2 = new MessageChannel(); + channel.port1.postMessage('', [channel2.port1]); +}); + +test_blob(function() { + var blob = new Blob(['foo']); + return new Blob([blob, blob]); +}, { + expected: "foofoo", + type: "", + desc: "Array with two blobs" +}); + +test_blob_binary(function() { + var view = new Uint8Array([0, 255, 0]); + return new Blob([view.buffer, view.buffer]); +}, { + expected: [0, 255, 0, 0, 255, 0], + type: "", + desc: "Array with two buffers" +}); + +test_blob_binary(function() { + var view = new Uint8Array([0, 255, 0, 4]); + var blob = new Blob([view, view]); + assert_equals(blob.size, 8); + var view1 = new Uint16Array(view.buffer, 2); + return new Blob([view1, view.buffer, view1]); +}, { + expected: [0, 4, 0, 255, 0, 4, 0, 4], + type: "", + desc: "Array with two bufferviews" +}); + +test_blob(function() { + var view = new Uint8Array([0]); + var blob = new Blob(["fo"]); + return new Blob([view.buffer, blob, "foo"]); +}, { + expected: "\0fofoo", + type: "", + desc: "Array with mixed types" +}); + +test(function() { + const accessed = []; + const stringified = []; + + new Blob([], { + get type() { accessed.push('type'); }, + get endings() { accessed.push('endings'); } + }); + new Blob([], { + type: { toString: () => { stringified.push('type'); return ''; } }, + endings: { toString: () => { stringified.push('endings'); return 'transparent'; } } + }); + assert_array_equals(accessed, ['endings', 'type']); + assert_array_equals(stringified, ['endings', 'type']); +}, "options properties should be accessed in lexicographic order."); + +test(function() { + assert_throws_exactly(test_error, function() { + new Blob( + [{ toString: function() { throw test_error } }], + { + get type() { assert_unreached("type getter should not be called."); } + } + ); + }); +}, "Arguments should be evaluated from left to right."); + +[ + null, + undefined, + {}, + { unrecognized: true }, + /regex/, + function() {} +].forEach(function(arg, idx) { + test_blob(function() { + return new Blob([], arg); + }, { + expected: "", + type: "", + desc: "Passing " + format_value(arg) + " (index " + idx + ") for options should use the defaults." + }); + test_blob(function() { + return new Blob(["\na\r\nb\n\rc\r"], arg); + }, { + expected: "\na\r\nb\n\rc\r", + type: "", + desc: "Passing " + format_value(arg) + " (index " + idx + ") for options should use the defaults (with newlines)." + }); +}); + +[ + 123, + 123.4, + true, + 'abc' +].forEach(arg => { + test(t => { + assert_throws_js(TypeError, () => new Blob([], arg), + 'Blob constructor should throw with invalid property bag'); + }, `Passing ${JSON.stringify(arg)} for options should throw`); +}); + +var type_tests = [ + // blobParts, type, expected type + [[], '', ''], + [[], 'a', 'a'], + [[], 'A', 'a'], + [[], 'text/html', 'text/html'], + [[], 'TEXT/HTML', 'text/html'], + [[], 'text/plain;charset=utf-8', 'text/plain;charset=utf-8'], + [[], '\u00E5', ''], + [[], '\uD801\uDC7E', ''], // U+1047E + [[], ' image/gif ', ' image/gif '], + [[], '\timage/gif\t', ''], + [[], 'image/gif;\u007f', ''], + [[], '\u0130mage/gif', ''], // uppercase i with dot + [[], '\u0131mage/gif', ''], // lowercase dotless i + [[], 'image/gif\u0000', ''], + // check that type isn't changed based on sniffing + [[0x3C, 0x48, 0x54, 0x4D, 0x4C, 0x3E], 'unknown/unknown', 'unknown/unknown'], // "" + [[0x00, 0xFF], 'text/plain', 'text/plain'], + [[0x47, 0x49, 0x46, 0x38, 0x39, 0x61], 'image/png', 'image/png'], // "GIF89a" +]; + +type_tests.forEach(function(t) { + test(function() { + var arr = new Uint8Array([t[0]]).buffer; + var b = new Blob([arr], {type:t[1]}); + assert_equals(b.type, t[2]); + }, "Blob with type " + format_value(t[1])); +}); diff --git a/test/wpt/tests/FileAPI/blob/Blob-in-worker.worker.js b/test/wpt/tests/FileAPI/blob/Blob-in-worker.worker.js new file mode 100644 index 0000000..a0ca845 --- /dev/null +++ b/test/wpt/tests/FileAPI/blob/Blob-in-worker.worker.js @@ -0,0 +1,9 @@ +importScripts("/resources/testharness.js"); + +promise_test(async () => { + const data = "TEST"; + const blob = new Blob([data], {type: "text/plain"}); + assert_equals(await blob.text(), data); +}, 'Create Blob in Worker'); + +done(); diff --git a/test/wpt/tests/FileAPI/blob/Blob-slice-overflow.any.js b/test/wpt/tests/FileAPI/blob/Blob-slice-overflow.any.js new file mode 100644 index 0000000..388fd92 --- /dev/null +++ b/test/wpt/tests/FileAPI/blob/Blob-slice-overflow.any.js @@ -0,0 +1,32 @@ +// META: title=Blob slice overflow +'use strict'; + +var text = ''; + +for (var i = 0; i < 2000; ++i) { + text += 'A'; +} + +test(function() { + var blob = new Blob([text]); + var sliceBlob = blob.slice(-1, blob.size); + assert_equals(sliceBlob.size, 1, "Blob slice size"); +}, "slice start is negative, relativeStart will be max((size + start), 0)"); + +test(function() { + var blob = new Blob([text]); + var sliceBlob = blob.slice(blob.size + 1, blob.size); + assert_equals(sliceBlob.size, 0, "Blob slice size"); +}, "slice start is greater than blob size, relativeStart will be min(start, size)"); + +test(function() { + var blob = new Blob([text]); + var sliceBlob = blob.slice(blob.size - 2, -1); + assert_equals(sliceBlob.size, 1, "Blob slice size"); +}, "slice end is negative, relativeEnd will be max((size + end), 0)"); + +test(function() { + var blob = new Blob([text]); + var sliceBlob = blob.slice(blob.size - 2, blob.size + 999); + assert_equals(sliceBlob.size, 2, "Blob slice size"); +}, "slice end is greater than blob size, relativeEnd will be min(end, size)"); diff --git a/test/wpt/tests/FileAPI/blob/Blob-slice.any.js b/test/wpt/tests/FileAPI/blob/Blob-slice.any.js new file mode 100644 index 0000000..1f85d44 --- /dev/null +++ b/test/wpt/tests/FileAPI/blob/Blob-slice.any.js @@ -0,0 +1,231 @@ +// META: title=Blob slice +// META: script=../support/Blob.js +'use strict'; + +test_blob(function() { + var blobTemp = new Blob(["PASS"]); + return blobTemp.slice(); +}, { + expected: "PASS", + type: "", + desc: "no-argument Blob slice" +}); + +test(function() { + var blob1, blob2; + + test_blob(function() { + return blob1 = new Blob(["squiggle"]); + }, { + expected: "squiggle", + type: "", + desc: "blob1." + }); + + test_blob(function() { + return blob2 = new Blob(["steak"], {type: "content/type"}); + }, { + expected: "steak", + type: "content/type", + desc: "blob2." + }); + + test_blob(function() { + return new Blob().slice(0,0,null); + }, { + expected: "", + type: "null", + desc: "null type Blob slice" + }); + + test_blob(function() { + return new Blob().slice(0,0,undefined); + }, { + expected: "", + type: "", + desc: "undefined type Blob slice" + }); + + test_blob(function() { + return new Blob().slice(0,0); + }, { + expected: "", + type: "", + desc: "no type Blob slice" + }); + + var arrayBuffer = new ArrayBuffer(16); + var int8View = new Int8Array(arrayBuffer); + for (var i = 0; i < 16; i++) { + int8View[i] = i + 65; + } + + var testData = [ + [ + ["PASSSTRING"], + [{start: -6, contents: "STRING"}, + {start: -12, contents: "PASSSTRING"}, + {start: 4, contents: "STRING"}, + {start: 12, contents: ""}, + {start: 0, end: -6, contents: "PASS"}, + {start: 0, end: -12, contents: ""}, + {start: 0, end: 4, contents: "PASS"}, + {start: 0, end: 12, contents: "PASSSTRING"}, + {start: 7, end: 4, contents: ""}] + ], + + // Test 3 strings + [ + ["foo", "bar", "baz"], + [{start: 0, end: 9, contents: "foobarbaz"}, + {start: 0, end: 3, contents: "foo"}, + {start: 3, end: 9, contents: "barbaz"}, + {start: 6, end: 9, contents: "baz"}, + {start: 6, end: 12, contents: "baz"}, + {start: 0, end: 9, contents: "foobarbaz"}, + {start: 0, end: 11, contents: "foobarbaz"}, + {start: 10, end: 15, contents: ""}] + ], + + // Test string, Blob, string + [ + ["foo", blob1, "baz"], + [{start: 0, end: 3, contents: "foo"}, + {start: 3, end: 11, contents: "squiggle"}, + {start: 2, end: 4, contents: "os"}, + {start: 10, end: 12, contents: "eb"}] + ], + + // Test blob, string, blob + [ + [blob1, "foo", blob1], + [{start: 0, end: 8, contents: "squiggle"}, + {start: 7, end: 9, contents: "ef"}, + {start: 10, end: 12, contents: "os"}, + {start: 1, end: 4, contents: "qui"}, + {start: 12, end: 15, contents: "qui"}, + {start: 40, end: 60, contents: ""}] + ], + + // Test blobs all the way down + [ + [blob2, blob1, blob2], + [{start: 0, end: 5, contents: "steak"}, + {start: 5, end: 13, contents: "squiggle"}, + {start: 13, end: 18, contents: "steak"}, + {start: 1, end: 3, contents: "te"}, + {start: 6, end: 10, contents: "quig"}] + ], + + // Test an ArrayBufferView + [ + [int8View, blob1, "foo"], + [{start: 0, end: 8, contents: "ABCDEFGH"}, + {start: 8, end: 18, contents: "IJKLMNOPsq"}, + {start: 17, end: 20, contents: "qui"}, + {start: 4, end: 12, contents: "EFGHIJKL"}] + ], + + // Test a partial ArrayBufferView + [ + [new Uint8Array(arrayBuffer, 3, 5), blob1, "foo"], + [{start: 0, end: 8, contents: "DEFGHsqu"}, + {start: 8, end: 18, contents: "igglefoo"}, + {start: 4, end: 12, contents: "Hsquiggl"}] + ], + + // Test type coercion of a number + [ + [3, int8View, "foo"], + [{start: 0, end: 8, contents: "3ABCDEFG"}, + {start: 8, end: 18, contents: "HIJKLMNOPf"}, + {start: 17, end: 21, contents: "foo"}, + {start: 4, end: 12, contents: "DEFGHIJK"}] + ], + + [ + [(new Uint8Array([0, 255, 0])).buffer, + new Blob(['abcd']), + 'efgh', + 'ijklmnopqrstuvwxyz'], + [{start: 1, end: 4, contents: "\uFFFD\u0000a"}, + {start: 4, end: 8, contents: "bcde"}, + {start: 8, end: 12, contents: "fghi"}, + {start: 1, end: 12, contents: "\uFFFD\u0000abcdefghi"}] + ] + ]; + + testData.forEach(function(data, i) { + var blobs = data[0]; + var tests = data[1]; + tests.forEach(function(expectations, j) { + test(function() { + var blob = new Blob(blobs); + assert_true(blob instanceof Blob); + assert_false(blob instanceof File); + + test_blob(function() { + return expectations.end === undefined + ? blob.slice(expectations.start) + : blob.slice(expectations.start, expectations.end); + }, { + expected: expectations.contents, + type: "", + desc: "Slicing test: slice (" + i + "," + j + ")." + }); + }, "Slicing test (" + i + "," + j + ")."); + }); + }); +}, "Slices"); + +var invalidTypes = [ + "\xFF", + "te\x09xt/plain", + "te\x00xt/plain", + "te\x1Fxt/plain", + "te\x7Fxt/plain" +]; +invalidTypes.forEach(function(type) { + test_blob(function() { + var blob = new Blob(["PASS"]); + return blob.slice(0, 4, type); + }, { + expected: "PASS", + type: "", + desc: "Invalid contentType (" + format_value(type) + ")" + }); +}); + +var validTypes = [ + "te(xt/plain", + "te)xt/plain", + "text/plain", + "te@xt/plain", + "te,xt/plain", + "te;xt/plain", + "te:xt/plain", + "te\\xt/plain", + "te\"xt/plain", + "te/xt/plain", + "te[xt/plain", + "te]xt/plain", + "te?xt/plain", + "te=xt/plain", + "te{xt/plain", + "te}xt/plain", + "te\x20xt/plain", + "TEXT/PLAIN", + "text/plain;charset = UTF-8", + "text/plain;charset=UTF-8" +]; +validTypes.forEach(function(type) { + test_blob(function() { + var blob = new Blob(["PASS"]); + return blob.slice(0, 4, type); + }, { + expected: "PASS", + type: type.toLowerCase(), + desc: "Valid contentType (" + format_value(type) + ")" + }); +}); diff --git a/test/wpt/tests/FileAPI/blob/Blob-stream-byob-crash.html b/test/wpt/tests/FileAPI/blob/Blob-stream-byob-crash.html new file mode 100644 index 0000000..5992ed1 --- /dev/null +++ b/test/wpt/tests/FileAPI/blob/Blob-stream-byob-crash.html @@ -0,0 +1,11 @@ + + diff --git a/test/wpt/tests/FileAPI/blob/Blob-stream-sync-xhr-crash.html b/test/wpt/tests/FileAPI/blob/Blob-stream-sync-xhr-crash.html new file mode 100644 index 0000000..fe54fb6 --- /dev/null +++ b/test/wpt/tests/FileAPI/blob/Blob-stream-sync-xhr-crash.html @@ -0,0 +1,13 @@ + + diff --git a/test/wpt/tests/FileAPI/blob/Blob-stream.any.js b/test/wpt/tests/FileAPI/blob/Blob-stream.any.js new file mode 100644 index 0000000..87710a1 --- /dev/null +++ b/test/wpt/tests/FileAPI/blob/Blob-stream.any.js @@ -0,0 +1,83 @@ +// META: title=Blob Stream +// META: script=../support/Blob.js +// META: script=/common/gc.js +'use strict'; + +// Helper function that triggers garbage collection while reading a chunk +// if perform_gc is true. +async function read_and_gc(reader, perform_gc) { + // Passing Uint8Array for byte streams; non-byte streams will simply ignore it + const read_promise = reader.read(new Uint8Array(64)); + if (perform_gc) { + await garbageCollect(); + } + return read_promise; +} + +// Takes in a ReadableStream and reads from it until it is done, returning +// an array that contains the results of each read operation. If perform_gc +// is true, garbage collection is triggered while reading every chunk. +async function read_all_chunks(stream, { perform_gc = false, mode } = {}) { + assert_true(stream instanceof ReadableStream); + assert_true('getReader' in stream); + const reader = stream.getReader({ mode }); + + assert_true('read' in reader); + let read_value = await read_and_gc(reader, perform_gc); + + let out = []; + let i = 0; + while (!read_value.done) { + for (let val of read_value.value) { + out[i++] = val; + } + read_value = await read_and_gc(reader, perform_gc); + } + return out; +} + +promise_test(async () => { + const blob = new Blob(["PASS"]); + const stream = blob.stream(); + const chunks = await read_all_chunks(stream); + for (let [index, value] of chunks.entries()) { + assert_equals(value, "PASS".charCodeAt(index)); + } +}, "Blob.stream()") + +promise_test(async () => { + const blob = new Blob(); + const stream = blob.stream(); + const chunks = await read_all_chunks(stream); + assert_array_equals(chunks, []); +}, "Blob.stream() empty Blob") + +promise_test(async () => { + const input_arr = [8, 241, 48, 123, 151]; + const typed_arr = new Uint8Array(input_arr); + const blob = new Blob([typed_arr]); + const stream = blob.stream(); + const chunks = await read_all_chunks(stream); + assert_array_equals(chunks, input_arr); +}, "Blob.stream() non-unicode input") + +promise_test(async() => { + const input_arr = [8, 241, 48, 123, 151]; + const typed_arr = new Uint8Array(input_arr); + let blob = new Blob([typed_arr]); + const stream = blob.stream(); + blob = null; + await garbageCollect(); + const chunks = await read_all_chunks(stream, { perform_gc: true }); + assert_array_equals(chunks, input_arr); +}, "Blob.stream() garbage collection of blob shouldn't break stream" + + "consumption") + +promise_test(async () => { + const input_arr = [8, 241, 48, 123, 151]; + const typed_arr = new Uint8Array(input_arr); + let blob = new Blob([typed_arr]); + const stream = blob.stream(); + const chunks = await read_all_chunks(stream, { mode: "byob" }); + assert_array_equals(chunks, input_arr); +}, "Reading Blob.stream() with BYOB reader") diff --git a/test/wpt/tests/FileAPI/blob/Blob-text.any.js b/test/wpt/tests/FileAPI/blob/Blob-text.any.js new file mode 100644 index 0000000..d04fa97 --- /dev/null +++ b/test/wpt/tests/FileAPI/blob/Blob-text.any.js @@ -0,0 +1,64 @@ +// META: title=Blob Text +// META: script=../support/Blob.js +'use strict'; + +promise_test(async () => { + const blob = new Blob(["PASS"]); + const text = await blob.text(); + assert_equals(text, "PASS"); +}, "Blob.text()") + +promise_test(async () => { + const blob = new Blob(); + const text = await blob.text(); + assert_equals(text, ""); +}, "Blob.text() empty blob data") + +promise_test(async () => { + const blob = new Blob(["P", "A", "SS"]); + const text = await blob.text(); + assert_equals(text, "PASS"); +}, "Blob.text() multi-element array in constructor") + +promise_test(async () => { + const non_unicode = "\u0061\u030A"; + const input_arr = new TextEncoder().encode(non_unicode); + const blob = new Blob([input_arr]); + const text = await blob.text(); + assert_equals(text, non_unicode); +}, "Blob.text() non-unicode") + +promise_test(async () => { + const blob = new Blob(["PASS"], { type: "text/plain;charset=utf-16le" }); + const text = await blob.text(); + assert_equals(text, "PASS"); +}, "Blob.text() different charset param in type option") + +promise_test(async () => { + const non_unicode = "\u0061\u030A"; + const input_arr = new TextEncoder().encode(non_unicode); + const blob = new Blob([input_arr], { type: "text/plain;charset=utf-16le" }); + const text = await blob.text(); + assert_equals(text, non_unicode); +}, "Blob.text() different charset param with non-ascii input") + +promise_test(async () => { + const input_arr = new Uint8Array([192, 193, 245, 246, 247, 248, 249, 250, 251, + 252, 253, 254, 255]); + const blob = new Blob([input_arr]); + const text = await blob.text(); + assert_equals(text, "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd" + + "\ufffd\ufffd\ufffd\ufffd"); +}, "Blob.text() invalid utf-8 input") + +promise_test(async () => { + const input_arr = new Uint8Array([192, 193, 245, 246, 247, 248, 249, 250, 251, + 252, 253, 254, 255]); + const blob = new Blob([input_arr]); + const text_results = await Promise.all([blob.text(), blob.text(), + blob.text()]); + for (let text of text_results) { + assert_equals(text, "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd" + + "\ufffd\ufffd\ufffd\ufffd"); + } +}, "Blob.text() concurrent reads") diff --git a/test/wpt/tests/FileAPI/file/File-constructor-endings.html b/test/wpt/tests/FileAPI/file/File-constructor-endings.html new file mode 100644 index 0000000..1282b6c --- /dev/null +++ b/test/wpt/tests/FileAPI/file/File-constructor-endings.html @@ -0,0 +1,104 @@ + + +File constructor: endings option + + + + diff --git a/test/wpt/tests/FileAPI/file/File-constructor.any.js b/test/wpt/tests/FileAPI/file/File-constructor.any.js new file mode 100644 index 0000000..0b0185c --- /dev/null +++ b/test/wpt/tests/FileAPI/file/File-constructor.any.js @@ -0,0 +1,155 @@ +// META: title=File constructor + +const to_string_obj = { toString: () => 'a string' }; +const to_string_throws = { toString: () => { throw new Error('expected'); } }; + +test(function() { + assert_true("File" in globalThis, "globalThis should have a File property."); +}, "File interface object exists"); + +test(t => { + assert_throws_js(TypeError, () => new File(), + 'Bits argument is required'); + assert_throws_js(TypeError, () => new File([]), + 'Name argument is required'); +}, 'Required arguments'); + +function test_first_argument(arg1, expectedSize, testName) { + test(function() { + var file = new File(arg1, "dummy"); + assert_true(file instanceof File); + assert_equals(file.name, "dummy"); + assert_equals(file.size, expectedSize); + assert_equals(file.type, ""); + // assert_false(file.isClosed); XXX: File.isClosed doesn't seem to be implemented + assert_not_equals(file.lastModified, ""); + }, testName); +} + +test_first_argument([], 0, "empty fileBits"); +test_first_argument(["bits"], 4, "DOMString fileBits"); +test_first_argument(["ð“½ð“®ð”ð“½"], 16, "Unicode DOMString fileBits"); +test_first_argument([new String('string object')], 13, "String object fileBits"); +test_first_argument([new Blob()], 0, "Empty Blob fileBits"); +test_first_argument([new Blob(["bits"])], 4, "Blob fileBits"); +test_first_argument([new File([], 'world.txt')], 0, "Empty File fileBits"); +test_first_argument([new File(["bits"], 'world.txt')], 4, "File fileBits"); +test_first_argument([new ArrayBuffer(8)], 8, "ArrayBuffer fileBits"); +test_first_argument([new Uint8Array([0x50, 0x41, 0x53, 0x53])], 4, "Typed array fileBits"); +test_first_argument(["bits", new Blob(["bits"]), new Blob(), new Uint8Array([0x50, 0x41]), + new Uint16Array([0x5353]), new Uint32Array([0x53534150])], 16, "Various fileBits"); +test_first_argument([12], 2, "Number in fileBits"); +test_first_argument([[1,2,3]], 5, "Array in fileBits"); +test_first_argument([{}], 15, "Object in fileBits"); // "[object Object]" +if (globalThis.document !== undefined) { + test_first_argument([document.body], 24, "HTMLBodyElement in fileBits"); // "[object HTMLBodyElement]" +} +test_first_argument([to_string_obj], 8, "Object with toString in fileBits"); +test_first_argument({[Symbol.iterator]() { + let i = 0; + return {next: () => [ + {done:false, value:'ab'}, + {done:false, value:'cde'}, + {done:true} + ][i++]}; +}}, 5, 'Custom @@iterator'); + +[ + 'hello', + 0, + null +].forEach(arg => { + test(t => { + assert_throws_js(TypeError, () => new File(arg, 'world.html'), + 'Constructor should throw for invalid bits argument'); + }, `Invalid bits argument: ${JSON.stringify(arg)}`); +}); + +test(t => { + assert_throws_js(Error, () => new File([to_string_throws], 'name.txt'), + 'Constructor should propagate exceptions'); +}, 'Bits argument: object that throws'); + + +function test_second_argument(arg2, expectedFileName, testName) { + test(function() { + var file = new File(["bits"], arg2); + assert_true(file instanceof File); + assert_equals(file.name, expectedFileName); + }, testName); +} + +test_second_argument("dummy", "dummy", "Using fileName"); +test_second_argument("dummy/foo", "dummy/foo", + "No replacement when using special character in fileName"); +test_second_argument(null, "null", "Using null fileName"); +test_second_argument(1, "1", "Using number fileName"); +test_second_argument('', '', "Using empty string fileName"); +if (globalThis.document !== undefined) { + test_second_argument(document.body, '[object HTMLBodyElement]', "Using object fileName"); +} + +// testing the third argument +[ + {type: 'text/plain', expected: 'text/plain'}, + {type: 'text/plain;charset=UTF-8', expected: 'text/plain;charset=utf-8'}, + {type: 'TEXT/PLAIN', expected: 'text/plain'}, + {type: 'ð“½ð“®ð”ð“½/ð”­ð”©ð”žð”¦ð”«', expected: ''}, + {type: 'ascii/nonprintable\u001F', expected: ''}, + {type: 'ascii/nonprintable\u007F', expected: ''}, + {type: 'nonascii\u00EE', expected: ''}, + {type: 'nonascii\u1234', expected: ''}, + {type: 'nonparsable', expected: 'nonparsable'} +].forEach(testCase => { + test(t => { + var file = new File(["bits"], "dummy", { type: testCase.type}); + assert_true(file instanceof File); + assert_equals(file.type, testCase.expected); + }, `Using type in File constructor: ${testCase.type}`); +}); +test(function() { + var file = new File(["bits"], "dummy", { lastModified: 42 }); + assert_true(file instanceof File); + assert_equals(file.lastModified, 42); +}, "Using lastModified"); +test(function() { + var file = new File(["bits"], "dummy", { name: "foo" }); + assert_true(file instanceof File); + assert_equals(file.name, "dummy"); +}, "Misusing name"); +test(function() { + var file = new File(["bits"], "dummy", { unknownKey: "value" }); + assert_true(file instanceof File); + assert_equals(file.name, "dummy"); +}, "Unknown properties are ignored"); + +[ + 123, + 123.4, + true, + 'abc' +].forEach(arg => { + test(t => { + assert_throws_js(TypeError, () => new File(['bits'], 'name.txt', arg), + 'Constructor should throw for invalid property bag type'); + }, `Invalid property bag: ${JSON.stringify(arg)}`); +}); + +[ + null, + undefined, + [1,2,3], + /regex/, + function() {} +].forEach(arg => { + test(t => { + assert_equals(new File(['bits'], 'name.txt', arg).size, 4, + 'Constructor should accept object-ish property bag type'); + }, `Unusual but valid property bag: ${arg}`); +}); + +test(t => { + assert_throws_js(Error, + () => new File(['bits'], 'name.txt', {type: to_string_throws}), + 'Constructor should propagate exceptions'); +}, 'Property bag propagates exceptions'); diff --git a/test/wpt/tests/FileAPI/file/Worker-read-file-constructor.worker.js b/test/wpt/tests/FileAPI/file/Worker-read-file-constructor.worker.js new file mode 100644 index 0000000..4e003b3 --- /dev/null +++ b/test/wpt/tests/FileAPI/file/Worker-read-file-constructor.worker.js @@ -0,0 +1,15 @@ +importScripts("/resources/testharness.js"); + +async_test(function() { + var file = new File(["bits"], "dummy", { 'type': 'text/plain', lastModified: 42 }); + var reader = new FileReader(); + reader.onload = this.step_func_done(function() { + assert_equals(file.name, "dummy", "file name"); + assert_equals(reader.result, "bits", "file content"); + assert_equals(file.lastModified, 42, "file lastModified"); + }); + reader.onerror = this.unreached_func("Unexpected error event"); + reader.readAsText(file); +}, "FileReader in Worker"); + +done(); diff --git a/test/wpt/tests/FileAPI/file/resources/echo-content-escaped.py b/test/wpt/tests/FileAPI/file/resources/echo-content-escaped.py new file mode 100644 index 0000000..5370e1e --- /dev/null +++ b/test/wpt/tests/FileAPI/file/resources/echo-content-escaped.py @@ -0,0 +1,26 @@ +from wptserve.utils import isomorphic_encode + +# Outputs the request body, with controls and non-ASCII bytes escaped +# (b"\n" becomes b"\\x0a"), and with backslashes doubled. +# As a convenience, CRLF newlines are left as is. + +def escape_byte(byte): + # Convert int byte into a single-char binary string. + byte = bytes([byte]) + if b"\0" <= byte <= b"\x1F" or byte >= b"\x7F": + return b"\\x%02x" % ord(byte) + if byte == b"\\": + return b"\\\\" + return byte + +def main(request, response): + + headers = [(b"X-Request-Method", isomorphic_encode(request.method)), + (b"X-Request-Content-Length", request.headers.get(b"Content-Length", b"NO")), + (b"X-Request-Content-Type", request.headers.get(b"Content-Type", b"NO")), + # Avoid any kind of content sniffing on the response. + (b"Content-Type", b"text/plain; charset=UTF-8")] + + content = b"".join(map(escape_byte, request.body)).replace(b"\\x0d\\x0a", b"\r\n") + + return headers, content diff --git a/test/wpt/tests/FileAPI/file/send-file-form-controls.html b/test/wpt/tests/FileAPI/file/send-file-form-controls.html new file mode 100644 index 0000000..6347065 --- /dev/null +++ b/test/wpt/tests/FileAPI/file/send-file-form-controls.html @@ -0,0 +1,113 @@ + + +Upload files named using controls + + + + + + + + diff --git a/test/wpt/tests/FileAPI/file/send-file-form-iso-2022-jp.html b/test/wpt/tests/FileAPI/file/send-file-form-iso-2022-jp.html new file mode 100644 index 0000000..c931c9b --- /dev/null +++ b/test/wpt/tests/FileAPI/file/send-file-form-iso-2022-jp.html @@ -0,0 +1,65 @@ + + + +Upload files in ISO-2022-JP form + + + + + + + + diff --git a/test/wpt/tests/FileAPI/file/send-file-form-punctuation.html b/test/wpt/tests/FileAPI/file/send-file-form-punctuation.html new file mode 100644 index 0000000..a6568e2 --- /dev/null +++ b/test/wpt/tests/FileAPI/file/send-file-form-punctuation.html @@ -0,0 +1,226 @@ + + +Upload files named using punctuation + + + + + + + + diff --git a/test/wpt/tests/FileAPI/file/send-file-form-utf-8.html b/test/wpt/tests/FileAPI/file/send-file-form-utf-8.html new file mode 100644 index 0000000..1be44f4 --- /dev/null +++ b/test/wpt/tests/FileAPI/file/send-file-form-utf-8.html @@ -0,0 +1,62 @@ + + +Upload files in UTF-8 form + + + + + + + + diff --git a/test/wpt/tests/FileAPI/file/send-file-form-windows-1252.html b/test/wpt/tests/FileAPI/file/send-file-form-windows-1252.html new file mode 100644 index 0000000..21b219f --- /dev/null +++ b/test/wpt/tests/FileAPI/file/send-file-form-windows-1252.html @@ -0,0 +1,62 @@ + + +Upload files in Windows-1252 form + + + + + + + + diff --git a/test/wpt/tests/FileAPI/file/send-file-form-x-user-defined.html b/test/wpt/tests/FileAPI/file/send-file-form-x-user-defined.html new file mode 100644 index 0000000..8d6605d --- /dev/null +++ b/test/wpt/tests/FileAPI/file/send-file-form-x-user-defined.html @@ -0,0 +1,63 @@ + + +Upload files in x-user-defined form + + + + + + + + diff --git a/test/wpt/tests/FileAPI/file/send-file-form.html b/test/wpt/tests/FileAPI/file/send-file-form.html new file mode 100644 index 0000000..baa8d42 --- /dev/null +++ b/test/wpt/tests/FileAPI/file/send-file-form.html @@ -0,0 +1,25 @@ + + +Upload ASCII-named file in UTF-8 form + + + + + + + + diff --git a/test/wpt/tests/FileAPI/file/send-file-formdata-controls.any.js b/test/wpt/tests/FileAPI/file/send-file-formdata-controls.any.js new file mode 100644 index 0000000..e95d3aa --- /dev/null +++ b/test/wpt/tests/FileAPI/file/send-file-formdata-controls.any.js @@ -0,0 +1,69 @@ +// META: title=FormData: FormData: Upload files named using controls +// META: script=../support/send-file-formdata-helper.js + "use strict"; + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-NUL-[\0].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-BS-[\b].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-VT-[\v].txt", + }); + + // These have characters that undergo processing in name=, + // filename=, and/or value; formDataPostFileUploadTest postprocesses + // expectedEncodedBaseName for these internally. + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-LF-[\n].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-LF-CR-[\n\r].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-CR-[\r].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-CR-LF-[\r\n].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-HT-[\t].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-FF-[\f].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-DEL-[\x7F].txt", + }); + + // The rest should be passed through unmodified: + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-ESC-[\x1B].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-SPACE-[ ].txt", + }); diff --git a/test/wpt/tests/FileAPI/file/send-file-formdata-punctuation.any.js b/test/wpt/tests/FileAPI/file/send-file-formdata-punctuation.any.js new file mode 100644 index 0000000..987dba3 --- /dev/null +++ b/test/wpt/tests/FileAPI/file/send-file-formdata-punctuation.any.js @@ -0,0 +1,144 @@ +// META: title=FormData: FormData: Upload files named using punctuation +// META: script=../support/send-file-formdata-helper.js + "use strict"; + + // These have characters that undergo processing in name=, + // filename=, and/or value; formDataPostFileUploadTest postprocesses + // expectedEncodedBaseName for these internally. + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-QUOTATION-MARK-[\x22].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: '"file-for-upload-in-form-double-quoted.txt"', + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-REVERSE-SOLIDUS-[\\].txt", + }); + + // The rest should be passed through unmodified: + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-EXCLAMATION-MARK-[!].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-DOLLAR-SIGN-[$].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-PERCENT-SIGN-[%].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-AMPERSAND-[&].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-APOSTROPHE-['].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-LEFT-PARENTHESIS-[(].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-RIGHT-PARENTHESIS-[)].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-ASTERISK-[*].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-PLUS-SIGN-[+].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-COMMA-[,].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-FULL-STOP-[.].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-SOLIDUS-[/].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-COLON-[:].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-SEMICOLON-[;].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-EQUALS-SIGN-[=].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-QUESTION-MARK-[?].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-CIRCUMFLEX-ACCENT-[^].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-LEFT-SQUARE-BRACKET-[[].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-RIGHT-SQUARE-BRACKET-[]].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-LEFT-CURLY-BRACKET-[{].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-VERTICAL-LINE-[|].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-RIGHT-CURLY-BRACKET-[}].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form-TILDE-[~].txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "'file-for-upload-in-form-single-quoted.txt'", + }); diff --git a/test/wpt/tests/FileAPI/file/send-file-formdata-utf-8.any.js b/test/wpt/tests/FileAPI/file/send-file-formdata-utf-8.any.js new file mode 100644 index 0000000..b8bd74c --- /dev/null +++ b/test/wpt/tests/FileAPI/file/send-file-formdata-utf-8.any.js @@ -0,0 +1,33 @@ +// META: title=FormData: FormData: Upload files in UTF-8 fetch() +// META: script=../support/send-file-formdata-helper.js + "use strict"; + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form.txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "x-user-defined", + fileBaseName: "file-for-upload-in-form-\uF7F0\uF793\uF783\uF7A0.txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "windows-1252", + fileBaseName: "file-for-upload-in-form-☺😂.txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "JIS X 0201 and JIS X 0208", + fileBaseName: "file-for-upload-in-form-★星★.txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "Unicode", + fileBaseName: "file-for-upload-in-form-☺😂.txt", + }); + + formDataPostFileUploadTest({ + fileNameSource: "Unicode", + fileBaseName: `file-for-upload-in-form-${kTestChars}.txt`, + }); diff --git a/test/wpt/tests/FileAPI/file/send-file-formdata.any.js b/test/wpt/tests/FileAPI/file/send-file-formdata.any.js new file mode 100644 index 0000000..e13a348 --- /dev/null +++ b/test/wpt/tests/FileAPI/file/send-file-formdata.any.js @@ -0,0 +1,8 @@ +// META: title=FormData: Upload ASCII-named file in UTF-8 form +// META: script=../support/send-file-formdata-helper.js + "use strict"; + + formDataPostFileUploadTest({ + fileNameSource: "ASCII", + fileBaseName: "file-for-upload-in-form.txt", + }); diff --git a/test/wpt/tests/FileAPI/fileReader.any.js b/test/wpt/tests/FileAPI/fileReader.any.js new file mode 100644 index 0000000..2876dcb --- /dev/null +++ b/test/wpt/tests/FileAPI/fileReader.any.js @@ -0,0 +1,59 @@ +// META: title=FileReader States + +'use strict'; + +test(function () { + assert_true( + "FileReader" in globalThis, + "globalThis should have a FileReader property.", + ); +}, "FileReader interface object"); + +test(function () { + var fileReader = new FileReader(); + assert_true(fileReader instanceof FileReader); +}, "no-argument FileReader constructor"); + +var t_abort = async_test("FileReader States -- abort"); +t_abort.step(function () { + var fileReader = new FileReader(); + assert_equals(fileReader.readyState, 0); + assert_equals(fileReader.readyState, FileReader.EMPTY); + + var blob = new Blob(); + fileReader.readAsArrayBuffer(blob); + assert_equals(fileReader.readyState, 1); + assert_equals(fileReader.readyState, FileReader.LOADING); + + fileReader.onabort = this.step_func(function (e) { + assert_equals(fileReader.readyState, 2); + assert_equals(fileReader.readyState, FileReader.DONE); + t_abort.done(); + }); + fileReader.abort(); + fileReader.onabort = this.unreached_func("abort event should fire sync"); +}); + +var t_event = async_test("FileReader States -- events"); +t_event.step(function () { + var fileReader = new FileReader(); + + var blob = new Blob(); + fileReader.readAsArrayBuffer(blob); + + fileReader.onloadstart = this.step_func(function (e) { + assert_equals(fileReader.readyState, 1); + assert_equals(fileReader.readyState, FileReader.LOADING); + }); + + fileReader.onprogress = this.step_func(function (e) { + assert_equals(fileReader.readyState, 1); + assert_equals(fileReader.readyState, FileReader.LOADING); + }); + + fileReader.onloadend = this.step_func(function (e) { + assert_equals(fileReader.readyState, 2); + assert_equals(fileReader.readyState, FileReader.DONE); + t_event.done(); + }); +}); diff --git a/test/wpt/tests/FileAPI/filelist-section/filelist.html b/test/wpt/tests/FileAPI/filelist-section/filelist.html new file mode 100644 index 0000000..b97dcde --- /dev/null +++ b/test/wpt/tests/FileAPI/filelist-section/filelist.html @@ -0,0 +1,57 @@ + + + + + FileAPI Test: filelist + + + + + + + + + +
+ +
+
+ + + + + diff --git a/test/wpt/tests/FileAPI/filelist-section/filelist_multiple_selected_files-manual.html b/test/wpt/tests/FileAPI/filelist-section/filelist_multiple_selected_files-manual.html new file mode 100644 index 0000000..2efaa05 --- /dev/null +++ b/test/wpt/tests/FileAPI/filelist-section/filelist_multiple_selected_files-manual.html @@ -0,0 +1,64 @@ + + + + + FileAPI Test: filelist_multiple_selected_files + + + + + + + + + +
+ +
+
+

Test steps:

+
    +
  1. Download upload.txt, upload.zip to local.
  2. +
  3. Select the local two files (upload.txt, upload.zip) to run the test.
  4. +
+
+ +
+ + + + diff --git a/test/wpt/tests/FileAPI/filelist-section/filelist_selected_file-manual.html b/test/wpt/tests/FileAPI/filelist-section/filelist_selected_file-manual.html new file mode 100644 index 0000000..966aadd --- /dev/null +++ b/test/wpt/tests/FileAPI/filelist-section/filelist_selected_file-manual.html @@ -0,0 +1,64 @@ + + + + + FileAPI Test: filelist_selected_file + + + + + + + + + +
+ +
+
+

Test steps:

+
    +
  1. Download upload.txt to local.
  2. +
  3. Select the local upload.txt file to run the test.
  4. +
+
+ +
+ + + + diff --git a/test/wpt/tests/FileAPI/filelist-section/support/upload.txt b/test/wpt/tests/FileAPI/filelist-section/support/upload.txt new file mode 100644 index 0000000..f45965b --- /dev/null +++ b/test/wpt/tests/FileAPI/filelist-section/support/upload.txt @@ -0,0 +1 @@ +Hello, this is test file for file upload. diff --git a/test/wpt/tests/FileAPI/filelist-section/support/upload.zip b/test/wpt/tests/FileAPI/filelist-section/support/upload.zip new file mode 100644 index 0000000..a933d6a Binary files /dev/null and b/test/wpt/tests/FileAPI/filelist-section/support/upload.zip differ diff --git a/test/wpt/tests/FileAPI/historical.https.html b/test/wpt/tests/FileAPI/historical.https.html new file mode 100644 index 0000000..4f841f1 --- /dev/null +++ b/test/wpt/tests/FileAPI/historical.https.html @@ -0,0 +1,65 @@ + + + + + Historical features + + + + + +
+ + + diff --git a/test/wpt/tests/FileAPI/idlharness-manual.html b/test/wpt/tests/FileAPI/idlharness-manual.html new file mode 100644 index 0000000..c1d8b0c --- /dev/null +++ b/test/wpt/tests/FileAPI/idlharness-manual.html @@ -0,0 +1,45 @@ + + + + + File API manual IDL tests + + + + + + + + +

File API manual IDL tests

+ +

Either download upload.txt and select it below or select an + arbitrary local file.

+ +
+ +
+ +
+ + + + diff --git a/test/wpt/tests/FileAPI/idlharness.any.js b/test/wpt/tests/FileAPI/idlharness.any.js new file mode 100644 index 0000000..1744242 --- /dev/null +++ b/test/wpt/tests/FileAPI/idlharness.any.js @@ -0,0 +1,19 @@ +// META: script=/resources/WebIDLParser.js +// META: script=/resources/idlharness.js +// META: timeout=long + +'use strict'; + +// https://w3c.github.io/FileAPI/ + +idl_test( + ['FileAPI'], + ['dom', 'html', 'url'], + idl_array => { + idl_array.add_objects({ + Blob: ['new Blob(["TEST"])'], + File: ['new File(["myFileBits"], "myFileName")'], + FileReader: ['new FileReader()'] + }); + } +); diff --git a/test/wpt/tests/FileAPI/idlharness.html b/test/wpt/tests/FileAPI/idlharness.html new file mode 100644 index 0000000..45e8684 --- /dev/null +++ b/test/wpt/tests/FileAPI/idlharness.html @@ -0,0 +1,37 @@ + + + + + File API automated IDL tests (requiring dom) + + + + + + + + +

File API automated IDL tests

+ +
+ +
+ +
+ + + + + diff --git a/test/wpt/tests/FileAPI/idlharness.worker.js b/test/wpt/tests/FileAPI/idlharness.worker.js new file mode 100644 index 0000000..002aaed --- /dev/null +++ b/test/wpt/tests/FileAPI/idlharness.worker.js @@ -0,0 +1,17 @@ +importScripts("/resources/testharness.js"); +importScripts("/resources/WebIDLParser.js", "/resources/idlharness.js"); + +'use strict'; + +// https://w3c.github.io/FileAPI/ + +idl_test( + ['FileAPI'], + ['dom', 'html', 'url'], + idl_array => { + idl_array.add_objects({ + FileReaderSync: ['new FileReaderSync()'] + }); + } +); +done(); diff --git a/test/wpt/tests/FileAPI/progress-manual.html b/test/wpt/tests/FileAPI/progress-manual.html new file mode 100644 index 0000000..b2e03b3 --- /dev/null +++ b/test/wpt/tests/FileAPI/progress-manual.html @@ -0,0 +1,49 @@ + + +Process Events for FileReader + + + + +Please choose one file through this input below.
+ +
+ diff --git a/test/wpt/tests/FileAPI/reading-data-section/Determining-Encoding.any.js b/test/wpt/tests/FileAPI/reading-data-section/Determining-Encoding.any.js new file mode 100644 index 0000000..5b69f7e --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/Determining-Encoding.any.js @@ -0,0 +1,81 @@ +// META: title=FileAPI Test: Blob Determining Encoding + +var t = async_test("Blob Determing Encoding with encoding argument"); +t.step(function() { + // string 'hello' + var data = [0xFE,0xFF,0x00,0x68,0x00,0x65,0x00,0x6C,0x00,0x6C,0x00,0x6F]; + var blob = new Blob([new Uint8Array(data)]); + var reader = new FileReader(); + + reader.onloadend = t.step_func_done (function(event) { + assert_equals(this.result, "hello", "The FileReader should read the ArrayBuffer through UTF-16BE.") + }, reader); + + reader.readAsText(blob, "UTF-16BE"); +}); + +var t = async_test("Blob Determing Encoding with type attribute"); +t.step(function() { + var data = [0xFE,0xFF,0x00,0x68,0x00,0x65,0x00,0x6C,0x00,0x6C,0x00,0x6F]; + var blob = new Blob([new Uint8Array(data)], {type:"text/plain;charset=UTF-16BE"}); + var reader = new FileReader(); + + reader.onloadend = t.step_func_done (function(event) { + assert_equals(this.result, "hello", "The FileReader should read the ArrayBuffer through UTF-16BE.") + }, reader); + + reader.readAsText(blob); +}); + + +var t = async_test("Blob Determing Encoding with UTF-8 BOM"); +t.step(function() { + var data = [0xEF,0xBB,0xBF,0x68,0x65,0x6C,0x6C,0xC3,0xB6]; + var blob = new Blob([new Uint8Array(data)]); + var reader = new FileReader(); + + reader.onloadend = t.step_func_done (function(event) { + assert_equals(this.result, "hellö", "The FileReader should read the blob with UTF-8."); + }, reader); + + reader.readAsText(blob); +}); + +var t = async_test("Blob Determing Encoding without anything implying charset."); +t.step(function() { + var data = [0x68,0x65,0x6C,0x6C,0xC3,0xB6]; + var blob = new Blob([new Uint8Array(data)]); + var reader = new FileReader(); + + reader.onloadend = t.step_func_done (function(event) { + assert_equals(this.result, "hellö", "The FileReader should read the blob by default with UTF-8."); + }, reader); + + reader.readAsText(blob); +}); + +var t = async_test("Blob Determing Encoding with UTF-16BE BOM"); +t.step(function() { + var data = [0xFE,0xFF,0x00,0x68,0x00,0x65,0x00,0x6C,0x00,0x6C,0x00,0x6F]; + var blob = new Blob([new Uint8Array(data)]); + var reader = new FileReader(); + + reader.onloadend = t.step_func_done (function(event) { + assert_equals(this.result, "hello", "The FileReader should read the ArrayBuffer through UTF-16BE."); + }, reader); + + reader.readAsText(blob); +}); + +var t = async_test("Blob Determing Encoding with UTF-16LE BOM"); +t.step(function() { + var data = [0xFF,0xFE,0x68,0x00,0x65,0x00,0x6C,0x00,0x6C,0x00,0x6F,0x00]; + var blob = new Blob([new Uint8Array(data)]); + var reader = new FileReader(); + + reader.onloadend = t.step_func_done (function(event) { + assert_equals(this.result, "hello", "The FileReader should read the ArrayBuffer through UTF-16LE."); + }, reader); + + reader.readAsText(blob); +}); diff --git a/test/wpt/tests/FileAPI/reading-data-section/FileReader-event-handler-attributes.any.js b/test/wpt/tests/FileAPI/reading-data-section/FileReader-event-handler-attributes.any.js new file mode 100644 index 0000000..fc71c64 --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/FileReader-event-handler-attributes.any.js @@ -0,0 +1,17 @@ +// META: title=FileReader event handler attributes + +var attributes = [ + "onloadstart", + "onprogress", + "onload", + "onabort", + "onerror", + "onloadend", +]; +attributes.forEach(function(a) { + test(function() { + var reader = new FileReader(); + assert_equals(reader[a], null, + "event handler attribute should initially be null"); + }, "FileReader." + a + ": initial value"); +}); diff --git a/test/wpt/tests/FileAPI/reading-data-section/FileReader-multiple-reads.any.js b/test/wpt/tests/FileAPI/reading-data-section/FileReader-multiple-reads.any.js new file mode 100644 index 0000000..4b19c69 --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/FileReader-multiple-reads.any.js @@ -0,0 +1,81 @@ +// META: title=FileReader: starting new reads while one is in progress + +test(function() { + var blob_1 = new Blob(['TEST000000001']) + var blob_2 = new Blob(['TEST000000002']) + var reader = new FileReader(); + reader.readAsText(blob_1) + assert_equals(reader.readyState, FileReader.LOADING, "readyState Must be LOADING") + assert_throws_dom("InvalidStateError", function () { + reader.readAsText(blob_2) + }) +}, 'test FileReader InvalidStateError exception for readAsText'); + +test(function() { + var blob_1 = new Blob(['TEST000000001']) + var blob_2 = new Blob(['TEST000000002']) + var reader = new FileReader(); + reader.readAsDataURL(blob_1) + assert_equals(reader.readyState, FileReader.LOADING, "readyState Must be LOADING") + assert_throws_dom("InvalidStateError", function () { + reader.readAsDataURL(blob_2) + }) +}, 'test FileReader InvalidStateError exception for readAsDataURL'); + +test(function() { + var blob_1 = new Blob(['TEST000000001']) + var blob_2 = new Blob(['TEST000000002']) + var reader = new FileReader(); + reader.readAsArrayBuffer(blob_1) + assert_equals(reader.readyState, FileReader.LOADING, "readyState Must be LOADING") + assert_throws_dom("InvalidStateError", function () { + reader.readAsArrayBuffer(blob_2) + }) +}, 'test FileReader InvalidStateError exception for readAsArrayBuffer'); + +async_test(function() { + var blob_1 = new Blob(['TEST000000001']) + var blob_2 = new Blob(['TEST000000002']) + var reader = new FileReader(); + var triggered = false; + reader.onloadstart = this.step_func_done(function() { + assert_false(triggered, "Only one loadstart event should be dispatched"); + triggered = true; + assert_equals(reader.readyState, FileReader.LOADING, + "readyState must be LOADING") + assert_throws_dom("InvalidStateError", function () { + reader.readAsArrayBuffer(blob_2) + }) + }); + reader.readAsArrayBuffer(blob_1) + assert_equals(reader.readyState, FileReader.LOADING, "readyState Must be LOADING") +}, 'test FileReader InvalidStateError exception in onloadstart event for readAsArrayBuffer'); + +async_test(function() { + var blob_1 = new Blob(['TEST000000001']) + var blob_2 = new Blob(['TEST000000002']) + var reader = new FileReader(); + reader.onloadend = this.step_func_done(function() { + assert_equals(reader.readyState, FileReader.DONE, + "readyState must be DONE") + reader.readAsArrayBuffer(blob_2) + assert_equals(reader.readyState, FileReader.LOADING, "readyState Must be LOADING") + }); + reader.readAsArrayBuffer(blob_1) + assert_equals(reader.readyState, FileReader.LOADING, "readyState Must be LOADING") +}, 'test FileReader no InvalidStateError exception in loadend event handler for readAsArrayBuffer'); + +async_test(function() { + var blob_1 = new Blob([new Uint8Array(0x414141)]); + var blob_2 = new Blob(['TEST000000002']); + var reader = new FileReader(); + reader.onloadstart = this.step_func(function() { + reader.abort(); + reader.onloadstart = null; + reader.onloadend = this.step_func_done(function() { + assert_equals('TEST000000002', reader.result); + }); + reader.readAsText(blob_2); + }); + reader.readAsText(blob_1); +}, 'test abort and restart in onloadstart event for readAsText'); diff --git a/test/wpt/tests/FileAPI/reading-data-section/filereader_abort.any.js b/test/wpt/tests/FileAPI/reading-data-section/filereader_abort.any.js new file mode 100644 index 0000000..c778ae5 --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/filereader_abort.any.js @@ -0,0 +1,38 @@ +// META: title=FileAPI Test: filereader_abort + + test(function() { + var readerNoRead = new FileReader(); + readerNoRead.abort(); + assert_equals(readerNoRead.readyState, readerNoRead.EMPTY); + assert_equals(readerNoRead.result, null); + }, "Aborting before read"); + + promise_test(t => { + var blob = new Blob(["TEST THE ABORT METHOD"]); + var readerAbort = new FileReader(); + + var eventWatcher = new EventWatcher(t, readerAbort, + ['abort', 'loadstart', 'loadend', 'error', 'load']); + + // EventWatcher doesn't let us inspect the state after the abort event, + // so add an extra event handler for that. + readerAbort.addEventListener('abort', t.step_func(e => { + assert_equals(readerAbort.readyState, readerAbort.DONE); + })); + + readerAbort.readAsText(blob); + return eventWatcher.wait_for('loadstart') + .then(() => { + assert_equals(readerAbort.readyState, readerAbort.LOADING); + // 'abort' and 'loadend' events are dispatched synchronously, so + // call wait_for before calling abort. + var nextEvent = eventWatcher.wait_for(['abort', 'loadend']); + readerAbort.abort(); + return nextEvent; + }) + .then(() => { + // https://www.w3.org/Bugs/Public/show_bug.cgi?id=24401 + assert_equals(readerAbort.result, null); + assert_equals(readerAbort.readyState, readerAbort.DONE); + }); + }, "Aborting after read"); diff --git a/test/wpt/tests/FileAPI/reading-data-section/filereader_error.any.js b/test/wpt/tests/FileAPI/reading-data-section/filereader_error.any.js new file mode 100644 index 0000000..9845962 --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/filereader_error.any.js @@ -0,0 +1,19 @@ +// META: title=FileAPI Test: filereader_error + + async_test(function() { + var blob = new Blob(["TEST THE ERROR ATTRIBUTE AND ERROR EVENT"]); + var reader = new FileReader(); + assert_equals(reader.error, null, "The error is null when no error occurred"); + + reader.onload = this.step_func(function(evt) { + assert_unreached("Should not dispatch the load event"); + }); + + reader.onloadend = this.step_func(function(evt) { + assert_equals(reader.result, null, "The result is null"); + this.done(); + }); + + reader.readAsText(blob); + reader.abort(); + }); diff --git a/test/wpt/tests/FileAPI/reading-data-section/filereader_events.any.js b/test/wpt/tests/FileAPI/reading-data-section/filereader_events.any.js new file mode 100644 index 0000000..ac69290 --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/filereader_events.any.js @@ -0,0 +1,19 @@ +promise_test(async t => { + var reader = new FileReader(); + var eventWatcher = new EventWatcher(t, reader, ['loadstart', 'progress', 'abort', 'error', 'load', 'loadend']); + reader.readAsText(new Blob([])); + await eventWatcher.wait_for('loadstart'); + // No progress event for an empty blob, as no data is loaded. + await eventWatcher.wait_for('load'); + await eventWatcher.wait_for('loadend'); +}, 'events are dispatched in the correct order for an empty blob'); + +promise_test(async t => { + var reader = new FileReader(); + var eventWatcher = new EventWatcher(t, reader, ['loadstart', 'progress', 'abort', 'error', 'load', 'loadend']); + reader.readAsText(new Blob(['a'])); + await eventWatcher.wait_for('loadstart'); + await eventWatcher.wait_for('progress'); + await eventWatcher.wait_for('load'); + await eventWatcher.wait_for('loadend'); +}, 'events are dispatched in the correct order for a non-empty blob'); diff --git a/test/wpt/tests/FileAPI/reading-data-section/filereader_file-manual.html b/test/wpt/tests/FileAPI/reading-data-section/filereader_file-manual.html new file mode 100644 index 0000000..702ca9a --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/filereader_file-manual.html @@ -0,0 +1,69 @@ + + + + + FileAPI Test: filereader_file + + + + + + + +
+

Test step:

+
    +
  1. Download blue-100x100.png to local.
  2. +
  3. Select the local file (blue-100x100.png) to run the test.
  4. +
+
+ +
+ +
+ +
+ + + diff --git a/test/wpt/tests/FileAPI/reading-data-section/filereader_file_img-manual.html b/test/wpt/tests/FileAPI/reading-data-section/filereader_file_img-manual.html new file mode 100644 index 0000000..fca42c7 --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/filereader_file_img-manual.html @@ -0,0 +1,47 @@ + + + + + FileAPI Test: filereader_file_img + + + + + + + +
+

Test step:

+
    +
  1. Download blue-100x100.png to local.
  2. +
  3. Select the local file (blue-100x100.png) to run the test.
  4. +
+
+ +
+ +
+ +
+ + + diff --git a/test/wpt/tests/FileAPI/reading-data-section/filereader_readAsArrayBuffer.any.js b/test/wpt/tests/FileAPI/reading-data-section/filereader_readAsArrayBuffer.any.js new file mode 100644 index 0000000..d06e317 --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/filereader_readAsArrayBuffer.any.js @@ -0,0 +1,23 @@ +// META: title=FileAPI Test: filereader_readAsArrayBuffer + + async_test(function() { + var blob = new Blob(["TEST"]); + var reader = new FileReader(); + + reader.onload = this.step_func(function(evt) { + assert_equals(reader.result.byteLength, 4, "The byteLength is 4"); + assert_true(reader.result instanceof ArrayBuffer, "The result is instanceof ArrayBuffer"); + assert_equals(reader.readyState, reader.DONE); + this.done(); + }); + + reader.onloadstart = this.step_func(function(evt) { + assert_equals(reader.readyState, reader.LOADING); + }); + + reader.onprogress = this.step_func(function(evt) { + assert_equals(reader.readyState, reader.LOADING); + }); + + reader.readAsArrayBuffer(blob); + }); diff --git a/test/wpt/tests/FileAPI/reading-data-section/filereader_readAsBinaryString.any.js b/test/wpt/tests/FileAPI/reading-data-section/filereader_readAsBinaryString.any.js new file mode 100644 index 0000000..e69ff15 --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/filereader_readAsBinaryString.any.js @@ -0,0 +1,23 @@ +// META: title=FileAPI Test: filereader_readAsBinaryString + +async_test(t => { + const blob = new Blob(["σ"]); + const reader = new FileReader(); + + reader.onload = t.step_func_done(() => { + assert_equals(typeof reader.result, "string", "The result is string"); + assert_equals(reader.result.length, 2, "The result length is 2"); + assert_equals(reader.result, "\xcf\x83", "The result is \xcf\x83"); + assert_equals(reader.readyState, reader.DONE); + }); + + reader.onloadstart = t.step_func(() => { + assert_equals(reader.readyState, reader.LOADING); + }); + + reader.onprogress = t.step_func(() => { + assert_equals(reader.readyState, reader.LOADING); + }); + + reader.readAsBinaryString(blob); +}); diff --git a/test/wpt/tests/FileAPI/reading-data-section/filereader_readAsDataURL.any.js b/test/wpt/tests/FileAPI/reading-data-section/filereader_readAsDataURL.any.js new file mode 100644 index 0000000..4f9dbf7 --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/filereader_readAsDataURL.any.js @@ -0,0 +1,54 @@ +// META: title=FileAPI Test: FileReader.readAsDataURL + +async_test(function(testCase) { + var blob = new Blob(["TEST"]); + var reader = new FileReader(); + + reader.onload = this.step_func(function(evt) { + assert_equals(reader.readyState, reader.DONE); + testCase.done(); + }); + reader.onloadstart = this.step_func(function(evt) { + assert_equals(reader.readyState, reader.LOADING); + }); + reader.onprogress = this.step_func(function(evt) { + assert_equals(reader.readyState, reader.LOADING); + }); + + reader.readAsDataURL(blob); +}, 'FileReader readyState during readAsDataURL'); + +async_test(function(testCase) { + var blob = new Blob(["TEST"], { type: 'text/plain' }); + var reader = new FileReader(); + + reader.onload = this.step_func(function() { + assert_equals(reader.result, "data:text/plain;base64,VEVTVA=="); + testCase.done(); + }); + reader.readAsDataURL(blob); +}, 'readAsDataURL result for Blob with specified MIME type'); + +async_test(function(testCase) { + var blob = new Blob(["TEST"]); + var reader = new FileReader(); + + reader.onload = this.step_func(function() { + assert_equals(reader.result, + "data:application/octet-stream;base64,VEVTVA=="); + testCase.done(); + }); + reader.readAsDataURL(blob); +}, 'readAsDataURL result for Blob with unspecified MIME type'); + +async_test(function(testCase) { + var blob = new Blob([]); + var reader = new FileReader(); + + reader.onload = this.step_func(function() { + assert_equals(reader.result, + "data:application/octet-stream;base64,"); + testCase.done(); + }); + reader.readAsDataURL(blob); +}, 'readAsDataURL result for empty Blob'); \ No newline at end of file diff --git a/test/wpt/tests/FileAPI/reading-data-section/filereader_readAsText.any.js b/test/wpt/tests/FileAPI/reading-data-section/filereader_readAsText.any.js new file mode 100644 index 0000000..4d0fa11 --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/filereader_readAsText.any.js @@ -0,0 +1,36 @@ +// META: title=FileAPI Test: filereader_readAsText + + async_test(function() { + var blob = new Blob(["TEST"]); + var reader = new FileReader(); + + reader.onload = this.step_func(function(evt) { + assert_equals(typeof reader.result, "string", "The result is typeof string"); + assert_equals(reader.result, "TEST", "The result is TEST"); + this.done(); + }); + + reader.onloadstart = this.step_func(function(evt) { + assert_equals(reader.readyState, reader.LOADING, "The readyState"); + }); + + reader.onprogress = this.step_func(function(evt) { + assert_equals(reader.readyState, reader.LOADING); + }); + + reader.readAsText(blob); + }, "readAsText should correctly read UTF-8."); + + async_test(function() { + var blob = new Blob(["TEST"]); + var reader = new FileReader(); + var reader_UTF16 = new FileReader(); + reader_UTF16.onload = this.step_func(function(evt) { + // "TEST" in UTF-8 is 0x54 0x45 0x53 0x54. + // Decoded as utf-16 (little-endian), we get 0x4554 0x5453. + assert_equals(reader_UTF16.readyState, reader.DONE, "The readyState"); + assert_equals(reader_UTF16.result, "\u4554\u5453", "The result is not TEST"); + this.done(); + }); + reader_UTF16.readAsText(blob, "UTF-16"); + }, "readAsText should correctly read UTF-16."); diff --git a/test/wpt/tests/FileAPI/reading-data-section/filereader_readystate.any.js b/test/wpt/tests/FileAPI/reading-data-section/filereader_readystate.any.js new file mode 100644 index 0000000..3cb36ab --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/filereader_readystate.any.js @@ -0,0 +1,19 @@ +// META: title=FileAPI Test: filereader_readystate + + async_test(function() { + var blob = new Blob(["THIS TEST THE READYSTATE WHEN READ BLOB"]); + var reader = new FileReader(); + + assert_equals(reader.readyState, reader.EMPTY); + + reader.onloadstart = this.step_func(function(evt) { + assert_equals(reader.readyState, reader.LOADING); + }); + + reader.onloadend = this.step_func(function(evt) { + assert_equals(reader.readyState, reader.DONE); + this.done(); + }); + + reader.readAsDataURL(blob); + }); diff --git a/test/wpt/tests/FileAPI/reading-data-section/filereader_result.any.js b/test/wpt/tests/FileAPI/reading-data-section/filereader_result.any.js new file mode 100644 index 0000000..28c068b --- /dev/null +++ b/test/wpt/tests/FileAPI/reading-data-section/filereader_result.any.js @@ -0,0 +1,82 @@ +// META: title=FileAPI Test: filereader_result + + var blob, blob2; + setup(function() { + blob = new Blob(["This test the result attribute"]); + blob2 = new Blob(["This is a second blob"]); + }); + + async_test(function() { + var readText = new FileReader(); + assert_equals(readText.result, null); + + readText.onloadend = this.step_func(function(evt) { + assert_equals(typeof readText.result, "string", "The result type is string"); + assert_equals(readText.result, "This test the result attribute", "The result is correct"); + this.done(); + }); + + readText.readAsText(blob); + }, "readAsText"); + + async_test(function() { + var readDataURL = new FileReader(); + assert_equals(readDataURL.result, null); + + readDataURL.onloadend = this.step_func(function(evt) { + assert_equals(typeof readDataURL.result, "string", "The result type is string"); + assert_true(readDataURL.result.indexOf("VGhpcyB0ZXN0IHRoZSByZXN1bHQgYXR0cmlidXRl") != -1, "return the right base64 string"); + this.done(); + }); + + readDataURL.readAsDataURL(blob); + }, "readAsDataURL"); + + async_test(function() { + var readArrayBuffer = new FileReader(); + assert_equals(readArrayBuffer.result, null); + + readArrayBuffer.onloadend = this.step_func(function(evt) { + assert_true(readArrayBuffer.result instanceof ArrayBuffer, "The result is instanceof ArrayBuffer"); + this.done(); + }); + + readArrayBuffer.readAsArrayBuffer(blob); + }, "readAsArrayBuffer"); + + async_test(function() { + var readBinaryString = new FileReader(); + assert_equals(readBinaryString.result, null); + + readBinaryString.onloadend = this.step_func(function(evt) { + assert_equals(typeof readBinaryString.result, "string", "The result type is string"); + assert_equals(readBinaryString.result, "This test the result attribute", "The result is correct"); + this.done(); + }); + + readBinaryString.readAsBinaryString(blob); + }, "readAsBinaryString"); + + + for (let event of ['loadstart', 'progress']) { + for (let method of ['readAsText', 'readAsDataURL', 'readAsArrayBuffer', 'readAsBinaryString']) { + promise_test(async function(t) { + var reader = new FileReader(); + assert_equals(reader.result, null, 'result is null before read'); + + var eventWatcher = new EventWatcher(t, reader, + [event, 'loadend']); + + reader[method](blob); + assert_equals(reader.result, null, 'result is null after first read call'); + await eventWatcher.wait_for(event); + assert_equals(reader.result, null, 'result is null during event'); + await eventWatcher.wait_for('loadend'); + assert_not_equals(reader.result, null); + reader[method](blob); + assert_equals(reader.result, null, 'result is null after second read call'); + await eventWatcher.wait_for(event); + assert_equals(reader.result, null, 'result is null during second read event'); + }, 'result is null during "' + event + '" event for ' + method); + } + } diff --git a/test/wpt/tests/FileAPI/reading-data-section/support/blue-100x100.png b/test/wpt/tests/FileAPI/reading-data-section/support/blue-100x100.png new file mode 100644 index 0000000..5748719 Binary files /dev/null and b/test/wpt/tests/FileAPI/reading-data-section/support/blue-100x100.png differ diff --git a/test/wpt/tests/FileAPI/support/Blob.js b/test/wpt/tests/FileAPI/support/Blob.js new file mode 100644 index 0000000..2c24974 --- /dev/null +++ b/test/wpt/tests/FileAPI/support/Blob.js @@ -0,0 +1,70 @@ +'use strict' + +self.test_blob = (fn, expectations) => { + var expected = expectations.expected, + type = expectations.type, + desc = expectations.desc; + + var t = async_test(desc); + t.step(function() { + var blob = fn(); + assert_true(blob instanceof Blob); + assert_false(blob instanceof File); + assert_equals(blob.type, type); + assert_equals(blob.size, expected.length); + + var fr = new FileReader(); + fr.onload = t.step_func_done(function(event) { + assert_equals(this.result, expected); + }, fr); + fr.onerror = t.step_func(function(e) { + assert_unreached("got error event on FileReader"); + }); + fr.readAsText(blob, "UTF-8"); + }); +} + +self.test_blob_binary = (fn, expectations) => { + var expected = expectations.expected, + type = expectations.type, + desc = expectations.desc; + + var t = async_test(desc); + t.step(function() { + var blob = fn(); + assert_true(blob instanceof Blob); + assert_false(blob instanceof File); + assert_equals(blob.type, type); + assert_equals(blob.size, expected.length); + + var fr = new FileReader(); + fr.onload = t.step_func_done(function(event) { + assert_true(this.result instanceof ArrayBuffer, + "Result should be an ArrayBuffer"); + assert_array_equals(new Uint8Array(this.result), expected); + }, fr); + fr.onerror = t.step_func(function(e) { + assert_unreached("got error event on FileReader"); + }); + fr.readAsArrayBuffer(blob); + }); +} + +// Assert that two TypedArray objects have the same byte values +self.assert_equals_typed_array = (array1, array2) => { + const [view1, view2] = [array1, array2].map((array) => { + assert_true(array.buffer instanceof ArrayBuffer, + 'Expect input ArrayBuffers to contain field `buffer`'); + return new DataView(array.buffer, array.byteOffset, array.byteLength); + }); + + assert_equals(view1.byteLength, view2.byteLength, + 'Expect both arrays to be of the same byte length'); + + const byteLength = view1.byteLength; + + for (let i = 0; i < byteLength; ++i) { + assert_equals(view1.getUint8(i), view2.getUint8(i), + `Expect byte at buffer position ${i} to be equal`); + } +} diff --git a/test/wpt/tests/FileAPI/support/document-domain-setter.sub.html b/test/wpt/tests/FileAPI/support/document-domain-setter.sub.html new file mode 100644 index 0000000..61aebdf --- /dev/null +++ b/test/wpt/tests/FileAPI/support/document-domain-setter.sub.html @@ -0,0 +1,7 @@ + +Relevant/current/blob source page used as a test helper + + diff --git a/test/wpt/tests/FileAPI/support/empty-document.html b/test/wpt/tests/FileAPI/support/empty-document.html new file mode 100644 index 0000000..b9cd130 --- /dev/null +++ b/test/wpt/tests/FileAPI/support/empty-document.html @@ -0,0 +1,3 @@ + + + diff --git a/test/wpt/tests/FileAPI/support/historical-serviceworker.js b/test/wpt/tests/FileAPI/support/historical-serviceworker.js new file mode 100644 index 0000000..8bd89a2 --- /dev/null +++ b/test/wpt/tests/FileAPI/support/historical-serviceworker.js @@ -0,0 +1,5 @@ +importScripts('/resources/testharness.js'); + +test(() => { + assert_false('FileReaderSync' in self); +}, '"FileReaderSync" should not be supported in service workers'); diff --git a/test/wpt/tests/FileAPI/support/incumbent.sub.html b/test/wpt/tests/FileAPI/support/incumbent.sub.html new file mode 100644 index 0000000..63a81cd --- /dev/null +++ b/test/wpt/tests/FileAPI/support/incumbent.sub.html @@ -0,0 +1,22 @@ + +Incumbent page used as a test helper + + + + + + diff --git a/test/wpt/tests/FileAPI/support/send-file-form-helper.js b/test/wpt/tests/FileAPI/support/send-file-form-helper.js new file mode 100644 index 0000000..d6adf21 --- /dev/null +++ b/test/wpt/tests/FileAPI/support/send-file-form-helper.js @@ -0,0 +1,282 @@ +'use strict'; + +// See /FileAPI/file/resources/echo-content-escaped.py +function escapeString(string) { + return string.replace(/\\/g, "\\\\").replace( + /[^\x20-\x7E]/g, + (x) => { + let hex = x.charCodeAt(0).toString(16); + if (hex.length < 2) hex = "0" + hex; + return `\\x${hex}`; + }, + ).replace(/\\x0d\\x0a/g, "\r\n"); +} + +// Rationale for this particular test character sequence, which is +// used in filenames and also in file contents: +// +// - ABC~ ensures the string starts with something we can read to +// ensure it is from the correct source; ~ is used because even +// some 1-byte otherwise-ASCII-like parts of ISO-2022-JP +// interpret it differently. +// - ‾¥ are inside a single-byte range of ISO-2022-JP and help +// diagnose problems due to filesystem encoding or locale +// - ≈ is inside IBM437 and helps diagnose problems due to filesystem +// encoding or locale +// - ¤ is inside Latin-1 and helps diagnose problems due to +// filesystem encoding or locale; it is also the "simplest" case +// needing substitution in ISO-2022-JP +// - ï½¥ is inside a single-byte range of ISO-2022-JP in some variants +// and helps diagnose problems due to filesystem encoding or locale; +// on the web it is distinct when decoding but unified when encoding +// - ・ is inside a double-byte range of ISO-2022-JP and helps +// diagnose problems due to filesystem encoding or locale +// - • is inside Windows-1252 and helps diagnose problems due to +// filesystem encoding or locale and also ensures these aren't +// accidentally turned into e.g. control codes +// - ∙ is inside IBM437 and helps diagnose problems due to filesystem +// encoding or locale +// - · is inside Latin-1 and helps diagnose problems due to +// filesystem encoding or locale and also ensures HTML named +// character references (e.g. ·) are not used +// - ☼ is inside IBM437 shadowing C0 and helps diagnose problems due to +// filesystem encoding or locale and also ensures these aren't +// accidentally turned into e.g. control codes +// - ★ is inside ISO-2022-JP on a non-Kanji page and makes correct +// output easier to spot +// - 星 is inside ISO-2022-JP on a Kanji page and makes correct +// output easier to spot +// - 🌟 is outside the BMP and makes incorrect surrogate pair +// substitution detectable and ensures substitutions work +// correctly immediately after Kanji 2-byte ISO-2022-JP +// - 星 repeated here ensures the correct codec state is used +// after a non-BMP substitution +// - ★ repeated here also makes correct output easier to spot +// - ☼ is inside IBM437 shadowing C0 and helps diagnose problems due to +// filesystem encoding or locale and also ensures these aren't +// accidentally turned into e.g. control codes and also ensures +// substitutions work correctly immediately after non-Kanji +// 2-byte ISO-2022-JP +// - · is inside Latin-1 and helps diagnose problems due to +// filesystem encoding or locale and also ensures HTML named +// character references (e.g. ·) are not used +// - ∙ is inside IBM437 and helps diagnose problems due to filesystem +// encoding or locale +// - • is inside Windows-1252 and again helps diagnose problems +// due to filesystem encoding or locale +// - ・ is inside a double-byte range of ISO-2022-JP and helps +// diagnose problems due to filesystem encoding or locale +// - ï½¥ is inside a single-byte range of ISO-2022-JP in some variants +// and helps diagnose problems due to filesystem encoding or locale; +// on the web it is distinct when decoding but unified when encoding +// - ¤ is inside Latin-1 and helps diagnose problems due to +// filesystem encoding or locale; again it is a "simple" +// substitution case +// - ≈ is inside IBM437 and helps diagnose problems due to filesystem +// encoding or locale +// - ¥‾ are inside a single-byte range of ISO-2022-JP and help +// diagnose problems due to filesystem encoding or locale +// - ~XYZ ensures earlier errors don't lead to misencoding of +// simple ASCII +// +// Overall the near-symmetry makes common I18N mistakes like +// off-by-1-after-non-BMP easier to spot. All the characters +// are also allowed in Windows Unicode filenames. +const kTestChars = 'ABC~‾¥≈¤・・•∙·☼★星🌟星★☼·∙•・・¤≈¥‾~XYZ'; + +// The kTestFallback* strings represent the expected byte sequence from +// encoding kTestChars with the given encoding with "html" replacement +// mode, isomorphic-decoded. That means, characters that can't be +// encoded in that encoding get HTML-escaped, but no further +// `escapeString`-like escapes are needed. +const kTestFallbackUtf8 = ( + "ABC~\xE2\x80\xBE\xC2\xA5\xE2\x89\x88\xC2\xA4\xEF\xBD\xA5\xE3\x83\xBB\xE2" + + "\x80\xA2\xE2\x88\x99\xC2\xB7\xE2\x98\xBC\xE2\x98\x85\xE6\x98\x9F\xF0\x9F" + + "\x8C\x9F\xE6\x98\x9F\xE2\x98\x85\xE2\x98\xBC\xC2\xB7\xE2\x88\x99\xE2\x80" + + "\xA2\xE3\x83\xBB\xEF\xBD\xA5\xC2\xA4\xE2\x89\x88\xC2\xA5\xE2\x80\xBE~XYZ" +); + +const kTestFallbackIso2022jp = ( + ("ABC~\x1B(J~\\≈¤\x1B$B!&!&\x1B(B•∙·☼\x1B$B!z@1\x1B(B🌟" + + "\x1B$B@1!z\x1B(B☼·∙•\x1B$B!&!&\x1B(B¤≈\x1B(J\\~\x1B(B~XYZ") + .replace(/[^\0-\x7F]/gu, (x) => `&#${x.codePointAt(0)};`) +); + +const kTestFallbackWindows1252 = ( + "ABC~‾\xA5≈\xA4・・\x95∙\xB7☼★星🌟星★☼\xB7∙\x95・・\xA4≈\xA5‾~XYZ".replace( + /[^\0-\xFF]/gu, + (x) => `&#${x.codePointAt(0)};`, + ) +); + +const kTestFallbackXUserDefined = kTestChars.replace( + /[^\0-\x7F]/gu, + (x) => `&#${x.codePointAt(0)};`, +); + +// formPostFileUploadTest - verifies multipart upload structure and +// numeric character reference replacement for filenames, field names, +// and field values using form submission. +// +// Uses /FileAPI/file/resources/echo-content-escaped.py to echo the +// upload POST with controls and non-ASCII bytes escaped. This is done +// because navigations whose response body contains [\0\b\v] may get +// treated as a download, which is not what we want. Use the +// `escapeString` function to replicate that kind of escape (note that +// it takes an isomorphic-decoded string, not a byte sequence). +// +// Fields in the parameter object: +// +// - fileNameSource: purely explanatory and gives a clue about which +// character encoding is the source for the non-7-bit-ASCII parts of +// the fileBaseName, or Unicode if no smaller-than-Unicode source +// contains all the characters. Used in the test name. +// - fileBaseName: the not-necessarily-just-7-bit-ASCII file basename +// used for the constructed test file. Used in the test name. +// - formEncoding: the acceptCharset of the form used to submit the +// test file. Used in the test name. +// - expectedEncodedBaseName: the expected formEncoding-encoded +// version of fileBaseName, isomorphic-decoded. That means, characters +// that can't be encoded in that encoding get HTML-escaped, but no +// further `escapeString`-like escapes are needed. +const formPostFileUploadTest = ({ + fileNameSource, + fileBaseName, + formEncoding, + expectedEncodedBaseName, +}) => { + promise_test(async testCase => { + + if (document.readyState !== 'complete') { + await new Promise(resolve => addEventListener('load', resolve)); + } + + const formTargetFrame = Object.assign(document.createElement('iframe'), { + name: 'formtargetframe', + }); + document.body.append(formTargetFrame); + testCase.add_cleanup(() => { + document.body.removeChild(formTargetFrame); + }); + + const form = Object.assign(document.createElement('form'), { + acceptCharset: formEncoding, + action: '/FileAPI/file/resources/echo-content-escaped.py', + method: 'POST', + enctype: 'multipart/form-data', + target: formTargetFrame.name, + }); + document.body.append(form); + testCase.add_cleanup(() => { + document.body.removeChild(form); + }); + + // Used to verify that the browser agrees with the test about + // which form charset is used. + form.append(Object.assign(document.createElement('input'), { + type: 'hidden', + name: '_charset_', + })); + + // Used to verify that the browser agrees with the test about + // field value replacement and encoding independently of file system + // idiosyncracies. + form.append(Object.assign(document.createElement('input'), { + type: 'hidden', + name: 'filename', + value: fileBaseName, + })); + + // Same, but with name and value reversed to ensure field names + // get the same treatment. + form.append(Object.assign(document.createElement('input'), { + type: 'hidden', + name: fileBaseName, + value: 'filename', + })); + + const fileInput = Object.assign(document.createElement('input'), { + type: 'file', + name: 'file', + }); + form.append(fileInput); + + // Removes c:\fakepath\ or other pseudofolder and returns just the + // final component of filePath; allows both / and \ as segment + // delimiters. + const baseNameOfFilePath = filePath => filePath.split(/[\/\\]/).pop(); + await new Promise(resolve => { + const dataTransfer = new DataTransfer; + dataTransfer.items.add( + new File([kTestChars], fileBaseName, {type: 'text/plain'})); + fileInput.files = dataTransfer.files; + // For historical reasons .value will be prefixed with + // c:\fakepath\, but the basename should match the file name + // exposed through the newer .files[0].name API. This check + // verifies that assumption. + assert_equals( + baseNameOfFilePath(fileInput.files[0].name), + baseNameOfFilePath(fileInput.value), + `The basename of the field's value should match its files[0].name`); + form.submit(); + formTargetFrame.onload = resolve; + }); + + const formDataText = formTargetFrame.contentDocument.body.textContent; + const formDataLines = formDataText.split('\n'); + if (formDataLines.length && !formDataLines[formDataLines.length - 1]) { + --formDataLines.length; + } + assert_greater_than( + formDataLines.length, + 2, + `${fileBaseName}: multipart form data must have at least 3 lines: ${ + JSON.stringify(formDataText) + }`); + const boundary = formDataLines[0]; + assert_equals( + formDataLines[formDataLines.length - 1], + boundary + '--', + `${fileBaseName}: multipart form data must end with ${boundary}--: ${ + JSON.stringify(formDataText) + }`); + + const asValue = expectedEncodedBaseName.replace(/\r\n?|\n/g, "\r\n"); + const asName = asValue.replace(/[\r\n"]/g, encodeURIComponent); + const asFilename = expectedEncodedBaseName.replace(/[\r\n"]/g, encodeURIComponent); + + // The response body from echo-content-escaped.py has controls and non-ASCII + // bytes escaped, so any caller-provided field that might contain such bytes + // must be passed to `escapeString`, after any other expected + // transformations. + const expectedText = [ + boundary, + 'Content-Disposition: form-data; name="_charset_"', + '', + formEncoding, + boundary, + 'Content-Disposition: form-data; name="filename"', + '', + // Unlike for names and filenames, multipart/form-data values don't escape + // \r\n linebreaks, and when they're read from an iframe they become \n. + escapeString(asValue).replace(/\r\n/g, "\n"), + boundary, + `Content-Disposition: form-data; name="${escapeString(asName)}"`, + '', + 'filename', + boundary, + `Content-Disposition: form-data; name="file"; ` + + `filename="${escapeString(asFilename)}"`, + 'Content-Type: text/plain', + '', + escapeString(kTestFallbackUtf8), + boundary + '--', + ].join('\n'); + + assert_true( + formDataText.startsWith(expectedText), + `Unexpected multipart-shaped form data received:\n${ + formDataText + }\nExpected:\n${expectedText}`); + }, `Upload ${fileBaseName} (${fileNameSource}) in ${formEncoding} form`); +}; diff --git a/test/wpt/tests/FileAPI/support/send-file-formdata-helper.js b/test/wpt/tests/FileAPI/support/send-file-formdata-helper.js new file mode 100644 index 0000000..53c8cca --- /dev/null +++ b/test/wpt/tests/FileAPI/support/send-file-formdata-helper.js @@ -0,0 +1,99 @@ +"use strict"; + +const kTestChars = "ABC~‾¥≈¤・・•∙·☼★星🌟星★☼·∙•・・¤≈¥‾~XYZ"; + +// formDataPostFileUploadTest - verifies multipart upload structure and +// numeric character reference replacement for filenames, field names, +// and field values using FormData and fetch(). +// +// Uses /fetch/api/resources/echo-content.py to echo the upload +// POST (unlike in send-file-form-helper.js, here we expect all +// multipart/form-data request bodies to be UTF-8, so we don't need to +// escape controls and non-ASCII bytes). +// +// Fields in the parameter object: +// +// - fileNameSource: purely explanatory and gives a clue about which +// character encoding is the source for the non-7-bit-ASCII parts of +// the fileBaseName, or Unicode if no smaller-than-Unicode source +// contains all the characters. Used in the test name. +// - fileBaseName: the not-necessarily-just-7-bit-ASCII file basename +// used for the constructed test file. Used in the test name. +const formDataPostFileUploadTest = ({ + fileNameSource, + fileBaseName, +}) => { + promise_test(async (testCase) => { + const formData = new FormData(); + let file = new Blob([kTestChars], { type: "text/plain" }); + try { + // Switch to File in browsers that allow this + file = new File([file], fileBaseName, { type: file.type }); + } catch (ignoredException) { + } + + // Used to verify that the browser agrees with the test about + // field value replacement and encoding independently of file system + // idiosyncracies. + formData.append("filename", fileBaseName); + + // Same, but with name and value reversed to ensure field names + // get the same treatment. + formData.append(fileBaseName, "filename"); + + formData.append("file", file, fileBaseName); + + const formDataText = await (await fetch( + `/fetch/api/resources/echo-content.py`, + { + method: "POST", + body: formData, + }, + )).text(); + const formDataLines = formDataText.split("\r\n"); + if (formDataLines.length && !formDataLines[formDataLines.length - 1]) { + --formDataLines.length; + } + assert_greater_than( + formDataLines.length, + 2, + `${fileBaseName}: multipart form data must have at least 3 lines: ${ + JSON.stringify(formDataText) + }`, + ); + const boundary = formDataLines[0]; + assert_equals( + formDataLines[formDataLines.length - 1], + boundary + "--", + `${fileBaseName}: multipart form data must end with ${boundary}--: ${ + JSON.stringify(formDataText) + }`, + ); + + const asValue = fileBaseName.replace(/\r\n?|\n/g, "\r\n"); + const asName = asValue.replace(/[\r\n"]/g, encodeURIComponent); + const asFilename = fileBaseName.replace(/[\r\n"]/g, encodeURIComponent); + const expectedText = [ + boundary, + 'Content-Disposition: form-data; name="filename"', + "", + asValue, + boundary, + `Content-Disposition: form-data; name="${asName}"`, + "", + "filename", + boundary, + `Content-Disposition: form-data; name="file"; ` + + `filename="${asFilename}"`, + "Content-Type: text/plain", + "", + kTestChars, + boundary + "--", + ].join("\r\n"); + + assert_true( + formDataText.startsWith(expectedText), + `Unexpected multipart-shaped form data received:\n${formDataText}\nExpected:\n${expectedText}`, + ); + }, `Upload ${fileBaseName} (${fileNameSource}) in fetch with FormData`); +}; diff --git a/test/wpt/tests/FileAPI/support/upload.txt b/test/wpt/tests/FileAPI/support/upload.txt new file mode 100644 index 0000000..5ab2f8a --- /dev/null +++ b/test/wpt/tests/FileAPI/support/upload.txt @@ -0,0 +1 @@ +Hello \ No newline at end of file diff --git a/test/wpt/tests/FileAPI/support/url-origin.html b/test/wpt/tests/FileAPI/support/url-origin.html new file mode 100644 index 0000000..6375511 --- /dev/null +++ b/test/wpt/tests/FileAPI/support/url-origin.html @@ -0,0 +1,6 @@ + + diff --git a/test/wpt/tests/FileAPI/unicode.html b/test/wpt/tests/FileAPI/unicode.html new file mode 100644 index 0000000..ce3e357 --- /dev/null +++ b/test/wpt/tests/FileAPI/unicode.html @@ -0,0 +1,46 @@ + + +Blob/Unicode interaction: normalization and encoding + + + diff --git a/test/wpt/tests/FileAPI/url/cross-global-revoke.sub.html b/test/wpt/tests/FileAPI/url/cross-global-revoke.sub.html new file mode 100644 index 0000000..ce9d680 --- /dev/null +++ b/test/wpt/tests/FileAPI/url/cross-global-revoke.sub.html @@ -0,0 +1,62 @@ + + + + + + + diff --git a/test/wpt/tests/FileAPI/url/multi-global-origin-serialization.sub.html b/test/wpt/tests/FileAPI/url/multi-global-origin-serialization.sub.html new file mode 100644 index 0000000..0052b26 --- /dev/null +++ b/test/wpt/tests/FileAPI/url/multi-global-origin-serialization.sub.html @@ -0,0 +1,26 @@ + + +Blob URL serialization (specifically the origin) in multi-global situations + + + + + + + + + + + diff --git a/test/wpt/tests/FileAPI/url/resources/create-helper.html b/test/wpt/tests/FileAPI/url/resources/create-helper.html new file mode 100644 index 0000000..fa6cf4e --- /dev/null +++ b/test/wpt/tests/FileAPI/url/resources/create-helper.html @@ -0,0 +1,7 @@ + + \ No newline at end of file diff --git a/test/wpt/tests/FileAPI/url/resources/create-helper.js b/test/wpt/tests/FileAPI/url/resources/create-helper.js new file mode 100644 index 0000000..e6344f7 --- /dev/null +++ b/test/wpt/tests/FileAPI/url/resources/create-helper.js @@ -0,0 +1,4 @@ +self.addEventListener('message', e => { + let url = URL.createObjectURL(e.data.blob); + self.postMessage({url: url}); +}); diff --git a/test/wpt/tests/FileAPI/url/resources/fetch-tests.js b/test/wpt/tests/FileAPI/url/resources/fetch-tests.js new file mode 100644 index 0000000..a81ea1e --- /dev/null +++ b/test/wpt/tests/FileAPI/url/resources/fetch-tests.js @@ -0,0 +1,71 @@ +// This method generates a number of tests verifying fetching of blob URLs, +// allowing the same tests to be used both with fetch() and XMLHttpRequest. +// +// |fetch_method| is only used in test names, and should describe the +// (javascript) method being used by the other two arguments (i.e. 'fetch' or 'XHR'). +// +// |fetch_should_succeed| is a callback that is called with the Test and a URL. +// Fetching the URL is expected to succeed. The callback should return a promise +// resolved with whatever contents were fetched. +// +// |fetch_should_fail| similarly is a callback that is called with the Test, a URL +// to fetch, and optionally a method to use to do the fetch. If no method is +// specified the callback should use the 'GET' method. Fetching of these URLs is +// expected to fail, and the callback should return a promise that resolves iff +// fetching did indeed fail. +function fetch_tests(fetch_method, fetch_should_succeed, fetch_should_fail) { + const blob_contents = 'test blob contents'; + const blob = new Blob([blob_contents]); + + promise_test(t => { + const url = URL.createObjectURL(blob); + + return fetch_should_succeed(t, url).then(text => { + assert_equals(text, blob_contents); + }); + }, 'Blob URLs can be used in ' + fetch_method); + + promise_test(t => { + const url = URL.createObjectURL(blob); + + return fetch_should_succeed(t, url + '#fragment').then(text => { + assert_equals(text, blob_contents); + }); + }, fetch_method + ' with a fragment should succeed'); + + promise_test(t => { + const url = URL.createObjectURL(blob); + URL.revokeObjectURL(url); + + return fetch_should_fail(t, url); + }, fetch_method + ' of a revoked URL should fail'); + + promise_test(t => { + const url = URL.createObjectURL(blob); + URL.revokeObjectURL(url + '#fragment'); + + return fetch_should_succeed(t, url).then(text => { + assert_equals(text, blob_contents); + }); + }, 'Only exact matches should revoke URLs, using ' + fetch_method); + + promise_test(t => { + const url = URL.createObjectURL(blob); + + return fetch_should_fail(t, url + '?querystring'); + }, 'Appending a query string should cause ' + fetch_method + ' to fail'); + + promise_test(t => { + const url = URL.createObjectURL(blob); + + return fetch_should_fail(t, url + '/path'); + }, 'Appending a path should cause ' + fetch_method + ' to fail'); + + for (const method of ['HEAD', 'POST', 'DELETE', 'OPTIONS', 'PUT', 'CUSTOM']) { + const url = URL.createObjectURL(blob); + + promise_test(t => { + return fetch_should_fail(t, url, method); + }, fetch_method + ' with method "' + method + '" should fail'); + } +} \ No newline at end of file diff --git a/test/wpt/tests/FileAPI/url/resources/revoke-helper.html b/test/wpt/tests/FileAPI/url/resources/revoke-helper.html new file mode 100644 index 0000000..adf5a01 --- /dev/null +++ b/test/wpt/tests/FileAPI/url/resources/revoke-helper.html @@ -0,0 +1,7 @@ + + \ No newline at end of file diff --git a/test/wpt/tests/FileAPI/url/resources/revoke-helper.js b/test/wpt/tests/FileAPI/url/resources/revoke-helper.js new file mode 100644 index 0000000..c3e05b6 --- /dev/null +++ b/test/wpt/tests/FileAPI/url/resources/revoke-helper.js @@ -0,0 +1,9 @@ +self.addEventListener('message', e => { + URL.revokeObjectURL(e.data.url); + // Registering a new object URL will make absolutely sure that the revocation + // has propagated. Without this at least in chrome it is possible for the + // below postMessage to arrive at its destination before the revocation has + // been fully processed. + URL.createObjectURL(new Blob([])); + self.postMessage('revoked'); +}); diff --git a/test/wpt/tests/FileAPI/url/sandboxed-iframe.html b/test/wpt/tests/FileAPI/url/sandboxed-iframe.html new file mode 100644 index 0000000..a52939a --- /dev/null +++ b/test/wpt/tests/FileAPI/url/sandboxed-iframe.html @@ -0,0 +1,32 @@ + + +FileAPI Test: Verify behavior of Blob URL in unique origins + + + + + + + diff --git a/test/wpt/tests/FileAPI/url/unicode-origin.sub.html b/test/wpt/tests/FileAPI/url/unicode-origin.sub.html new file mode 100644 index 0000000..2c4921c --- /dev/null +++ b/test/wpt/tests/FileAPI/url/unicode-origin.sub.html @@ -0,0 +1,23 @@ + + +FileAPI Test: Verify origin of Blob URL + + + + diff --git a/test/wpt/tests/FileAPI/url/url-charset.window.js b/test/wpt/tests/FileAPI/url/url-charset.window.js new file mode 100644 index 0000000..777709b --- /dev/null +++ b/test/wpt/tests/FileAPI/url/url-charset.window.js @@ -0,0 +1,34 @@ +async_test(t => { + // This could be detected as ISO-2022-JP, in which case there would be no + // bbb` + ], + {type: 'text/html;charset=utf-8'}); + const url = URL.createObjectURL(blob); + const win = window.open(url); + t.add_cleanup(() => { + win.close(); + }); + + win.onload = t.step_func_done(() => { + assert_equals(win.document.charset, 'UTF-8'); + }); +}, 'Blob charset should override any auto-detected charset.'); + +async_test(t => { + const blob = new Blob( + [`\n`], + {type: 'text/html;charset=utf-8'}); + const url = URL.createObjectURL(blob); + const win = window.open(url); + t.add_cleanup(() => { + win.close(); + }); + + win.onload = t.step_func_done(() => { + assert_equals(win.document.charset, 'UTF-8'); + }); +}, 'Blob charset should override .'); diff --git a/test/wpt/tests/FileAPI/url/url-format.any.js b/test/wpt/tests/FileAPI/url/url-format.any.js new file mode 100644 index 0000000..69c5111 --- /dev/null +++ b/test/wpt/tests/FileAPI/url/url-format.any.js @@ -0,0 +1,70 @@ +// META: timeout=long +const blob = new Blob(['test']); +const file = new File(['test'], 'name'); + +test(t => { + const url_count = 5000; + let list = []; + + t.add_cleanup(() => { + for (let url of list) { + URL.revokeObjectURL(url); + } + }); + + for (let i = 0; i < url_count; ++i) + list.push(URL.createObjectURL(blob)); + + list.sort(); + + for (let i = 1; i < list.length; ++i) + assert_not_equals(list[i], list[i-1], 'generated Blob URLs should be unique'); +}, 'Generated Blob URLs are unique'); + +test(() => { + const url = URL.createObjectURL(blob); + assert_equals(typeof url, 'string'); + assert_true(url.startsWith('blob:')); +}, 'Blob URL starts with "blob:"'); + +test(() => { + const url = URL.createObjectURL(file); + assert_equals(typeof url, 'string'); + assert_true(url.startsWith('blob:')); +}, 'Blob URL starts with "blob:" for Files'); + +test(() => { + const url = URL.createObjectURL(blob); + assert_equals(new URL(url).origin, location.origin); + if (location.origin !== 'null') { + assert_true(url.includes(location.origin)); + assert_true(url.startsWith('blob:' + location.protocol)); + } +}, 'Origin of Blob URL matches our origin'); + +test(() => { + const url = URL.createObjectURL(blob); + const url_record = new URL(url); + assert_equals(url_record.protocol, 'blob:'); + assert_equals(url_record.origin, location.origin); + assert_equals(url_record.host, '', 'host should be an empty string'); + assert_equals(url_record.port, '', 'port should be an empty string'); + const uuid_path_re = /\/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + assert_true(uuid_path_re.test(url_record.pathname), 'Path must end with a valid UUID'); + if (location.origin !== 'null') { + const nested_url = new URL(url_record.pathname); + assert_equals(nested_url.origin, location.origin); + assert_equals(nested_url.pathname.search(uuid_path_re), 0, 'Path must be a valid UUID'); + assert_true(url.includes(location.origin)); + assert_true(url.startsWith('blob:' + location.protocol)); + } +}, 'Blob URL parses correctly'); + +test(() => { + const url = URL.createObjectURL(file); + assert_equals(new URL(url).origin, location.origin); + if (location.origin !== 'null') { + assert_true(url.includes(location.origin)); + assert_true(url.startsWith('blob:' + location.protocol)); + } +}, 'Origin of Blob URL matches our origin for Files'); diff --git a/test/wpt/tests/FileAPI/url/url-in-tags-revoke.window.js b/test/wpt/tests/FileAPI/url/url-in-tags-revoke.window.js new file mode 100644 index 0000000..1cdad79 --- /dev/null +++ b/test/wpt/tests/FileAPI/url/url-in-tags-revoke.window.js @@ -0,0 +1,115 @@ +// META: timeout=long +async_test(t => { + const run_result = 'test_frame_OK'; + const blob_contents = '\n\n' + + ''; + const blob = new Blob([blob_contents], {type: 'text/html'}); + const url = URL.createObjectURL(blob); + + const frame = document.createElement('iframe'); + frame.setAttribute('src', url); + frame.setAttribute('style', 'display:none;'); + document.body.appendChild(frame); + URL.revokeObjectURL(url); + + frame.onload = t.step_func_done(() => { + assert_equals(frame.contentWindow.test_result, run_result); + }); +}, 'Fetching a blob URL immediately before revoking it works in an iframe.'); + +async_test(t => { + const run_result = 'test_frame_OK'; + const blob_contents = '\n\n' + + ''; + const blob = new Blob([blob_contents], {type: 'text/html'}); + const url = URL.createObjectURL(blob); + + const frame = document.createElement('iframe'); + frame.setAttribute('src', '/common/blank.html'); + frame.setAttribute('style', 'display:none;'); + document.body.appendChild(frame); + + frame.onload = t.step_func(() => { + frame.contentWindow.location = url; + URL.revokeObjectURL(url); + frame.onload = t.step_func_done(() => { + assert_equals(frame.contentWindow.test_result, run_result); + }); + }); +}, 'Fetching a blob URL immediately before revoking it works in an iframe navigation.'); + +async_test(t => { + const run_result = 'test_frame_OK'; + const blob_contents = '\n\n' + + ''; + const blob = new Blob([blob_contents], {type: 'text/html'}); + const url = URL.createObjectURL(blob); + const win = window.open(url); + URL.revokeObjectURL(url); + add_completion_callback(() => { win.close(); }); + + win.onload = t.step_func_done(() => { + assert_equals(win.test_result, run_result); + }); +}, 'Opening a blob URL in a new window immediately before revoking it works.'); + +function receive_message_on_channel(t, channel_name) { + const channel = new BroadcastChannel(channel_name); + return new Promise(resolve => { + channel.addEventListener('message', t.step_func(e => { + resolve(e.data); + })); + }); +} + +function window_contents_for_channel(channel_name) { + return '\n' + + ''; +} + +async_test(t => { + const channel_name = 'noopener-window-test'; + const blob = new Blob([window_contents_for_channel(channel_name)], {type: 'text/html'}); + receive_message_on_channel(t, channel_name).then(t.step_func_done(t => { + assert_equals(t, 'foobar'); + })); + const url = URL.createObjectURL(blob); + const win = window.open(); + win.opener = null; + win.location = url; + URL.revokeObjectURL(url); +}, 'Opening a blob URL in a noopener about:blank window immediately before revoking it works.'); + +async_test(t => { + const run_result = 'test_script_OK'; + const blob_contents = 'window.script_test_result = "' + run_result + '";'; + const blob = new Blob([blob_contents]); + const url = URL.createObjectURL(blob); + + const e = document.createElement('script'); + e.setAttribute('src', url); + e.onload = t.step_func_done(() => { + assert_equals(window.script_test_result, run_result); + }); + + document.body.appendChild(e); + URL.revokeObjectURL(url); +}, 'Fetching a blob URL immediately before revoking it works in '; + const blob = new Blob([blob_contents], {type: 'text/html'}); + const url = URL.createObjectURL(blob); + + const frame = document.createElement('iframe'); + frame.setAttribute('src', url); + frame.setAttribute('style', 'display:none;'); + document.body.appendChild(frame); + + frame.onload = t.step_func_done(() => { + assert_equals(frame.contentWindow.test_result, run_result); + }); +}, 'Blob URLs can be used in iframes, and are treated same origin'); + +async_test(t => { + const blob_contents = '\n\n' + + '\n' + + '\n' + + '
\n' + + '
'; + const blob = new Blob([blob_contents], {type: 'text/html'}); + const url = URL.createObjectURL(blob); + + const frame = document.createElement('iframe'); + frame.setAttribute('src', url + '#block2'); + document.body.appendChild(frame); + frame.contentWindow.onscroll = t.step_func_done(() => { + assert_equals(frame.contentWindow.scrollY, 5000); + }); +}, 'Blob URL fragment is implemented.'); diff --git a/test/wpt/tests/FileAPI/url/url-lifetime.html b/test/wpt/tests/FileAPI/url/url-lifetime.html new file mode 100644 index 0000000..ad5d667 --- /dev/null +++ b/test/wpt/tests/FileAPI/url/url-lifetime.html @@ -0,0 +1,56 @@ + + + + + + \ No newline at end of file diff --git a/test/wpt/tests/FileAPI/url/url-reload.window.js b/test/wpt/tests/FileAPI/url/url-reload.window.js new file mode 100644 index 0000000..d333b3a --- /dev/null +++ b/test/wpt/tests/FileAPI/url/url-reload.window.js @@ -0,0 +1,36 @@ +function blob_url_reload_test(t, revoke_before_reload) { + const run_result = 'test_frame_OK'; + const blob_contents = '\n\n' + + ''; + const blob = new Blob([blob_contents], {type: 'text/html'}); + const url = URL.createObjectURL(blob); + + const frame = document.createElement('iframe'); + frame.setAttribute('src', url); + frame.setAttribute('style', 'display:none;'); + document.body.appendChild(frame); + + frame.onload = t.step_func(() => { + if (revoke_before_reload) + URL.revokeObjectURL(url); + assert_equals(frame.contentWindow.test_result, run_result); + frame.contentWindow.test_result = null; + frame.onload = t.step_func_done(() => { + assert_equals(frame.contentWindow.test_result, run_result); + }); + // Slight delay before reloading to ensure revoke actually has had a chance + // to be processed. + t.step_timeout(() => { + frame.contentWindow.location.reload(); + }, 250); + }); +} + +async_test(t => { + blob_url_reload_test(t, false); +}, 'Reloading a blob URL succeeds.'); + + +async_test(t => { + blob_url_reload_test(t, true); +}, 'Reloading a blob URL succeeds even if the URL was revoked.'); diff --git a/test/wpt/tests/FileAPI/url/url-with-fetch.any.js b/test/wpt/tests/FileAPI/url/url-with-fetch.any.js new file mode 100644 index 0000000..54e6a3d --- /dev/null +++ b/test/wpt/tests/FileAPI/url/url-with-fetch.any.js @@ -0,0 +1,72 @@ +// META: script=resources/fetch-tests.js +// META: script=/common/gc.js + +function fetch_should_succeed(test, request) { + return fetch(request).then(response => response.text()); +} + +function fetch_should_fail(test, url, method = 'GET') { + return promise_rejects_js(test, TypeError, fetch(url, {method: method})); +} + +fetch_tests('fetch', fetch_should_succeed, fetch_should_fail); + +promise_test(t => { + const blob_contents = 'test blob contents'; + const blob_type = 'image/png'; + const blob = new Blob([blob_contents], {type: blob_type}); + const url = URL.createObjectURL(blob); + + return fetch(url).then(response => { + assert_equals(response.headers.get('Content-Type'), blob_type); + }); +}, 'fetch should return Content-Type from Blob'); + +promise_test(t => { + const blob_contents = 'test blob contents'; + const blob = new Blob([blob_contents]); + const url = URL.createObjectURL(blob); + const request = new Request(url); + + // Revoke the object URL. Request should take a reference to the blob as + // soon as it receives it in open(), so the request succeeds even though we + // revoke the URL before calling fetch(). + URL.revokeObjectURL(url); + + return fetch_should_succeed(t, request).then(text => { + assert_equals(text, blob_contents); + }); +}, 'Revoke blob URL after creating Request, will fetch'); + +promise_test(async t => { + const blob_contents = 'test blob contents'; + const blob = new Blob([blob_contents]); + const url = URL.createObjectURL(blob); + let request = new Request(url); + + // Revoke the object URL. Request should take a reference to the blob as + // soon as it receives it in open(), so the request succeeds even though we + // revoke the URL before calling fetch(). + URL.revokeObjectURL(url); + + request = request.clone(); + await garbageCollect(); + + const text = await fetch_should_succeed(t, request); + assert_equals(text, blob_contents); +}, 'Revoke blob URL after creating Request, then clone Request, will fetch'); + +promise_test(function(t) { + const blob_contents = 'test blob contents'; + const blob = new Blob([blob_contents]); + const url = URL.createObjectURL(blob); + + const result = fetch_should_succeed(t, url).then(text => { + assert_equals(text, blob_contents); + }); + + // Revoke the object URL. fetch should have already resolved the blob URL. + URL.revokeObjectURL(url); + + return result; +}, 'Revoke blob URL after calling fetch, fetch should succeed'); diff --git a/test/wpt/tests/FileAPI/url/url-with-xhr.any.js b/test/wpt/tests/FileAPI/url/url-with-xhr.any.js new file mode 100644 index 0000000..29d8308 --- /dev/null +++ b/test/wpt/tests/FileAPI/url/url-with-xhr.any.js @@ -0,0 +1,68 @@ +// META: script=resources/fetch-tests.js + +function xhr_should_succeed(test, url) { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open('GET', url); + xhr.onload = test.step_func(() => { + assert_equals(xhr.status, 200); + assert_equals(xhr.statusText, 'OK'); + resolve(xhr.response); + }); + xhr.onerror = () => reject('Got unexpected error event'); + xhr.send(); + }); +} + +function xhr_should_fail(test, url, method = 'GET') { + const xhr = new XMLHttpRequest(); + xhr.open(method, url); + const result1 = new Promise((resolve, reject) => { + xhr.onload = () => reject('Got unexpected load event'); + xhr.onerror = resolve; + }); + const result2 = new Promise(resolve => { + xhr.onreadystatechange = test.step_func(() => { + if (xhr.readyState !== xhr.DONE) return; + assert_equals(xhr.status, 0); + resolve(); + }); + }); + xhr.send(); + return Promise.all([result1, result2]); +} + +fetch_tests('XHR', xhr_should_succeed, xhr_should_fail); + +async_test(t => { + const blob_contents = 'test blob contents'; + const blob_type = 'image/png'; + const blob = new Blob([blob_contents], {type: blob_type}); + const url = URL.createObjectURL(blob); + const xhr = new XMLHttpRequest(); + xhr.open('GET', url); + xhr.onloadend = t.step_func_done(() => { + assert_equals(xhr.getResponseHeader('Content-Type'), blob_type); + }); + xhr.send(); +}, 'XHR should return Content-Type from Blob'); + +async_test(t => { + const blob_contents = 'test blob contents'; + const blob = new Blob([blob_contents]); + const url = URL.createObjectURL(blob); + const xhr = new XMLHttpRequest(); + xhr.open('GET', url); + + // Revoke the object URL. XHR should take a reference to the blob as soon as + // it receives it in open(), so the request succeeds even though we revoke the + // URL before calling send(). + URL.revokeObjectURL(url); + + xhr.onload = t.step_func_done(() => { + assert_equals(xhr.response, blob_contents); + }); + xhr.onerror = t.unreached_func('Got unexpected error event'); + + xhr.send(); +}, 'Revoke blob URL after open(), will fetch'); diff --git a/test/wpt/tests/FileAPI/url/url_createobjecturl_file-manual.html b/test/wpt/tests/FileAPI/url/url_createobjecturl_file-manual.html new file mode 100644 index 0000000..7ae3251 --- /dev/null +++ b/test/wpt/tests/FileAPI/url/url_createobjecturl_file-manual.html @@ -0,0 +1,45 @@ + + +FileAPI Test: Creating Blob URL with File + + + + + + +
+

Test steps:

+
    +
  1. Download blue96x96.png to local.
  2. +
  3. Select the local file (blue96x96.png) to run the test.
  4. +
+
+ +
+ +
+ +
+ + + diff --git a/test/wpt/tests/FileAPI/url/url_createobjecturl_file_img-manual.html b/test/wpt/tests/FileAPI/url/url_createobjecturl_file_img-manual.html new file mode 100644 index 0000000..534c1de --- /dev/null +++ b/test/wpt/tests/FileAPI/url/url_createobjecturl_file_img-manual.html @@ -0,0 +1,28 @@ + + +FileAPI Test: Creating Blob URL with File as image source + + + +
+

Test steps:

+
    +
  1. Download blue96x96.png to local.
  2. +
  3. Select the local file (blue96x96.png) to run the test.
  4. +
+

Pass/fail criteria:

+

Test passes if there is a filled blue square.

+ +

+

+
+ + + diff --git a/test/wpt/tests/FileAPI/url/url_xmlhttprequest_img-ref.html b/test/wpt/tests/FileAPI/url/url_xmlhttprequest_img-ref.html new file mode 100644 index 0000000..7d73904 --- /dev/null +++ b/test/wpt/tests/FileAPI/url/url_xmlhttprequest_img-ref.html @@ -0,0 +1,12 @@ + + +FileAPI Reference File + + + +

Test passes if there is a filled blue square.

+ +

+ +

+ diff --git a/test/wpt/tests/FileAPI/url/url_xmlhttprequest_img.html b/test/wpt/tests/FileAPI/url/url_xmlhttprequest_img.html new file mode 100644 index 0000000..468dcb0 --- /dev/null +++ b/test/wpt/tests/FileAPI/url/url_xmlhttprequest_img.html @@ -0,0 +1,27 @@ + + + +FileAPI Test: Creating Blob URL via XMLHttpRequest as image source + + + + +

Test passes if there is a filled blue square.

+ +

+ +

+ + + + diff --git a/test/wpt/tests/LICENSE.md b/test/wpt/tests/LICENSE.md new file mode 100644 index 0000000..39c46d0 --- /dev/null +++ b/test/wpt/tests/LICENSE.md @@ -0,0 +1,11 @@ +# The 3-Clause BSD License + +Copyright © web-platform-tests contributors + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/test/wpt/tests/README.md b/test/wpt/tests/README.md new file mode 100644 index 0000000..7e8e994 --- /dev/null +++ b/test/wpt/tests/README.md @@ -0,0 +1,124 @@ +The web-platform-tests Project +============================== + +[![Taskcluster CI Status](https://community-tc.services.mozilla.com/api/github/v1/repository/web-platform-tests/wpt/master/badge.svg)](https://community-tc.services.mozilla.com/api/github/v1/repository/web-platform-tests/wpt/master/latest) [![documentation](https://github.com/web-platform-tests/wpt/workflows/documentation/badge.svg)](https://github.com/web-platform-tests/wpt/actions?query=workflow%3Adocumentation+branch%3Amaster) [![manifest](https://github.com/web-platform-tests/wpt/workflows/manifest/badge.svg)](https://github.com/web-platform-tests/wpt/actions?query=workflow%3Amanifest+branch%3Amaster) [![Python 3](https://pyup.io/repos/github/web-platform-tests/wpt/python-3-shield.svg)](https://pyup.io/repos/github/web-platform-tests/wpt/) + +The web-platform-tests Project is a cross-browser test suite for the +Web-platform stack. Writing tests in a way that allows them to be run in all +browsers gives browser projects confidence that they are shipping software that +is compatible with other implementations, and that later implementations will +be compatible with their implementations. This in turn gives Web +authors/developers confidence that they can actually rely on the Web platform +to deliver on the promise of working across browsers and devices without +needing extra layers of abstraction to paper over the gaps left by +specification editors and implementors. + +The most important sources of information and activity are: + +- [github.com/web-platform-tests/wpt](https://github.com/web-platform-tests/wpt): + the canonical location of the project's source code revision history and the + discussion forum for changes to the code +- [web-platform-tests.org](https://web-platform-tests.org): the documentation + website; details how to set up the project, how to write tests, how to give + and receive peer review, how to serve as an administrator, and more +- [wpt.live](https://wpt.live): a public deployment of the test suite, + allowing anyone to run the tests by visiting from an + Internet-enabled browser of their choice +- [wpt.fyi](https://wpt.fyi): an archive of test results collected from an + array of web browsers on a regular basis +- [Real-time chat room](https://app.element.io/#/room/#wpt:matrix.org): the + `wpt:matrix.org` matrix channel; includes participants located + around the world, but busiest during the European working day. +- [Mailing list](https://lists.w3.org/Archives/Public/public-test-infra/): a + public and low-traffic discussion list +- [RFCs](https://github.com/web-platform-tests/rfcs): a repo for requesting + comments on substantial changes that would impact other stakeholders or + users; people who work on WPT infra are encouraged to watch the repo. + +**If you'd like clarification about anything**, don't hesitate to ask in the +chat room or on the mailing list. + +Setting Up the Repo +=================== + +Clone or otherwise get https://github.com/web-platform-tests/wpt. + +Note: because of the frequent creation and deletion of branches in this +repo, it is recommended to "prune" stale branches when fetching updates, +i.e. use `git pull --prune` (or `git fetch -p && git merge`). + +Running the Tests +================= + +See the [documentation website](https://web-platform-tests.org/running-tests/) +and in particular the +[system setup for running tests locally](https://web-platform-tests.org/running-tests/from-local-system.html#system-setup). + +Command Line Tools +================== + +The `wpt` command provides a frontend to a variety of tools for +working with and running web-platform-tests. Some of the most useful +commands are: + +* `wpt serve` - For starting the wpt http server +* `wpt run` - For running tests in a browser +* `wpt lint` - For running the lint against all tests +* `wpt manifest` - For updating or generating a `MANIFEST.json` test manifest +* `wpt install` - For installing the latest release of a browser or + webdriver server on the local machine. +* `wpt serve-wave` - For starting the wpt http server and the WAVE test runner. +For more details on how to use the WAVE test runner see the [documentation](./tools/wave/docs/usage/usage.md). + +Windows Notes +============================================= + +On Windows `wpt` commands must be prefixed with `python` or the path +to the python binary (if `python` is not in your `%PATH%`). + +```bash +python wpt [command] +``` + +Alternatively, you may also use +[Bash on Ubuntu on Windows](https://msdn.microsoft.com/en-us/commandline/wsl/about) +in the Windows 10 Anniversary Update build, then access your windows +partition from there to launch `wpt` commands. + +Please make sure git and your text editor do not automatically convert +line endings, as it will cause lint errors. For git, please set +`git config core.autocrlf false` in your working tree. + +Publication +=========== + +The master branch is automatically synced to [wpt.live](https://wpt.live/) and +[w3c-test.org](https://w3c-test.org/). + +Contributing +============ + +Save the Web, Write Some Tests! + +Absolutely everyone is welcome to contribute to test development. No +test is too small or too simple, especially if it corresponds to +something for which you've noted an interoperability bug in a browser. + +The way to contribute is just as usual: + +* Fork this repository (and make sure you're still relatively in sync + with it if you forked a while ago). +* Create a branch for your changes: + `git checkout -b topic`. +* Make your changes. +* Run `./wpt lint` as described above. +* Commit locally and push that to your repo. +* Create a pull request based on the above. + +Issues with web-platform-tests +------------------------------ + +If you spot an issue with a test and are not comfortable providing a +pull request per above to fix it, please +[file a new issue](https://github.com/web-platform-tests/wpt/issues/new). +Thank you! diff --git a/test/wpt/tests/common/CustomCorsResponse.py b/test/wpt/tests/common/CustomCorsResponse.py new file mode 100644 index 0000000..fc4d122 --- /dev/null +++ b/test/wpt/tests/common/CustomCorsResponse.py @@ -0,0 +1,30 @@ +import json + +def main(request, response): + '''Handler for getting an HTTP response customised by the given query + parameters. + + The returned response will have + - HTTP headers defined by the 'headers' query parameter + - Must be a serialized JSON dictionary mapping header names to header + values + - HTTP status code defined by the 'status' query parameter + - Must be a positive serialized JSON integer like the string '200' + - Response content defined by the 'content' query parameter + - Must be a serialized JSON string representing the desired response body + ''' + def query_parameter_or_default(param, default): + return request.GET.first(param) if param in request.GET else default + + headers = json.loads(query_parameter_or_default(b'headers', b'"{}"')) + for k, v in headers.items(): + response.headers.set(k, v) + + # Note that, in order to have out-of-the-box support for tests that don't call + # setup({'allow_uncaught_exception': true}) + # we return a no-op JS payload. This approach will avoid syntax errors in + # script resources that would otherwise cause the test harness to fail. + response.content = json.loads(query_parameter_or_default(b'content', + b'"/* CustomCorsResponse.py content */"')) + response.status_code = json.loads(query_parameter_or_default(b'status', + b'200')) diff --git a/test/wpt/tests/common/META.yml b/test/wpt/tests/common/META.yml new file mode 100644 index 0000000..ca4d2e5 --- /dev/null +++ b/test/wpt/tests/common/META.yml @@ -0,0 +1,3 @@ +suggested_reviewers: + - zqzhang + - deniak diff --git a/test/wpt/tests/common/PrefixedLocalStorage.js b/test/wpt/tests/common/PrefixedLocalStorage.js new file mode 100644 index 0000000..2f4e7b6 --- /dev/null +++ b/test/wpt/tests/common/PrefixedLocalStorage.js @@ -0,0 +1,116 @@ +/** + * Supports pseudo-"namespacing" localStorage for a given test + * by generating and using a unique prefix for keys. Why trounce on other + * tests' localStorage items when you can keep it "separated"? + * + * PrefixedLocalStorageTest: Instantiate in testharness.js tests to generate + * a new unique-ish prefix + * PrefixedLocalStorageResource: Instantiate in supporting test resource + * files to use/share a prefix generated by a test. + */ +var PrefixedLocalStorage = function () { + this.prefix = ''; // Prefix for localStorage keys + this.param = 'prefixedLocalStorage'; // Param to use in querystrings +}; + +PrefixedLocalStorage.prototype.clear = function () { + if (this.prefix === '') { return; } + Object.keys(localStorage).forEach(sKey => { + if (sKey.indexOf(this.prefix) === 0) { + localStorage.removeItem(sKey); + } + }); +}; + +/** + * Append/replace prefix parameter and value in URI querystring + * Use to generate URLs to resource files that will share the prefix. + */ +PrefixedLocalStorage.prototype.url = function (uri) { + function updateUrlParameter (uri, key, value) { + var i = uri.indexOf('#'); + var hash = (i === -1) ? '' : uri.substr(i); + uri = (i === -1) ? uri : uri.substr(0, i); + var re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i'); + var separator = uri.indexOf('?') !== -1 ? '&' : '?'; + uri = (uri.match(re)) ? uri.replace(re, `$1${key}=${value}$2`) : + `${uri}${separator}${key}=${value}`; + return uri + hash; + } + return updateUrlParameter(uri, this.param, this.prefix); +}; + +PrefixedLocalStorage.prototype.prefixedKey = function (baseKey) { + return `${this.prefix}${baseKey}`; +}; + +PrefixedLocalStorage.prototype.setItem = function (baseKey, value) { + localStorage.setItem(this.prefixedKey(baseKey), value); +}; + +/** + * Listen for `storage` events pertaining to a particular key, + * prefixed with this object's prefix. Ignore when value is being set to null + * (i.e. removeItem). + */ +PrefixedLocalStorage.prototype.onSet = function (baseKey, fn) { + window.addEventListener('storage', e => { + var match = this.prefixedKey(baseKey); + if (e.newValue !== null && e.key.indexOf(match) === 0) { + fn.call(this, e); + } + }); +}; + +/***************************************************************************** + * Use in a testharnessjs test to generate a new key prefix. + * async_test(t => { + * var prefixedStorage = new PrefixedLocalStorageTest(); + * t.add_cleanup(() => prefixedStorage.cleanup()); + * /... + * }); + */ +var PrefixedLocalStorageTest = function () { + PrefixedLocalStorage.call(this); + this.prefix = `${document.location.pathname}-${Math.random()}-${Date.now()}-`; +}; +PrefixedLocalStorageTest.prototype = Object.create(PrefixedLocalStorage.prototype); +PrefixedLocalStorageTest.prototype.constructor = PrefixedLocalStorageTest; + +/** + * Use in a cleanup function to clear out prefixed entries in localStorage + */ +PrefixedLocalStorageTest.prototype.cleanup = function () { + this.setItem('closeAll', 'true'); + this.clear(); +}; + +/***************************************************************************** + * Use in test resource files to share a prefix generated by a + * PrefixedLocalStorageTest. Will look in URL querystring for prefix. + * Setting `close_on_cleanup` opt truthy will make this script's window listen + * for storage `closeAll` event from controlling test and close itself. + * + * var PrefixedLocalStorageResource({ close_on_cleanup: true }); + */ +var PrefixedLocalStorageResource = function (options) { + PrefixedLocalStorage.call(this); + this.options = Object.assign({}, { + close_on_cleanup: false + }, options || {}); + // Check URL querystring for prefix to use + var regex = new RegExp(`[?&]${this.param}(=([^&#]*)|&|#|$)`), + results = regex.exec(document.location.href); + if (results && results[2]) { + this.prefix = results[2]; + } + // Optionally have this window close itself when the PrefixedLocalStorageTest + // sets a `closeAll` item. + if (this.options.close_on_cleanup) { + this.onSet('closeAll', () => { + window.close(); + }); + } +}; +PrefixedLocalStorageResource.prototype = Object.create(PrefixedLocalStorage.prototype); +PrefixedLocalStorageResource.prototype.constructor = PrefixedLocalStorageResource; diff --git a/test/wpt/tests/common/PrefixedLocalStorage.js.headers b/test/wpt/tests/common/PrefixedLocalStorage.js.headers new file mode 100644 index 0000000..6805c32 --- /dev/null +++ b/test/wpt/tests/common/PrefixedLocalStorage.js.headers @@ -0,0 +1 @@ +Content-Type: text/javascript; charset=utf-8 diff --git a/test/wpt/tests/common/PrefixedPostMessage.js b/test/wpt/tests/common/PrefixedPostMessage.js new file mode 100644 index 0000000..674b528 --- /dev/null +++ b/test/wpt/tests/common/PrefixedPostMessage.js @@ -0,0 +1,100 @@ +/** + * Supports pseudo-"namespacing" for window-posted messages for a given test + * by generating and using a unique prefix that gets wrapped into message + * objects. This makes it more feasible to have multiple tests that use + * `window.postMessage` in a single test file. Basically, make it possible + * for the each test to listen for only the messages that are pertinent to it. + * + * 'Prefix' not an elegant term to use here but this models itself after + * PrefixedLocalStorage. + * + * PrefixedMessageTest: Instantiate in testharness.js tests to generate + * a new unique-ish prefix that can be used by other test support files + * PrefixedMessageResource: Instantiate in supporting test resource + * files to use/share a prefix generated by a test. + */ +var PrefixedMessage = function () { + this.prefix = ''; + this.param = 'prefixedMessage'; // Param to use in querystrings +}; + +/** + * Generate a URL that adds/replaces param with this object's prefix + * Use to link to test support files that make use of + * PrefixedMessageResource. + */ +PrefixedMessage.prototype.url = function (uri) { + function updateUrlParameter (uri, key, value) { + var i = uri.indexOf('#'); + var hash = (i === -1) ? '' : uri.substr(i); + uri = (i === -1) ? uri : uri.substr(0, i); + var re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i'); + var separator = uri.indexOf('?') !== -1 ? '&' : '?'; + uri = (uri.match(re)) ? uri.replace(re, `$1${key}=${value}$2`) : + `${uri}${separator}${key}=${value}`; + return uri + hash; + } + return updateUrlParameter(uri, this.param, this.prefix); +}; + +/** + * Add an eventListener on `message` but only invoke the given callback + * for messages whose object contains this object's prefix. Remove the + * event listener once the anticipated message has been received. + */ +PrefixedMessage.prototype.onMessage = function (fn) { + window.addEventListener('message', e => { + if (typeof e.data === 'object' && e.data.hasOwnProperty('prefix')) { + if (e.data.prefix === this.prefix) { + // Only invoke callback when `data` is an object containing + // a `prefix` key with this object's prefix value + // Note fn is invoked with "unwrapped" data first, then the event `e` + // (which contains the full, wrapped e.data should it be needed) + fn.call(this, e.data.data, e); + window.removeEventListener('message', fn); + } + } + }); +}; + +/** + * Instantiate in a test file (e.g. during `setup`) to create a unique-ish + * prefix that can be shared by support files + */ +var PrefixedMessageTest = function () { + PrefixedMessage.call(this); + this.prefix = `${document.location.pathname}-${Math.random()}-${Date.now()}-`; +}; +PrefixedMessageTest.prototype = Object.create(PrefixedMessage.prototype); +PrefixedMessageTest.prototype.constructor = PrefixedMessageTest; + +/** + * Instantiate in a test support script to use a "prefix" generated by a + * PrefixedMessageTest in a controlling test file. It will look for + * the prefix in a URL param (see also PrefixedMessage#url) + */ +var PrefixedMessageResource = function () { + PrefixedMessage.call(this); + // Check URL querystring for prefix to use + var regex = new RegExp(`[?&]${this.param}(=([^&#]*)|&|#|$)`), + results = regex.exec(document.location.href); + if (results && results[2]) { + this.prefix = results[2]; + } +}; +PrefixedMessageResource.prototype = Object.create(PrefixedMessage.prototype); +PrefixedMessageResource.prototype.constructor = PrefixedMessageResource; + +/** + * This is how a test resource document can "send info" to its + * opener context. It will whatever message is being sent (`data`) in + * an object that injects the prefix. + */ +PrefixedMessageResource.prototype.postToOpener = function (data) { + if (window.opener) { + window.opener.postMessage({ + prefix: this.prefix, + data: data + }, '*'); + } +}; diff --git a/test/wpt/tests/common/PrefixedPostMessage.js.headers b/test/wpt/tests/common/PrefixedPostMessage.js.headers new file mode 100644 index 0000000..6805c32 --- /dev/null +++ b/test/wpt/tests/common/PrefixedPostMessage.js.headers @@ -0,0 +1 @@ +Content-Type: text/javascript; charset=utf-8 diff --git a/test/wpt/tests/common/README.md b/test/wpt/tests/common/README.md new file mode 100644 index 0000000..9aef19c --- /dev/null +++ b/test/wpt/tests/common/README.md @@ -0,0 +1,10 @@ +The files in this directory are non-infrastructure support files that can be used by tests. + +* `blank.html` - An empty HTML document. +* `domain-setter.sub.html` - An HTML document that sets `document.domain`. +* `dummy.xhtml` - An XHTML document. +* `dummy.xml` - An XML document. +* `text-plain.txt` - A text/plain document. +* `*.js` - Utility scripts. These are documented in the source. +* `*.py` - wptserve [Python Handlers](https://web-platform-tests.org/writing-tests/python-handlers/). These are documented in the source. +* `security-features` - Documented in `security-features/README.md`. diff --git a/test/wpt/tests/common/__init__.py b/test/wpt/tests/common/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/common/arrays.js b/test/wpt/tests/common/arrays.js new file mode 100644 index 0000000..2b31bb4 --- /dev/null +++ b/test/wpt/tests/common/arrays.js @@ -0,0 +1,31 @@ +/** + * Callback for checking equality of c and d. + * + * @callback equalityCallback + * @param {*} c + * @param {*} d + * @returns {boolean} + */ + +/** + * Returns true if the given arrays are equal. Optionally can pass an equality function. + * @param {Array} a + * @param {Array} b + * @param {equalityCallback} callbackFunction - defaults to `c === d` + * @returns {boolean} + */ +export function areArraysEqual(a, b, equalityFunction = (c, d) => { return c === d; }) { + try { + if (a.length !== b.length) + return false; + + for (let i = 0; i < a.length; i++) { + if (!equalityFunction(a[i], b[i])) + return false; + } + } catch (ex) { + return false; + } + + return true; +} diff --git a/test/wpt/tests/common/blank-with-cors.html b/test/wpt/tests/common/blank-with-cors.html new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/common/blank-with-cors.html.headers b/test/wpt/tests/common/blank-with-cors.html.headers new file mode 100644 index 0000000..cb762ef --- /dev/null +++ b/test/wpt/tests/common/blank-with-cors.html.headers @@ -0,0 +1 @@ +Access-Control-Allow-Origin: * diff --git a/test/wpt/tests/common/blank.html b/test/wpt/tests/common/blank.html new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/common/custom-cors-response.js b/test/wpt/tests/common/custom-cors-response.js new file mode 100644 index 0000000..be9c7ce --- /dev/null +++ b/test/wpt/tests/common/custom-cors-response.js @@ -0,0 +1,32 @@ +const custom_cors_response = (payload, base_url) => { + base_url = base_url || new URL(location.href); + + // Clone the given `payload` so that, as we modify it, we won't be mutating + // the caller's value in unexpected ways. + payload = Object.assign({}, payload); + payload.headers = payload.headers || {}; + // Note that, in order to have out-of-the-box support for tests that don't + // call `setup({'allow_uncaught_exception': true})` we return a no-op JS + // payload. This approach will avoid hitting syntax errors if the resource is + // interpreted as script. Without this workaround, the SyntaxError would be + // caught by the test harness and trigger a test failure. + payload.content = payload.content || '/* custom-cors-response.js content */'; + payload.status_code = payload.status_code || 200; + + // Assume that we'll be doing a CORS-enabled fetch so we'll need to set ACAO. + const acao = "Access-Control-Allow-Origin"; + if (!(acao in payload.headers)) { + payload.headers[acao] = '*'; + } + + if (!("Content-Type" in payload.headers)) { + payload.headers["Content-Type"] = "text/javascript"; + } + + let ret = new URL("/common/CustomCorsResponse.py", base_url); + for (const key in payload) { + ret.searchParams.append(key, JSON.stringify(payload[key])); + } + + return ret; +}; diff --git a/test/wpt/tests/common/dispatcher/README.md b/test/wpt/tests/common/dispatcher/README.md new file mode 100644 index 0000000..cfaafb6 --- /dev/null +++ b/test/wpt/tests/common/dispatcher/README.md @@ -0,0 +1,228 @@ +# `RemoteContext`: API for script execution in another context + +`RemoteContext` in `/common/dispatcher/dispatcher.js` provides an interface to +execute JavaScript in another global object (page or worker, the "executor"), +based on: + +- [WPT RFC 88: context IDs from uuid searchParams in URL](https://github.com/web-platform-tests/rfcs/pull/88), +- [WPT RFC 89: execute_script](https://github.com/web-platform-tests/rfcs/pull/89) and +- [WPT RFC 91: RemoteContext](https://github.com/web-platform-tests/rfcs/pull/91). + +Tests can send arbitrary javascript to executors to evaluate in its global +object, like: + +``` +// injector.html +const argOnLocalContext = ...; + +async function execute() { + window.open('executor.html?uuid=' + uuid); + const ctx = new RemoteContext(uuid); + await ctx.execute_script( + (arg) => functionOnRemoteContext(arg), + [argOnLocalContext]); +}; +``` + +and on executor: + +``` +// executor.html +function functionOnRemoteContext(arg) { ... } + +const uuid = new URLSearchParams(window.location.search).get('uuid'); +const executor = new Executor(uuid); +``` + +For concrete examples, see +[events.html](../../html/browsers/browsing-the-web/back-forward-cache/events.html) +and +[executor.html](../../html/browsers/browsing-the-web/back-forward-cache/resources/executor.html) +in back-forward cache tests. + +Note that `executor*` files under `/common/dispatcher/` are NOT for +`RemoteContext.execute_script()`. Use `remote-executor.html` instead. + +This is universal and avoids introducing many specific `XXX-helper.html` +resources. +Moreover, tests are easier to read, because the whole logic of the test can be +defined in a single file. + +## `new RemoteContext(uuid)` + +- `uuid` is a UUID string that identifies the remote context and should match + with the `uuid` parameter of the URL of the remote context. +- Callers should create the remote context outside this constructor (e.g. + `window.open('executor.html?uuid=' + uuid)`). + +## `RemoteContext.execute_script(fn, args)` + +- `fn` is a JavaScript function to execute on the remote context, which is + converted to a string using `toString()` and sent to the remote context. +- `args` is null or an array of arguments to pass to the function on the + remote context. Arguments are passed as JSON. +- If the return value of `fn` when executed in the remote context is a promise, + the promise returned by `execute_script` resolves to the resolved value of + that promise. Otherwise the `execute_script` promise resolves to the return + value of `fn`. + +Note that `fn` is evaluated on the remote context (`executor.html` in the +example above), while `args` are evaluated on the caller context +(`injector.html`) and then passed to the remote context. + +## Return value of injected functions and `execute_script()` + +If the return value of the injected function when executed in the remote +context is a promise, the promise returned by `execute_script` resolves to the +resolved value of that promise. Otherwise the `execute_script` promise resolves +to the return value of the function. + +When the return value of an injected script is a Promise, it should be resolved +before any navigation starts on the remote context. For example, it shouldn't +be resolved after navigating out and navigating back to the page again. +It's fine to create a Promise to be resolved after navigations, if it's not the +return value of the injected function. + +## Calling timing of `execute_script()` + +When `RemoteContext.execute_script()` is called when the remote context is not +active (for example before it is created, before navigation to the page, or +during the page is in back-forward cache), the injected script is evaluated +after the remote context becomes active. + +Multiple calls to `RemoteContext.execute_script()` will result in multiple scripts +being executed in remote context and ordering will be maintained. + +## Errors from `execute_script()` + +Errors from `execute_script()` will result in promise rejections, so it is +important to await the result. This can be `await ctx.execute_script(...)` for +every call but if there are multiple scripts to executed, it may be preferable +to wait on them in parallel to avoid incurring full round-trip time for each, +e.g. + +```js +await Promise.all( + ctx1.execute_script(...), + ctx1.execute_script(...), + ctx2.execute_script(...), + ctx2.execute_script(...), + ... +) +``` + +## Evaluation timing of injected functions + +The script injected by `RemoteContext.execute_script()` can be evaluated any +time during the remote context is active. +For example, even before DOMContentLoaded events or even during navigation. +It's the responsibility of test-specific code/helpers to ensure evaluation +timing constraints (which can be also test-specific), if any needed. + +### Ensuring evaluation timing around page load + +For example, to ensure that injected functions (`mainFunction` below) are +evaluated after the first `pageshow` event, we can use pure JavaScript code +like below: + +``` +// executor.html +window.pageShowPromise = new Promise(resolve => + window.addEventListener('pageshow', resolve, {once: true})); + + +// injector.html +const waitForPageShow = async () => { + while (!window.pageShowPromise) { + await new Promise(resolve => setTimeout(resolve, 100)); + } + await window.pageShowPromise; +}; + +await ctx.execute(waitForPageShow); +await ctx.execute(mainFunction); +``` + +### Ensuring evaluation timing around navigation out/unloading + +It can be important to ensure there are no injected functions nor code behind +`RemoteContext` (such as Fetch APIs accessing server-side stash) running after +navigation is initiated, for example in the case of back-forward cache testing. + +To ensure this, + +- Do not call the next `RemoteContext.execute()` for the remote context after + triggering the navigation, until we are sure that the remote context is not + active (e.g. after we confirm that the new page is loaded). +- Call `Executor.suspend(callback)` synchronously within the injected script. + This suspends executor-related code, and calls `callback` when it is ready + to start navigation. + +The code on the injector side would be like: + +``` +// injector.html +await ctx.execute_script(() => { + executor.suspend(() => { + location.href = 'new-url.html'; + }); +}); +``` + +## Future Work: Possible integration with `test_driver` + +Currently `RemoteContext` is implemented by JavaScript and WPT-server-side +stash, and not integrated with `test_driver` nor `testharness`. +There is a proposal of `test_driver`-integrated version (see the RFCs listed +above). + +The API semantics and guidelines in this document are designed to be applicable +to both the current stash-based `RemoteContext` and `test_driver`-based +version, and thus the tests using `RemoteContext` will be migrated with minimum +modifications (mostly in `/common/dispatcher/dispatcher.js` and executors), for +example in a +[draft CL](https://chromium-review.googlesource.com/c/chromium/src/+/3082215/). + + +# `send()`/`receive()` Message passing APIs + +`dispatcher.js` (and its server-side backend `dispatcher.py`) provides a +universal queue-based message passing API. +Each queue is identified by a UUID, and accessed via the following APIs: + +- `send(uuid, message)` pushes a string `message` to the queue `uuid`. +- `receive(uuid)` pops the first item from the queue `uuid`. +- `showRequestHeaders(origin, uuid)` and + `cacheableShowRequestHeaders(origin, uuid)` return URLs, that push request + headers to the queue `uuid` upon fetching. + +It works cross-origin, and even access different browser context groups. + +Messages are queued, this means one doesn't need to wait for the receiver to +listen, before sending the first message +(but still need to wait for the resolution of the promise returned by `send()` +to ensure the order between `send()`s). + +## Executors + +Similar to `RemoteContext.execute_script()`, `send()`/`receive()` can be used +for sending arbitrary javascript to be evaluated in another page or worker. + +- `executor.html` (as a Document), +- `executor-worker.js` (as a Web Worker), and +- `executor-service-worker.js` (as a Service Worker) + +are examples of executors. +Note that these executors are NOT compatible with +`RemoteContext.execute_script()`. + +## Future Work + +`send()`, `receive()` and the executors below are kept for COEP/COOP tests. + +For remote script execution, new tests should use +`RemoteContext.execute_script()` instead. + +For message passing, +[WPT RFC 90](https://github.com/web-platform-tests/rfcs/pull/90) is still under +discussion. diff --git a/test/wpt/tests/common/dispatcher/dispatcher.js b/test/wpt/tests/common/dispatcher/dispatcher.js new file mode 100644 index 0000000..a0f9f43 --- /dev/null +++ b/test/wpt/tests/common/dispatcher/dispatcher.js @@ -0,0 +1,256 @@ +// Define a universal message passing API. It works cross-origin and across +// browsing context groups. +const dispatcher_path = "/common/dispatcher/dispatcher.py"; +const dispatcher_url = new URL(dispatcher_path, location.href).href; + +// Return a promise, limiting the number of concurrent accesses to a shared +// resources to |max_concurrent_access|. +const concurrencyLimiter = (max_concurrency) => { + let pending = 0; + let waiting = []; + return async (task) => { + pending++; + if (pending > max_concurrency) + await new Promise(resolve => waiting.push(resolve)); + let result = await task(); + pending--; + waiting.shift()?.(); + return result; + }; +} + +// Wait for a random amount of time in the range [10ms,100ms]. +const randomDelay = () => { + return new Promise(resolve => setTimeout(resolve, 10 + 90*Math.random())); +} + +// Sending too many requests in parallel causes congestion. Limiting it improves +// throughput. +// +// Note: The following table has been determined on the test: +// ../cache-storage.tentative.https.html +// using Chrome with a 64 core CPU / 64GB ram, in release mode: +// ┌───────────┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬────┠+// │concurrency│ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 10│ 15│ 20│ 30│ 50│ 100│ +// ├───────────┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼────┤ +// │time (s) │ 54│ 38│ 31│ 29│ 26│ 24│ 22│ 22│ 22│ 22│ 34│ 36 │ +// └───────────┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴────┘ +const limiter = concurrencyLimiter(6); + +// While requests to different remote contexts can go in parallel, we need to +// ensure that requests to each remote context are done in order. This maps a +// uuid to a queue of requests to send. A queue is processed until it is empty +// and then is deleted from the map. +const sendQueues = new Map(); + +// Sends a single item (with rate-limiting) and calls the associated resolver +// when it is successfully sent. +const sendItem = async function (uuid, resolver, message) { + await limiter(async () => { + // Requests might be dropped. Retry until getting a confirmation it has been + // processed. + while(1) { + try { + let response = await fetch(dispatcher_url + `?uuid=${uuid}`, { + method: 'POST', + body: message + }) + if (await response.text() == "done") { + resolver(); + return; + } + } catch (fetch_error) {} + await randomDelay(); + }; + }); +} + +// While the queue is non-empty, send the next item. This is async and new items +// may be added to the queue while others are being sent. +const processQueue = async function (uuid, queue) { + while (queue.length) { + const [resolver, message] = queue.shift(); + await sendItem(uuid, resolver, message); + } + // The queue is empty, delete it. + sendQueues.delete(uuid); +} + +const send = async function (uuid, message) { + const itemSentPromise = new Promise((resolve) => { + const item = [resolve, message]; + if (sendQueues.has(uuid)) { + // There is already a queue for `uuid`, just add to it and it will be processed. + sendQueues.get(uuid).push(item); + } else { + // There is no queue for `uuid`, create it and start processing. + const queue = [item]; + sendQueues.set(uuid, queue); + processQueue(uuid, queue); + } + }); + // Wait until the item has been successfully sent. + await itemSentPromise; +} + +const receive = async function (uuid) { + while(1) { + let data = "not ready"; + try { + data = await limiter(async () => { + let response = await fetch(dispatcher_url + `?uuid=${uuid}`); + return await response.text(); + }); + } catch (fetch_error) {} + + if (data == "not ready") { + await randomDelay(); + continue; + } + + return data; + } +} + +// Returns an URL. When called, the server sends toward the `uuid` queue the +// request headers. Useful for determining if something was requested with +// Cookies. +const showRequestHeaders = function(origin, uuid) { + return origin + dispatcher_path + `?uuid=${uuid}&show-headers`; +} + +// Same as above, except for the response is cacheable. +const cacheableShowRequestHeaders = function(origin, uuid) { + return origin + dispatcher_path + `?uuid=${uuid}&cacheable&show-headers`; +} + +// This script requires +// - `/common/utils.js` for `token()`. + +// Returns the URL of a document that can be used as a `RemoteContext`. +// +// `uuid` should be a UUID uniquely identifying the given remote context. +// `options` has the following shape: +// +// { +// host: (optional) Sets the returned URL's `host` property. Useful for +// cross-origin executors. +// protocol: (optional) Sets the returned URL's `protocol` property. +// } +function remoteExecutorUrl(uuid, options) { + const url = new URL("/common/dispatcher/remote-executor.html", location); + url.searchParams.set("uuid", uuid); + + if (options?.host) { + url.host = options.host; + } + + if (options?.protocol) { + url.protocol = options.protocol; + } + + return url; +} + +// Represents a remote executor. For more detailed explanation see `README.md`. +class RemoteContext { + // `uuid` is a UUID string that identifies the remote context and should + // match with the `uuid` parameter of the URL of the remote context. + constructor(uuid) { + this.context_id = uuid; + } + + // Evaluates the script `expr` on the executor. + // - If `expr` is evaluated to a Promise that is resolved with a value: + // `execute_script()` returns a Promise resolved with the value. + // - If `expr` is evaluated to a non-Promise value: + // `execute_script()` returns a Promise resolved with the value. + // - If `expr` throws an error or is evaluated to a Promise that is rejected: + // `execute_script()` returns a rejected Promise with the error's + // `message`. + // Note that currently the type of error (e.g. DOMException) is not + // preserved, except for `TypeError`. + // The values should be able to be serialized by JSON.stringify(). + async execute_script(fn, args) { + const receiver = token(); + await this.send({receiver: receiver, fn: fn.toString(), args: args}); + const response = JSON.parse(await receive(receiver)); + if (response.status === 'success') { + return response.value; + } + + // exception + if (response.name === 'TypeError') { + throw new TypeError(response.value); + } + throw new Error(response.value); + } + + async send(msg) { + return await send(this.context_id, JSON.stringify(msg)); + } +}; + +class Executor { + constructor(uuid) { + this.uuid = uuid; + + // If `suspend_callback` is not `null`, the executor should be suspended + // when there are no ongoing tasks. + this.suspend_callback = null; + + this.execute(); + } + + // Wait until there are no ongoing tasks nor fetch requests for polling + // tasks, and then suspend the executor and call `callback()`. + // Navigation from the executor page should be triggered inside `callback()`, + // to avoid conflict with in-flight fetch requests. + suspend(callback) { + this.suspend_callback = callback; + } + + resume() { + } + + async execute() { + while(true) { + if (this.suspend_callback !== null) { + this.suspend_callback(); + this.suspend_callback = null; + // Wait for `resume()` to be called. + await new Promise(resolve => this.resume = resolve); + + // Workaround for https://crbug.com/1244230. + // Without this workaround, the executor is resumed and the fetch + // request to poll the next task is initiated synchronously from + // pageshow event after the page restored from BFCache, and the fetch + // request promise is never resolved (and thus the test results in + // timeout) due to https://crbug.com/1244230. The root cause is not yet + // known, but setTimeout() with 0ms causes the resume triggered on + // another task and seems to resolve the issue. + await new Promise(resolve => setTimeout(resolve, 0)); + + continue; + } + + const task = JSON.parse(await receive(this.uuid)); + + let response; + try { + const value = await eval(task.fn).apply(null, task.args); + response = JSON.stringify({ + status: 'success', + value: value + }); + } catch(e) { + response = JSON.stringify({ + status: 'exception', + name: e.name, + value: e.message + }); + } + await send(task.receiver, response); + } + } +} diff --git a/test/wpt/tests/common/dispatcher/dispatcher.py b/test/wpt/tests/common/dispatcher/dispatcher.py new file mode 100644 index 0000000..9fe7a38 --- /dev/null +++ b/test/wpt/tests/common/dispatcher/dispatcher.py @@ -0,0 +1,53 @@ +import json +from wptserve.utils import isomorphic_decode + +# A server used to store and retrieve arbitrary data. +# This is used by: ./dispatcher.js +def main(request, response): + # This server is configured so that is accept to receive any requests and + # any cookies the web browser is willing to send. + response.headers.set(b"Access-Control-Allow-Credentials", b"true") + response.headers.set(b'Access-Control-Allow-Methods', b'OPTIONS, GET, POST') + response.headers.set(b'Access-Control-Allow-Headers', b'Content-Type') + response.headers.set(b"Access-Control-Allow-Origin", request.headers.get(b"origin") or '*') + + if b"cacheable" in request.GET: + response.headers.set(b"Cache-Control", b"max-age=31536000") + else: + response.headers.set(b'Cache-Control', b'no-cache, no-store, must-revalidate') + + # CORS preflight + if request.method == u'OPTIONS': + return b'' + + uuid = request.GET[b'uuid'] + stash = request.server.stash; + + # The stash is accessed concurrently by many clients. A lock is used to + # avoid unterleaved read/write from different clients. + with stash.lock: + queue = stash.take(uuid, '/common/dispatcher') or []; + + # Push into the |uuid| queue, the requested headers. + if b"show-headers" in request.GET: + headers = {}; + for key, value in request.headers.items(): + headers[isomorphic_decode(key)] = isomorphic_decode(request.headers[key]) + headers = json.dumps(headers); + queue.append(headers); + ret = b''; + + # Push into the |uuid| queue, the posted data. + elif request.method == u'POST': + queue.append(request.body) + ret = b'done' + + # Pull from the |uuid| queue, the posted data. + else: + if len(queue) == 0: + ret = b'not ready' + else: + ret = queue.pop(0) + + stash.put(uuid, queue, '/common/dispatcher') + return ret; diff --git a/test/wpt/tests/common/dispatcher/executor-service-worker.js b/test/wpt/tests/common/dispatcher/executor-service-worker.js new file mode 100644 index 0000000..0b47d66 --- /dev/null +++ b/test/wpt/tests/common/dispatcher/executor-service-worker.js @@ -0,0 +1,24 @@ +importScripts('./dispatcher.js'); + +const params = new URLSearchParams(location.search); +const uuid = params.get('uuid'); + +// The fetch handler must be registered before parsing the main script response. +// So do it here, for future use. +fetchHandler = () => {} +addEventListener('fetch', e => { + fetchHandler(e); +}); + +// Force ServiceWorker to immediately activate itself. +addEventListener('install', event => { + skipWaiting(); +}); + +let executeOrders = async function() { + while(true) { + let task = await receive(uuid); + eval(`(async () => {${task}})()`); + } +}; +executeOrders(); diff --git a/test/wpt/tests/common/dispatcher/executor-worker.js b/test/wpt/tests/common/dispatcher/executor-worker.js new file mode 100644 index 0000000..ea065a6 --- /dev/null +++ b/test/wpt/tests/common/dispatcher/executor-worker.js @@ -0,0 +1,12 @@ +importScripts('./dispatcher.js'); + +const params = new URLSearchParams(location.search); +const uuid = params.get('uuid'); + +let executeOrders = async function() { + while(true) { + let task = await receive(uuid); + eval(`(async () => {${task}})()`); + } +}; +executeOrders(); diff --git a/test/wpt/tests/common/dispatcher/executor.html b/test/wpt/tests/common/dispatcher/executor.html new file mode 100644 index 0000000..5fe6a95 --- /dev/null +++ b/test/wpt/tests/common/dispatcher/executor.html @@ -0,0 +1,15 @@ + + diff --git a/test/wpt/tests/common/dispatcher/remote-executor.html b/test/wpt/tests/common/dispatcher/remote-executor.html new file mode 100644 index 0000000..8b00303 --- /dev/null +++ b/test/wpt/tests/common/dispatcher/remote-executor.html @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/test/wpt/tests/common/domain-setter.sub.html b/test/wpt/tests/common/domain-setter.sub.html new file mode 100644 index 0000000..ad3b9f8 --- /dev/null +++ b/test/wpt/tests/common/domain-setter.sub.html @@ -0,0 +1,8 @@ + + +A page that will likely be same-origin-domain but not same-origin + + diff --git a/test/wpt/tests/common/dummy.xhtml b/test/wpt/tests/common/dummy.xhtml new file mode 100644 index 0000000..dba6945 --- /dev/null +++ b/test/wpt/tests/common/dummy.xhtml @@ -0,0 +1,2 @@ + +Dummy XHTML document diff --git a/test/wpt/tests/common/dummy.xml b/test/wpt/tests/common/dummy.xml new file mode 100644 index 0000000..4a60c30 --- /dev/null +++ b/test/wpt/tests/common/dummy.xml @@ -0,0 +1 @@ +Dummy XML document diff --git a/test/wpt/tests/common/echo.py b/test/wpt/tests/common/echo.py new file mode 100644 index 0000000..911b54a --- /dev/null +++ b/test/wpt/tests/common/echo.py @@ -0,0 +1,6 @@ +def main(request, response): + # Without X-XSS-Protection to disable non-standard XSS protection the functionality this + # resource offers is useless + response.headers.set(b"X-XSS-Protection", b"0") + response.headers.set(b"Content-Type", b"text/html") + response.content = request.GET.first(b"content") diff --git a/test/wpt/tests/common/gc.js b/test/wpt/tests/common/gc.js new file mode 100644 index 0000000..ac43a4c --- /dev/null +++ b/test/wpt/tests/common/gc.js @@ -0,0 +1,52 @@ +/** + * Does a best-effort attempt at invoking garbage collection. Attempts to use + * the standardized `TestUtils.gc()` function, but falls back to other + * environment-specific nonstandard functions, with a final result of just + * creating a lot of garbage (in which case you will get a console warning). + * + * This should generally only be used to attempt to trigger bugs and crashes + * inside tests, i.e. cases where if garbage collection happened, then this + * should not trigger some misbehavior. You cannot rely on garbage collection + * successfully trigger, or that any particular unreachable object will be + * collected. + * + * @returns {Promise} A promise you should await to ensure garbage + * collection has had a chance to complete. + */ +self.garbageCollect = async () => { + // https://testutils.spec.whatwg.org/#the-testutils-namespace + if (self.TestUtils?.gc) { + return TestUtils.gc(); + } + + // Use --expose_gc for V8 (and Node.js) + // to pass this flag at chrome launch use: --js-flags="--expose-gc" + // Exposed in SpiderMonkey shell as well + if (self.gc) { + return self.gc(); + } + + // Present in some WebKit development environments + if (self.GCController) { + return GCController.collect(); + } + + console.warn( + 'Tests are running without the ability to do manual garbage collection. ' + + 'They will still work, but coverage will be suboptimal.'); + + for (var i = 0; i < 1000; i++) { + gcRec(10); + } + + function gcRec(n) { + if (n < 1) { + return {}; + } + + let temp = { i: "ab" + i + i / 100000 }; + temp += "foo"; + + gcRec(n - 1); + } +}; diff --git a/test/wpt/tests/common/get-host-info.sub.js b/test/wpt/tests/common/get-host-info.sub.js new file mode 100644 index 0000000..9b8c2b5 --- /dev/null +++ b/test/wpt/tests/common/get-host-info.sub.js @@ -0,0 +1,63 @@ +/** + * Host information for cross-origin tests. + * @returns {Object} with properties for different host information. + */ +function get_host_info() { + + var HTTP_PORT = '{{ports[http][0]}}'; + var HTTP_PORT2 = '{{ports[http][1]}}'; + var HTTPS_PORT = '{{ports[https][0]}}'; + var HTTPS_PORT2 = '{{ports[https][1]}}'; + var PROTOCOL = self.location.protocol; + var IS_HTTPS = (PROTOCOL == "https:"); + var PORT = IS_HTTPS ? HTTPS_PORT : HTTP_PORT; + var PORT2 = IS_HTTPS ? HTTPS_PORT2 : HTTP_PORT2; + var HTTP_PORT_ELIDED = HTTP_PORT == "80" ? "" : (":" + HTTP_PORT); + var HTTP_PORT2_ELIDED = HTTP_PORT2 == "80" ? "" : (":" + HTTP_PORT2); + var HTTPS_PORT_ELIDED = HTTPS_PORT == "443" ? "" : (":" + HTTPS_PORT); + var PORT_ELIDED = IS_HTTPS ? HTTPS_PORT_ELIDED : HTTP_PORT_ELIDED; + var ORIGINAL_HOST = '{{host}}'; + var REMOTE_HOST = (ORIGINAL_HOST === 'localhost') ? '127.0.0.1' : ('www1.' + ORIGINAL_HOST); + var OTHER_HOST = '{{domains[www2]}}'; + var NOTSAMESITE_HOST = (ORIGINAL_HOST === 'localhost') ? '127.0.0.1' : ('{{hosts[alt][]}}'); + + return { + HTTP_PORT: HTTP_PORT, + HTTP_PORT2: HTTP_PORT2, + HTTPS_PORT: HTTPS_PORT, + HTTPS_PORT2: HTTPS_PORT2, + PORT: PORT, + PORT2: PORT2, + ORIGINAL_HOST: ORIGINAL_HOST, + REMOTE_HOST: REMOTE_HOST, + + ORIGIN: PROTOCOL + "//" + ORIGINAL_HOST + PORT_ELIDED, + HTTP_ORIGIN: 'http://' + ORIGINAL_HOST + HTTP_PORT_ELIDED, + HTTPS_ORIGIN: 'https://' + ORIGINAL_HOST + HTTPS_PORT_ELIDED, + HTTPS_ORIGIN_WITH_CREDS: 'https://foo:bar@' + ORIGINAL_HOST + HTTPS_PORT_ELIDED, + HTTP_ORIGIN_WITH_DIFFERENT_PORT: 'http://' + ORIGINAL_HOST + HTTP_PORT2_ELIDED, + REMOTE_ORIGIN: PROTOCOL + "//" + REMOTE_HOST + PORT_ELIDED, + OTHER_ORIGIN: PROTOCOL + "//" + OTHER_HOST + PORT_ELIDED, + HTTP_REMOTE_ORIGIN: 'http://' + REMOTE_HOST + HTTP_PORT_ELIDED, + HTTP_NOTSAMESITE_ORIGIN: 'http://' + NOTSAMESITE_HOST + HTTP_PORT_ELIDED, + HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT: 'http://' + REMOTE_HOST + HTTP_PORT2_ELIDED, + HTTPS_REMOTE_ORIGIN: 'https://' + REMOTE_HOST + HTTPS_PORT_ELIDED, + HTTPS_REMOTE_ORIGIN_WITH_CREDS: 'https://foo:bar@' + REMOTE_HOST + HTTPS_PORT_ELIDED, + HTTPS_NOTSAMESITE_ORIGIN: 'https://' + NOTSAMESITE_HOST + HTTPS_PORT_ELIDED, + UNAUTHENTICATED_ORIGIN: 'http://' + OTHER_HOST + HTTP_PORT_ELIDED, + AUTHENTICATED_ORIGIN: 'https://' + OTHER_HOST + HTTPS_PORT_ELIDED + }; +} + +/** + * When a default port is used, location.port returns the empty string. + * This function attempts to provide an exact port, assuming we are running under wptserve. + * @param {*} loc - can be Location///URL, but assumes http/https only. + * @returns {string} The port number. + */ +function get_port(loc) { + if (loc.port) { + return loc.port; + } + return loc.protocol === 'https:' ? '443' : '80'; +} diff --git a/test/wpt/tests/common/get-host-info.sub.js.headers b/test/wpt/tests/common/get-host-info.sub.js.headers new file mode 100644 index 0000000..6805c32 --- /dev/null +++ b/test/wpt/tests/common/get-host-info.sub.js.headers @@ -0,0 +1 @@ +Content-Type: text/javascript; charset=utf-8 diff --git a/test/wpt/tests/common/media.js b/test/wpt/tests/common/media.js new file mode 100644 index 0000000..800593f --- /dev/null +++ b/test/wpt/tests/common/media.js @@ -0,0 +1,61 @@ +/** + * Returns the URL of a supported video source based on the user agent + * @param {string} base - media URL without file extension + * @returns {string} + */ +function getVideoURI(base) +{ + var extension = '.mp4'; + + var videotag = document.createElement("video"); + + if ( videotag.canPlayType ) + { + if (videotag.canPlayType('video/webm; codecs="vp9, opus"') ) + { + extension = '.webm'; + } else if ( videotag.canPlayType('video/ogg; codecs="theora, vorbis"') ) + { + extension = '.ogv'; + } + } + + return base + extension; +} + +/** + * Returns the URL of a supported audio source based on the user agent + * @param {string} base - media URL without file extension + * @returns {string} + */ +function getAudioURI(base) +{ + var extension = '.mp3'; + + var audiotag = document.createElement("audio"); + + if ( audiotag.canPlayType && + audiotag.canPlayType('audio/ogg') ) + { + extension = '.oga'; + } + + return base + extension; +} + +/** + * Returns the MIME type for a media URL based on the file extension. + * @param {string} url + * @returns {string} + */ +function getMediaContentType(url) { + var extension = new URL(url, location).pathname.split(".").pop(); + var map = { + "mp4" : "video/mp4", + "ogv" : "application/ogg", + "webm": "video/webm", + "mp3" : "audio/mp3", + "oga" : "application/ogg", + }; + return map[extension]; +} diff --git a/test/wpt/tests/common/media.js.headers b/test/wpt/tests/common/media.js.headers new file mode 100644 index 0000000..6805c32 --- /dev/null +++ b/test/wpt/tests/common/media.js.headers @@ -0,0 +1 @@ +Content-Type: text/javascript; charset=utf-8 diff --git a/test/wpt/tests/common/object-association.js b/test/wpt/tests/common/object-association.js new file mode 100644 index 0000000..669c17c --- /dev/null +++ b/test/wpt/tests/common/object-association.js @@ -0,0 +1,74 @@ +"use strict"; + +// This is for testing whether an object (e.g., a global property) is associated with Window, or +// with Document. Recall that Window and Document are 1:1 except when doing a same-origin navigation +// away from the initial about:blank. In that case the Window object gets reused for the new +// Document. +// +// So: +// - If something is per-Window, then it should maintain its identity across an about:blank +// navigation. +// - If something is per-Document, then it should be recreated across an about:blank navigation. + +window.testIsPerWindow = propertyName => { + runTests(propertyName, assert_equals, "must not"); +}; + +window.testIsPerDocument = propertyName => { + runTests(propertyName, assert_not_equals, "must"); +}; + +function runTests(propertyName, equalityOrInequalityAsserter, mustOrMustNotReplace) { + async_test(t => { + const iframe = document.createElement("iframe"); + document.body.appendChild(iframe); + const frame = iframe.contentWindow; + + const before = frame[propertyName]; + assert_implements(before, `window.${propertyName} must be implemented`); + + iframe.onload = t.step_func_done(() => { + const after = frame[propertyName]; + equalityOrInequalityAsserter(after, before); + }); + + iframe.src = "/common/blank.html"; + }, `Navigating from the initial about:blank ${mustOrMustNotReplace} replace window.${propertyName}`); + + // Per spec, discarding a browsing context should not change any of the global objects. + test(() => { + const iframe = document.createElement("iframe"); + document.body.appendChild(iframe); + const frame = iframe.contentWindow; + + const before = frame[propertyName]; + assert_implements(before, `window.${propertyName} must be implemented`); + + iframe.remove(); + + const after = frame[propertyName]; + assert_equals(after, before, `window.${propertyName} should not change after iframe.remove()`); + }, `Discarding the browsing context must not change window.${propertyName}`); + + // Per spec, document.open() should not change any of the global objects. In historical versions + // of the spec, it did, so we test here. + async_test(t => { + const iframe = document.createElement("iframe"); + + iframe.onload = t.step_func_done(() => { + const frame = iframe.contentWindow; + const before = frame[propertyName]; + assert_implements(before, `window.${propertyName} must be implemented`); + + frame.document.open(); + + const after = frame[propertyName]; + assert_equals(after, before); + + frame.document.close(); + }); + + iframe.src = "/common/blank.html"; + document.body.appendChild(iframe); + }, `document.open() must not replace window.${propertyName}`); +} diff --git a/test/wpt/tests/common/object-association.js.headers b/test/wpt/tests/common/object-association.js.headers new file mode 100644 index 0000000..6805c32 --- /dev/null +++ b/test/wpt/tests/common/object-association.js.headers @@ -0,0 +1 @@ +Content-Type: text/javascript; charset=utf-8 diff --git a/test/wpt/tests/common/performance-timeline-utils.js b/test/wpt/tests/common/performance-timeline-utils.js new file mode 100644 index 0000000..b20241c --- /dev/null +++ b/test/wpt/tests/common/performance-timeline-utils.js @@ -0,0 +1,56 @@ +/* +author: W3C http://www.w3.org/ +help: http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute +*/ +var performanceNamespace = window.performance; +var namespace_check = false; +function wp_test(func, msg, properties) +{ + // only run the namespace check once + if (!namespace_check) + { + namespace_check = true; + + if (performanceNamespace === undefined || performanceNamespace == null) + { + // show a single error that window.performance is undefined + // The window.performance attribute provides a hosting area for performance related attributes. + test(function() { assert_true(performanceNamespace !== undefined && performanceNamespace != null, "window.performance is defined and not null"); }, "window.performance is defined and not null."); + } + } + + test(func, msg, properties); +} + +function test_true(value, msg, properties) +{ + wp_test(function () { assert_true(value, msg); }, msg, properties); +} + +function test_equals(value, equals, msg, properties) +{ + wp_test(function () { assert_equals(value, equals, msg); }, msg, properties); +} + +// assert for every entry in `expectedEntries`, there is a matching entry _somewhere_ in `actualEntries` +function test_entries(actualEntries, expectedEntries) { + test_equals(actualEntries.length, expectedEntries.length) + expectedEntries.forEach(function (expectedEntry) { + var foundEntry = actualEntries.find(function (actualEntry) { + return typeof Object.keys(expectedEntry).find(function (key) { + return actualEntry[key] !== expectedEntry[key] + }) === 'undefined' + }) + test_true(!!foundEntry, `Entry ${JSON.stringify(expectedEntry)} could not be found.`) + if (foundEntry) { + assert_object_equals(foundEntry.toJSON(), expectedEntry) + } + }) +} + +function delayedLoadListener(callback) { + window.addEventListener('load', function() { + // TODO(cvazac) Remove this setTimeout when spec enforces sync entries. + step_timeout(callback, 0) + }) +} diff --git a/test/wpt/tests/common/performance-timeline-utils.js.headers b/test/wpt/tests/common/performance-timeline-utils.js.headers new file mode 100644 index 0000000..6805c32 --- /dev/null +++ b/test/wpt/tests/common/performance-timeline-utils.js.headers @@ -0,0 +1 @@ +Content-Type: text/javascript; charset=utf-8 diff --git a/test/wpt/tests/common/proxy-all.sub.pac b/test/wpt/tests/common/proxy-all.sub.pac new file mode 100644 index 0000000..de601e5 --- /dev/null +++ b/test/wpt/tests/common/proxy-all.sub.pac @@ -0,0 +1,3 @@ +function FindProxyForURL(url, host) { + return "PROXY {{host}}:{{ports[http][0]}}" +} diff --git a/test/wpt/tests/common/redirect-opt-in.py b/test/wpt/tests/common/redirect-opt-in.py new file mode 100644 index 0000000..b5e674a --- /dev/null +++ b/test/wpt/tests/common/redirect-opt-in.py @@ -0,0 +1,20 @@ +def main(request, response): + """Simple handler that causes redirection. + + The request should typically have two query parameters: + status - The status to use for the redirection. Defaults to 302. + location - The resource to redirect to. + """ + status = 302 + if b"status" in request.GET: + try: + status = int(request.GET.first(b"status")) + except ValueError: + pass + + response.status = status + + location = request.GET.first(b"location") + + response.headers.set(b"Location", location) + response.headers.set(b"Timing-Allow-Origin", b"*") diff --git a/test/wpt/tests/common/redirect.py b/test/wpt/tests/common/redirect.py new file mode 100644 index 0000000..f2fd1eb --- /dev/null +++ b/test/wpt/tests/common/redirect.py @@ -0,0 +1,19 @@ +def main(request, response): + """Simple handler that causes redirection. + + The request should typically have two query parameters: + status - The status to use for the redirection. Defaults to 302. + location - The resource to redirect to. + """ + status = 302 + if b"status" in request.GET: + try: + status = int(request.GET.first(b"status")) + except ValueError: + pass + + response.status = status + + location = request.GET.first(b"location") + + response.headers.set(b"Location", location) diff --git a/test/wpt/tests/common/refresh.py b/test/wpt/tests/common/refresh.py new file mode 100644 index 0000000..0d30990 --- /dev/null +++ b/test/wpt/tests/common/refresh.py @@ -0,0 +1,11 @@ +def main(request, response): + """ + Respond with a blank HTML document and a `Refresh` header which describes + an immediate redirect to the URL specified by the requests `location` query + string parameter + """ + headers = [ + (b'Content-Type', b'text/html'), + (b'Refresh', b'0; URL=' + request.GET.first(b'location')) + ] + return (200, headers, b'') diff --git a/test/wpt/tests/common/reftest-wait.js b/test/wpt/tests/common/reftest-wait.js new file mode 100644 index 0000000..64fe9bf --- /dev/null +++ b/test/wpt/tests/common/reftest-wait.js @@ -0,0 +1,39 @@ +/** + * Remove the `reftest-wait` class on the document element. + * The reftest runner will wait with taking a screenshot while + * this class is present. + * + * See https://web-platform-tests.org/writing-tests/reftests.html#controlling-when-comparison-occurs + */ +function takeScreenshot() { + document.documentElement.classList.remove("reftest-wait"); +} + +/** + * Call `takeScreenshot()` after a delay of at least |timeout| milliseconds. + * @param {number} timeout - milliseconds + */ +function takeScreenshotDelayed(timeout) { + setTimeout(function() { + takeScreenshot(); + }, timeout); +} + +/** + * Ensure that a precondition is met before waiting for a screenshot. + * @param {bool} condition - Fail the test if this evaluates to false + * @param {string} msg - Error message to write to the screenshot + */ +function failIfNot(condition, msg) { + const fail = () => { + (document.body || document.documentElement).textContent = `Precondition Failed: ${msg}`; + takeScreenshot(); + }; + if (!condition) { + if (document.readyState == "interactive") { + fail(); + } else { + document.addEventListener("DOMContentLoaded", fail, false); + } + } +} diff --git a/test/wpt/tests/common/reftest-wait.js.headers b/test/wpt/tests/common/reftest-wait.js.headers new file mode 100644 index 0000000..6805c32 --- /dev/null +++ b/test/wpt/tests/common/reftest-wait.js.headers @@ -0,0 +1 @@ +Content-Type: text/javascript; charset=utf-8 diff --git a/test/wpt/tests/common/rendering-utils.js b/test/wpt/tests/common/rendering-utils.js new file mode 100644 index 0000000..46283bd --- /dev/null +++ b/test/wpt/tests/common/rendering-utils.js @@ -0,0 +1,19 @@ +"use strict"; + +/** + * Waits until we have at least one frame rendered, regardless of the engine. + * + * @returns {Promise} + */ +function waitForAtLeastOneFrame() { + return new Promise(resolve => { + // Different web engines work slightly different on this area but waiting + // for two requestAnimationFrames() to happen, one after another, should be + // sufficient to ensure at least one frame has been generated anywhere. + window.requestAnimationFrame(() => { + window.requestAnimationFrame(() => { + resolve(); + }); + }); + }); +} diff --git a/test/wpt/tests/common/sab.js b/test/wpt/tests/common/sab.js new file mode 100644 index 0000000..a3ea610 --- /dev/null +++ b/test/wpt/tests/common/sab.js @@ -0,0 +1,21 @@ +const createBuffer = (() => { + // See https://github.com/whatwg/html/issues/5380 for why not `new SharedArrayBuffer()` + let sabConstructor; + try { + sabConstructor = new WebAssembly.Memory({ shared:true, initial:0, maximum:0 }).buffer.constructor; + } catch(e) { + sabConstructor = null; + } + return (type, length, opts) => { + if (type === "ArrayBuffer") { + return new ArrayBuffer(length, opts); + } else if (type === "SharedArrayBuffer") { + if (sabConstructor && sabConstructor.name !== "SharedArrayBuffer") { + throw new Error("WebAssembly.Memory does not support shared:true"); + } + return new sabConstructor(length, opts); + } else { + throw new Error("type has to be ArrayBuffer or SharedArrayBuffer"); + } + } +})(); diff --git a/test/wpt/tests/common/security-features/README.md b/test/wpt/tests/common/security-features/README.md new file mode 100644 index 0000000..f957541 --- /dev/null +++ b/test/wpt/tests/common/security-features/README.md @@ -0,0 +1,460 @@ +This directory contains the common infrastructure for the following tests (also referred below as projects). + +- referrer-policy/ +- mixed-content/ +- upgrade-insecure-requests/ + +Subdirectories: + +- `resources`: + Serves JavaScript test helpers. +- `subresource`: + Serves subresources, with support for redirects, stash, etc. + The subresource paths are managed by `subresourceMap` and + fetched in `requestVia*()` functions in `resources/common.js`. +- `scope`: + Serves nested contexts, such as iframe documents or workers. + Used from `invokeFrom*()` functions in `resources/common.js`. +- `tools`: + Scripts that generate test HTML files. Not used while running tests. +- `/referrer-policy/generic/subresource-test`: + Sanity checking tests for subresource invocation + (This is still placed outside common/) + +# Test generator + +The test generator ([common/security-features/tools/generate.py](tools/generate.py)) generates test HTML files from templates and a seed (`spec.src.json`) that defines all the test scenarios. + +The project (i.e. a WPT subdirectory, for example `referrer-policy/`) that uses the generator should define per-project data and invoke the common generator logic in `common/security-features/tools`. + +This is the overview of the project structure: + +``` +common/security-features/ +└── tools/ - the common test generator logic + ├── spec.src.json + └── template/ - the test files templates +project-directory/ (e.g. referrer-policy/) +├── spec.src.json +├── generic/ +│ ├── test-case.sub.js - Per-project test helper +│ ├── sanity-checker.js (Used by debug target only) +│ └── spec_json.js (Used by debug target only) +└── gen/ - generated tests +``` + +## Generating the tests + +Note: When the repository already contains generated tests, [remove all generated tests](#removing-all-generated-tests) first. + +```bash +# Install json5 module if needed. +pip install --user json5 + +# Generate the test files under gen/ (HTMLs and .headers files). +path/to/common/security-features/tools/generate.py --spec path/to/project-directory/ + +# Add all generated tests to the repo. +git add path/to/project-directory/gen/ && git commit -m "Add generated tests" +``` + +This will parse the spec JSON5 files and determine which tests to generate (or skip) while using templates. + +- The default spec JSON5: `common/security-features/tools/spec.src.json`. + - Describes common configurations, such as subresource types, source context types, etc. +- The per-project spec JSON5: `project-directory/spec.src.json`. + - Describes project-specific configurations, particularly those related to test generation patterns (`specification`), policy deliveries (e.g. `delivery_type`, `delivery_value`) and `expectation`. + +For how these two spec JSON5 files are merged, see [Sub projects](#sub-projects) section. + +Note: `spec.src.json` is transitioning to JSON5 [#21710](https://github.com/web-platform-tests/wpt/issues/21710). + +During the generation, the spec is validated by ```common/security-features/tools/spec_validator.py```. This is specially important when you're making changes to `spec.src.json`. Make sure it's a valid JSON (no comments or trailing commas). The validator reports specific errors (missing keys etc.), if any. + +### Removing all generated tests + +Simply remove all files under `project-directory/gen/`. + +```bash +rm -r path/to/project-directory/gen/ +``` + +### Options for generating tests + +Note: this section is currently obsolete. Only the release template is working. + +The generator script has two targets: ```release``` and ```debug```. + +* Using **release** for the target will produce tests using a template for optimizing size and performance. The release template is intended for the official web-platform-tests and possibly other test suites. No sanity checking is done in release mode. Use this option whenever you're checking into web-platform-tests. + +* When generating for ```debug```, the produced tests will contain more verbosity and sanity checks. Use this target to identify problems with the test suites when making changes locally. Make sure you don't check in tests generated with the debug target. + +Note that **release** is the default target when invoking ```generate.py```. + + +## Sub projects + +Projects can be nested, for example to reuse a single `spec.src.json` across similar but slightly different sets of generated tests. +The directory structure would look like: + +``` +project-directory/ (e.g. referrer-policy/) +├── spec.src.json - Parent project's spec JSON +├── generic/ +│ └── test-case.sub.js - Parent project's test helper +├── gen/ - parent project's generated tests +└── sub-project-directory/ (e.g. 4K) + ├── spec.src.json - Child project's spec JSON + ├── generic/ + │ └── test-case.sub.js - Child project's test helper + └── gen/ - child project's generated tests +``` + +`generate.py --spec project-directory/sub-project-directory` generates test files under `project-directory/sub-project-directory/gen`, based on `project-directory/spec.src.json` and `project-directory/sub-project-directory/spec.src.json`. + +- The child project's `spec.src.json` is merged into parent project's `spec.src.json`. + - Two spec JSON objects are merged recursively. + - If a same key exists in both objects, the child's value overwrites the parent's value. + - If both (child's and parent's) values are arrays, then the child's value is concatenated to the parent's value. + - For debugging, `generate.py` dumps the merged spec JSON object as `generic/debug-output.spec.src.json`. +- The child project's generated tests include both of the parent and child project's `test-case.sub.js`: + ```html + + + + ``` + + +## Updating the tests + +The main test logic lives in ```project-directory/generic/test-case.sub.js``` with helper functions defined in ```/common/security-features/resources/common.js``` so you should probably start there. + +For updating the test suites you will most likely do **a subset** of the following: + +* Add a new subresource type: + + * Add a new sub-resource python script to `/common/security-features/subresource/`. + * Add a sanity check test for a sub-resource to `referrer-policy/generic/subresource-test/`. + * Add a new entry to `subresourceMap` in `/common/security-features/resources/common.js`. + * Add a new entry to `valid_subresource_names` in `/common/security-features/tools/spec_validator.py`. + * Add a new entry to `subresource_schema` in `spec.src.json`. + * Update `source_context_schema` to specify in which source context the subresource can be used. + +* Add a new subresource redirection type + + * TODO: to be documented. Example: [https://github.com/web-platform-tests/wpt/pull/18939](https://github.com/web-platform-tests/wpt/pull/18939) + +* Add a new subresource origin type + + * TODO: to be documented. Example: [https://github.com/web-platform-tests/wpt/pull/18940](https://github.com/web-platform-tests/wpt/pull/18940) + +* Add a new source context (e.g. "module sharedworker global scope") + + * TODO: to be documented. Example: [https://github.com/web-platform-tests/wpt/pull/18904](https://github.com/web-platform-tests/wpt/pull/18904) + +* Add a new source context list (e.g. "subresource request from a dedicated worker in a ` + invoker: invokeFromIframe, + }, + "iframe": { // + invoker: invokeFromIframe, + }, + "iframe-blank": { // + invoker: invokeFromIframe, + }, + "worker-classic": { + // Classic dedicated worker loaded from same-origin. + invoker: invokeFromWorker.bind(undefined, "worker", false, {}), + }, + "worker-classic-data": { + // Classic dedicated worker loaded from data: URL. + invoker: invokeFromWorker.bind(undefined, "worker", true, {}), + }, + "worker-module": { + // Module dedicated worker loaded from same-origin. + invoker: invokeFromWorker.bind(undefined, "worker", false, {type: 'module'}), + }, + "worker-module-data": { + // Module dedicated worker loaded from data: URL. + invoker: invokeFromWorker.bind(undefined, "worker", true, {type: 'module'}), + }, + "sharedworker-classic": { + // Classic shared worker loaded from same-origin. + invoker: invokeFromWorker.bind(undefined, "sharedworker", false, {}), + }, + "sharedworker-classic-data": { + // Classic shared worker loaded from data: URL. + invoker: invokeFromWorker.bind(undefined, "sharedworker", true, {}), + }, + "sharedworker-module": { + // Module shared worker loaded from same-origin. + invoker: invokeFromWorker.bind(undefined, "sharedworker", false, {type: 'module'}), + }, + "sharedworker-module-data": { + // Module shared worker loaded from data: URL. + invoker: invokeFromWorker.bind(undefined, "sharedworker", true, {type: 'module'}), + }, + }; + + return sourceContextMap[sourceContextList[0].sourceContextType].invoker( + subresource, sourceContextList); +} + +// Quick hack to expose invokeRequest when common.sub.js is loaded either +// as a classic or module script. +self.invokeRequest = invokeRequest; + +/** + invokeFrom*() functions are helper functions with the same parameters + and return values as invokeRequest(), that are tied to specific types + of top-most environment settings objects. + For example, invokeFromIframe() is the helper function for the cases where + sourceContextList[0] is an iframe. +*/ + +/** + @param {string} workerType + "worker" (for dedicated worker) or "sharedworker". + @param {boolean} isDataUrl + true if the worker script is loaded from data: URL. + Otherwise, the script is loaded from same-origin. + @param {object} workerOptions + The `options` argument for Worker constructor. + + Other parameters and return values are the same as those of invokeRequest(). +*/ +function invokeFromWorker(workerType, isDataUrl, workerOptions, + subresource, sourceContextList) { + const currentSourceContext = sourceContextList[0]; + let workerUrl = + "/common/security-features/scope/worker.py?policyDeliveries=" + + encodeURIComponent(JSON.stringify( + currentSourceContext.policyDeliveries || [])); + if (workerOptions.type === 'module') { + workerUrl += "&type=module"; + } + + let promise; + if (isDataUrl) { + promise = fetch(workerUrl) + .then(r => r.text()) + .then(source => { + return 'data:text/javascript;base64,' + btoa(source); + }); + } else { + promise = Promise.resolve(workerUrl); + } + + return promise + .then(url => { + if (workerType === "worker") { + const worker = new Worker(url, workerOptions); + worker.postMessage({subresource: subresource, + sourceContextList: sourceContextList.slice(1)}); + return bindEvents2(worker, "message", worker, "error", window, "error"); + } else if (workerType === "sharedworker") { + const worker = new SharedWorker(url, workerOptions); + worker.port.start(); + worker.port.postMessage({subresource: subresource, + sourceContextList: sourceContextList.slice(1)}); + return bindEvents2(worker.port, "message", worker, "error", window, "error"); + } else { + throw new Error('Invalid worker type: ' + workerType); + } + }) + .then(event => { + if (event.data.error) + return Promise.reject(event.data.error); + return event.data; + }); +} + +function invokeFromIframe(subresource, sourceContextList) { + const currentSourceContext = sourceContextList[0]; + const frameUrl = + "/common/security-features/scope/document.py?policyDeliveries=" + + encodeURIComponent(JSON.stringify( + currentSourceContext.policyDeliveries || [])); + + let iframe; + let promise; + if (currentSourceContext.sourceContextType === 'srcdoc') { + promise = fetch(frameUrl) + .then(r => r.text()) + .then(srcdoc => { + iframe = createElement( + "iframe", {srcdoc: srcdoc}, document.body, true); + return iframe.eventPromise; + }); + } else if (currentSourceContext.sourceContextType === 'iframe') { + iframe = createElement("iframe", {src: frameUrl}, document.body, true); + promise = iframe.eventPromise; + } else if (currentSourceContext.sourceContextType === 'iframe-blank') { + let frameContent; + promise = fetch(frameUrl) + .then(r => r.text()) + .then(t => { + frameContent = t; + iframe = createElement("iframe", {}, document.body, true); + return iframe.eventPromise; + }) + .then(() => { + // Reinitialize `iframe.eventPromise` with a new promise + // that catches the load event for the document.write() below. + bindEvents(iframe); + + iframe.contentDocument.write(frameContent); + iframe.contentDocument.close(); + return iframe.eventPromise; + }); + } + + return promise + .then(() => { + const promise = bindEvents2( + window, "message", iframe, "error", window, "error"); + iframe.contentWindow.postMessage( + {subresource: subresource, + sourceContextList: sourceContextList.slice(1)}, + "*"); + return promise; + }) + .then(event => { + if (event.data.error) + return Promise.reject(event.data.error); + return event.data; + }); +} + +// SanityChecker does nothing in release mode. See sanity-checker.js for debug +// mode. +function SanityChecker() {} +SanityChecker.prototype.checkScenario = function() {}; +SanityChecker.prototype.setFailTimeout = function(test, timeout) {}; +SanityChecker.prototype.checkSubresourceResult = function() {}; diff --git a/test/wpt/tests/common/security-features/resources/common.sub.js.headers b/test/wpt/tests/common/security-features/resources/common.sub.js.headers new file mode 100644 index 0000000..cb762ef --- /dev/null +++ b/test/wpt/tests/common/security-features/resources/common.sub.js.headers @@ -0,0 +1 @@ +Access-Control-Allow-Origin: * diff --git a/test/wpt/tests/common/security-features/scope/__init__.py b/test/wpt/tests/common/security-features/scope/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/common/security-features/scope/document.py b/test/wpt/tests/common/security-features/scope/document.py new file mode 100644 index 0000000..9a9f045 --- /dev/null +++ b/test/wpt/tests/common/security-features/scope/document.py @@ -0,0 +1,36 @@ +import os, sys, json + +from wptserve.utils import isomorphic_decode, isomorphic_encode + +import importlib +util = importlib.import_module("common.security-features.scope.util") + +def main(request, response): + policyDeliveries = json.loads(request.GET.first(b"policyDeliveries", b"[]")) + maybe_additional_headers = {} + meta = u'' + error = u'' + for delivery in policyDeliveries: + if delivery[u'deliveryType'] == u'meta': + if delivery[u'key'] == u'referrerPolicy': + meta += u'' % delivery[u'value'] + else: + error = u'invalid delivery key' + elif delivery[u'deliveryType'] == u'http-rp': + if delivery[u'key'] == u'referrerPolicy': + maybe_additional_headers[b'Referrer-Policy'] = isomorphic_encode(delivery[u'value']) + else: + error = u'invalid delivery key' + else: + error = u'invalid deliveryType' + + handler = lambda: util.get_template(u"document.html.template") % ({ + u"meta": meta, + u"error": error + }) + util.respond( + request, + response, + payload_generator=handler, + content_type=b"text/html", + maybe_additional_headers=maybe_additional_headers) diff --git a/test/wpt/tests/common/security-features/scope/template/document.html.template b/test/wpt/tests/common/security-features/scope/template/document.html.template new file mode 100644 index 0000000..37e29f8 --- /dev/null +++ b/test/wpt/tests/common/security-features/scope/template/document.html.template @@ -0,0 +1,30 @@ + + + + %(meta)s + + + + diff --git a/test/wpt/tests/common/security-features/scope/template/worker.js.template b/test/wpt/tests/common/security-features/scope/template/worker.js.template new file mode 100644 index 0000000..7a2a6e0 --- /dev/null +++ b/test/wpt/tests/common/security-features/scope/template/worker.js.template @@ -0,0 +1,29 @@ +%(import)s + +if ('DedicatedWorkerGlobalScope' in self && + self instanceof DedicatedWorkerGlobalScope) { + self.onmessage = event => onMessageFromParent(event, self); +} else if ('SharedWorkerGlobalScope' in self && + self instanceof SharedWorkerGlobalScope) { + onconnect = event => { + const port = event.ports[0]; + port.onmessage = event => onMessageFromParent(event, port); + }; +} + +// Receive a message from the parent and start the test. +function onMessageFromParent(event, port) { + const configurationError = "%(error)s"; + if (configurationError.length > 0) { + port.postMessage({error: configurationError}); + return; + } + + invokeRequest(event.data.subresource, + event.data.sourceContextList) + .then(result => port.postMessage(result)) + .catch(e => { + const message = (e.error && e.error.stack) || e.message || "Error"; + port.postMessage({error: message}); + }); +} diff --git a/test/wpt/tests/common/security-features/scope/util.py b/test/wpt/tests/common/security-features/scope/util.py new file mode 100644 index 0000000..da5aacf --- /dev/null +++ b/test/wpt/tests/common/security-features/scope/util.py @@ -0,0 +1,43 @@ +import os + +from wptserve.utils import isomorphic_decode + +def get_template(template_basename): + script_directory = os.path.dirname(os.path.abspath(isomorphic_decode(__file__))) + template_directory = os.path.abspath( + os.path.join(script_directory, u"template")) + template_filename = os.path.join(template_directory, template_basename) + + with open(template_filename, "r") as f: + return f.read() + + +def __noop(request, response): + return u"" + + +def respond(request, + response, + status_code=200, + content_type=b"text/html", + payload_generator=__noop, + cache_control=b"no-cache; must-revalidate", + access_control_allow_origin=b"*", + maybe_additional_headers=None): + response.add_required_headers = False + response.writer.write_status(status_code) + + if access_control_allow_origin != None: + response.writer.write_header(b"access-control-allow-origin", + access_control_allow_origin) + response.writer.write_header(b"content-type", content_type) + response.writer.write_header(b"cache-control", cache_control) + + additional_headers = maybe_additional_headers or {} + for header, value in additional_headers.items(): + response.writer.write_header(header, value) + + response.writer.end_headers() + + payload = payload_generator() + response.writer.write(payload) diff --git a/test/wpt/tests/common/security-features/scope/worker.py b/test/wpt/tests/common/security-features/scope/worker.py new file mode 100644 index 0000000..6b321e7 --- /dev/null +++ b/test/wpt/tests/common/security-features/scope/worker.py @@ -0,0 +1,44 @@ +import os, sys, json + +from wptserve.utils import isomorphic_decode, isomorphic_encode +import importlib +util = importlib.import_module("common.security-features.scope.util") + +def main(request, response): + policyDeliveries = json.loads(request.GET.first(b'policyDeliveries', b'[]')) + worker_type = request.GET.first(b'type', b'classic') + commonjs_url = u'%s://%s:%s/common/security-features/resources/common.sub.js' % ( + request.url_parts.scheme, request.url_parts.hostname, + request.url_parts.port) + if worker_type == b'classic': + import_line = u'importScripts("%s");' % commonjs_url + else: + import_line = u'import "%s";' % commonjs_url + + maybe_additional_headers = {} + error = u'' + for delivery in policyDeliveries: + if delivery[u'deliveryType'] == u'meta': + error = u' cannot be used in WorkerGlobalScope' + elif delivery[u'deliveryType'] == u'http-rp': + if delivery[u'key'] == u'referrerPolicy': + maybe_additional_headers[b'Referrer-Policy'] = isomorphic_encode(delivery[u'value']) + elif delivery[u'key'] == u'mixedContent' and delivery[u'value'] == u'opt-in': + maybe_additional_headers[b'Content-Security-Policy'] = b'block-all-mixed-content' + elif delivery[u'key'] == u'upgradeInsecureRequests' and delivery[u'value'] == u'upgrade': + maybe_additional_headers[b'Content-Security-Policy'] = b'upgrade-insecure-requests' + else: + error = u'invalid delivery key for http-rp: %s' % delivery[u'key'] + else: + error = u'invalid deliveryType: %s' % delivery[u'deliveryType'] + + handler = lambda: util.get_template(u'worker.js.template') % ({ + u'import': import_line, + u'error': error + }) + util.respond( + request, + response, + payload_generator=handler, + content_type=b'text/javascript', + maybe_additional_headers=maybe_additional_headers) diff --git a/test/wpt/tests/common/security-features/subresource/__init__.py b/test/wpt/tests/common/security-features/subresource/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/common/security-features/subresource/audio.py b/test/wpt/tests/common/security-features/subresource/audio.py new file mode 100644 index 0000000..f16a0f7 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/audio.py @@ -0,0 +1,18 @@ +import os, sys +from wptserve.utils import isomorphic_decode +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + +def generate_payload(request, server_data): + file = os.path.join(request.doc_root, u"webaudio", u"resources", + u"sin_440Hz_-6dBFS_1s.wav") + return open(file, "rb").read() + + +def main(request, response): + handler = lambda data: generate_payload(request, data) + subresource.respond(request, + response, + payload_generator = handler, + access_control_allow_origin = b"*", + content_type = b"audio/wav") diff --git a/test/wpt/tests/common/security-features/subresource/document.py b/test/wpt/tests/common/security-features/subresource/document.py new file mode 100644 index 0000000..52b684a --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/document.py @@ -0,0 +1,12 @@ +import os, sys +from wptserve.utils import isomorphic_decode +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + +def generate_payload(server_data): + return subresource.get_template(u"document.html.template") % server_data + +def main(request, response): + subresource.respond(request, + response, + payload_generator = generate_payload) diff --git a/test/wpt/tests/common/security-features/subresource/empty.py b/test/wpt/tests/common/security-features/subresource/empty.py new file mode 100644 index 0000000..312e12c --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/empty.py @@ -0,0 +1,14 @@ +import os, sys +from wptserve.utils import isomorphic_decode +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + +def generate_payload(server_data): + return u'' + +def main(request, response): + subresource.respond(request, + response, + payload_generator = generate_payload, + access_control_allow_origin = b"*", + content_type = b"text/plain") diff --git a/test/wpt/tests/common/security-features/subresource/font.py b/test/wpt/tests/common/security-features/subresource/font.py new file mode 100644 index 0000000..7900079 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/font.py @@ -0,0 +1,76 @@ +import os, sys +from base64 import decodebytes + +from wptserve.utils import isomorphic_decode +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + + +def generate_payload(request, server_data): + data = (u'{"headers": %(headers)s}') % server_data + if b"id" in request.GET: + request.server.stash.put(request.GET[b"id"], data) + # Simple base64 encoded .tff font + return decodebytes(b"AAEAAAANAIAAAwBQRkZUTU6u6MkAAAXcAAAAHE9TLzJWYW" + b"QKAAABWAAAAFZjbWFwAA8D7wAAAcAAAAFCY3Z0IAAhAnkA" + b"AAMEAAAABGdhc3D//wADAAAF1AAAAAhnbHlmCC6aTwAAAx" + b"QAAACMaGVhZO8ooBcAAADcAAAANmhoZWEIkAV9AAABFAAA" + b"ACRobXR4EZQAhQAAAbAAAAAQbG9jYQBwAFQAAAMIAAAACm" + b"1heHAASQA9AAABOAAAACBuYW1lehAVOgAAA6AAAAIHcG9z" + b"dP+uADUAAAWoAAAAKgABAAAAAQAAMhPyuV8PPPUACwPoAA" + b"AAAMU4Lm0AAAAAxTgubQAh/5wFeAK8AAAACAACAAAAAAAA" + b"AAEAAAK8/5wAWgXcAAAAAAV4AAEAAAAAAAAAAAAAAAAAAA" + b"AEAAEAAAAEAAwAAwAAAAAAAgAAAAEAAQAAAEAALgAAAAAA" + b"AQXcAfQABQAAAooCvAAAAIwCigK8AAAB4AAxAQIAAAIABg" + b"kAAAAAAAAAAAABAAAAAAAAAAAAAAAAUGZFZABAAEEAQQMg" + b"/zgAWgK8AGQAAAABAAAAAAAABdwAIQAAAAAF3AAABdwAZA" + b"AAAAMAAAADAAAAHAABAAAAAAA8AAMAAQAAABwABAAgAAAA" + b"BAAEAAEAAABB//8AAABB////wgABAAAAAAAAAQYAAAEAAA" + b"AAAAAAAQIAAAACAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAA" + b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAA" + b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + b"AAAAAAAAAAAAAAAAAAAhAnkAAAAqACoAKgBGAAAAAgAhAA" + b"ABKgKaAAMABwAusQEALzyyBwQA7TKxBgXcPLIDAgDtMgCx" + b"AwAvPLIFBADtMrIHBgH8PLIBAgDtMjMRIREnMxEjIQEJ6M" + b"fHApr9ZiECWAAAAwBk/5wFeAK8AAMABwALAAABNSEVATUh" + b"FQE1IRUB9AH0/UQDhPu0BRQB9MjI/tTIyP7UyMgAAAAAAA" + b"4ArgABAAAAAAAAACYATgABAAAAAAABAAUAgQABAAAAAAAC" + b"AAYAlQABAAAAAAADACEA4AABAAAAAAAEAAUBDgABAAAAAA" + b"AFABABNgABAAAAAAAGAAUBUwADAAEECQAAAEwAAAADAAEE" + b"CQABAAoAdQADAAEECQACAAwAhwADAAEECQADAEIAnAADAA" + b"EECQAEAAoBAgADAAEECQAFACABFAADAAEECQAGAAoBRwBD" + b"AG8AcAB5AHIAaQBnAGgAdAAgACgAYwApACAAMgAwADAAOA" + b"AgAE0AbwB6AGkAbABsAGEAIABDAG8AcgBwAG8AcgBhAHQA" + b"aQBvAG4AAENvcHlyaWdodCAoYykgMjAwOCBNb3ppbGxhIE" + b"NvcnBvcmF0aW9uAABNAGEAcgBrAEEAAE1hcmtBAABNAGUA" + b"ZABpAHUAbQAATWVkaXVtAABGAG8AbgB0AEYAbwByAGcAZQ" + b"AgADIALgAwACAAOgAgAE0AYQByAGsAQQAgADoAIAA1AC0A" + b"MQAxAC0AMgAwADAAOAAARm9udEZvcmdlIDIuMCA6IE1hcm" + b"tBIDogNS0xMS0yMDA4AABNAGEAcgBrAEEAAE1hcmtBAABW" + b"AGUAcgBzAGkAbwBuACAAMAAwADEALgAwADAAMAAgAABWZX" + b"JzaW9uIDAwMS4wMDAgAABNAGEAcgBrAEEAAE1hcmtBAAAA" + b"AgAAAAAAAP+DADIAAAABAAAAAAAAAAAAAAAAAAAAAAAEAA" + b"AAAQACACQAAAAAAAH//wACAAAAAQAAAADEPovuAAAAAMU4" + b"Lm0AAAAAxTgubQ==") + +def generate_report_headers_payload(request, server_data): + stashed_data = request.server.stash.take(request.GET[b"id"]) + return stashed_data + +def main(request, response): + handler = lambda data: generate_payload(request, data) + content_type = b'application/x-font-truetype' + + if b"report-headers" in request.GET: + handler = lambda data: generate_report_headers_payload(request, data) + content_type = b'application/json' + + subresource.respond(request, + response, + payload_generator = handler, + content_type = content_type, + access_control_allow_origin = b"*") diff --git a/test/wpt/tests/common/security-features/subresource/image.py b/test/wpt/tests/common/security-features/subresource/image.py new file mode 100644 index 0000000..5c9a0c0 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/image.py @@ -0,0 +1,116 @@ +import os, sys, array, math + +from io import BytesIO + +from wptserve.utils import isomorphic_decode + +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + +class Image: + """This class partially implements the interface of the PIL.Image.Image. + One day in the future WPT might support the PIL module or another imaging + library, so this hacky BMP implementation will no longer be required. + """ + def __init__(self, width, height): + self.width = width + self.height = height + self.img = bytearray([0 for i in range(3 * width * height)]) + + @staticmethod + def new(mode, size, color=0): + return Image(size[0], size[1]) + + def _int_to_bytes(self, number): + packed_bytes = [0, 0, 0, 0] + for i in range(4): + packed_bytes[i] = number & 0xFF + number >>= 8 + + return packed_bytes + + def putdata(self, color_data): + for y in range(self.height): + for x in range(self.width): + i = x + y * self.width + if i > len(color_data) - 1: + return + + self.img[i * 3: i * 3 + 3] = color_data[i][::-1] + + def save(self, f, type): + assert type == "BMP" + # 54 bytes of preambule + image color data. + filesize = 54 + 3 * self.width * self.height + # 14 bytes of header. + bmpfileheader = bytearray([ord('B'), ord('M')] + self._int_to_bytes(filesize) + + [0, 0, 0, 0, 54, 0, 0, 0]) + # 40 bytes of info. + bmpinfoheader = bytearray([40, 0, 0, 0] + + self._int_to_bytes(self.width) + + self._int_to_bytes(self.height) + + [1, 0, 24] + (25 * [0])) + + padlength = (4 - (self.width * 3) % 4) % 4 + bmppad = bytearray([0, 0, 0]) + padding = bmppad[0 : padlength] + + f.write(bmpfileheader) + f.write(bmpinfoheader) + + for i in range(self.height): + offset = self.width * (self.height - i - 1) * 3 + f.write(self.img[offset : offset + 3 * self.width]) + f.write(padding) + +def encode_string_as_bmp_image(string_data): + data_bytes = array.array("B", string_data.encode("utf-8")) + + num_bytes = len(data_bytes) + + # Encode data bytes to color data (RGB), one bit per channel. + # This is to avoid errors due to different color spaces used in decoding. + color_data = [] + for byte in data_bytes: + p = [int(x) * 255 for x in '{0:08b}'.format(byte)] + color_data.append((p[0], p[1], p[2])) + color_data.append((p[3], p[4], p[5])) + color_data.append((p[6], p[7], 0)) + + # Render image. + num_pixels = len(color_data) + sqrt = int(math.ceil(math.sqrt(num_pixels))) + img = Image.new("RGB", (sqrt, sqrt), "black") + img.putdata(color_data) + + # Flush image to string. + f = BytesIO() + img.save(f, "BMP") + f.seek(0) + + return f.read() + +def generate_payload(request, server_data): + data = (u'{"headers": %(headers)s}') % server_data + if b"id" in request.GET: + request.server.stash.put(request.GET[b"id"], data) + data = encode_string_as_bmp_image(data) + return data + +def generate_report_headers_payload(request, server_data): + stashed_data = request.server.stash.take(request.GET[b"id"]) + return stashed_data + +def main(request, response): + handler = lambda data: generate_payload(request, data) + content_type = b'image/bmp' + + if b"report-headers" in request.GET: + handler = lambda data: generate_report_headers_payload(request, data) + content_type = b'application/json' + + subresource.respond(request, + response, + payload_generator = handler, + content_type = content_type, + access_control_allow_origin = b"*") diff --git a/test/wpt/tests/common/security-features/subresource/referrer.py b/test/wpt/tests/common/security-features/subresource/referrer.py new file mode 100644 index 0000000..e366314 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/referrer.py @@ -0,0 +1,4 @@ +def main(request, response): + referrer = request.headers.get(b"referer", b"") + response_headers = [(b"Content-Type", b"text/javascript")] + return (200, response_headers, b"window.referrer = '" + referrer + b"'") diff --git a/test/wpt/tests/common/security-features/subresource/script.py b/test/wpt/tests/common/security-features/subresource/script.py new file mode 100644 index 0000000..9701816 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/script.py @@ -0,0 +1,14 @@ +import os, sys +from wptserve.utils import isomorphic_decode + +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + +def generate_payload(server_data): + return subresource.get_template(u"script.js.template") % server_data + +def main(request, response): + subresource.respond(request, + response, + payload_generator = generate_payload, + content_type = b"application/javascript") diff --git a/test/wpt/tests/common/security-features/subresource/shared-worker.py b/test/wpt/tests/common/security-features/subresource/shared-worker.py new file mode 100644 index 0000000..bdfb61b --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/shared-worker.py @@ -0,0 +1,13 @@ +import os, sys +from wptserve.utils import isomorphic_decode +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + +def generate_payload(server_data): + return subresource.get_template(u"shared-worker.js.template") % server_data + +def main(request, response): + subresource.respond(request, + response, + payload_generator = generate_payload, + content_type = b"application/javascript") diff --git a/test/wpt/tests/common/security-features/subresource/static-import.py b/test/wpt/tests/common/security-features/subresource/static-import.py new file mode 100644 index 0000000..3c3a6f6 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/static-import.py @@ -0,0 +1,61 @@ +import os, sys, json +from urllib.parse import unquote + +from wptserve.utils import isomorphic_decode +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + +def get_csp_value(value): + ''' + Returns actual CSP header values (e.g. "worker-src 'self'") for the + given string used in PolicyDelivery's value (e.g. "worker-src-self"). + ''' + + # script-src + # Test-related scripts like testharness.js and inline scripts containing + # test bodies. + # 'unsafe-inline' is added as a workaround here. This is probably not so + # bad, as it shouldn't intefere non-inline-script requests that we want to + # test. + if value == 'script-src-wildcard': + return "script-src * 'unsafe-inline'" + if value == 'script-src-self': + return "script-src 'self' 'unsafe-inline'" + # Workaround for "script-src 'none'" would be more complicated, because + # - "script-src 'none' 'unsafe-inline'" is handled somehow differently from + # "script-src 'none'", i.e. + # https://w3c.github.io/webappsec-csp/#match-url-to-source-list Step 3 + # handles the latter but not the former. + # - We need nonce- or path-based additional values to allow same-origin + # test scripts like testharness.js. + # Therefore, we disable 'script-src-none' tests for now in + # `/content-security-policy/spec.src.json`. + if value == 'script-src-none': + return "script-src 'none'" + + # worker-src + if value == 'worker-src-wildcard': + return 'worker-src *' + if value == 'worker-src-self': + return "worker-src 'self'" + if value == 'worker-src-none': + return "worker-src 'none'" + raise Exception('Invalid delivery_value: %s' % value) + +def generate_payload(request): + import_url = unquote(isomorphic_decode(request.GET[b'import_url'])) + return subresource.get_template(u"static-import.js.template") % { + u"import_url": import_url + } + +def main(request, response): + def payload_generator(_): return generate_payload(request) + maybe_additional_headers = {} + if b'contentSecurityPolicy' in request.GET: + csp = unquote(isomorphic_decode(request.GET[b'contentSecurityPolicy'])) + maybe_additional_headers[b'Content-Security-Policy'] = get_csp_value(csp) + subresource.respond(request, + response, + payload_generator = payload_generator, + content_type = b"application/javascript", + maybe_additional_headers = maybe_additional_headers) diff --git a/test/wpt/tests/common/security-features/subresource/stylesheet.py b/test/wpt/tests/common/security-features/subresource/stylesheet.py new file mode 100644 index 0000000..05db249 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/stylesheet.py @@ -0,0 +1,61 @@ +import os, sys +from wptserve.utils import isomorphic_decode +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + +def generate_payload(request, server_data): + data = (u'{"headers": %(headers)s}') % server_data + type = b'image' + if b"type" in request.GET: + type = request.GET[b"type"] + + if b"id" in request.GET: + request.server.stash.put(request.GET[b"id"], data) + + if type == b'image': + return subresource.get_template(u"image.css.template") % {u"id": isomorphic_decode(request.GET[b"id"])} + + elif type == b'font': + return subresource.get_template(u"font.css.template") % {u"id": isomorphic_decode(request.GET[b"id"])} + + elif type == b'svg': + return subresource.get_template(u"svg.css.template") % { + u"id": isomorphic_decode(request.GET[b"id"]), + u"property": isomorphic_decode(request.GET[b"property"])} + + # A `'stylesheet-only'`-type stylesheet has no nested resources; this is + # useful in tests that cover referrers for stylesheet fetches (e.g. fetches + # triggered by `@import` statements). + elif type == b'stylesheet-only': + return u'' + +def generate_import_rule(request, server_data): + return u"@import url('%(url)s');" % { + u"url": subresource.create_url(request, swap_origin=True, + query_parameter_to_remove=u"import-rule") + } + +def generate_report_headers_payload(request, server_data): + stashed_data = request.server.stash.take(request.GET[b"id"]) + return stashed_data + +def main(request, response): + payload_generator = lambda data: generate_payload(request, data) + content_type = b"text/css" + referrer_policy = b"unsafe-url" + if b"import-rule" in request.GET: + payload_generator = lambda data: generate_import_rule(request, data) + + if b"report-headers" in request.GET: + payload_generator = lambda data: generate_report_headers_payload(request, data) + content_type = b'application/json' + + if b"referrer-policy" in request.GET: + referrer_policy = request.GET[b"referrer-policy"] + + subresource.respond( + request, + response, + payload_generator = payload_generator, + content_type = content_type, + maybe_additional_headers = { b"Referrer-Policy": referrer_policy }) diff --git a/test/wpt/tests/common/security-features/subresource/subresource.py b/test/wpt/tests/common/security-features/subresource/subresource.py new file mode 100644 index 0000000..b3c055a --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/subresource.py @@ -0,0 +1,199 @@ +import os, json +from urllib.parse import parse_qsl, SplitResult, urlencode, urlsplit, urlunsplit + +from wptserve.utils import isomorphic_decode, isomorphic_encode + +def get_template(template_basename): + script_directory = os.path.dirname(os.path.abspath(isomorphic_decode(__file__))) + template_directory = os.path.abspath(os.path.join(script_directory, + u"template")) + template_filename = os.path.join(template_directory, template_basename) + + with open(template_filename, "r") as f: + return f.read() + + +def redirect(url, response): + response.add_required_headers = False + response.writer.write_status(301) + response.writer.write_header(b"access-control-allow-origin", b"*") + response.writer.write_header(b"location", isomorphic_encode(url)) + response.writer.end_headers() + response.writer.write(u"") + + +# TODO(kristijanburnik): subdomain_prefix is a hardcoded value aligned with +# referrer-policy-test-case.js. The prefix should be configured in one place. +def __get_swapped_origin_netloc(netloc, subdomain_prefix = u"www1."): + if netloc.startswith(subdomain_prefix): + return netloc[len(subdomain_prefix):] + else: + return subdomain_prefix + netloc + + +# Creates a URL (typically a redirect target URL) that is the same as the +# current request URL `request.url`, except for: +# - When `swap_scheme` or `swap_origin` is True, its scheme/origin is changed +# to the other one. (http <-> https, ws <-> wss, etc.) +# - For `downgrade`, we redirect to a URL that would be successfully loaded +# if and only if upgrade-insecure-request is applied. +# - `query_parameter_to_remove` parameter is removed from query part. +# Its default is "redirection" to avoid redirect loops. +def create_url(request, + swap_scheme=False, + swap_origin=False, + downgrade=False, + query_parameter_to_remove=u"redirection"): + parsed = urlsplit(request.url) + destination_netloc = parsed.netloc + + scheme = parsed.scheme + if swap_scheme: + scheme = u"http" if parsed.scheme == u"https" else u"https" + hostname = parsed.netloc.split(u':')[0] + port = request.server.config[u"ports"][scheme][0] + destination_netloc = u":".join([hostname, str(port)]) + + if downgrade: + # These rely on some unintuitive cleverness due to WPT's test setup: + # 'Upgrade-Insecure-Requests' does not upgrade the port number, + # so we use URLs in the form `http://[domain]:[https-port]`, + # which will be upgraded to `https://[domain]:[https-port]`. + # If the upgrade fails, the load will fail, as we don't serve HTTP over + # the secure port. + if parsed.scheme == u"https": + scheme = u"http" + elif parsed.scheme == u"wss": + scheme = u"ws" + else: + raise ValueError(u"Downgrade redirection: Invalid scheme '%s'" % + parsed.scheme) + hostname = parsed.netloc.split(u':')[0] + port = request.server.config[u"ports"][parsed.scheme][0] + destination_netloc = u":".join([hostname, str(port)]) + + if swap_origin: + destination_netloc = __get_swapped_origin_netloc(destination_netloc) + + parsed_query = parse_qsl(parsed.query, keep_blank_values=True) + parsed_query = [x for x in parsed_query if x[0] != query_parameter_to_remove] + + destination_url = urlunsplit(SplitResult( + scheme = scheme, + netloc = destination_netloc, + path = parsed.path, + query = urlencode(parsed_query), + fragment = None)) + + return destination_url + + +def preprocess_redirection(request, response): + if b"redirection" not in request.GET: + return False + + redirection = request.GET[b"redirection"] + + if redirection == b"no-redirect": + return False + elif redirection == b"keep-scheme": + redirect_url = create_url(request, swap_scheme=False) + elif redirection == b"swap-scheme": + redirect_url = create_url(request, swap_scheme=True) + elif redirection == b"downgrade": + redirect_url = create_url(request, downgrade=True) + elif redirection == b"keep-origin": + redirect_url = create_url(request, swap_origin=False) + elif redirection == b"swap-origin": + redirect_url = create_url(request, swap_origin=True) + else: + raise ValueError(u"Invalid redirection type '%s'" % isomorphic_decode(redirection)) + + redirect(redirect_url, response) + return True + + +def preprocess_stash_action(request, response): + if b"action" not in request.GET: + return False + + action = request.GET[b"action"] + + key = request.GET[b"key"] + stash = request.server.stash + path = request.GET[b"path"] if b"path" in request.GET \ + else isomorphic_encode(request.url.split(u'?')[0]) + + if action == b"put": + value = isomorphic_decode(request.GET[b"value"]) + stash.take(key=key, path=path) + stash.put(key=key, value=value, path=path) + response_data = json.dumps({u"status": u"success", u"result": isomorphic_decode(key)}) + elif action == b"purge": + value = stash.take(key=key, path=path) + return False + elif action == b"take": + value = stash.take(key=key, path=path) + if value is None: + status = u"allowed" + else: + status = u"blocked" + response_data = json.dumps({u"status": status, u"result": value}) + else: + return False + + response.add_required_headers = False + response.writer.write_status(200) + response.writer.write_header(b"content-type", b"text/javascript") + response.writer.write_header(b"cache-control", b"no-cache; must-revalidate") + response.writer.end_headers() + response.writer.write(response_data) + return True + + +def __noop(request, response): + return u"" + + +def respond(request, + response, + status_code = 200, + content_type = b"text/html", + payload_generator = __noop, + cache_control = b"no-cache; must-revalidate", + access_control_allow_origin = b"*", + maybe_additional_headers = None): + if preprocess_redirection(request, response): + return + + if preprocess_stash_action(request, response): + return + + response.add_required_headers = False + response.writer.write_status(status_code) + + if access_control_allow_origin != None: + response.writer.write_header(b"access-control-allow-origin", + access_control_allow_origin) + response.writer.write_header(b"content-type", content_type) + response.writer.write_header(b"cache-control", cache_control) + + additional_headers = maybe_additional_headers or {} + for header, value in additional_headers.items(): + response.writer.write_header(header, value) + + response.writer.end_headers() + + new_headers = {} + new_val = [] + for key, val in request.headers.items(): + if len(val) == 1: + new_val = isomorphic_decode(val[0]) + else: + new_val = [isomorphic_decode(x) for x in val] + new_headers[isomorphic_decode(key)] = new_val + + server_data = {u"headers": json.dumps(new_headers, indent = 4)} + + payload = payload_generator(server_data) + response.writer.write(payload) diff --git a/test/wpt/tests/common/security-features/subresource/svg.py b/test/wpt/tests/common/security-features/subresource/svg.py new file mode 100644 index 0000000..9c569e3 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/svg.py @@ -0,0 +1,37 @@ +import os, sys +from wptserve.utils import isomorphic_decode +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + +def generate_payload(request, server_data): + data = (u'{"headers": %(headers)s}') % server_data + if b"id" in request.GET: + with request.server.stash.lock: + request.server.stash.take(request.GET[b"id"]) + request.server.stash.put(request.GET[b"id"], data) + return u"" + +def generate_payload_embedded(request, server_data): + return subresource.get_template(u"svg.embedded.template") % { + u"id": isomorphic_decode(request.GET[b"id"]), + u"property": isomorphic_decode(request.GET[b"property"])} + +def generate_report_headers_payload(request, server_data): + stashed_data = request.server.stash.take(request.GET[b"id"]) + return stashed_data + +def main(request, response): + handler = lambda data: generate_payload(request, data) + content_type = b'image/svg+xml' + + if b"embedded-svg" in request.GET: + handler = lambda data: generate_payload_embedded(request, data) + + if b"report-headers" in request.GET: + handler = lambda data: generate_report_headers_payload(request, data) + content_type = b'application/json' + + subresource.respond(request, + response, + payload_generator = handler, + content_type = content_type) diff --git a/test/wpt/tests/common/security-features/subresource/template/document.html.template b/test/wpt/tests/common/security-features/subresource/template/document.html.template new file mode 100644 index 0000000..141711c --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/template/document.html.template @@ -0,0 +1,16 @@ + + + + This page reports back it's request details to the parent frame + + + + + diff --git a/test/wpt/tests/common/security-features/subresource/template/font.css.template b/test/wpt/tests/common/security-features/subresource/template/font.css.template new file mode 100644 index 0000000..9d1e9c4 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/template/font.css.template @@ -0,0 +1,9 @@ +@font-face { + font-family: 'wpt'; + font-style: normal; + font-weight: normal; + src: url(/common/security-features/subresource/font.py?id=%(id)s) format('truetype'); +} +body { + font-family: 'wpt'; +} diff --git a/test/wpt/tests/common/security-features/subresource/template/image.css.template b/test/wpt/tests/common/security-features/subresource/template/image.css.template new file mode 100644 index 0000000..dfe41f1 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/template/image.css.template @@ -0,0 +1,3 @@ +div.styled::before { + content:url(/common/security-features/subresource/image.py?id=%(id)s) +} diff --git a/test/wpt/tests/common/security-features/subresource/template/script.js.template b/test/wpt/tests/common/security-features/subresource/template/script.js.template new file mode 100644 index 0000000..e2edf21 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/template/script.js.template @@ -0,0 +1,3 @@ +postMessage({ + "headers": %(headers)s +}, "*"); diff --git a/test/wpt/tests/common/security-features/subresource/template/shared-worker.js.template b/test/wpt/tests/common/security-features/subresource/template/shared-worker.js.template new file mode 100644 index 0000000..c3f109e --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/template/shared-worker.js.template @@ -0,0 +1,5 @@ +onconnect = function(e) { + e.ports[0].postMessage({ + "headers": %(headers)s + }); +}; diff --git a/test/wpt/tests/common/security-features/subresource/template/static-import.js.template b/test/wpt/tests/common/security-features/subresource/template/static-import.js.template new file mode 100644 index 0000000..095459b --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/template/static-import.js.template @@ -0,0 +1 @@ +import '%(import_url)s'; diff --git a/test/wpt/tests/common/security-features/subresource/template/svg.css.template b/test/wpt/tests/common/security-features/subresource/template/svg.css.template new file mode 100644 index 0000000..c2e509c --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/template/svg.css.template @@ -0,0 +1,3 @@ +path { + %(property)s: url(/common/security-features/subresource/svg.py?id=%(id)s#invalidFragment); +} diff --git a/test/wpt/tests/common/security-features/subresource/template/svg.embedded.template b/test/wpt/tests/common/security-features/subresource/template/svg.embedded.template new file mode 100644 index 0000000..5986c48 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/template/svg.embedded.template @@ -0,0 +1,5 @@ + + + + + diff --git a/test/wpt/tests/common/security-features/subresource/template/worker.js.template b/test/wpt/tests/common/security-features/subresource/template/worker.js.template new file mode 100644 index 0000000..817dd8c --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/template/worker.js.template @@ -0,0 +1,3 @@ +postMessage({ + "headers": %(headers)s +}); diff --git a/test/wpt/tests/common/security-features/subresource/video.py b/test/wpt/tests/common/security-features/subresource/video.py new file mode 100644 index 0000000..7cfbbfa --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/video.py @@ -0,0 +1,17 @@ +import os, sys +from wptserve.utils import isomorphic_decode +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + +def generate_payload(request, server_data): + file = os.path.join(request.doc_root, u"media", u"movie_5.ogv") + return open(file, "rb").read() + + +def main(request, response): + handler = lambda data: generate_payload(request, data) + subresource.respond(request, + response, + payload_generator = handler, + access_control_allow_origin = b"*", + content_type = b"video/ogg") diff --git a/test/wpt/tests/common/security-features/subresource/worker.py b/test/wpt/tests/common/security-features/subresource/worker.py new file mode 100644 index 0000000..f655633 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/worker.py @@ -0,0 +1,13 @@ +import os, sys +from wptserve.utils import isomorphic_decode +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + +def generate_payload(server_data): + return subresource.get_template(u"worker.js.template") % server_data + +def main(request, response): + subresource.respond(request, + response, + payload_generator = generate_payload, + content_type = b"application/javascript") diff --git a/test/wpt/tests/common/security-features/subresource/xhr.py b/test/wpt/tests/common/security-features/subresource/xhr.py new file mode 100644 index 0000000..75921e9 --- /dev/null +++ b/test/wpt/tests/common/security-features/subresource/xhr.py @@ -0,0 +1,16 @@ +import os, sys +from wptserve.utils import isomorphic_decode +import importlib +subresource = importlib.import_module("common.security-features.subresource.subresource") + +def generate_payload(server_data): + data = (u'{"headers": %(headers)s}') % server_data + return data + +def main(request, response): + subresource.respond(request, + response, + payload_generator = generate_payload, + access_control_allow_origin = b"*", + content_type = b"application/json", + cache_control = b"no-store") diff --git a/test/wpt/tests/common/security-features/tools/format_spec_src_json.py b/test/wpt/tests/common/security-features/tools/format_spec_src_json.py new file mode 100644 index 0000000..d1bf581 --- /dev/null +++ b/test/wpt/tests/common/security-features/tools/format_spec_src_json.py @@ -0,0 +1,24 @@ +import collections +import json +import os + + +def main(): + '''Formats spec.src.json.''' + script_directory = os.path.dirname(os.path.abspath(__file__)) + for dir in [ + 'mixed-content', 'referrer-policy', 'referrer-policy/4K-1', + 'referrer-policy/4K', 'referrer-policy/4K+1', + 'upgrade-insecure-requests' + ]: + filename = os.path.join(script_directory, '..', '..', '..', dir, + 'spec.src.json') + spec = json.load( + open(filename, 'r'), object_pairs_hook=collections.OrderedDict) + with open(filename, 'w') as f: + f.write(json.dumps(spec, indent=2, separators=(',', ': '))) + f.write('\n') + + +if __name__ == '__main__': + main() diff --git a/test/wpt/tests/common/security-features/tools/generate.py b/test/wpt/tests/common/security-features/tools/generate.py new file mode 100644 index 0000000..409b4f1 --- /dev/null +++ b/test/wpt/tests/common/security-features/tools/generate.py @@ -0,0 +1,462 @@ +#!/usr/bin/env python3 + +import argparse +import collections +import copy +import json +import os +import sys + +import spec_validator +import util + + +def expand_pattern(expansion_pattern, test_expansion_schema): + expansion = {} + for artifact_key in expansion_pattern: + artifact_value = expansion_pattern[artifact_key] + if artifact_value == '*': + expansion[artifact_key] = test_expansion_schema[artifact_key] + elif isinstance(artifact_value, list): + expansion[artifact_key] = artifact_value + elif isinstance(artifact_value, dict): + # Flattened expansion. + expansion[artifact_key] = [] + values_dict = expand_pattern(artifact_value, + test_expansion_schema[artifact_key]) + for sub_key in values_dict.keys(): + expansion[artifact_key] += values_dict[sub_key] + else: + expansion[artifact_key] = [artifact_value] + + return expansion + + +def permute_expansion(expansion, + artifact_order, + selection={}, + artifact_index=0): + assert isinstance(artifact_order, list), "artifact_order should be a list" + + if artifact_index >= len(artifact_order): + yield selection + return + + artifact_key = artifact_order[artifact_index] + + for artifact_value in expansion[artifact_key]: + selection[artifact_key] = artifact_value + for next_selection in permute_expansion(expansion, artifact_order, + selection, artifact_index + 1): + yield next_selection + + +# Dumps the test config `selection` into a serialized JSON string. +def dump_test_parameters(selection): + return json.dumps( + selection, + indent=2, + separators=(',', ': '), + sort_keys=True, + cls=util.CustomEncoder) + + +def get_test_filename(spec_directory, spec_json, selection): + '''Returns the filname for the main test HTML file''' + + selection_for_filename = copy.deepcopy(selection) + # Use 'unset' rather than 'None' in test filenames. + if selection_for_filename['delivery_value'] is None: + selection_for_filename['delivery_value'] = 'unset' + + return os.path.join( + spec_directory, + spec_json['test_file_path_pattern'] % selection_for_filename) + + +def get_csp_value(value): + ''' + Returns actual CSP header values (e.g. "worker-src 'self'") for the + given string used in PolicyDelivery's value (e.g. "worker-src-self"). + ''' + + # script-src + # Test-related scripts like testharness.js and inline scripts containing + # test bodies. + # 'unsafe-inline' is added as a workaround here. This is probably not so + # bad, as it shouldn't intefere non-inline-script requests that we want to + # test. + if value == 'script-src-wildcard': + return "script-src * 'unsafe-inline'" + if value == 'script-src-self': + return "script-src 'self' 'unsafe-inline'" + # Workaround for "script-src 'none'" would be more complicated, because + # - "script-src 'none' 'unsafe-inline'" is handled somehow differently from + # "script-src 'none'", i.e. + # https://w3c.github.io/webappsec-csp/#match-url-to-source-list Step 3 + # handles the latter but not the former. + # - We need nonce- or path-based additional values to allow same-origin + # test scripts like testharness.js. + # Therefore, we disable 'script-src-none' tests for now in + # `/content-security-policy/spec.src.json`. + if value == 'script-src-none': + return "script-src 'none'" + + # worker-src + if value == 'worker-src-wildcard': + return 'worker-src *' + if value == 'worker-src-self': + return "worker-src 'self'" + if value == 'worker-src-none': + return "worker-src 'none'" + raise Exception('Invalid delivery_value: %s' % value) + +def handle_deliveries(policy_deliveries): + ''' + Generate elements and HTTP headers for the given list of + PolicyDelivery. + TODO(hiroshige): Merge duplicated code here, scope/document.py, etc. + ''' + + meta = '' + headers = {} + + for delivery in policy_deliveries: + if delivery.value is None: + continue + if delivery.key == 'referrerPolicy': + if delivery.delivery_type == 'meta': + meta += \ + '' % delivery.value + elif delivery.delivery_type == 'http-rp': + headers['Referrer-Policy'] = delivery.value + # TODO(kristijanburnik): Limit to WPT origins. + headers['Access-Control-Allow-Origin'] = '*' + else: + raise Exception( + 'Invalid delivery_type: %s' % delivery.delivery_type) + elif delivery.key == 'mixedContent': + assert (delivery.value == 'opt-in') + if delivery.delivery_type == 'meta': + meta += '' + elif delivery.delivery_type == 'http-rp': + headers['Content-Security-Policy'] = 'block-all-mixed-content' + else: + raise Exception( + 'Invalid delivery_type: %s' % delivery.delivery_type) + elif delivery.key == 'contentSecurityPolicy': + csp_value = get_csp_value(delivery.value) + if delivery.delivery_type == 'meta': + meta += '' + elif delivery.delivery_type == 'http-rp': + headers['Content-Security-Policy'] = csp_value + else: + raise Exception( + 'Invalid delivery_type: %s' % delivery.delivery_type) + elif delivery.key == 'upgradeInsecureRequests': + # https://w3c.github.io/webappsec-upgrade-insecure-requests/#delivery + assert (delivery.value == 'upgrade') + if delivery.delivery_type == 'meta': + meta += '' + elif delivery.delivery_type == 'http-rp': + headers[ + 'Content-Security-Policy'] = 'upgrade-insecure-requests' + else: + raise Exception( + 'Invalid delivery_type: %s' % delivery.delivery_type) + else: + raise Exception('Invalid delivery_key: %s' % delivery.key) + return {"meta": meta, "headers": headers} + + +def generate_selection(spec_json, selection): + ''' + Returns a scenario object (with a top-level source_context_list entry, + which will be removed in generate_test_file() later). + ''' + + target_policy_delivery = util.PolicyDelivery(selection['delivery_type'], + selection['delivery_key'], + selection['delivery_value']) + del selection['delivery_type'] + del selection['delivery_key'] + del selection['delivery_value'] + + # Parse source context list and policy deliveries of source contexts. + # `util.ShouldSkip()` exceptions are raised if e.g. unsuppported + # combinations of source contexts and policy deliveries are used. + source_context_list_scheme = spec_json['source_context_list_schema'][ + selection['source_context_list']] + selection['source_context_list'] = [ + util.SourceContext.from_json(source_context, target_policy_delivery, + spec_json['source_context_schema']) + for source_context in source_context_list_scheme['sourceContextList'] + ] + + # Check if the subresource is supported by the innermost source context. + innermost_source_context = selection['source_context_list'][-1] + supported_subresource = spec_json['source_context_schema'][ + 'supported_subresource'][innermost_source_context.source_context_type] + if supported_subresource != '*': + if selection['subresource'] not in supported_subresource: + raise util.ShouldSkip() + + # Parse subresource policy deliveries. + selection[ + 'subresource_policy_deliveries'] = util.PolicyDelivery.list_from_json( + source_context_list_scheme['subresourcePolicyDeliveries'], + target_policy_delivery, spec_json['subresource_schema'] + ['supported_delivery_type'][selection['subresource']]) + + # Generate per-scenario test description. + selection['test_description'] = spec_json[ + 'test_description_template'] % selection + + return selection + + +def generate_test_file(spec_directory, test_helper_filenames, + test_html_template_basename, test_filename, scenarios): + ''' + Generates a test HTML file (and possibly its associated .headers file) + from `scenarios`. + ''' + + # Scenarios for the same file should have the same `source_context_list`, + # including the top-level one. + # Note: currently, non-top-level source contexts aren't necessarily required + # to be the same, but we set this requirement as it will be useful e.g. when + # we e.g. reuse a worker among multiple scenarios. + for scenario in scenarios: + assert (scenario['source_context_list'] == scenarios[0] + ['source_context_list']) + + # We process the top source context below, and do not include it in + # the JSON objects (i.e. `scenarios`) in generated HTML files. + top_source_context = scenarios[0]['source_context_list'].pop(0) + assert (top_source_context.source_context_type == 'top') + for scenario in scenarios[1:]: + assert (scenario['source_context_list'].pop(0) == top_source_context) + + parameters = {} + + # Sort scenarios, to avoid unnecessary diffs due to different orders in + # `scenarios`. + serialized_scenarios = sorted( + [dump_test_parameters(scenario) for scenario in scenarios]) + + parameters['scenarios'] = ",\n".join(serialized_scenarios).replace( + "\n", "\n" + " " * 10) + + test_directory = os.path.dirname(test_filename) + + parameters['helper_js'] = "" + for test_helper_filename in test_helper_filenames: + parameters['helper_js'] += ' \n' % ( + os.path.relpath(test_helper_filename, test_directory)) + parameters['sanity_checker_js'] = os.path.relpath( + os.path.join(spec_directory, 'generic', 'sanity-checker.js'), + test_directory) + parameters['spec_json_js'] = os.path.relpath( + os.path.join(spec_directory, 'generic', 'spec_json.js'), + test_directory) + + test_headers_filename = test_filename + ".headers" + + test_html_template = util.get_template(test_html_template_basename) + disclaimer_template = util.get_template('disclaimer.template') + + html_template_filename = os.path.join(util.template_directory, + test_html_template_basename) + generated_disclaimer = disclaimer_template \ + % {'generating_script_filename': os.path.relpath(sys.argv[0], + util.test_root_directory), + 'spec_directory': os.path.relpath(spec_directory, + util.test_root_directory)} + + # Adjust the template for the test invoking JS. Indent it to look nice. + parameters['generated_disclaimer'] = generated_disclaimer.rstrip() + + # Directory for the test files. + try: + os.makedirs(test_directory) + except: + pass + + delivery = handle_deliveries(top_source_context.policy_deliveries) + + if len(delivery['headers']) > 0: + with open(test_headers_filename, "w") as f: + for header in delivery['headers']: + f.write('%s: %s\n' % (header, delivery['headers'][header])) + + parameters['meta_delivery_method'] = delivery['meta'] + # Obey the lint and pretty format. + if len(parameters['meta_delivery_method']) > 0: + parameters['meta_delivery_method'] = "\n " + \ + parameters['meta_delivery_method'] + + # Write out the generated HTML file. + util.write_file(test_filename, test_html_template % parameters) + + +def generate_test_source_files(spec_directory, test_helper_filenames, + spec_json, target): + test_expansion_schema = spec_json['test_expansion_schema'] + specification = spec_json['specification'] + + if target == "debug": + spec_json_js_template = util.get_template('spec_json.js.template') + util.write_file( + os.path.join(spec_directory, "generic", "spec_json.js"), + spec_json_js_template % {'spec_json': json.dumps(spec_json)}) + util.write_file( + os.path.join(spec_directory, "generic", + "debug-output.spec.src.json"), + json.dumps(spec_json, indent=2, separators=(',', ': '))) + + # Choose a debug/release template depending on the target. + html_template = "test.%s.html.template" % target + + artifact_order = test_expansion_schema.keys() + artifact_order.remove('expansion') + + excluded_selection_pattern = '' + for key in artifact_order: + excluded_selection_pattern += '%(' + key + ')s/' + + # Create list of excluded tests. + exclusion_dict = set() + for excluded_pattern in spec_json['excluded_tests']: + excluded_expansion = \ + expand_pattern(excluded_pattern, test_expansion_schema) + for excluded_selection in permute_expansion(excluded_expansion, + artifact_order): + excluded_selection['delivery_key'] = spec_json['delivery_key'] + exclusion_dict.add(excluded_selection_pattern % excluded_selection) + + # `scenarios[filename]` represents the list of scenario objects to be + # generated into `filename`. + scenarios = {} + + for spec in specification: + # Used to make entries with expansion="override" override preceding + # entries with the same |selection_path|. + output_dict = {} + + for expansion_pattern in spec['test_expansion']: + expansion = expand_pattern(expansion_pattern, + test_expansion_schema) + for selection in permute_expansion(expansion, artifact_order): + selection['delivery_key'] = spec_json['delivery_key'] + selection_path = spec_json['selection_pattern'] % selection + if selection_path in output_dict: + if expansion_pattern['expansion'] != 'override': + print("Error: expansion is default in:") + print(dump_test_parameters(selection)) + print("but overrides:") + print(dump_test_parameters( + output_dict[selection_path])) + sys.exit(1) + output_dict[selection_path] = copy.deepcopy(selection) + + for selection_path in output_dict: + selection = output_dict[selection_path] + if (excluded_selection_pattern % selection) in exclusion_dict: + print('Excluding selection:', selection_path) + continue + try: + test_filename = get_test_filename(spec_directory, spec_json, + selection) + scenario = generate_selection(spec_json, selection) + scenarios[test_filename] = scenarios.get(test_filename, + []) + [scenario] + except util.ShouldSkip: + continue + + for filename in scenarios: + generate_test_file(spec_directory, test_helper_filenames, + html_template, filename, scenarios[filename]) + + +def merge_json(base, child): + for key in child: + if key not in base: + base[key] = child[key] + continue + # `base[key]` and `child[key]` both exists. + if isinstance(base[key], list) and isinstance(child[key], list): + base[key].extend(child[key]) + elif isinstance(base[key], dict) and isinstance(child[key], dict): + merge_json(base[key], child[key]) + else: + base[key] = child[key] + + +def main(): + parser = argparse.ArgumentParser( + description='Test suite generator utility') + parser.add_argument( + '-t', + '--target', + type=str, + choices=("release", "debug"), + default="release", + help='Sets the appropriate template for generating tests') + parser.add_argument( + '-s', + '--spec', + type=str, + default=os.getcwd(), + help='Specify a file used for describing and generating the tests') + # TODO(kristijanburnik): Add option for the spec_json file. + args = parser.parse_args() + + spec_directory = os.path.abspath(args.spec) + + # Read `spec.src.json` files, starting from `spec_directory`, and + # continuing to parent directories as long as `spec.src.json` exists. + spec_filenames = [] + test_helper_filenames = [] + spec_src_directory = spec_directory + while len(spec_src_directory) >= len(util.test_root_directory): + spec_filename = os.path.join(spec_src_directory, "spec.src.json") + if not os.path.exists(spec_filename): + break + spec_filenames.append(spec_filename) + test_filename = os.path.join(spec_src_directory, 'generic', + 'test-case.sub.js') + assert (os.path.exists(test_filename)) + test_helper_filenames.append(test_filename) + spec_src_directory = os.path.abspath( + os.path.join(spec_src_directory, "..")) + + spec_filenames = list(reversed(spec_filenames)) + test_helper_filenames = list(reversed(test_helper_filenames)) + + if len(spec_filenames) == 0: + print('Error: No spec.src.json is found at %s.' % spec_directory) + return + + # Load the default spec JSON file, ... + default_spec_filename = os.path.join(util.script_directory, + 'spec.src.json') + spec_json = collections.OrderedDict() + if os.path.exists(default_spec_filename): + spec_json = util.load_spec_json(default_spec_filename) + + # ... and then make spec JSON files in subdirectories override the default. + for spec_filename in spec_filenames: + child_spec_json = util.load_spec_json(spec_filename) + merge_json(spec_json, child_spec_json) + + spec_validator.assert_valid_spec_json(spec_json) + generate_test_source_files(spec_directory, test_helper_filenames, + spec_json, args.target) + + +if __name__ == '__main__': + main() diff --git a/test/wpt/tests/common/security-features/tools/spec.src.json b/test/wpt/tests/common/security-features/tools/spec.src.json new file mode 100644 index 0000000..4a84493 --- /dev/null +++ b/test/wpt/tests/common/security-features/tools/spec.src.json @@ -0,0 +1,533 @@ +{ + "selection_pattern": "%(source_context_list)s.%(delivery_type)s/%(delivery_value)s/%(subresource)s/%(origin)s.%(redirection)s.%(source_scheme)s", + "test_file_path_pattern": "gen/%(source_context_list)s.%(delivery_type)s/%(delivery_value)s/%(subresource)s.%(source_scheme)s.html", + "excluded_tests": [ + { + // Workers are same-origin only + "expansion": "*", + "source_scheme": "*", + "source_context_list": "*", + "delivery_type": "*", + "delivery_value": "*", + "redirection": "*", + "subresource": [ + "worker-classic", + "worker-module", + "sharedworker-classic", + "sharedworker-module" + ], + "origin": [ + "cross-https", + "cross-http", + "cross-http-downgrade", + "cross-wss", + "cross-ws", + "cross-ws-downgrade" + ], + "expectation": "*" + }, + { + // Workers are same-origin only (redirects) + "expansion": "*", + "source_scheme": "*", + "source_context_list": "*", + "delivery_type": "*", + "delivery_value": "*", + "redirection": [ + "swap-origin", + "swap-scheme" + ], + "subresource": [ + "worker-classic", + "worker-module", + "sharedworker-classic", + "sharedworker-module" + ], + "origin": "*", + "expectation": "*" + }, + { + // Websockets are ws/wss-only + "expansion": "*", + "source_scheme": "*", + "source_context_list": "*", + "delivery_type": "*", + "delivery_value": "*", + "redirection": "*", + "subresource": "websocket", + "origin": [ + "same-https", + "same-http", + "same-http-downgrade", + "cross-https", + "cross-http", + "cross-http-downgrade" + ], + "expectation": "*" + }, + { + // Redirects are intentionally forbidden in browsers: + // https://fetch.spec.whatwg.org/#concept-websocket-establish + // Websockets are no-redirect only + "expansion": "*", + "source_scheme": "*", + "source_context_list": "*", + "delivery_type": "*", + "delivery_value": "*", + "redirection": [ + "keep-origin", + "swap-origin", + "keep-scheme", + "swap-scheme", + "downgrade" + ], + "subresource": "websocket", + "origin": "*", + "expectation": "*" + }, + { + // ws/wss are websocket-only + "expansion": "*", + "source_scheme": "*", + "source_context_list": "*", + "delivery_type": "*", + "delivery_value": "*", + "redirection": "*", + "subresource": [ + "a-tag", + "area-tag", + "audio-tag", + "beacon", + "fetch", + "iframe-tag", + "img-tag", + "link-css-tag", + "link-prefetch-tag", + "object-tag", + "picture-tag", + "script-tag", + "script-tag-dynamic-import", + "sharedworker-classic", + "sharedworker-import", + "sharedworker-import-data", + "sharedworker-module", + "video-tag", + "worker-classic", + "worker-import", + "worker-import-data", + "worker-module", + "worklet-animation", + "worklet-animation-import-data", + "worklet-audio", + "worklet-audio-import-data", + "worklet-layout", + "worklet-layout-import-data", + "worklet-paint", + "worklet-paint-import-data", + "xhr" + ], + "origin": [ + "same-wss", + "same-ws", + "same-ws-downgrade", + "cross-wss", + "cross-ws", + "cross-ws-downgrade" + ], + "expectation": "*" + }, + { + // Worklets are HTTPS contexts only + "expansion": "*", + "source_scheme": "http", + "source_context_list": "*", + "delivery_type": "*", + "delivery_value": "*", + "redirection": "*", + "subresource": [ + "worklet-animation", + "worklet-animation-import-data", + "worklet-audio", + "worklet-audio-import-data", + "worklet-layout", + "worklet-layout-import-data", + "worklet-paint", + "worklet-paint-import-data" + ], + "origin": "*", + "expectation": "*" + } + ], + "source_context_schema": { + "supported_subresource": { + "top": "*", + "iframe": "*", + "iframe-blank": "*", + "srcdoc": "*", + "worker-classic": [ + "xhr", + "fetch", + "websocket", + "worker-classic", + "worker-module" + ], + "worker-module": [ + "xhr", + "fetch", + "websocket", + "worker-classic", + "worker-module" + ], + "worker-classic-data": [ + "xhr", + "fetch", + "websocket" + ], + "worker-module-data": [ + "xhr", + "fetch", + "websocket" + ], + "sharedworker-classic": [ + "xhr", + "fetch", + "websocket" + ], + "sharedworker-module": [ + "xhr", + "fetch", + "websocket" + ], + "sharedworker-classic-data": [ + "xhr", + "fetch", + "websocket" + ], + "sharedworker-module-data": [ + "xhr", + "fetch", + "websocket" + ] + } + }, + "source_context_list_schema": { + // Warning: Currently, some nested patterns of contexts have different + // inheritance rules for different kinds of policies. + // The generated tests will be used to test/investigate the policy + // inheritance rules, and eventually the policy inheritance rules will + // be unified (https://github.com/w3ctag/design-principles/issues/111). + "top": { + "description": "Policy set by the top-level Document", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "policy" + ] + } + ], + "subresourcePolicyDeliveries": [] + }, + "req": { + "description": "Subresource request's policy should override Document's policy", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "anotherPolicy" + ] + } + ], + "subresourcePolicyDeliveries": [ + "nonNullPolicy" + ] + }, + "srcdoc-inherit": { + "description": "srcdoc iframe without its own policy should inherit parent Document's policy", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "policy" + ] + }, + { + "sourceContextType": "srcdoc" + } + ], + "subresourcePolicyDeliveries": [] + }, + "srcdoc": { + "description": "srcdoc iframe's policy should override parent Document's policy", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "anotherPolicy" + ] + }, + { + "sourceContextType": "srcdoc", + "policyDeliveries": [ + "nonNullPolicy" + ] + } + ], + "subresourcePolicyDeliveries": [] + }, + "iframe": { + "description": "external iframe's policy should override parent Document's policy", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "anotherPolicy" + ] + }, + { + "sourceContextType": "iframe", + "policyDeliveries": [ + "policy" + ] + } + ], + "subresourcePolicyDeliveries": [] + }, + "iframe-blank-inherit": { + "description": "blank iframe should inherit parent Document's policy", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "policy" + ] + }, + { + "sourceContextType": "iframe-blank" + } + ], + "subresourcePolicyDeliveries": [] + }, + "worker-classic": { + // This is applicable to referrer-policy tests. + // Use "worker-classic-inherit" for CSP (mixed-content, etc.). + "description": "dedicated workers shouldn't inherit its parent's policy.", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "anotherPolicy" + ] + }, + { + "sourceContextType": "worker-classic", + "policyDeliveries": [ + "policy" + ] + } + ], + "subresourcePolicyDeliveries": [] + }, + "worker-classic-data": { + "description": "data: dedicated workers should inherit its parent's policy.", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "policy" + ] + }, + { + "sourceContextType": "worker-classic-data", + "policyDeliveries": [] + } + ], + "subresourcePolicyDeliveries": [] + }, + "worker-module": { + // This is applicable to referrer-policy tests. + "description": "dedicated workers shouldn't inherit its parent's policy.", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "anotherPolicy" + ] + }, + { + "sourceContextType": "worker-module", + "policyDeliveries": [ + "policy" + ] + } + ], + "subresourcePolicyDeliveries": [] + }, + "worker-module-data": { + "description": "data: dedicated workers should inherit its parent's policy.", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "policy" + ] + }, + { + "sourceContextType": "worker-module-data", + "policyDeliveries": [] + } + ], + "subresourcePolicyDeliveries": [] + }, + "sharedworker-classic": { + "description": "shared workers shouldn't inherit its parent's policy.", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "anotherPolicy" + ] + }, + { + "sourceContextType": "sharedworker-classic", + "policyDeliveries": [ + "policy" + ] + } + ], + "subresourcePolicyDeliveries": [] + }, + "sharedworker-classic-data": { + "description": "data: shared workers should inherit its parent's policy.", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "policy" + ] + }, + { + "sourceContextType": "sharedworker-classic-data", + "policyDeliveries": [] + } + ], + "subresourcePolicyDeliveries": [] + }, + "sharedworker-module": { + "description": "shared workers shouldn't inherit its parent's policy.", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "anotherPolicy" + ] + }, + { + "sourceContextType": "sharedworker-module", + "policyDeliveries": [ + "policy" + ] + } + ], + "subresourcePolicyDeliveries": [] + }, + "sharedworker-module-data": { + "description": "data: shared workers should inherit its parent's policy.", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "policy" + ] + }, + { + "sourceContextType": "sharedworker-module-data", + "policyDeliveries": [] + } + ], + "subresourcePolicyDeliveries": [] + } + }, + "test_expansion_schema": { + "expansion": [ + "default", + "override" + ], + "source_scheme": [ + "http", + "https" + ], + "source_context_list": [ + "top", + "req", + "srcdoc-inherit", + "srcdoc", + "iframe", + "iframe-blank-inherit", + "worker-classic", + "worker-classic-data", + "worker-module", + "worker-module-data", + "sharedworker-classic", + "sharedworker-classic-data", + "sharedworker-module", + "sharedworker-module-data" + ], + "redirection": [ + "no-redirect", + "keep-origin", + "swap-origin", + "keep-scheme", + "swap-scheme", + "downgrade" + ], + "origin": [ + "same-https", + "same-http", + "same-http-downgrade", + "cross-https", + "cross-http", + "cross-http-downgrade", + "same-wss", + "same-ws", + "same-ws-downgrade", + "cross-wss", + "cross-ws", + "cross-ws-downgrade" + ], + "subresource": [ + "a-tag", + "area-tag", + "audio-tag", + "beacon", + "fetch", + "iframe-tag", + "img-tag", + "link-css-tag", + "link-prefetch-tag", + "object-tag", + "picture-tag", + "script-tag", + "script-tag-dynamic-import", + "sharedworker-classic", + "sharedworker-import", + "sharedworker-import-data", + "sharedworker-module", + "video-tag", + "websocket", + "worker-classic", + "worker-import", + "worker-import-data", + "worker-module", + "worklet-animation", + "worklet-animation-import-data", + "worklet-audio", + "worklet-audio-import-data", + "worklet-layout", + "worklet-layout-import-data", + "worklet-paint", + "worklet-paint-import-data", + "xhr" + ] + } +} diff --git a/test/wpt/tests/common/security-features/tools/spec_validator.py b/test/wpt/tests/common/security-features/tools/spec_validator.py new file mode 100644 index 0000000..f8a1390 --- /dev/null +++ b/test/wpt/tests/common/security-features/tools/spec_validator.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 + +import json, sys + + +def assert_non_empty_string(obj, field): + assert field in obj, 'Missing field "%s"' % field + assert isinstance(obj[field], basestring), \ + 'Field "%s" must be a string' % field + assert len(obj[field]) > 0, 'Field "%s" must not be empty' % field + + +def assert_non_empty_list(obj, field): + assert isinstance(obj[field], list), \ + '%s must be a list' % field + assert len(obj[field]) > 0, \ + '%s list must not be empty' % field + + +def assert_non_empty_dict(obj, field): + assert isinstance(obj[field], dict), \ + '%s must be a dict' % field + assert len(obj[field]) > 0, \ + '%s dict must not be empty' % field + + +def assert_contains(obj, field): + assert field in obj, 'Must contain field "%s"' % field + + +def assert_value_from(obj, field, items): + assert obj[field] in items, \ + 'Field "%s" must be from: %s' % (field, str(items)) + + +def assert_atom_or_list_items_from(obj, field, items): + if isinstance(obj[field], basestring) or isinstance( + obj[field], int) or obj[field] is None: + assert_value_from(obj, field, items) + return + + assert isinstance(obj[field], list), '%s must be a list' % field + for allowed_value in obj[field]: + assert allowed_value != '*', "Wildcard is not supported for lists!" + assert allowed_value in items, \ + 'Field "%s" must be from: %s' % (field, str(items)) + + +def assert_contains_only_fields(obj, expected_fields): + for expected_field in expected_fields: + assert_contains(obj, expected_field) + + for actual_field in obj: + assert actual_field in expected_fields, \ + 'Unexpected field "%s".' % actual_field + + +def leaf_values(schema): + if isinstance(schema, list): + return schema + ret = [] + for _, sub_schema in schema.iteritems(): + ret += leaf_values(sub_schema) + return ret + + +def assert_value_unique_in(value, used_values): + assert value not in used_values, 'Duplicate value "%s"!' % str(value) + used_values[value] = True + + +def assert_valid_artifact(exp_pattern, artifact_key, schema): + if isinstance(schema, list): + assert_atom_or_list_items_from(exp_pattern, artifact_key, + ["*"] + schema) + return + + for sub_artifact_key, sub_schema in schema.iteritems(): + assert_valid_artifact(exp_pattern[artifact_key], sub_artifact_key, + sub_schema) + + +def validate(spec_json, details): + """ Validates the json specification for generating tests. """ + + details['object'] = spec_json + assert_contains_only_fields(spec_json, [ + "selection_pattern", "test_file_path_pattern", + "test_description_template", "test_page_title_template", + "specification", "delivery_key", "subresource_schema", + "source_context_schema", "source_context_list_schema", + "test_expansion_schema", "excluded_tests" + ]) + assert_non_empty_list(spec_json, "specification") + assert_non_empty_dict(spec_json, "test_expansion_schema") + assert_non_empty_list(spec_json, "excluded_tests") + + specification = spec_json['specification'] + test_expansion_schema = spec_json['test_expansion_schema'] + excluded_tests = spec_json['excluded_tests'] + + valid_test_expansion_fields = test_expansion_schema.keys() + + # Should be consistent with `sourceContextMap` in + # `/common/security-features/resources/common.sub.js`. + valid_source_context_names = [ + "top", "iframe", "iframe-blank", "srcdoc", "worker-classic", + "worker-module", "worker-classic-data", "worker-module-data", + "sharedworker-classic", "sharedworker-module", + "sharedworker-classic-data", "sharedworker-module-data" + ] + + valid_subresource_names = [ + "a-tag", "area-tag", "audio-tag", "form-tag", "iframe-tag", "img-tag", + "link-css-tag", "link-prefetch-tag", "object-tag", "picture-tag", + "script-tag", "script-tag-dynamic-import", "video-tag" + ] + ["beacon", "fetch", "xhr", "websocket"] + [ + "worker-classic", "worker-module", "worker-import", + "worker-import-data", "sharedworker-classic", "sharedworker-module", + "sharedworker-import", "sharedworker-import-data", + "serviceworker-classic", "serviceworker-module", + "serviceworker-import", "serviceworker-import-data" + ] + [ + "worklet-animation", "worklet-audio", "worklet-layout", + "worklet-paint", "worklet-animation-import", "worklet-audio-import", + "worklet-layout-import", "worklet-paint-import", + "worklet-animation-import-data", "worklet-audio-import-data", + "worklet-layout-import-data", "worklet-paint-import-data" + ] + + # Validate each single spec. + for spec in specification: + details['object'] = spec + + # Validate required fields for a single spec. + assert_contains_only_fields(spec, [ + 'title', 'description', 'specification_url', 'test_expansion' + ]) + assert_non_empty_string(spec, 'title') + assert_non_empty_string(spec, 'description') + assert_non_empty_string(spec, 'specification_url') + assert_non_empty_list(spec, 'test_expansion') + + for spec_exp in spec['test_expansion']: + details['object'] = spec_exp + assert_contains_only_fields(spec_exp, valid_test_expansion_fields) + + for artifact in test_expansion_schema: + details['test_expansion_field'] = artifact + assert_valid_artifact(spec_exp, artifact, + test_expansion_schema[artifact]) + del details['test_expansion_field'] + + # Validate source_context_schema. + details['object'] = spec_json['source_context_schema'] + assert_contains_only_fields( + spec_json['source_context_schema'], + ['supported_delivery_type', 'supported_subresource']) + assert_contains_only_fields( + spec_json['source_context_schema']['supported_delivery_type'], + valid_source_context_names) + for source_context in spec_json['source_context_schema'][ + 'supported_delivery_type']: + assert_valid_artifact( + spec_json['source_context_schema']['supported_delivery_type'], + source_context, test_expansion_schema['delivery_type']) + assert_contains_only_fields( + spec_json['source_context_schema']['supported_subresource'], + valid_source_context_names) + for source_context in spec_json['source_context_schema'][ + 'supported_subresource']: + assert_valid_artifact( + spec_json['source_context_schema']['supported_subresource'], + source_context, leaf_values(test_expansion_schema['subresource'])) + + # Validate subresource_schema. + details['object'] = spec_json['subresource_schema'] + assert_contains_only_fields(spec_json['subresource_schema'], + ['supported_delivery_type']) + assert_contains_only_fields( + spec_json['subresource_schema']['supported_delivery_type'], + leaf_values(test_expansion_schema['subresource'])) + for subresource in spec_json['subresource_schema'][ + 'supported_delivery_type']: + assert_valid_artifact( + spec_json['subresource_schema']['supported_delivery_type'], + subresource, test_expansion_schema['delivery_type']) + + # Validate the test_expansion schema members. + details['object'] = test_expansion_schema + assert_contains_only_fields(test_expansion_schema, [ + 'expansion', 'source_scheme', 'source_context_list', 'delivery_type', + 'delivery_value', 'redirection', 'subresource', 'origin', 'expectation' + ]) + assert_atom_or_list_items_from(test_expansion_schema, 'expansion', + ['default', 'override']) + assert_atom_or_list_items_from(test_expansion_schema, 'source_scheme', + ['http', 'https']) + assert_atom_or_list_items_from( + test_expansion_schema, 'source_context_list', + spec_json['source_context_list_schema'].keys()) + + # Should be consistent with `preprocess_redirection` in + # `/common/security-features/subresource/subresource.py`. + assert_atom_or_list_items_from(test_expansion_schema, 'redirection', [ + 'no-redirect', 'keep-origin', 'swap-origin', 'keep-scheme', + 'swap-scheme', 'downgrade' + ]) + for subresource in leaf_values(test_expansion_schema['subresource']): + assert subresource in valid_subresource_names, "Invalid subresource %s" % subresource + # Should be consistent with getSubresourceOrigin() in + # `/common/security-features/resources/common.sub.js`. + assert_atom_or_list_items_from(test_expansion_schema, 'origin', [ + 'same-http', 'same-https', 'same-ws', 'same-wss', 'cross-http', + 'cross-https', 'cross-ws', 'cross-wss', 'same-http-downgrade', + 'cross-http-downgrade', 'same-ws-downgrade', 'cross-ws-downgrade' + ]) + + # Validate excluded tests. + details['object'] = excluded_tests + for excluded_test_expansion in excluded_tests: + assert_contains_only_fields(excluded_test_expansion, + valid_test_expansion_fields) + details['object'] = excluded_test_expansion + for artifact in test_expansion_schema: + details['test_expansion_field'] = artifact + assert_valid_artifact(excluded_test_expansion, artifact, + test_expansion_schema[artifact]) + del details['test_expansion_field'] + + del details['object'] + + +def assert_valid_spec_json(spec_json): + error_details = {} + try: + validate(spec_json, error_details) + except AssertionError as err: + print('ERROR:', err.message) + print(json.dumps(error_details, indent=4)) + sys.exit(1) + + +def main(): + spec_json = load_spec_json() + assert_valid_spec_json(spec_json) + print("Spec JSON is valid.") + + +if __name__ == '__main__': + main() diff --git a/test/wpt/tests/common/security-features/tools/template/disclaimer.template b/test/wpt/tests/common/security-features/tools/template/disclaimer.template new file mode 100644 index 0000000..ba9458c --- /dev/null +++ b/test/wpt/tests/common/security-features/tools/template/disclaimer.template @@ -0,0 +1 @@ + diff --git a/test/wpt/tests/common/security-features/tools/template/spec_json.js.template b/test/wpt/tests/common/security-features/tools/template/spec_json.js.template new file mode 100644 index 0000000..e4cbd03 --- /dev/null +++ b/test/wpt/tests/common/security-features/tools/template/spec_json.js.template @@ -0,0 +1 @@ +var SPEC_JSON = %(spec_json)s; diff --git a/test/wpt/tests/common/security-features/tools/template/test.debug.html.template b/test/wpt/tests/common/security-features/tools/template/test.debug.html.template new file mode 100644 index 0000000..b6be088 --- /dev/null +++ b/test/wpt/tests/common/security-features/tools/template/test.debug.html.template @@ -0,0 +1,26 @@ + +%(generated_disclaimer)s + + + + %(meta_delivery_method)s + + + + + + + +%(helper_js)s + + +
+ + diff --git a/test/wpt/tests/common/security-features/tools/template/test.release.html.template b/test/wpt/tests/common/security-features/tools/template/test.release.html.template new file mode 100644 index 0000000..bac2d5b --- /dev/null +++ b/test/wpt/tests/common/security-features/tools/template/test.release.html.template @@ -0,0 +1,22 @@ + +%(generated_disclaimer)s + + + + %(meta_delivery_method)s + + + +%(helper_js)s + + +
+ + diff --git a/test/wpt/tests/common/security-features/tools/util.py b/test/wpt/tests/common/security-features/tools/util.py new file mode 100644 index 0000000..5da06f9 --- /dev/null +++ b/test/wpt/tests/common/security-features/tools/util.py @@ -0,0 +1,228 @@ +import os, sys, json, json5, re +import collections + +script_directory = os.path.dirname(os.path.abspath(__file__)) +template_directory = os.path.abspath( + os.path.join(script_directory, 'template')) +test_root_directory = os.path.abspath( + os.path.join(script_directory, '..', '..', '..')) + + +def get_template(basename): + with open(os.path.join(template_directory, basename), "r") as f: + return f.read() + + +def write_file(filename, contents): + with open(filename, "w") as f: + f.write(contents) + + +def read_nth_line(fp, line_number): + fp.seek(0) + for i, line in enumerate(fp): + if (i + 1) == line_number: + return line + + +def load_spec_json(path_to_spec): + re_error_location = re.compile('line ([0-9]+) column ([0-9]+)') + with open(path_to_spec, "r") as f: + try: + return json5.load(f, object_pairs_hook=collections.OrderedDict) + except ValueError as ex: + print(ex.message) + match = re_error_location.search(ex.message) + if match: + line_number, column = int(match.group(1)), int(match.group(2)) + print(read_nth_line(f, line_number).rstrip()) + print(" " * (column - 1) + "^") + sys.exit(1) + + +class ShouldSkip(Exception): + ''' + Raised when the given combination of subresource type, source context type, + delivery type etc. are not supported and we should skip that configuration. + ShouldSkip is expected in normal generator execution (and thus subsequent + generation continues), as we first enumerate a broad range of configurations + first, and later raise ShouldSkip to filter out unsupported combinations. + + ShouldSkip is distinguished from other general errors that cause immediate + termination of the generator and require fix. + ''' + def __init__(self): + pass + + +class PolicyDelivery(object): + ''' + See `@typedef PolicyDelivery` comments in + `common/security-features/resources/common.sub.js`. + ''' + + def __init__(self, delivery_type, key, value): + self.delivery_type = delivery_type + self.key = key + self.value = value + + def __eq__(self, other): + return type(self) is type(other) and self.__dict__ == other.__dict__ + + @classmethod + def list_from_json(cls, list, target_policy_delivery, + supported_delivery_types): + # type: (dict, PolicyDelivery, typing.List[str]) -> typing.List[PolicyDelivery] + ''' + Parses a JSON object `list` that represents a list of `PolicyDelivery` + and returns a list of `PolicyDelivery`, plus supporting placeholders + (see `from_json()` comments below or + `common/security-features/README.md`). + + Can raise `ShouldSkip`. + ''' + if list is None: + return [] + + out = [] + for obj in list: + policy_delivery = PolicyDelivery.from_json( + obj, target_policy_delivery, supported_delivery_types) + # Drop entries with null values. + if policy_delivery.value is None: + continue + out.append(policy_delivery) + return out + + @classmethod + def from_json(cls, obj, target_policy_delivery, supported_delivery_types): + # type: (dict, PolicyDelivery, typing.List[str]) -> PolicyDelivery + ''' + Parses a JSON object `obj` and returns a `PolicyDelivery` object. + In addition to dicts (in the same format as to_json() outputs), + this method accepts the following placeholders: + "policy": + `target_policy_delivery` + "policyIfNonNull": + `target_policy_delivery` if its value is not None. + "anotherPolicy": + A PolicyDelivery that has the same key as + `target_policy_delivery` but a different value. + The delivery type is selected from `supported_delivery_types`. + + Can raise `ShouldSkip`. + ''' + + if obj == "policy": + policy_delivery = target_policy_delivery + elif obj == "nonNullPolicy": + if target_policy_delivery.value is None: + raise ShouldSkip() + policy_delivery = target_policy_delivery + elif obj == "anotherPolicy": + if len(supported_delivery_types) == 0: + raise ShouldSkip() + policy_delivery = target_policy_delivery.get_another_policy( + supported_delivery_types[0]) + elif isinstance(obj, dict): + policy_delivery = PolicyDelivery(obj['deliveryType'], obj['key'], + obj['value']) + else: + raise Exception('policy delivery is invalid: ' + obj) + + # Omit unsupported combinations of source contexts and delivery type. + if policy_delivery.delivery_type not in supported_delivery_types: + raise ShouldSkip() + + return policy_delivery + + def to_json(self): + # type: () -> dict + return { + "deliveryType": self.delivery_type, + "key": self.key, + "value": self.value + } + + def get_another_policy(self, delivery_type): + # type: (str) -> PolicyDelivery + if self.key == 'referrerPolicy': + # Return 'unsafe-url' (i.e. more unsafe policy than `self.value`) + # as long as possible, to make sure the tests to fail if the + # returned policy is used unexpectedly instead of `self.value`. + # Using safer policy wouldn't be distinguishable from acceptable + # arbitrary policy enforcement by user agents, as specified at + # Step 7 of + # https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer: + # "The user agent MAY alter referrerURL or referrerOrigin at this + # point to enforce arbitrary policy considerations in the + # interests of minimizing data leakage." + # See also the comments at `referrerUrlResolver` in + # `wpt/referrer-policy/generic/test-case.sub.js`. + if self.value != 'unsafe-url': + return PolicyDelivery(delivery_type, self.key, 'unsafe-url') + else: + return PolicyDelivery(delivery_type, self.key, 'no-referrer') + elif self.key == 'mixedContent': + if self.value == 'opt-in': + return PolicyDelivery(delivery_type, self.key, None) + else: + return PolicyDelivery(delivery_type, self.key, 'opt-in') + elif self.key == 'contentSecurityPolicy': + if self.value is not None: + return PolicyDelivery(delivery_type, self.key, None) + else: + return PolicyDelivery(delivery_type, self.key, 'worker-src-none') + elif self.key == 'upgradeInsecureRequests': + if self.value == 'upgrade': + return PolicyDelivery(delivery_type, self.key, None) + else: + return PolicyDelivery(delivery_type, self.key, 'upgrade') + else: + raise Exception('delivery key is invalid: ' + self.key) + + +class SourceContext(object): + def __init__(self, source_context_type, policy_deliveries): + # type: (unicode, typing.List[PolicyDelivery]) -> None + self.source_context_type = source_context_type + self.policy_deliveries = policy_deliveries + + def __eq__(self, other): + return type(self) is type(other) and self.__dict__ == other.__dict__ + + @classmethod + def from_json(cls, obj, target_policy_delivery, source_context_schema): + ''' + Parses a JSON object `obj` and returns a `SourceContext` object. + + `target_policy_delivery` and `source_context_schema` are used for + policy delivery placeholders and filtering out unsupported + delivery types. + + Can raise `ShouldSkip`. + ''' + source_context_type = obj.get('sourceContextType') + policy_deliveries = PolicyDelivery.list_from_json( + obj.get('policyDeliveries'), target_policy_delivery, + source_context_schema['supported_delivery_type'] + [source_context_type]) + return SourceContext(source_context_type, policy_deliveries) + + def to_json(self): + return { + "sourceContextType": self.source_context_type, + "policyDeliveries": [x.to_json() for x in self.policy_deliveries] + } + + +class CustomEncoder(json.JSONEncoder): + ''' + Used to dump dicts containing `SourceContext`/`PolicyDelivery` into JSON. + ''' + def default(self, obj): + if isinstance(obj, SourceContext): + return obj.to_json() + if isinstance(obj, PolicyDelivery): + return obj.to_json() + return json.JSONEncoder.default(self, obj) diff --git a/test/wpt/tests/common/security-features/types.md b/test/wpt/tests/common/security-features/types.md new file mode 100644 index 0000000..1707991 --- /dev/null +++ b/test/wpt/tests/common/security-features/types.md @@ -0,0 +1,62 @@ +# Types around the generator and generated tests + +This document describes types and concepts used across JavaScript and Python parts of this test framework. +Please refer to the JSDoc in `common.sub.js` or docstrings in Python scripts (if any). + +## Scenario + +### Properties + +- All keys of `test_expansion_schema` in `spec.src.json`, except for `expansion`, `delivery_type`, `delivery_value`, and `source_context_list`. Their values are **string**s specified in `test_expansion_schema`. +- `source_context_list` +- `subresource_policy_deliveries` + +### Types + +- Generator (`spec.src.json`): JSON object +- Generator (Python): `dict` +- Runtime (JS): JSON object +- Runtime (Python): N/A + +## `PolicyDelivery` + +### Types + +- Generator (`spec.src.json`): JSON object +- Generator (Python): `util.PolicyDelivery` +- Runtime (JS): JSON object (`@typedef PolicyDelivery` in `common.sub.js`) +- Runtime (Python): N/A + +## `SourceContext` + +Subresource requests can be possibly sent from various kinds of fetch client's environment settings objects. For example: + +- top-level windows, +- ` diff --git a/test/wpt/tests/fetch/api/abort/general.any.js b/test/wpt/tests/fetch/api/abort/general.any.js new file mode 100644 index 0000000..3727bb4 --- /dev/null +++ b/test/wpt/tests/fetch/api/abort/general.any.js @@ -0,0 +1,572 @@ +// META: timeout=long +// META: global=window,worker +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=../request/request-error.js + +const BODY_METHODS = ['arrayBuffer', 'blob', 'formData', 'json', 'text']; + +const error1 = new Error('error1'); +error1.name = 'error1'; + +// This is used to close connections that weren't correctly closed during the tests, +// otherwise you can end up running out of HTTP connections. +let requestAbortKeys = []; + +function abortRequests() { + const keys = requestAbortKeys; + requestAbortKeys = []; + return Promise.all( + keys.map(key => fetch(`../resources/stash-put.py?key=${key}&value=close`)) + ); +} + +const hostInfo = get_host_info(); +const urlHostname = hostInfo.REMOTE_HOST; + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + const fetchPromise = fetch('../resources/data.json', { signal }); + + await promise_rejects_dom(t, "AbortError", fetchPromise); +}, "Aborting rejects with AbortError"); + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(error1); + + const fetchPromise = fetch('../resources/data.json', { signal }); + + await promise_rejects_exactly(t, error1, fetchPromise, 'fetch() should reject with abort reason'); +}, "Aborting rejects with abort reason"); + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + const url = new URL('../resources/data.json', location); + url.hostname = urlHostname; + + const fetchPromise = fetch(url, { + signal, + mode: 'no-cors' + }); + + await promise_rejects_dom(t, "AbortError", fetchPromise); +}, "Aborting rejects with AbortError - no-cors"); + +// Test that errors thrown from the request constructor take priority over abort errors. +// badRequestArgTests is from response-error.js +for (const { args, testName } of badRequestArgTests) { + promise_test(async t => { + try { + // If this doesn't throw, we'll effectively skip the test. + // It'll fail properly in ../request/request-error.html + new Request(...args); + } + catch (err) { + const controller = new AbortController(); + controller.abort(); + + // Add signal to 2nd arg + args[1] = args[1] || {}; + args[1].signal = controller.signal; + await promise_rejects_js(t, TypeError, fetch(...args)); + } + }, `TypeError from request constructor takes priority - ${testName}`); +} + +test(() => { + const request = new Request(''); + assert_true(Boolean(request.signal), "Signal member is present & truthy"); + assert_equals(request.signal.constructor, AbortSignal); +}, "Request objects have a signal property"); + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + const request = new Request('../resources/data.json', { signal }); + + assert_true(Boolean(request.signal), "Signal member is present & truthy"); + assert_equals(request.signal.constructor, AbortSignal); + assert_not_equals(request.signal, signal, 'Request has a new signal, not a reference'); + assert_true(request.signal.aborted, `Request's signal has aborted`); + + const fetchPromise = fetch(request); + + await promise_rejects_dom(t, "AbortError", fetchPromise); +}, "Signal on request object"); + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(error1); + + const request = new Request('../resources/data.json', { signal }); + + assert_not_equals(request.signal, signal, 'Request has a new signal, not a reference'); + assert_true(request.signal.aborted, `Request's signal has aborted`); + assert_equals(request.signal.reason, error1, `Request's signal's abort reason is error1`); + + const fetchPromise = fetch(request); + + await promise_rejects_exactly(t, error1, fetchPromise, "fetch() should reject with abort reason"); +}, "Signal on request object should also have abort reason"); + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + const request = new Request('../resources/data.json', { signal }); + const requestFromRequest = new Request(request); + + const fetchPromise = fetch(requestFromRequest); + + await promise_rejects_dom(t, "AbortError", fetchPromise); +}, "Signal on request object created from request object"); + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + const request = new Request('../resources/data.json'); + const requestFromRequest = new Request(request, { signal }); + + const fetchPromise = fetch(requestFromRequest); + + await promise_rejects_dom(t, "AbortError", fetchPromise); +}, "Signal on request object created from request object, with signal on second request"); + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + const request = new Request('../resources/data.json', { signal: new AbortController().signal }); + const requestFromRequest = new Request(request, { signal }); + + const fetchPromise = fetch(requestFromRequest); + + await promise_rejects_dom(t, "AbortError", fetchPromise); +}, "Signal on request object created from request object, with signal on second request overriding another"); + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + const request = new Request('../resources/data.json', { signal }); + + const fetchPromise = fetch(request, {method: 'POST'}); + + await promise_rejects_dom(t, "AbortError", fetchPromise); +}, "Signal retained after unrelated properties are overridden by fetch"); + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + const request = new Request('../resources/data.json', { signal }); + + const data = await fetch(request, { signal: null }).then(r => r.json()); + assert_equals(data.key, 'value', 'Fetch fully completes'); +}, "Signal removed by setting to null"); + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + const log = []; + + await Promise.all([ + fetch('../resources/data.json', { signal }).then( + () => assert_unreached("Fetch must not resolve"), + () => log.push('fetch-reject') + ), + Promise.resolve().then(() => log.push('next-microtask')) + ]); + + assert_array_equals(log, ['fetch-reject', 'next-microtask']); +}, "Already aborted signal rejects immediately"); + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + const request = new Request('../resources/data.json', { + signal, + method: 'POST', + body: 'foo', + headers: { 'Content-Type': 'text/plain' } + }); + + await fetch(request).catch(() => {}); + + assert_true(request.bodyUsed, "Body has been used"); +}, "Request is still 'used' if signal is aborted before fetching"); + +for (const bodyMethod of BODY_METHODS) { + promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + + const log = []; + const response = await fetch('../resources/data.json', { signal }); + + controller.abort(); + + const bodyPromise = response[bodyMethod](); + + await Promise.all([ + bodyPromise.catch(() => log.push(`${bodyMethod}-reject`)), + Promise.resolve().then(() => log.push('next-microtask')) + ]); + + await promise_rejects_dom(t, "AbortError", bodyPromise); + + assert_array_equals(log, [`${bodyMethod}-reject`, 'next-microtask']); + }, `response.${bodyMethod}() rejects if already aborted`); +} + +promise_test(async (t) => { + const controller = new AbortController(); + const signal = controller.signal; + + const res = await fetch('../resources/data.json', { signal }); + controller.abort(); + + await promise_rejects_dom(t, 'AbortError', res.text()); + await promise_rejects_dom(t, 'AbortError', res.text()); +}, 'Call text() twice on aborted response'); + +promise_test(async t => { + await abortRequests(); + + const controller = new AbortController(); + const signal = controller.signal; + const stateKey = token(); + const abortKey = token(); + requestAbortKeys.push(abortKey); + controller.abort(); + + await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal }).catch(() => {}); + + // I'm hoping this will give the browser enough time to (incorrectly) make the request + // above, if it intends to. + await fetch('../resources/data.json').then(r => r.json()); + + const response = await fetch(`../resources/stash-take.py?key=${stateKey}`); + const data = await response.json(); + + assert_equals(data, null, "Request hasn't been made to the server"); +}, "Already aborted signal does not make request"); + +promise_test(async t => { + await abortRequests(); + + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + const fetches = []; + + for (let i = 0; i < 3; i++) { + const abortKey = token(); + requestAbortKeys.push(abortKey); + + fetches.push( + fetch(`../resources/infinite-slow-response.py?${i}&abortKey=${abortKey}`, { signal }) + ); + } + + for (const fetchPromise of fetches) { + await promise_rejects_dom(t, "AbortError", fetchPromise); + } +}, "Already aborted signal can be used for many fetches"); + +promise_test(async t => { + await abortRequests(); + + const controller = new AbortController(); + const signal = controller.signal; + + await fetch('../resources/data.json', { signal }).then(r => r.json()); + + controller.abort(); + + const fetches = []; + + for (let i = 0; i < 3; i++) { + const abortKey = token(); + requestAbortKeys.push(abortKey); + + fetches.push( + fetch(`../resources/infinite-slow-response.py?${i}&abortKey=${abortKey}`, { signal }) + ); + } + + for (const fetchPromise of fetches) { + await promise_rejects_dom(t, "AbortError", fetchPromise); + } +}, "Signal can be used to abort other fetches, even if another fetch succeeded before aborting"); + +promise_test(async t => { + await abortRequests(); + + const controller = new AbortController(); + const signal = controller.signal; + const stateKey = token(); + const abortKey = token(); + requestAbortKeys.push(abortKey); + + await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal }); + + const beforeAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json()); + assert_equals(beforeAbortResult, "open", "Connection is open"); + + controller.abort(); + + // The connection won't close immediately, but it should close at some point: + const start = Date.now(); + + while (true) { + // Stop spinning if 10 seconds have passed + if (Date.now() - start > 10000) throw Error('Timed out'); + + const afterAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json()); + if (afterAbortResult == 'closed') break; + } +}, "Underlying connection is closed when aborting after receiving response"); + +promise_test(async t => { + await abortRequests(); + + const controller = new AbortController(); + const signal = controller.signal; + const stateKey = token(); + const abortKey = token(); + requestAbortKeys.push(abortKey); + + const url = new URL(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, location); + url.hostname = urlHostname; + + await fetch(url, { + signal, + mode: 'no-cors' + }); + + const stashTakeURL = new URL(`../resources/stash-take.py?key=${stateKey}`, location); + stashTakeURL.hostname = urlHostname; + + const beforeAbortResult = await fetch(stashTakeURL).then(r => r.json()); + assert_equals(beforeAbortResult, "open", "Connection is open"); + + controller.abort(); + + // The connection won't close immediately, but it should close at some point: + const start = Date.now(); + + while (true) { + // Stop spinning if 10 seconds have passed + if (Date.now() - start > 10000) throw Error('Timed out'); + + const afterAbortResult = await fetch(stashTakeURL).then(r => r.json()); + if (afterAbortResult == 'closed') break; + } +}, "Underlying connection is closed when aborting after receiving response - no-cors"); + +for (const bodyMethod of BODY_METHODS) { + promise_test(async t => { + await abortRequests(); + + const controller = new AbortController(); + const signal = controller.signal; + const stateKey = token(); + const abortKey = token(); + requestAbortKeys.push(abortKey); + + const response = await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal }); + + const beforeAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json()); + assert_equals(beforeAbortResult, "open", "Connection is open"); + + const bodyPromise = response[bodyMethod](); + + controller.abort(); + + await promise_rejects_dom(t, "AbortError", bodyPromise); + + const start = Date.now(); + + while (true) { + // Stop spinning if 10 seconds have passed + if (Date.now() - start > 10000) throw Error('Timed out'); + + const afterAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json()); + if (afterAbortResult == 'closed') break; + } + }, `Fetch aborted & connection closed when aborted after calling response.${bodyMethod}()`); +} + +promise_test(async t => { + await abortRequests(); + + const controller = new AbortController(); + const signal = controller.signal; + const stateKey = token(); + const abortKey = token(); + requestAbortKeys.push(abortKey); + + const response = await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal }); + const reader = response.body.getReader(); + + controller.abort(); + + await promise_rejects_dom(t, "AbortError", reader.read()); + await promise_rejects_dom(t, "AbortError", reader.closed); + + // The connection won't close immediately, but it should close at some point: + const start = Date.now(); + + while (true) { + // Stop spinning if 10 seconds have passed + if (Date.now() - start > 10000) throw Error('Timed out'); + + const afterAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json()); + if (afterAbortResult == 'closed') break; + } +}, "Stream errors once aborted. Underlying connection closed."); + +promise_test(async t => { + await abortRequests(); + + const controller = new AbortController(); + const signal = controller.signal; + const stateKey = token(); + const abortKey = token(); + requestAbortKeys.push(abortKey); + + const response = await fetch(`../resources/infinite-slow-response.py?stateKey=${stateKey}&abortKey=${abortKey}`, { signal }); + const reader = response.body.getReader(); + + await reader.read(); + + controller.abort(); + + await promise_rejects_dom(t, "AbortError", reader.read()); + await promise_rejects_dom(t, "AbortError", reader.closed); + + // The connection won't close immediately, but it should close at some point: + const start = Date.now(); + + while (true) { + // Stop spinning if 10 seconds have passed + if (Date.now() - start > 10000) throw Error('Timed out'); + + const afterAbortResult = await fetch(`../resources/stash-take.py?key=${stateKey}`).then(r => r.json()); + if (afterAbortResult == 'closed') break; + } +}, "Stream errors once aborted, after reading. Underlying connection closed."); + +promise_test(async t => { + await abortRequests(); + + const controller = new AbortController(); + const signal = controller.signal; + + const response = await fetch(`../resources/empty.txt`, { signal }); + + // Read whole response to ensure close signal has sent. + await response.clone().text(); + + const reader = response.body.getReader(); + + controller.abort(); + + const item = await reader.read(); + + assert_true(item.done, "Stream is done"); +}, "Stream will not error if body is empty. It's closed with an empty queue before it errors."); + +promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + let cancelReason; + + const body = new ReadableStream({ + pull(controller) { + controller.enqueue(new Uint8Array([42])); + }, + cancel(reason) { + cancelReason = reason; + } + }); + + const fetchPromise = fetch('../resources/empty.txt', { + body, signal, + method: 'POST', + duplex: 'half', + headers: { + 'Content-Type': 'text/plain' + } + }); + + assert_true(!!cancelReason, 'Cancel called sync'); + assert_equals(cancelReason.constructor, DOMException); + assert_equals(cancelReason.name, 'AbortError'); + + await promise_rejects_dom(t, "AbortError", fetchPromise); + + const fetchErr = await fetchPromise.catch(e => e); + + assert_equals(cancelReason, fetchErr, "Fetch rejects with same error instance"); +}, "Readable stream synchronously cancels with AbortError if aborted before reading"); + +test(() => { + const controller = new AbortController(); + const signal = controller.signal; + controller.abort(); + + const request = new Request('.', { signal }); + const requestSignal = request.signal; + + const clonedRequest = request.clone(); + + assert_equals(requestSignal, request.signal, "Original request signal the same after cloning"); + assert_true(request.signal.aborted, "Original request signal aborted"); + assert_not_equals(clonedRequest.signal, request.signal, "Cloned request has different signal"); + assert_true(clonedRequest.signal.aborted, "Cloned request signal aborted"); +}, "Signal state is cloned"); + +test(() => { + const controller = new AbortController(); + const signal = controller.signal; + + const request = new Request('.', { signal }); + const clonedRequest = request.clone(); + + const log = []; + + request.signal.addEventListener('abort', () => log.push('original-aborted')); + clonedRequest.signal.addEventListener('abort', () => log.push('clone-aborted')); + + controller.abort(); + + assert_array_equals(log, ['original-aborted', 'clone-aborted'], "Abort events fired in correct order"); + assert_true(request.signal.aborted, 'Signal aborted'); + assert_true(clonedRequest.signal.aborted, 'Signal aborted'); +}, "Clone aborts with original controller"); diff --git a/test/wpt/tests/fetch/api/abort/keepalive.html b/test/wpt/tests/fetch/api/abort/keepalive.html new file mode 100644 index 0000000..db12df0 --- /dev/null +++ b/test/wpt/tests/fetch/api/abort/keepalive.html @@ -0,0 +1,85 @@ + + + + + + + + diff --git a/test/wpt/tests/fetch/api/abort/request.any.js b/test/wpt/tests/fetch/api/abort/request.any.js new file mode 100644 index 0000000..dcc7803 --- /dev/null +++ b/test/wpt/tests/fetch/api/abort/request.any.js @@ -0,0 +1,85 @@ +// META: timeout=long +// META: global=window,worker + +const BODY_FUNCTION_AND_DATA = { + arrayBuffer: null, + blob: null, + formData: new FormData(), + json: new Blob(["{}"]), + text: null, +}; + +for (const [bodyFunction, body] of Object.entries(BODY_FUNCTION_AND_DATA)) { + promise_test(async () => { + const controller = new AbortController(); + const signal = controller.signal; + const request = new Request("../resources/data.json", { + method: "post", + signal, + body, + }); + + controller.abort(); + await request[bodyFunction](); + assert_true( + true, + `An aborted request should still be able to run ${bodyFunction}()` + ); + }, `Calling ${bodyFunction}() on an aborted request`); + + promise_test(async () => { + const controller = new AbortController(); + const signal = controller.signal; + const request = new Request("../resources/data.json", { + method: "post", + signal, + body, + }); + + const p = request[bodyFunction](); + controller.abort(); + await p; + assert_true( + true, + `An aborted request should still be able to run ${bodyFunction}()` + ); + }, `Aborting a request after calling ${bodyFunction}()`); + + if (!body) { + promise_test(async () => { + const controller = new AbortController(); + const signal = controller.signal; + const request = new Request("../resources/data.json", { + method: "post", + signal, + body, + }); + + // consuming happens synchronously, so don't wait + fetch(request).catch(() => {}); + + controller.abort(); + await request[bodyFunction](); + assert_true( + true, + `An aborted consumed request should still be able to run ${bodyFunction}() when empty` + ); + }, `Calling ${bodyFunction}() on an aborted consumed empty request`); + } + + promise_test(async t => { + const controller = new AbortController(); + const signal = controller.signal; + const request = new Request("../resources/data.json", { + method: "post", + signal, + body: body || new Blob(["foo"]), + }); + + // consuming happens synchronously, so don't wait + fetch(request).catch(() => {}); + + controller.abort(); + await promise_rejects_js(t, TypeError, request[bodyFunction]()); + }, `Calling ${bodyFunction}() on an aborted consumed nonempty request`); +} diff --git a/test/wpt/tests/fetch/api/abort/serviceworker-intercepted.https.html b/test/wpt/tests/fetch/api/abort/serviceworker-intercepted.https.html new file mode 100644 index 0000000..ed9bc97 --- /dev/null +++ b/test/wpt/tests/fetch/api/abort/serviceworker-intercepted.https.html @@ -0,0 +1,212 @@ + + + + + Aborting fetch when intercepted by a service worker + + + + + + + + diff --git a/test/wpt/tests/fetch/api/basic/accept-header.any.js b/test/wpt/tests/fetch/api/basic/accept-header.any.js new file mode 100644 index 0000000..cd54cf2 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/accept-header.any.js @@ -0,0 +1,34 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +promise_test(function() { + return fetch(RESOURCES_DIR + "inspect-headers.py?headers=Accept").then(function(response) { + assert_equals(response.status, 200, "HTTP status is 200"); + assert_equals(response.type , "basic", "Response's type is basic"); + assert_equals(response.headers.get("x-request-accept"), "*/*", "Request has accept header with value '*/*'"); + }); +}, "Request through fetch should have 'accept' header with value '*/*'"); + +promise_test(function() { + return fetch(RESOURCES_DIR + "inspect-headers.py?headers=Accept", {"headers": [["Accept", "custom/*"]]}).then(function(response) { + assert_equals(response.status, 200, "HTTP status is 200"); + assert_equals(response.type , "basic", "Response's type is basic"); + assert_equals(response.headers.get("x-request-accept"), "custom/*", "Request has accept header with value 'custom/*'"); + }); +}, "Request through fetch should have 'accept' header with value 'custom/*'"); + +promise_test(function() { + return fetch(RESOURCES_DIR + "inspect-headers.py?headers=Accept-Language").then(function(response) { + assert_equals(response.status, 200, "HTTP status is 200"); + assert_equals(response.type , "basic", "Response's type is basic"); + assert_true(response.headers.has("x-request-accept-language")); + }); +}, "Request through fetch should have a 'accept-language' header"); + +promise_test(function() { + return fetch(RESOURCES_DIR + "inspect-headers.py?headers=Accept-Language", {"headers": [["Accept-Language", "bzh"]]}).then(function(response) { + assert_equals(response.status, 200, "HTTP status is 200"); + assert_equals(response.type , "basic", "Response's type is basic"); + assert_equals(response.headers.get("x-request-accept-language"), "bzh", "Request has accept header with value 'bzh'"); + }); +}, "Request through fetch should have 'accept-language' header with value 'bzh'"); diff --git a/test/wpt/tests/fetch/api/basic/block-mime-as-script.html b/test/wpt/tests/fetch/api/basic/block-mime-as-script.html new file mode 100644 index 0000000..afc2bbb --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/block-mime-as-script.html @@ -0,0 +1,43 @@ + + +Block mime type as script + + +
+ diff --git a/test/wpt/tests/fetch/api/basic/conditional-get.any.js b/test/wpt/tests/fetch/api/basic/conditional-get.any.js new file mode 100644 index 0000000..2f9fa81 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/conditional-get.any.js @@ -0,0 +1,38 @@ +// META: title=Request ETag +// META: global=window,worker +// META: script=/common/utils.js + +promise_test(function() { + var cacheBuster = token(); // ensures first request is uncached + var url = "../resources/cache.py?v=" + cacheBuster; + var etag; + + // make the first request + return fetch(url).then(function(response) { + // ensure we're getting the regular, uncached response + assert_equals(response.status, 200); + assert_equals(response.headers.get("X-HTTP-STATUS"), null) + + return response.text(); // consuming the body, just to be safe + }).then(function(body) { + // make a second request + return fetch(url); + }).then(function(response) { + // while the server responds with 304 if our browser sent the correct + // If-None-Match request header, at the JavaScript level this surfaces + // as 200 + assert_equals(response.status, 200); + assert_equals(response.headers.get("X-HTTP-STATUS"), "304") + + etag = response.headers.get("ETag") + + return response.text(); // consuming the body, just to be safe + }).then(function(body) { + // make a third request, explicitly setting If-None-Match request header + var headers = { "If-None-Match": etag } + return fetch(url, { headers: headers }) + }).then(function(response) { + // 304 now surfaces thanks to the explicit If-None-Match request header + assert_equals(response.status, 304); + }); +}, "Testing conditional GET with ETags"); diff --git a/test/wpt/tests/fetch/api/basic/error-after-response.any.js b/test/wpt/tests/fetch/api/basic/error-after-response.any.js new file mode 100644 index 0000000..f711442 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/error-after-response.any.js @@ -0,0 +1,24 @@ +// META: title=Fetch: network timeout after receiving the HTTP response headers +// META: global=window,worker +// META: timeout=long +// META: script=../resources/utils.js + +function checkReader(test, reader, promiseToTest) +{ + return reader.read().then((value) => { + validateBufferFromString(value.value, "TEST_CHUNK", "Should receive first chunk"); + return promise_rejects_js(test, TypeError, promiseToTest(reader)); + }); +} + +promise_test((test) => { + return fetch("../resources/bad-chunk-encoding.py?count=1").then((response) => { + return checkReader(test, response.body.getReader(), reader => reader.read()); + }); +}, "Response reader read() promise should reject after a network error happening after resolving fetch promise"); + +promise_test((test) => { + return fetch("../resources/bad-chunk-encoding.py?count=1").then((response) => { + return checkReader(test, response.body.getReader(), reader => reader.closed); + }); +}, "Response reader closed promise should reject after a network error happening after resolving fetch promise"); diff --git a/test/wpt/tests/fetch/api/basic/header-value-combining.any.js b/test/wpt/tests/fetch/api/basic/header-value-combining.any.js new file mode 100644 index 0000000..bb70d87 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/header-value-combining.any.js @@ -0,0 +1,15 @@ +// META: global=window,worker + +[ + ["content-length", "0", "header-content-length"], + ["content-length", "0, 0", "header-content-length-twice"], + ["double-trouble", ", ", "headers-double-empty"], + ["foo-test", "1, 2, 3", "headers-basic"], + ["heya", ", \u000B\u000C, 1, , , 2", "headers-some-are-empty"], + ["www-authenticate", "1, 2, 3, 4", "headers-www-authenticate"], +].forEach(testValues => { + promise_test(async t => { + const response = await fetch("../../../xhr/resources/" + testValues[2] + ".asis"); + assert_equals(response.headers.get(testValues[0]), testValues[1]); + }, "response.headers.get('" + testValues[0] + "') expects " + testValues[1]); +}); diff --git a/test/wpt/tests/fetch/api/basic/header-value-null-byte.any.js b/test/wpt/tests/fetch/api/basic/header-value-null-byte.any.js new file mode 100644 index 0000000..741d83b --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/header-value-null-byte.any.js @@ -0,0 +1,5 @@ +// META: global=window,worker + +promise_test(t => { + return promise_rejects_js(t, TypeError, fetch("../../../xhr/resources/parse-headers.py?my-custom-header="+encodeURIComponent("x\0x"))); +}, "Ensure fetch() rejects null bytes in headers"); diff --git a/test/wpt/tests/fetch/api/basic/historical.any.js b/test/wpt/tests/fetch/api/basic/historical.any.js new file mode 100644 index 0000000..c808126 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/historical.any.js @@ -0,0 +1,17 @@ +// META: global=window,worker + +test(() => { + assert_false("getAll" in new Headers()); + assert_false("getAll" in Headers.prototype); +}, "Headers object no longer has a getAll() method"); + +test(() => { + assert_false("type" in new Request("about:blank")); + assert_false("type" in Request.prototype); +}, "'type' getter should not exist on Request objects"); + +// See https://github.com/whatwg/fetch/pull/979 for the removal +test(() => { + assert_false("trailer" in new Response()); + assert_false("trailer" in Response.prototype); +}, "Response object no longer has a trailer getter"); diff --git a/test/wpt/tests/fetch/api/basic/http-response-code.any.js b/test/wpt/tests/fetch/api/basic/http-response-code.any.js new file mode 100644 index 0000000..1fd312a --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/http-response-code.any.js @@ -0,0 +1,14 @@ +// META: global=window,worker +// META: script=../resources/utils.js +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js + +promise_test(async (test) => { + const resp = await fetch( + "/fetch/connection-pool/resources/network-partition-key.py?" + + `status=425&uuid=${token()}&partition_id=${get_host_info().ORIGIN}` + + `&dispatch=check_partition&addcounter=true`); + assert_equals(resp.status, 425); + const text = await resp.text(); + assert_equals(text, "ok. Request was sent 1 times. 1 connections were created."); +}, "Fetch on 425 response should not be retried for non TLS early data."); diff --git a/test/wpt/tests/fetch/api/basic/integrity.sub.any.js b/test/wpt/tests/fetch/api/basic/integrity.sub.any.js new file mode 100644 index 0000000..e3cfd1b --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/integrity.sub.any.js @@ -0,0 +1,87 @@ +// META: global=window,dedicatedworker,sharedworker +// META: script=../resources/utils.js + +function integrity(desc, url, integrity, initRequestMode, shouldPass) { + var fetchRequestInit = {'integrity': integrity} + if (!!initRequestMode && initRequestMode !== "") { + fetchRequestInit.mode = initRequestMode; + } + + if (shouldPass) { + promise_test(function(test) { + return fetch(url, fetchRequestInit).then(function(resp) { + if (initRequestMode !== "no-cors") { + assert_equals(resp.status, 200, "Response's status is 200"); + } else { + assert_equals(resp.status, 0, "Opaque response's status is 0"); + assert_equals(resp.type, "opaque"); + } + }); + }, desc); + } else { + promise_test(function(test) { + return promise_rejects_js(test, TypeError, fetch(url, fetchRequestInit)); + }, desc); + } +} + +const topSha256 = "sha256-KHIDZcXnR2oBHk9DrAA+5fFiR6JjudYjqoXtMR1zvzk="; +const topSha384 = "sha384-MgZYnnAzPM/MjhqfOIMfQK5qcFvGZsGLzx4Phd7/A8fHTqqLqXqKo8cNzY3xEPTL"; +const topSha512 = "sha512-D6yns0qxG0E7+TwkevZ4Jt5t7Iy3ugmAajG/dlf6Pado1JqTyneKXICDiqFIkLMRExgtvg8PlxbKTkYfRejSOg=="; +const topSha512wrongpadding = "sha512-D6yns0qxG0E7+TwkevZ4Jt5t7Iy3ugmAajG/dlf6Pado1JqTyneKXICDiqFIkLMRExgtvg8PlxbKTkYfRejSOg"; +const topSha512base64url = "sha512-D6yns0qxG0E7-TwkevZ4Jt5t7Iy3ugmAajG_dlf6Pado1JqTyneKXICDiqFIkLMRExgtvg8PlxbKTkYfRejSOg=="; +const topSha512base64url_nopadding = "sha512-D6yns0qxG0E7-TwkevZ4Jt5t7Iy3ugmAajG_dlf6Pado1JqTyneKXICDiqFIkLMRExgtvg8PlxbKTkYfRejSOg"; +const invalidSha256 = "sha256-dKUcPOn/AlUjWIwcHeHNqYXPlvyGiq+2dWOdFcE+24I="; +const invalidSha512 = "sha512-oUceBRNxPxnY60g/VtPCj2syT4wo4EZh2CgYdWy9veW8+OsReTXoh7dizMGZafvx9+QhMS39L/gIkxnPIn41Zg=="; + +const path = dirname(location.pathname) + RESOURCES_DIR + "top.txt"; +const url = path; +const corsUrl = + `http://{{host}}:{{ports[http][1]}}${path}?pipe=header(Access-Control-Allow-Origin,*)`; +const corsUrl2 = `https://{{host}}:{{ports[https][0]}}${path}` + +integrity("Empty string integrity", url, "", /* initRequestMode */ undefined, + /* shouldPass */ true); +integrity("SHA-256 integrity", url, topSha256, /* initRequestMode */ undefined, + /* shouldPass */ true); +integrity("SHA-384 integrity", url, topSha384, /* initRequestMode */ undefined, + /* shouldPass */ true); +integrity("SHA-512 integrity", url, topSha512, /* initRequestMode */ undefined, + /* shouldPass */ true); +integrity("SHA-512 integrity with missing padding", url, topSha512wrongpadding, + /* initRequestMode */ undefined, /* shouldPass */ true); +integrity("SHA-512 integrity base64url encoded", url, topSha512base64url, + /* initRequestMode */ undefined, /* shouldPass */ true); +integrity("SHA-512 integrity base64url encoded with missing padding", url, + topSha512base64url_nopadding, /* initRequestMode */ undefined, + /* shouldPass */ true); +integrity("Invalid integrity", url, invalidSha256, + /* initRequestMode */ undefined, /* shouldPass */ false); +integrity("Multiple integrities: valid stronger than invalid", url, + invalidSha256 + " " + topSha384, /* initRequestMode */ undefined, + /* shouldPass */ true); +integrity("Multiple integrities: invalid stronger than valid", + url, invalidSha512 + " " + topSha384, /* initRequestMode */ undefined, + /* shouldPass */ false); +integrity("Multiple integrities: invalid as strong as valid", url, + invalidSha512 + " " + topSha512, /* initRequestMode */ undefined, + /* shouldPass */ true); +integrity("Multiple integrities: both are valid", url, + topSha384 + " " + topSha512, /* initRequestMode */ undefined, + /* shouldPass */ true); +integrity("Multiple integrities: both are invalid", url, + invalidSha256 + " " + invalidSha512, /* initRequestMode */ undefined, + /* shouldPass */ false); +integrity("CORS empty integrity", corsUrl, "", /* initRequestMode */ undefined, + /* shouldPass */ true); +integrity("CORS SHA-512 integrity", corsUrl, topSha512, + /* initRequestMode */ undefined, /* shouldPass */ true); +integrity("CORS invalid integrity", corsUrl, invalidSha512, + /* initRequestMode */ undefined, /* shouldPass */ false); + +integrity("Empty string integrity for opaque response", corsUrl2, "", + /* initRequestMode */ "no-cors", /* shouldPass */ true); +integrity("SHA-* integrity for opaque response", corsUrl2, topSha512, + /* initRequestMode */ "no-cors", /* shouldPass */ false); + +done(); diff --git a/test/wpt/tests/fetch/api/basic/keepalive.any.js b/test/wpt/tests/fetch/api/basic/keepalive.any.js new file mode 100644 index 0000000..899d41d --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/keepalive.any.js @@ -0,0 +1,43 @@ +// META: global=window +// META: title=Fetch API: keepalive handling +// META: script=/resources/testharness.js +// META: script=/resources/testharnessreport.js +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=../resources/keepalive-helper.js + +'use strict'; + +const { + HTTP_NOTSAMESITE_ORIGIN, + HTTP_REMOTE_ORIGIN, + HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT +} = get_host_info(); + +/** + * In a different-site iframe, test to fetch a keepalive URL on the specified + * document event. + */ +function keepaliveSimpleRequestTest(method) { + for (const evt of ['load', 'pagehide', 'unload']) { + const desc = + `[keepalive] simple ${method} request on '${evt}' [no payload]`; + promise_test(async (test) => { + const token1 = token(); + const iframe = document.createElement('iframe'); + iframe.src = getKeepAliveIframeUrl(token1, method, {sendOn: evt}); + document.body.appendChild(iframe); + await iframeLoaded(iframe); + if (evt != 'load') { + iframe.remove(); + } + assert_equals(await getTokenFromMessage(), token1); + + assertStashedTokenAsync(desc, token1); + }, `${desc}; setting up`); + } +} + +for (const method of ['GET', 'POST']) { + keepaliveSimpleRequestTest(method); +} diff --git a/test/wpt/tests/fetch/api/basic/mediasource.window.js b/test/wpt/tests/fetch/api/basic/mediasource.window.js new file mode 100644 index 0000000..1f89595 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/mediasource.window.js @@ -0,0 +1,5 @@ +promise_test(t => { + const mediaSource = new MediaSource(), + mediaSourceURL = URL.createObjectURL(mediaSource); + return promise_rejects_js(t, TypeError, fetch(mediaSourceURL)); +}, "Cannot fetch blob: URL from a MediaSource"); diff --git a/test/wpt/tests/fetch/api/basic/mode-no-cors.sub.any.js b/test/wpt/tests/fetch/api/basic/mode-no-cors.sub.any.js new file mode 100644 index 0000000..a4abcac --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/mode-no-cors.sub.any.js @@ -0,0 +1,29 @@ +// META: script=../resources/utils.js + +function fetchNoCors(url, isOpaqueFiltered) { + var urlQuery = "?pipe=header(x-is-filtered,value)" + promise_test(function(test) { + if (isOpaqueFiltered) + return fetch(url + urlQuery, {"mode": "no-cors"}).then(function(resp) { + assert_equals(resp.status, 0, "Opaque filter: status is 0"); + assert_equals(resp.statusText, "", "Opaque filter: statusText is \"\""); + assert_equals(resp.url, "", "Opaque filter: url is \"\""); + assert_equals(resp.type , "opaque", "Opaque filter: response's type is opaque"); + assert_equals(resp.headers.get("x-is-filtered"), null, "Header x-is-filtered is filtered"); + }); + else + return fetch(url + urlQuery, {"mode": "no-cors"}).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type , "basic", "Response's type is basic"); + assert_equals(resp.headers.get("x-is-filtered"), "value", "Header x-is-filtered is not filtered"); + }); + }, "Fetch "+ url + " with no-cors mode"); +} + +fetchNoCors(RESOURCES_DIR + "top.txt", false); +fetchNoCors("http://{{host}}:{{ports[http][0]}}/fetch/api/resources/top.txt", false); +fetchNoCors("https://{{host}}:{{ports[https][0]}}/fetch/api/resources/top.txt", true); +fetchNoCors("http://{{host}}:{{ports[http][1]}}/fetch/api/resources/top.txt", true); + +done(); + diff --git a/test/wpt/tests/fetch/api/basic/mode-same-origin.any.js b/test/wpt/tests/fetch/api/basic/mode-same-origin.any.js new file mode 100644 index 0000000..1457702 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/mode-same-origin.any.js @@ -0,0 +1,28 @@ +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +function fetchSameOrigin(url, shouldPass) { + promise_test(function(test) { + if (shouldPass) + return fetch(url , {"mode": "same-origin"}).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type, "basic", "response type is basic"); + }); + else + return promise_rejects_js(test, TypeError, fetch(url, {mode: "same-origin"})); + }, "Fetch "+ url + " with same-origin mode"); +} + +var host_info = get_host_info(); + +fetchSameOrigin(RESOURCES_DIR + "top.txt", true); +fetchSameOrigin(host_info.HTTP_ORIGIN + "/fetch/api/resources/top.txt", true); +fetchSameOrigin(host_info.HTTPS_ORIGIN + "/fetch/api/resources/top.txt", false); +fetchSameOrigin(host_info.HTTP_REMOTE_ORIGIN + "/fetch/api/resources/top.txt", false); + +var redirPath = dirname(location.pathname) + RESOURCES_DIR + "redirect.py?location="; + +fetchSameOrigin(redirPath + RESOURCES_DIR + "top.txt", true); +fetchSameOrigin(redirPath + host_info.HTTP_ORIGIN + "/fetch/api/resources/top.txt", true); +fetchSameOrigin(redirPath + host_info.HTTPS_ORIGIN + "/fetch/api/resources/top.txt", false); +fetchSameOrigin(redirPath + host_info.HTTP_REMOTE_ORIGIN + "/fetch/api/resources/top.txt", false); diff --git a/test/wpt/tests/fetch/api/basic/referrer.any.js b/test/wpt/tests/fetch/api/basic/referrer.any.js new file mode 100644 index 0000000..85745e6 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/referrer.any.js @@ -0,0 +1,29 @@ +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +function runTest(url, init, expectedReferrer, title) { + promise_test(function(test) { + url += (url.indexOf('?') !== -1 ? '&' : '?') + "headers=referer&cors"; + + return fetch(url , init).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.headers.get("x-request-referer"), expectedReferrer, "Request's referrer is correct"); + }); + }, title); +} + +var fetchedUrl = RESOURCES_DIR + "inspect-headers.py"; +var corsFetchedUrl = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "inspect-headers.py"; +var redirectUrl = RESOURCES_DIR + "redirect.py?location=" ; +var corsRedirectUrl = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "redirect.py?location="; + +runTest(fetchedUrl, { referrerPolicy: "origin-when-cross-origin"}, location.toString(), "origin-when-cross-origin policy on a same-origin URL"); +runTest(corsFetchedUrl, { referrerPolicy: "origin-when-cross-origin"}, get_host_info().HTTP_ORIGIN + "/", "origin-when-cross-origin policy on a cross-origin URL"); +runTest(redirectUrl + corsFetchedUrl, { referrerPolicy: "origin-when-cross-origin"}, get_host_info().HTTP_ORIGIN + "/", "origin-when-cross-origin policy on a cross-origin URL after same-origin redirection"); +runTest(corsRedirectUrl + fetchedUrl, { referrerPolicy: "origin-when-cross-origin"}, get_host_info().HTTP_ORIGIN + "/", "origin-when-cross-origin policy on a same-origin URL after cross-origin redirection"); + + +var referrerUrlWithCredentials = get_host_info().HTTP_ORIGIN.replace("http://", "http://username:password@"); +runTest(fetchedUrl, {referrer: referrerUrlWithCredentials}, get_host_info().HTTP_ORIGIN + "/", "Referrer with credentials should be stripped"); +var referrerUrlWithFragmentIdentifier = get_host_info().HTTP_ORIGIN + "#fragmentIdentifier"; +runTest(fetchedUrl, {referrer: referrerUrlWithFragmentIdentifier}, get_host_info().HTTP_ORIGIN + "/", "Referrer with fragment ID should be stripped"); diff --git a/test/wpt/tests/fetch/api/basic/request-forbidden-headers.any.js b/test/wpt/tests/fetch/api/basic/request-forbidden-headers.any.js new file mode 100644 index 0000000..511ce60 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/request-forbidden-headers.any.js @@ -0,0 +1,100 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +function requestForbiddenHeaders(desc, forbiddenHeaders) { + var url = RESOURCES_DIR + "inspect-headers.py"; + var requestInit = {"headers": forbiddenHeaders} + var urlParameters = "?headers=" + Object.keys(forbiddenHeaders).join("|"); + + promise_test(function(test){ + return fetch(url + urlParameters, requestInit).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type , "basic", "Response's type is basic"); + for (var header in forbiddenHeaders) + assert_not_equals(resp.headers.get("x-request-" + header), forbiddenHeaders[header], header + " does not have the value we defined"); + }); + }, desc); +} + +function requestValidOverrideHeaders(desc, validHeaders) { + var url = RESOURCES_DIR + "inspect-headers.py"; + var requestInit = {"headers": validHeaders} + var urlParameters = "?headers=" + Object.keys(validHeaders).join("|"); + + promise_test(function(test){ + return fetch(url + urlParameters, requestInit).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type , "basic", "Response's type is basic"); + for (var header in validHeaders) + assert_equals(resp.headers.get("x-request-" + header), validHeaders[header], header + "is not skipped for non-forbidden methods"); + }); + }, desc); +} + +requestForbiddenHeaders("Accept-Charset is a forbidden request header", {"Accept-Charset": "utf-8"}); +requestForbiddenHeaders("Accept-Encoding is a forbidden request header", {"Accept-Encoding": ""}); + +requestForbiddenHeaders("Access-Control-Request-Headers is a forbidden request header", {"Access-Control-Request-Headers": ""}); +requestForbiddenHeaders("Access-Control-Request-Method is a forbidden request header", {"Access-Control-Request-Method": ""}); +requestForbiddenHeaders( + 'Access-Control-Request-Private-Network is a forbidden request header', + {'Access-Control-Request-Private-Network': ''}); +requestForbiddenHeaders("Connection is a forbidden request header", {"Connection": "close"}); +requestForbiddenHeaders("Content-Length is a forbidden request header", {"Content-Length": "42"}); +requestForbiddenHeaders("Cookie is a forbidden request header", {"Cookie": "cookie=none"}); +requestForbiddenHeaders("Cookie2 is a forbidden request header", {"Cookie2": "cookie2=none"}); +requestForbiddenHeaders("Date is a forbidden request header", {"Date": "Wed, 04 May 1988 22:22:22 GMT"}); +requestForbiddenHeaders("DNT is a forbidden request header", {"DNT": "4"}); +requestForbiddenHeaders("Expect is a forbidden request header", {"Expect": "100-continue"}); +requestForbiddenHeaders("Host is a forbidden request header", {"Host": "http://wrong-host.com"}); +requestForbiddenHeaders("Keep-Alive is a forbidden request header", {"Keep-Alive": "timeout=15"}); +requestForbiddenHeaders("Origin is a forbidden request header", {"Origin": "http://wrong-origin.com"}); +requestForbiddenHeaders("Referer is a forbidden request header", {"Referer": "http://wrong-referer.com"}); +requestForbiddenHeaders("TE is a forbidden request header", {"TE": "trailers"}); +requestForbiddenHeaders("Trailer is a forbidden request header", {"Trailer": "Accept"}); +requestForbiddenHeaders("Transfer-Encoding is a forbidden request header", {"Transfer-Encoding": "chunked"}); +requestForbiddenHeaders("Upgrade is a forbidden request header", {"Upgrade": "HTTP/2.0"}); +requestForbiddenHeaders("Via is a forbidden request header", {"Via": "1.1 nowhere.com"}); +requestForbiddenHeaders("Proxy- is a forbidden request header", {"Proxy-": "value"}); +requestForbiddenHeaders("Proxy-Test is a forbidden request header", {"Proxy-Test": "value"}); +requestForbiddenHeaders("Sec- is a forbidden request header", {"Sec-": "value"}); +requestForbiddenHeaders("Sec-Test is a forbidden request header", {"Sec-Test": "value"}); + +let forbiddenMethods = [ + "TRACE", + "TRACK", + "CONNECT", + "trace", + "track", + "connect", + "trace,", + "GET,track ", + " connect", +]; + +let overrideHeaders = [ + "x-http-method-override", + "x-http-method", + "x-method-override", + "X-HTTP-METHOD-OVERRIDE", + "X-HTTP-METHOD", + "X-METHOD-OVERRIDE", +]; + +for (forbiddenMethod of forbiddenMethods) { + for (overrideHeader of overrideHeaders) { + requestForbiddenHeaders(`header ${overrideHeader} is forbidden to use value ${forbiddenMethod}`, {[overrideHeader]: forbiddenMethod}); + } +} + +let permittedValues = [ + "GETTRACE", + "GET", + "\",TRACE\",", +]; + +for (permittedValue of permittedValues) { + for (overrideHeader of overrideHeaders) { + requestValidOverrideHeaders(`header ${overrideHeader} is allowed to use value ${permittedValue}`, {[overrideHeader]: permittedValue}); + } +} diff --git a/test/wpt/tests/fetch/api/basic/request-head.any.js b/test/wpt/tests/fetch/api/basic/request-head.any.js new file mode 100644 index 0000000..e0b6afa --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/request-head.any.js @@ -0,0 +1,6 @@ +// META: global=window,worker + +promise_test(function(test) { + var requestInit = {"method": "HEAD", "body": "test"}; + return promise_rejects_js(test, TypeError, fetch(".", requestInit)); +}, "Fetch with HEAD with body"); diff --git a/test/wpt/tests/fetch/api/basic/request-headers-case.any.js b/test/wpt/tests/fetch/api/basic/request-headers-case.any.js new file mode 100644 index 0000000..4c10e71 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/request-headers-case.any.js @@ -0,0 +1,13 @@ +// META: global=window,worker + +promise_test(() => { + return fetch("/xhr/resources/echo-headers.py", {headers: [["THIS-is-A-test", 1], ["THIS-IS-A-TEST", 2]] }).then(res => res.text()).then(body => { + assert_regexp_match(body, /THIS-is-A-test: 1, 2/) + }) +}, "Multiple headers with the same name, different case (THIS-is-A-test first)") + +promise_test(() => { + return fetch("/xhr/resources/echo-headers.py", {headers: [["THIS-IS-A-TEST", 1], ["THIS-is-A-test", 2]] }).then(res => res.text()).then(body => { + assert_regexp_match(body, /THIS-IS-A-TEST: 1, 2/) + }) +}, "Multiple headers with the same name, different case (THIS-IS-A-TEST first)") diff --git a/test/wpt/tests/fetch/api/basic/request-headers-nonascii.any.js b/test/wpt/tests/fetch/api/basic/request-headers-nonascii.any.js new file mode 100644 index 0000000..4a9a801 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/request-headers-nonascii.any.js @@ -0,0 +1,29 @@ +// META: global=window,worker + +// This tests characters that are not +// https://infra.spec.whatwg.org/#ascii-code-point +// but are still +// https://infra.spec.whatwg.org/#byte-value +// in request header values. +// Such request header values are valid and thus sent to servers. +// Characters outside the #byte-value range are tested e.g. in +// fetch/api/headers/headers-errors.html. + +promise_test(() => { + return fetch( + "../resources/inspect-headers.py?headers=accept|x-test", + {headers: { + "Accept": "before-æøå-after", + "X-Test": "before-ß-after" + }}) + .then(res => { + assert_equals( + res.headers.get("x-request-accept"), + "before-æøå-after", + "Accept Header"); + assert_equals( + res.headers.get("x-request-x-test"), + "before-ß-after", + "X-Test Header"); + }); +}, "Non-ascii bytes in request headers"); diff --git a/test/wpt/tests/fetch/api/basic/request-headers.any.js b/test/wpt/tests/fetch/api/basic/request-headers.any.js new file mode 100644 index 0000000..ac54256 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/request-headers.any.js @@ -0,0 +1,82 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +function checkContentType(contentType, body) +{ + if (self.FormData && body instanceof self.FormData) { + assert_true(contentType.startsWith("multipart/form-data; boundary="), "Request should have header content-type starting with multipart/form-data; boundary=, but got " + contentType); + return; + } + + var expectedContentType = "text/plain;charset=UTF-8"; + if(body === null || body instanceof ArrayBuffer || body.buffer instanceof ArrayBuffer) + expectedContentType = null; + else if (body instanceof Blob) + expectedContentType = body.type ? body.type : null; + else if (body instanceof URLSearchParams) + expectedContentType = "application/x-www-form-urlencoded;charset=UTF-8"; + + assert_equals(contentType , expectedContentType, "Request should have header content-type: " + expectedContentType); +} + +function requestHeaders(desc, url, method, body, expectedOrigin, expectedContentLength) { + var urlParameters = "?headers=origin|user-agent|accept-charset|content-length|content-type"; + var requestInit = {"method": method} + promise_test(function(test){ + if (typeof body === "function") + body = body(); + if (body) + requestInit["body"] = body; + return fetch(url + urlParameters, requestInit).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type , "basic", "Response's type is basic"); + assert_true(resp.headers.has("x-request-user-agent"), "Request has header user-agent"); + assert_false(resp.headers.has("accept-charset"), "Request has header accept-charset"); + assert_equals(resp.headers.get("x-request-origin") , expectedOrigin, "Request should have header origin: " + expectedOrigin); + if (expectedContentLength !== undefined) + assert_equals(resp.headers.get("x-request-content-length") , expectedContentLength, "Request should have header content-length: " + expectedContentLength); + checkContentType(resp.headers.get("x-request-content-type"), body); + }); + }, desc); +} + +var url = RESOURCES_DIR + "inspect-headers.py" + +requestHeaders("Fetch with GET", url, "GET", null, null, null); +requestHeaders("Fetch with HEAD", url, "HEAD", null, null, null); +requestHeaders("Fetch with PUT without body", url, "POST", null, location.origin, "0"); +requestHeaders("Fetch with PUT with body", url, "PUT", "Request's body", location.origin, "14"); +requestHeaders("Fetch with POST without body", url, "POST", null, location.origin, "0"); +requestHeaders("Fetch with POST with text body", url, "POST", "Request's body", location.origin, "14"); +requestHeaders("Fetch with POST with FormData body", url, "POST", function() { return new FormData(); }, location.origin); +requestHeaders("Fetch with POST with URLSearchParams body", url, "POST", function() { return new URLSearchParams("name=value"); }, location.origin, "10"); +requestHeaders("Fetch with POST with Blob body", url, "POST", new Blob(["Test"]), location.origin, "4"); +requestHeaders("Fetch with POST with ArrayBuffer body", url, "POST", new ArrayBuffer(4), location.origin, "4"); +requestHeaders("Fetch with POST with Uint8Array body", url, "POST", new Uint8Array(4), location.origin, "4"); +requestHeaders("Fetch with POST with Int8Array body", url, "POST", new Int8Array(4), location.origin, "4"); +requestHeaders("Fetch with POST with Float32Array body", url, "POST", new Float32Array(1), location.origin, "4"); +requestHeaders("Fetch with POST with Float64Array body", url, "POST", new Float64Array(1), location.origin, "8"); +requestHeaders("Fetch with POST with DataView body", url, "POST", new DataView(new ArrayBuffer(8), 0, 4), location.origin, "4"); +requestHeaders("Fetch with POST with Blob body with mime type", url, "POST", new Blob(["Test"], { type: "text/maybe" }), location.origin, "4"); +requestHeaders("Fetch with Chicken", url, "Chicken", null, location.origin, null); +requestHeaders("Fetch with Chicken with body", url, "Chicken", "Request's body", location.origin, "14"); + +function requestOriginHeader(method, mode, needsOrigin) { + promise_test(function(test){ + return fetch(url + "?headers=origin", {method:method, mode:mode}).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type , "basic", "Response's type is basic"); + if(needsOrigin) + assert_equals(resp.headers.get("x-request-origin") , location.origin, "Request should have an Origin header with origin: " + location.origin); + else + assert_equals(resp.headers.get("x-request-origin"), null, "Request should not have an Origin header") + }); + }, "Fetch with " + method + " and mode \"" + mode + "\" " + (needsOrigin ? "needs" : "does not need") + " an Origin header"); +} + +requestOriginHeader("GET", "cors", false); +requestOriginHeader("POST", "same-origin", true); +requestOriginHeader("POST", "no-cors", true); +requestOriginHeader("PUT", "same-origin", true); +requestOriginHeader("TacO", "same-origin", true); +requestOriginHeader("TacO", "cors", true); diff --git a/test/wpt/tests/fetch/api/basic/request-referrer-redirected-worker.html b/test/wpt/tests/fetch/api/basic/request-referrer-redirected-worker.html new file mode 100644 index 0000000..bdea1e1 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/request-referrer-redirected-worker.html @@ -0,0 +1,17 @@ + + + + + Fetch in worker: referrer header + + + + + + + diff --git a/test/wpt/tests/fetch/api/basic/request-referrer.any.js b/test/wpt/tests/fetch/api/basic/request-referrer.any.js new file mode 100644 index 0000000..0c33576 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/request-referrer.any.js @@ -0,0 +1,24 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +function testReferrer(referrer, expected, desc) { + promise_test(function(test) { + var url = RESOURCES_DIR + "inspect-headers.py?headers=referer" + var req = new Request(url, { referrer: referrer }); + return fetch(req).then(function(resp) { + var actual = resp.headers.get("x-request-referer"); + if (expected) { + assert_equals(actual, expected, "request's referer should be: " + expected); + return; + } + if (actual) { + assert_equals(actual, "", "request's referer should be empty"); + } + }); + }, desc); +} + +testReferrer("about:client", self.location.href, 'about:client referrer'); + +var fooURL = new URL("./foo", self.location).href; +testReferrer(fooURL, fooURL, 'url referrer'); diff --git a/test/wpt/tests/fetch/api/basic/request-upload.any.js b/test/wpt/tests/fetch/api/basic/request-upload.any.js new file mode 100644 index 0000000..9168aa1 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/request-upload.any.js @@ -0,0 +1,135 @@ +// META: global=window,worker +// META: script=../resources/utils.js +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js + +function testUpload(desc, url, method, createBody, expectedBody) { + const requestInit = {method}; + promise_test(function(test){ + const body = createBody(); + if (body) { + requestInit["body"] = body; + requestInit.duplex = "half"; + } + return fetch(url, requestInit).then(function(resp) { + return resp.text().then((text)=> { + assert_equals(text, expectedBody); + }); + }); + }, desc); +} + +function testUploadFailure(desc, url, method, createBody) { + const requestInit = {method}; + promise_test(t => { + const body = createBody(); + if (body) { + requestInit["body"] = body; + } + return promise_rejects_js(t, TypeError, fetch(url, requestInit)); + }, desc); +} + +const url = RESOURCES_DIR + "echo-content.py" + +testUpload("Fetch with PUT with body", url, + "PUT", + () => "Request's body", + "Request's body"); +testUpload("Fetch with POST with text body", url, + "POST", + () => "Request's body", + "Request's body"); +testUpload("Fetch with POST with URLSearchParams body", url, + "POST", + () => new URLSearchParams("name=value"), + "name=value"); +testUpload("Fetch with POST with Blob body", url, + "POST", + () => new Blob(["Test"]), + "Test"); +testUpload("Fetch with POST with ArrayBuffer body", url, + "POST", + () => new ArrayBuffer(4), + "\0\0\0\0"); +testUpload("Fetch with POST with Uint8Array body", url, + "POST", + () => new Uint8Array(4), + "\0\0\0\0"); +testUpload("Fetch with POST with Int8Array body", url, + "POST", + () => new Int8Array(4), + "\0\0\0\0"); +testUpload("Fetch with POST with Float32Array body", url, + "POST", + () => new Float32Array(1), + "\0\0\0\0"); +testUpload("Fetch with POST with Float64Array body", url, + "POST", + () => new Float64Array(1), + "\0\0\0\0\0\0\0\0"); +testUpload("Fetch with POST with DataView body", url, + "POST", + () => new DataView(new ArrayBuffer(8), 0, 4), + "\0\0\0\0"); +testUpload("Fetch with POST with Blob body with mime type", url, + "POST", + () => new Blob(["Test"], { type: "text/maybe" }), + "Test"); + +testUploadFailure("Fetch with POST with ReadableStream containing String", url, + "POST", + () => { + return new ReadableStream({start: controller => { + controller.enqueue("Test"); + controller.close(); + }}) + }); +testUploadFailure("Fetch with POST with ReadableStream containing null", url, + "POST", + () => { + return new ReadableStream({start: controller => { + controller.enqueue(null); + controller.close(); + }}) + }); +testUploadFailure("Fetch with POST with ReadableStream containing number", url, + "POST", + () => { + return new ReadableStream({start: controller => { + controller.enqueue(99); + controller.close(); + }}) + }); +testUploadFailure("Fetch with POST with ReadableStream containing ArrayBuffer", url, + "POST", + () => { + return new ReadableStream({start: controller => { + controller.enqueue(new ArrayBuffer()); + controller.close(); + }}) + }); +testUploadFailure("Fetch with POST with ReadableStream containing Blob", url, + "POST", + () => { + return new ReadableStream({start: controller => { + controller.enqueue(new Blob()); + controller.close(); + }}) + }); + +promise_test(async (test) => { + const resp = await fetch( + "/fetch/connection-pool/resources/network-partition-key.py?" + + `status=421&uuid=${token()}&partition_id=${get_host_info().ORIGIN}` + + `&dispatch=check_partition&addcounter=true`, + {method: "POST", body: "foobar"}); + assert_equals(resp.status, 421); + const text = await resp.text(); + assert_equals(text, "ok. Request was sent 2 times. 2 connections were created."); +}, "Fetch with POST with text body on 421 response should be retried once on new connection."); + +promise_test(async (test) => { + const body = new ReadableStream({start: c => c.close()}); + await promise_rejects_js(test, TypeError, fetch('/', {method: 'POST', body})); +}, "Streaming upload shouldn't work on Http/1.1."); diff --git a/test/wpt/tests/fetch/api/basic/request-upload.h2.any.js b/test/wpt/tests/fetch/api/basic/request-upload.h2.any.js new file mode 100644 index 0000000..eedc2bf --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/request-upload.h2.any.js @@ -0,0 +1,186 @@ +// META: global=window,worker +// META: script=../resources/utils.js +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js + +const duplex = "half"; + +async function assertUpload(url, method, createBody, expectedBody) { + const requestInit = {method}; + const body = createBody(); + if (body) { + requestInit["body"] = body; + requestInit.duplex = "half"; + } + const resp = await fetch(url, requestInit); + const text = await resp.text(); + assert_equals(text, expectedBody); +} + +function testUpload(desc, url, method, createBody, expectedBody) { + promise_test(async () => { + await assertUpload(url, method, createBody, expectedBody); + }, desc); +} + +function createStream(chunks) { + return new ReadableStream({ + start: (controller) => { + for (const chunk of chunks) { + controller.enqueue(chunk); + } + controller.close(); + } + }); +} + +const url = RESOURCES_DIR + "echo-content.h2.py" + +testUpload("Fetch with POST with empty ReadableStream", url, + "POST", + () => { + return new ReadableStream({start: controller => { + controller.close(); + }}) + }, + ""); + +testUpload("Fetch with POST with ReadableStream", url, + "POST", + () => { + return new ReadableStream({start: controller => { + const encoder = new TextEncoder(); + controller.enqueue(encoder.encode("Test")); + controller.close(); + }}) + }, + "Test"); + +promise_test(async (test) => { + const body = new ReadableStream({start: controller => { + const encoder = new TextEncoder(); + controller.enqueue(encoder.encode("Test")); + controller.close(); + }}); + const resp = await fetch( + "/fetch/connection-pool/resources/network-partition-key.py?" + + `status=421&uuid=${token()}&partition_id=${self.origin}` + + `&dispatch=check_partition&addcounter=true`, + {method: "POST", body: body, duplex}); + assert_equals(resp.status, 421); + const text = await resp.text(); + assert_equals(text, "ok. Request was sent 1 times. 1 connections were created."); +}, "Fetch with POST with ReadableStream on 421 response should return the response and not retry."); + +promise_test(async (test) => { + const request = new Request('', { + body: new ReadableStream(), + method: 'POST', + duplex, + }); + + assert_equals(request.headers.get('Content-Type'), null, `Request should not have a content-type set`); + + const response = await fetch('data:a/a;charset=utf-8,test', { + method: 'POST', + body: new ReadableStream(), + duplex, + }); + + assert_equals(await response.text(), 'test', `Response has correct body`); +}, "Feature detect for POST with ReadableStream"); + +promise_test(async (test) => { + const request = new Request('data:a/a;charset=utf-8,test', { + body: new ReadableStream(), + method: 'POST', + duplex, + }); + + assert_equals(request.headers.get('Content-Type'), null, `Request should not have a content-type set`); + const response = await fetch(request); + assert_equals(await response.text(), 'test', `Response has correct body`); +}, "Feature detect for POST with ReadableStream, using request object"); + +test(() => { + let duplexAccessed = false; + + const request = new Request("", { + body: new ReadableStream(), + method: "POST", + get duplex() { + duplexAccessed = true; + return "half"; + }, + }); + + assert_equals( + request.headers.get("Content-Type"), + null, + `Request should not have a content-type set` + ); + assert_true(duplexAccessed, `duplex dictionary property should be accessed`); +}, "Synchronous feature detect"); + +// The asserts the synchronousFeatureDetect isn't broken by a partial implementation. +// An earlier feature detect was broken by Safari implementing streaming bodies as part of Request, +// but it failed when passed to fetch(). +// This tests ensures that UAs must not implement RequestInit.duplex and streaming request bodies without also implementing the fetch() parts. +promise_test(async () => { + let duplexAccessed = false; + + const request = new Request("", { + body: new ReadableStream(), + method: "POST", + get duplex() { + duplexAccessed = true; + return "half"; + }, + }); + + const supported = + request.headers.get("Content-Type") === null && duplexAccessed; + + // If the feature detect fails, assume the browser is being truthful (other tests pick up broken cases here) + if (!supported) return false; + + await assertUpload( + url, + "POST", + () => + new ReadableStream({ + start: (controller) => { + const encoder = new TextEncoder(); + controller.enqueue(encoder.encode("Test")); + controller.close(); + }, + }), + "Test" + ); +}, "Synchronous feature detect fails if feature unsupported"); + +promise_test(async (t) => { + const body = createStream(["hello"]); + const method = "POST"; + await promise_rejects_js(t, TypeError, fetch(url, { method, body, duplex })); +}, "Streaming upload with body containing a String"); + +promise_test(async (t) => { + const body = createStream([null]); + const method = "POST"; + await promise_rejects_js(t, TypeError, fetch(url, { method, body, duplex })); +}, "Streaming upload with body containing null"); + +promise_test(async (t) => { + const body = createStream([33]); + const method = "POST"; + await promise_rejects_js(t, TypeError, fetch(url, { method, body, duplex })); +}, "Streaming upload with body containing a number"); + +promise_test(async (t) => { + const url = "/fetch/api/resources/authentication.py?realm=test"; + const body = createStream([]); + const method = "POST"; + await promise_rejects_js(t, TypeError, fetch(url, { method, body, duplex })); +}, "Streaming upload should fail on a 401 response"); + diff --git a/test/wpt/tests/fetch/api/basic/response-null-body.any.js b/test/wpt/tests/fetch/api/basic/response-null-body.any.js new file mode 100644 index 0000000..bb05892 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/response-null-body.any.js @@ -0,0 +1,38 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +const nullBodyStatus = [204, 205, 304]; +const methods = ["GET", "POST", "OPTIONS"]; + +for (const status of nullBodyStatus) { + for (const method of methods) { + promise_test( + async () => { + const url = + `${RESOURCES_DIR}status.py?code=${status}&content=hello-world`; + const resp = await fetch(url, { method }); + assert_equals(resp.status, status); + assert_equals(resp.body, null, "the body should be null"); + const text = await resp.text(); + assert_equals(text, "", "null bodies result in empty text"); + }, + `Response.body is null for responses with status=${status} (method=${method})`, + ); + } +} + +promise_test(async () => { + const url = `${RESOURCES_DIR}status.py?code=200&content=hello-world`; + const resp = await fetch(url, { method: "HEAD" }); + assert_equals(resp.status, 200); + assert_equals(resp.body, null, "the body should be null"); + const text = await resp.text(); + assert_equals(text, "", "null bodies result in empty text"); +}, `Response.body is null for responses with method=HEAD`); + +promise_test(async (t) => { + const integrity = "sha384-UT6f7WCFp32YJnp1is4l/ZYnOeQKpE8xjmdkLOwZ3nIP+tmT2aMRFQGJomjVf5cE"; + const url = `${RESOURCES_DIR}status.py?code=204&content=hello-world`; + const promise = fetch(url, { method: "GET", integrity }); + promise_rejects_js(t, TypeError, promise); +}, "Null body status with subresource integrity should abort"); diff --git a/test/wpt/tests/fetch/api/basic/response-url.sub.any.js b/test/wpt/tests/fetch/api/basic/response-url.sub.any.js new file mode 100644 index 0000000..0d123c4 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/response-url.sub.any.js @@ -0,0 +1,16 @@ +function checkResponseURL(fetchedURL, expectedURL) +{ + promise_test(function() { + return fetch(fetchedURL).then(function(response) { + assert_equals(response.url, expectedURL); + }); + }, "Testing response url getter with " +fetchedURL); +} + +var baseURL = "http://{{host}}:{{ports[http][0]}}"; +checkResponseURL(baseURL + "/ada", baseURL + "/ada"); +checkResponseURL(baseURL + "/#", baseURL + "/"); +checkResponseURL(baseURL + "/#ada", baseURL + "/"); +checkResponseURL(baseURL + "#ada", baseURL + "/"); + +done(); diff --git a/test/wpt/tests/fetch/api/basic/scheme-about.any.js b/test/wpt/tests/fetch/api/basic/scheme-about.any.js new file mode 100644 index 0000000..9ef4418 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/scheme-about.any.js @@ -0,0 +1,26 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +function checkNetworkError(url, method) { + method = method || "GET"; + const desc = "Fetching " + url.substring(0, 45) + " with method " + method + " is KO" + promise_test(function(test) { + var promise = fetch(url, { method: method }); + return promise_rejects_js(test, TypeError, promise); + }, desc); +} + +checkNetworkError("about:blank", "GET"); +checkNetworkError("about:blank", "PUT"); +checkNetworkError("about:blank", "POST"); +checkNetworkError("about:invalid.com"); +checkNetworkError("about:config"); +checkNetworkError("about:unicorn"); + +promise_test(function(test) { + var promise = fetch("about:blank", { + "method": "GET", + "Range": "bytes=1-10" + }); + return promise_rejects_js(test, TypeError, promise); +}, "Fetching about:blank with range header does not affect behavior"); diff --git a/test/wpt/tests/fetch/api/basic/scheme-blob.sub.any.js b/test/wpt/tests/fetch/api/basic/scheme-blob.sub.any.js new file mode 100644 index 0000000..8afdc03 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/scheme-blob.sub.any.js @@ -0,0 +1,125 @@ +// META: script=../resources/utils.js + +function checkFetchResponse(url, data, mime, size, desc) { + promise_test(function(test) { + size = size.toString(); + return fetch(url).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type, "basic", "response type is basic"); + assert_equals(resp.headers.get("Content-Type"), mime, "Content-Type is " + resp.headers.get("Content-Type")); + assert_equals(resp.headers.get("Content-Length"), size, "Content-Length is " + resp.headers.get("Content-Length")); + return resp.text(); + }).then(function(bodyAsText) { + assert_equals(bodyAsText, data, "Response's body is " + data); + }); + }, desc); +} + +var blob = new Blob(["Blob's data"], { "type" : "text/plain" }); +checkFetchResponse(URL.createObjectURL(blob), "Blob's data", "text/plain", blob.size, + "Fetching [GET] URL.createObjectURL(blob) is OK"); + +function checkKoUrl(url, method, desc) { + promise_test(function(test) { + var promise = fetch(url, {"method": method}); + return promise_rejects_js(test, TypeError, promise); + }, desc); +} + +var blob2 = new Blob(["Blob's data"], { "type" : "text/plain" }); +checkKoUrl("blob:http://{{domains[www]}}:{{ports[http][0]}}/", "GET", + "Fetching [GET] blob:http://{{domains[www]}}:{{ports[http][0]}}/ is KO"); + +var invalidRequestMethods = [ + "POST", + "OPTIONS", + "HEAD", + "PUT", + "DELETE", + "INVALID", +]; +invalidRequestMethods.forEach(function(method) { + checkKoUrl(URL.createObjectURL(blob2), method, "Fetching [" + method + "] URL.createObjectURL(blob) is KO"); +}); + +checkKoUrl("blob:not-backed-by-a-blob/", "GET", + "Fetching [GET] blob:not-backed-by-a-blob/ is KO"); + +let empty_blob = new Blob([]); +checkFetchResponse(URL.createObjectURL(empty_blob), "", "", 0, + "Fetching URL.createObjectURL(empty_blob) is OK"); + +let empty_type_blob = new Blob([], {type: ""}); +checkFetchResponse(URL.createObjectURL(empty_type_blob), "", "", 0, + "Fetching URL.createObjectURL(empty_type_blob) is OK"); + +let empty_data_blob = new Blob([], {type: "text/plain"}); +checkFetchResponse(URL.createObjectURL(empty_data_blob), "", "text/plain", 0, + "Fetching URL.createObjectURL(empty_data_blob) is OK"); + +let invalid_type_blob = new Blob([], {type: "invalid"}); +checkFetchResponse(URL.createObjectURL(invalid_type_blob), "", "", 0, + "Fetching URL.createObjectURL(invalid_type_blob) is OK"); + +promise_test(function(test) { + return fetch("/images/blue.png").then(function(resp) { + return resp.arrayBuffer(); + }).then(function(image_buffer) { + let blob = new Blob([image_buffer]); + return fetch(URL.createObjectURL(blob)).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type, "basic", "response type is basic"); + assert_equals(resp.headers.get("Content-Type"), "", "Content-Type is " + resp.headers.get("Content-Type")); + }) + }); +}, "Blob content is not sniffed for a content type [image/png]"); + +let simple_xml_string = ''; +let xml_blob_no_type = new Blob([simple_xml_string]); +checkFetchResponse(URL.createObjectURL(xml_blob_no_type), simple_xml_string, "", 45, + "Blob content is not sniffed for a content type [text/xml]"); + +let simple_text_string = 'Hello, World!'; +promise_test(function(test) { + let blob = new Blob([simple_text_string], {"type": "text/plain"}); + let slice = blob.slice(7, simple_text_string.length, "\0"); + return fetch(URL.createObjectURL(slice)).then(function (resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type, "basic", "response type is basic"); + assert_equals(resp.headers.get("Content-Type"), ""); + assert_equals(resp.headers.get("Content-Length"), "6"); + return resp.text(); + }).then(function(bodyAsText) { + assert_equals(bodyAsText, "World!"); + }); +}, "Set content type to the empty string for slice with invalid content type"); + +promise_test(function(test) { + let blob = new Blob([simple_text_string], {"type": "text/plain"}); + let slice = blob.slice(7, simple_text_string.length, "\0"); + return fetch(URL.createObjectURL(slice)).then(function (resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type, "basic", "response type is basic"); + assert_equals(resp.headers.get("Content-Type"), ""); + assert_equals(resp.headers.get("Content-Length"), "6"); + return resp.text(); + }).then(function(bodyAsText) { + assert_equals(bodyAsText, "World!"); + }); +}, "Set content type to the empty string for slice with no content type "); + +promise_test(function(test) { + let blob = new Blob([simple_xml_string]); + let slice = blob.slice(0, 38); + return fetch(URL.createObjectURL(slice)).then(function (resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type, "basic", "response type is basic"); + assert_equals(resp.headers.get("Content-Type"), ""); + assert_equals(resp.headers.get("Content-Length"), "38"); + return resp.text(); + }).then(function(bodyAsText) { + assert_equals(bodyAsText, ''); + }); +}, "Blob.slice should not sniff the content for a content type"); + +done(); diff --git a/test/wpt/tests/fetch/api/basic/scheme-data.any.js b/test/wpt/tests/fetch/api/basic/scheme-data.any.js new file mode 100644 index 0000000..55df43b --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/scheme-data.any.js @@ -0,0 +1,43 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +function checkFetchResponse(url, data, mime, fetchMode, method) { + var cut = (url.length >= 40) ? "[...]" : ""; + var desc = "Fetching " + (method ? "[" + method + "] " : "") + url.substring(0, 40) + cut + " is OK"; + var init = {"method": method || "GET"}; + if (fetchMode) { + init.mode = fetchMode; + desc += " (" + fetchMode + ")"; + } + promise_test(function(test) { + return fetch(url, init).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.statusText, "OK", "HTTP statusText is OK"); + assert_equals(resp.type, "basic", "response type is basic"); + assert_equals(resp.headers.get("Content-Type"), mime, "Content-Type is " + resp.headers.get("Content-Type")); + return resp.text(); + }).then(function(body) { + assert_equals(body, data, "Response's body is correct"); + }); + }, desc); +} + +checkFetchResponse("data:,response%27s%20body", "response's body", "text/plain;charset=US-ASCII"); +checkFetchResponse("data:,response%27s%20body", "response's body", "text/plain;charset=US-ASCII", "same-origin"); +checkFetchResponse("data:,response%27s%20body", "response's body", "text/plain;charset=US-ASCII", "cors"); +checkFetchResponse("data:text/plain;base64,cmVzcG9uc2UncyBib2R5", "response's body", "text/plain"); +checkFetchResponse("data:image/png;base64,cmVzcG9uc2UncyBib2R5", + "response's body", + "image/png"); +checkFetchResponse("data:,response%27s%20body", "response's body", "text/plain;charset=US-ASCII", null, "POST"); +checkFetchResponse("data:,response%27s%20body", "", "text/plain;charset=US-ASCII", null, "HEAD"); + +function checkKoUrl(url, method, desc) { + var cut = (url.length >= 40) ? "[...]" : ""; + desc = "Fetching [" + method + "] " + url.substring(0, 45) + cut + " is KO" + promise_test(function(test) { + return promise_rejects_js(test, TypeError, fetch(url, {"method": method})); + }, desc); +} + +checkKoUrl("data:notAdataUrl.com", "GET"); diff --git a/test/wpt/tests/fetch/api/basic/scheme-others.sub.any.js b/test/wpt/tests/fetch/api/basic/scheme-others.sub.any.js new file mode 100644 index 0000000..550f69c --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/scheme-others.sub.any.js @@ -0,0 +1,31 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +function checkKoUrl(url, desc) { + if (!desc) + desc = "Fetching " + url.substring(0, 45) + " is KO" + promise_test(function(test) { + var promise = fetch(url); + return promise_rejects_js(test, TypeError, promise); + }, desc); +} + +var urlWithoutScheme = "://{{host}}:{{ports[http][0]}}/"; +checkKoUrl("aaa" + urlWithoutScheme); +checkKoUrl("cap" + urlWithoutScheme); +checkKoUrl("cid" + urlWithoutScheme); +checkKoUrl("dav" + urlWithoutScheme); +checkKoUrl("dict" + urlWithoutScheme); +checkKoUrl("dns" + urlWithoutScheme); +checkKoUrl("geo" + urlWithoutScheme); +checkKoUrl("im" + urlWithoutScheme); +checkKoUrl("imap" + urlWithoutScheme); +checkKoUrl("ipp" + urlWithoutScheme); +checkKoUrl("ldap" + urlWithoutScheme); +checkKoUrl("mailto" + urlWithoutScheme); +checkKoUrl("nfs" + urlWithoutScheme); +checkKoUrl("pop" + urlWithoutScheme); +checkKoUrl("rtsp" + urlWithoutScheme); +checkKoUrl("snmp" + urlWithoutScheme); + +done(); diff --git a/test/wpt/tests/fetch/api/basic/status.h2.any.js b/test/wpt/tests/fetch/api/basic/status.h2.any.js new file mode 100644 index 0000000..99fec88 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/status.h2.any.js @@ -0,0 +1,17 @@ +// See also /xhr/status.h2.window.js + +[ + 200, + 210, + 400, + 404, + 410, + 500, + 502 +].forEach(status => { + promise_test(async t => { + const response = await fetch("/xhr/resources/status.py?code=" + status); + assert_equals(response.status, status, "status should be " + status); + assert_equals(response.statusText, "", "statusText should be the empty string"); + }, "statusText over H2 for status " + status + " should be the empty string"); +}); diff --git a/test/wpt/tests/fetch/api/basic/stream-response.any.js b/test/wpt/tests/fetch/api/basic/stream-response.any.js new file mode 100644 index 0000000..d964dda --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/stream-response.any.js @@ -0,0 +1,40 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +function streamBody(reader, test, count = 0) { + return reader.read().then(function(data) { + if (!data.done && count < 2) { + count += 1; + return streamBody(reader, test, count); + } else { + test.step(function() { + assert_true(count >= 2, "Retrieve body progressively"); + }); + } + }); +} + +//simulate streaming: +//count is large enough to let the UA deliver the body before it is completely retrieved +promise_test(function(test) { + return fetch(RESOURCES_DIR + "trickle.py?ms=30&count=100").then(function(resp) { + if (resp.body) + return streamBody(resp.body.getReader(), test); + else + test.step(function() { + assert_unreached( "Body does not exist in response"); + }); + }); +}, "Stream response's body when content-type is present"); + +// This test makes sure that the response body is not buffered if no content type is provided. +promise_test(function(test) { + return fetch(RESOURCES_DIR + "trickle.py?ms=300&count=10¬ype=true").then(function(resp) { + if (resp.body) + return streamBody(resp.body.getReader(), test); + else + test.step(function() { + assert_unreached( "Body does not exist in response"); + }); + }); +}, "Stream response's body when content-type is not present"); diff --git a/test/wpt/tests/fetch/api/basic/stream-safe-creation.any.js b/test/wpt/tests/fetch/api/basic/stream-safe-creation.any.js new file mode 100644 index 0000000..382efc1 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/stream-safe-creation.any.js @@ -0,0 +1,54 @@ +// META: global=window,worker + +// These tests verify that stream creation is not affected by changes to +// Object.prototype. + +const creationCases = { + fetch: async () => fetch(location.href), + request: () => new Request(location.href, {method: 'POST', body: 'hi'}), + response: () => new Response('bye'), + consumeEmptyResponse: () => new Response().text(), + consumeNonEmptyResponse: () => new Response(new Uint8Array([64])).text(), + consumeEmptyRequest: () => new Request(location.href).text(), + consumeNonEmptyRequest: () => new Request(location.href, + {method: 'POST', body: 'yes'}).arrayBuffer(), +}; + +for (const creationCase of Object.keys(creationCases)) { + for (const accessorName of ['start', 'type', 'size', 'highWaterMark']) { + promise_test(async t => { + Object.defineProperty(Object.prototype, accessorName, { + get() { throw Error(`Object.prototype.${accessorName} was accessed`); }, + configurable: true + }); + t.add_cleanup(() => { + delete Object.prototype[accessorName]; + return Promise.resolve(); + }); + await creationCases[creationCase](); + }, `throwing Object.prototype.${accessorName} accessor should not affect ` + + `stream creation by '${creationCase}'`); + + promise_test(async t => { + // -1 is a convenient value which is invalid, and should cause the + // constructor to throw, for all four fields. + Object.prototype[accessorName] = -1; + t.add_cleanup(() => { + delete Object.prototype[accessorName]; + return Promise.resolve(); + }); + await creationCases[creationCase](); + }, `Object.prototype.${accessorName} accessor returning invalid value ` + + `should not affect stream creation by '${creationCase}'`); + } + + promise_test(async t => { + Object.prototype.start = controller => controller.error(new Error('start')); + t.add_cleanup(() => { + delete Object.prototype.start; + return Promise.resolve(); + }); + await creationCases[creationCase](); + }, `Object.prototype.start function which errors the stream should not ` + + `affect stream creation by '${creationCase}'`); +} diff --git a/test/wpt/tests/fetch/api/basic/text-utf8.any.js b/test/wpt/tests/fetch/api/basic/text-utf8.any.js new file mode 100644 index 0000000..05c8c88 --- /dev/null +++ b/test/wpt/tests/fetch/api/basic/text-utf8.any.js @@ -0,0 +1,74 @@ +// META: title=Fetch: Request and Response text() should decode as UTF-8 +// META: global=window,worker +// META: script=../resources/utils.js + +function testTextDecoding(body, expectedText, urlParameter, title) +{ + var arrayBuffer = stringToArray(body); + + promise_test(function(test) { + var request = new Request("", {method: "POST", body: arrayBuffer}); + return request.text().then(function(value) { + assert_equals(value, expectedText, "Request.text() should decode data as UTF-8"); + }); + }, title + " with Request.text()"); + + promise_test(function(test) { + var response = new Response(arrayBuffer); + return response.text().then(function(value) { + assert_equals(value, expectedText, "Response.text() should decode data as UTF-8"); + }); + }, title + " with Response.text()"); + + promise_test(function(test) { + return fetch("../resources/status.py?code=200&type=text%2Fplain%3Bcharset%3DUTF-8&content=" + urlParameter).then(function(response) { + return response.text().then(function(value) { + assert_equals(value, expectedText, "Fetched Response.text() should decode data as UTF-8"); + }); + }); + }, title + " with fetched data (UTF-8 charset)"); + + promise_test(function(test) { + return fetch("../resources/status.py?code=200&type=text%2Fplain%3Bcharset%3DUTF-16&content=" + urlParameter).then(function(response) { + return response.text().then(function(value) { + assert_equals(value, expectedText, "Fetched Response.text() should decode data as UTF-8"); + }); + }); + }, title + " with fetched data (UTF-16 charset)"); + + promise_test(function(test) { + return new Response(body).arrayBuffer().then(function(buffer) { + assert_array_equals(new Uint8Array(buffer), encode_utf8(body), "Response.arrayBuffer() should contain data encoded as UTF-8"); + }); + }, title + " (Response object)"); + + promise_test(function(test) { + return new Request("", {method: "POST", body: body}).arrayBuffer().then(function(buffer) { + assert_array_equals(new Uint8Array(buffer), encode_utf8(body), "Request.arrayBuffer() should contain data encoded as UTF-8"); + }); + }, title + " (Request object)"); + +} + +var utf8WithBOM = "\xef\xbb\xbf\xe4\xb8\x89\xe6\x9d\x91\xe3\x81\x8b\xe3\x81\xaa\xe5\xad\x90"; +var utf8WithBOMAsURLParameter = "%EF%BB%BF%E4%B8%89%E6%9D%91%E3%81%8B%E3%81%AA%E5%AD%90"; +var utf8WithoutBOM = "\xe4\xb8\x89\xe6\x9d\x91\xe3\x81\x8b\xe3\x81\xaa\xe5\xad\x90"; +var utf8WithoutBOMAsURLParameter = "%E4%B8%89%E6%9D%91%E3%81%8B%E3%81%AA%E5%AD%90"; +var utf8Decoded = "三æ‘ã‹ãªå­"; +testTextDecoding(utf8WithBOM, utf8Decoded, utf8WithBOMAsURLParameter, "UTF-8 with BOM"); +testTextDecoding(utf8WithoutBOM, utf8Decoded, utf8WithoutBOMAsURLParameter, "UTF-8 without BOM"); + +var utf16BEWithBOM = "\xfe\xff\x4e\x09\x67\x51\x30\x4b\x30\x6a\x5b\x50"; +var utf16BEWithBOMAsURLParameter = "%fe%ff%4e%09%67%51%30%4b%30%6a%5b%50"; +var utf16BEWithBOMDecodedAsUTF8 = "��N\tgQ0K0j[P"; +testTextDecoding(utf16BEWithBOM, utf16BEWithBOMDecodedAsUTF8, utf16BEWithBOMAsURLParameter, "UTF-16BE with BOM decoded as UTF-8"); + +var utf16LEWithBOM = "\xff\xfe\x09\x4e\x51\x67\x4b\x30\x6a\x30\x50\x5b"; +var utf16LEWithBOMAsURLParameter = "%ff%fe%09%4e%51%67%4b%30%6a%30%50%5b"; +var utf16LEWithBOMDecodedAsUTF8 = "��\tNQgK0j0P["; +testTextDecoding(utf16LEWithBOM, utf16LEWithBOMDecodedAsUTF8, utf16LEWithBOMAsURLParameter, "UTF-16LE with BOM decoded as UTF-8"); + +var utf16WithoutBOM = "\xe6\x00\xf8\x00\xe5\x00\x0a\x00\xc6\x30\xb9\x30\xc8\x30\x0a\x00"; +var utf16WithoutBOMAsURLParameter = "%E6%00%F8%00%E5%00%0A%00%C6%30%B9%30%C8%30%0A%00"; +var utf16WithoutBOMDecoded = "\ufffd\u0000\ufffd\u0000\ufffd\u0000\u000a\u0000\ufffd\u0030\ufffd\u0030\ufffd\u0030\u000a\u0000"; +testTextDecoding(utf16WithoutBOM, utf16WithoutBOMDecoded, utf16WithoutBOMAsURLParameter, "UTF-16 without BOM decoded as UTF-8"); diff --git a/test/wpt/tests/fetch/api/body/cloned-any.js b/test/wpt/tests/fetch/api/body/cloned-any.js new file mode 100644 index 0000000..2bca96c --- /dev/null +++ b/test/wpt/tests/fetch/api/body/cloned-any.js @@ -0,0 +1,50 @@ +// Changing the body after it have been passed to Response/Request +// should not change the outcome of the consumed body + +const url = 'http://a'; +const method = 'post'; + +promise_test(async t => { + const body = new FormData(); + body.set('a', '1'); + const res = new Response(body); + const req = new Request(url, { method, body }); + body.set('a', '2'); + assert_true((await res.formData()).get('a') === '1'); + assert_true((await req.formData()).get('a') === '1'); +}, 'FormData is cloned'); + +promise_test(async t => { + const body = new URLSearchParams({a: '1'}); + const res = new Response(body); + const req = new Request(url, { method, body }); + body.set('a', '2'); + assert_true((await res.formData()).get('a') === '1'); + assert_true((await req.formData()).get('a') === '1'); +}, 'URLSearchParams is cloned'); + +promise_test(async t => { + const body = new Uint8Array([97]); // a + const res = new Response(body); + const req = new Request(url, { method, body }); + body[0] = 98; // b + assert_true(await res.text() === 'a'); + assert_true(await req.text() === 'a'); +}, 'TypedArray is cloned'); + +promise_test(async t => { + const body = new Uint8Array([97]); // a + const res = new Response(body.buffer); + const req = new Request(url, { method, body: body.buffer }); + body[0] = 98; // b + assert_true(await res.text() === 'a'); + assert_true(await req.text() === 'a'); +}, 'ArrayBuffer is cloned'); + +promise_test(async t => { + const body = new Blob(['a']); + const res = new Response(body); + const req = new Request(url, { method, body }); + assert_true(await res.blob() !== body); + assert_true(await req.blob() !== body); +}, 'Blob is cloned'); diff --git a/test/wpt/tests/fetch/api/body/formdata.any.js b/test/wpt/tests/fetch/api/body/formdata.any.js new file mode 100644 index 0000000..e250359 --- /dev/null +++ b/test/wpt/tests/fetch/api/body/formdata.any.js @@ -0,0 +1,14 @@ +promise_test(async t => { + const res = new Response(new FormData()); + const fd = await res.formData(); + assert_true(fd instanceof FormData); +}, 'Consume empty response.formData() as FormData'); + +promise_test(async t => { + const req = new Request('about:blank', { + method: 'POST', + body: new FormData() + }); + const fd = await req.formData(); + assert_true(fd instanceof FormData); +}, 'Consume empty request.formData() as FormData'); diff --git a/test/wpt/tests/fetch/api/body/mime-type.any.js b/test/wpt/tests/fetch/api/body/mime-type.any.js new file mode 100644 index 0000000..67c9af7 --- /dev/null +++ b/test/wpt/tests/fetch/api/body/mime-type.any.js @@ -0,0 +1,127 @@ +[ + () => new Request("about:blank", { headers: { "Content-Type": "text/plain" } }), + () => new Response("", { headers: { "Content-Type": "text/plain" } }) +].forEach(bodyContainerCreator => { + const bodyContainer = bodyContainerCreator(); + promise_test(async t => { + assert_equals(bodyContainer.headers.get("Content-Type"), "text/plain"); + const newMIMEType = "test/test"; + bodyContainer.headers.set("Content-Type", newMIMEType); + const blob = await bodyContainer.blob(); + assert_equals(blob.type, newMIMEType); + }, `${bodyContainer.constructor.name}: overriding explicit Content-Type`); +}); + +[ + () => new Request("about:blank", { body: new URLSearchParams(), method: "POST" }), + () => new Response(new URLSearchParams()), +].forEach(bodyContainerCreator => { + const bodyContainer = bodyContainerCreator(); + promise_test(async t => { + assert_equals(bodyContainer.headers.get("Content-Type"), "application/x-www-form-urlencoded;charset=UTF-8"); + bodyContainer.headers.delete("Content-Type"); + const blob = await bodyContainer.blob(); + assert_equals(blob.type, ""); + }, `${bodyContainer.constructor.name}: removing implicit Content-Type`); +}); + +[ + () => new Request("about:blank", { body: new ArrayBuffer(), method: "POST" }), + () => new Response(new ArrayBuffer()), +].forEach(bodyContainerCreator => { + const bodyContainer = bodyContainerCreator(); + promise_test(async t => { + assert_equals(bodyContainer.headers.get("Content-Type"), null); + const newMIMEType = "test/test"; + bodyContainer.headers.set("Content-Type", newMIMEType); + const blob = await bodyContainer.blob(); + assert_equals(blob.type, newMIMEType); + }, `${bodyContainer.constructor.name}: setting missing Content-Type`); +}); + +[ + () => new Request("about:blank", { method: "POST" }), + () => new Response(), +].forEach(bodyContainerCreator => { + const bodyContainer = bodyContainerCreator(); + promise_test(async t => { + const blob = await bodyContainer.blob(); + assert_equals(blob.type, ""); + }, `${bodyContainer.constructor.name}: MIME type for Blob from empty body`); +}); + +[ + () => new Request("about:blank", { method: "POST", headers: [["Content-Type", "Mytext/Plain"]] }), + () => new Response("", { headers: [["Content-Type", "Mytext/Plain"]] }) +].forEach(bodyContainerCreator => { + const bodyContainer = bodyContainerCreator(); + promise_test(async t => { + const blob = await bodyContainer.blob(); + assert_equals(blob.type, 'mytext/plain'); + }, `${bodyContainer.constructor.name}: MIME type for Blob from empty body with Content-Type`); +}); + +[ + () => new Request("about:blank", { body: new Blob([""]), method: "POST" }), + () => new Response(new Blob([""])) +].forEach(bodyContainerCreator => { + const bodyContainer = bodyContainerCreator(); + promise_test(async t => { + const blob = await bodyContainer.blob(); + assert_equals(blob.type, ""); + assert_equals(bodyContainer.headers.get("Content-Type"), null); + }, `${bodyContainer.constructor.name}: MIME type for Blob`); +}); + +[ + () => new Request("about:blank", { body: new Blob([""], { type: "Text/Plain" }), method: "POST" }), + () => new Response(new Blob([""], { type: "Text/Plain" })) +].forEach(bodyContainerCreator => { + const bodyContainer = bodyContainerCreator(); + promise_test(async t => { + const blob = await bodyContainer.blob(); + assert_equals(blob.type, "text/plain"); + assert_equals(bodyContainer.headers.get("Content-Type"), "text/plain"); + }, `${bodyContainer.constructor.name}: MIME type for Blob with non-empty type`); +}); + +[ + () => new Request("about:blank", { method: "POST", body: new Blob([""], { type: "Text/Plain" }), headers: [["Content-Type", "Text/Html"]] }), + () => new Response(new Blob([""], { type: "Text/Plain" }, { headers: [["Content-Type", "Text/Html"]] })) +].forEach(bodyContainerCreator => { + const bodyContainer = bodyContainerCreator(); + const cloned = bodyContainer.clone(); + promise_test(async t => { + const blobs = [await bodyContainer.blob(), await cloned.blob()]; + assert_equals(blobs[0].type, "text/html"); + assert_equals(blobs[1].type, "text/html"); + assert_equals(bodyContainer.headers.get("Content-Type"), "Text/Html"); + assert_equals(cloned.headers.get("Content-Type"), "Text/Html"); + }, `${bodyContainer.constructor.name}: Extract a MIME type with clone`); +}); + +[ + () => new Request("about:blank", { body: new Blob([], { type: "text/plain" }), method: "POST", headers: [["Content-Type", "text/html"]] }), + () => new Response(new Blob([], { type: "text/plain" }), { headers: [["Content-Type", "text/html"]] }), +].forEach(bodyContainerCreator => { + const bodyContainer = bodyContainerCreator(); + promise_test(async t => { + assert_equals(bodyContainer.headers.get("Content-Type"), "text/html"); + const blob = await bodyContainer.blob(); + assert_equals(blob.type, "text/html"); + }, `${bodyContainer.constructor.name}: Content-Type in headers wins Blob"s type`); +}); + +[ + () => new Request("about:blank", { body: new Blob([], { type: "text/plain" }), method: "POST" }), + () => new Response(new Blob([], { type: "text/plain" })), +].forEach(bodyContainerCreator => { + const bodyContainer = bodyContainerCreator(); + promise_test(async t => { + assert_equals(bodyContainer.headers.get("Content-Type"), "text/plain"); + const newMIMEType = "text/html"; + bodyContainer.headers.set("Content-Type", newMIMEType); + const blob = await bodyContainer.blob(); + assert_equals(blob.type, newMIMEType); + }, `${bodyContainer.constructor.name}: setting missing Content-Type in headers and it wins Blob"s type`); +}); diff --git a/test/wpt/tests/fetch/api/cors/cors-basic.any.js b/test/wpt/tests/fetch/api/cors/cors-basic.any.js new file mode 100644 index 0000000..95de0af --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-basic.any.js @@ -0,0 +1,43 @@ +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +const { + HTTPS_ORIGIN, + HTTP_ORIGIN_WITH_DIFFERENT_PORT, + HTTP_REMOTE_ORIGIN, + HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT, + HTTPS_REMOTE_ORIGIN, +} = get_host_info(); + +function cors(desc, origin) { + const url = `${origin}${dirname(location.pathname)}${RESOURCES_DIR}top.txt`; + const urlAllowCors = `${url}?pipe=header(Access-Control-Allow-Origin,*)`; + + promise_test((test) => { + return fetch(urlAllowCors, {'mode': 'no-cors'}).then((resp) => { + assert_equals(resp.status, 0, "Opaque filter: status is 0"); + assert_equals(resp.statusText, "", "Opaque filter: statusText is \"\""); + assert_equals(resp.type , "opaque", "Opaque filter: response's type is opaque"); + return resp.text().then((value) => { + assert_equals(value, "", "Opaque response should have an empty body"); + }); + }); + }, `${desc} [no-cors mode]`); + + promise_test((test) => { + return promise_rejects_js(test, TypeError, fetch(url, {'mode': 'cors'})); + }, `${desc} [server forbid CORS]`); + + promise_test((test) => { + return fetch(urlAllowCors, {'mode': 'cors'}).then((resp) => { + assert_equals(resp.status, 200, "Fetch's response's status is 200"); + assert_equals(resp.type , "cors", "CORS response's type is cors"); + }); + }, `${desc} [cors mode]`); +} + +cors('Same domain different port', HTTP_ORIGIN_WITH_DIFFERENT_PORT); +cors('Same domain different protocol different port', HTTPS_ORIGIN); +cors('Cross domain basic usage', HTTP_REMOTE_ORIGIN); +cors('Cross domain different port', HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT); +cors('Cross domain different protocol', HTTPS_REMOTE_ORIGIN); diff --git a/test/wpt/tests/fetch/api/cors/cors-cookies-redirect.any.js b/test/wpt/tests/fetch/api/cors/cors-cookies-redirect.any.js new file mode 100644 index 0000000..f5217b4 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-cookies-redirect.any.js @@ -0,0 +1,49 @@ +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +var redirectUrl = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "redirect.py"; +var urlSetCookies1 = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "top.txt"; +var urlSetCookies2 = get_host_info().HTTP_ORIGIN_WITH_DIFFERENT_PORT + dirname(location.pathname) + RESOURCES_DIR + "top.txt"; +var urlCheckCookies = get_host_info().HTTP_ORIGIN_WITH_DIFFERENT_PORT + dirname(location.pathname) + RESOURCES_DIR + "inspect-headers.py?cors&headers=cookie"; + +var urlSetCookiesParameters = "?pipe=header(Access-Control-Allow-Origin," + location.origin + ")"; +urlSetCookiesParameters += "|header(Access-Control-Allow-Credentials,true)"; + +urlSetCookiesParameters1 = urlSetCookiesParameters + "|header(Set-Cookie,a=1)"; +urlSetCookiesParameters2 = urlSetCookiesParameters + "|header(Set-Cookie,a=2)"; + +urlClearCookiesParameters1 = urlSetCookiesParameters + "|header(Set-Cookie,a=1%3B%20max-age=0)"; +urlClearCookiesParameters2 = urlSetCookiesParameters + "|header(Set-Cookie,a=2%3B%20max-age=0)"; + +promise_test(async (test) => { + await fetch(urlSetCookies1 + urlSetCookiesParameters1, {"credentials": "include", "mode": "cors"}); + await fetch(urlSetCookies2 + urlSetCookiesParameters2, {"credentials": "include", "mode": "cors"}); +}, "Set cookies"); + +function doTest(usePreflight) { + promise_test(async (test) => { + var url = redirectUrl; + var uuid_token = token(); + var urlParameters = "?token=" + uuid_token + "&max_age=0"; + urlParameters += "&redirect_status=301"; + urlParameters += "&location=" + encodeURIComponent(urlCheckCookies); + urlParameters += "&allow_headers=a&headers=Cookie"; + headers = []; + if (usePreflight) + headers.push(["a", "b"]); + + var requestInit = {"credentials": "include", "mode": "cors", "headers": headers}; + var response = await fetch(url + urlParameters, requestInit); + + assert_equals(response.headers.get("x-request-cookie") , "a=2", "Request includes cookie(s)"); + }, "Testing credentials after cross-origin redirection with CORS and " + (usePreflight ? "" : "no ") + "preflight"); +} + +doTest(false); +doTest(true); + +promise_test(async (test) => { + await fetch(urlSetCookies1 + urlClearCookiesParameters1, {"credentials": "include", "mode": "cors"}); + await fetch(urlSetCookies2 + urlClearCookiesParameters2, {"credentials": "include", "mode": "cors"}); +}, "Clean cookies"); diff --git a/test/wpt/tests/fetch/api/cors/cors-cookies.any.js b/test/wpt/tests/fetch/api/cors/cors-cookies.any.js new file mode 100644 index 0000000..8c666e4 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-cookies.any.js @@ -0,0 +1,56 @@ +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +function corsCookies(desc, baseURL1, baseURL2, credentialsMode, cookies) { + var urlSetCookie = baseURL1 + dirname(location.pathname) + RESOURCES_DIR + "top.txt"; + var urlCheckCookies = baseURL2 + dirname(location.pathname) + RESOURCES_DIR + "inspect-headers.py?cors&headers=cookie"; + //enable cors with credentials + var urlParameters = "?pipe=header(Access-Control-Allow-Origin," + location.origin + ")"; + urlParameters += "|header(Access-Control-Allow-Credentials,true)"; + + var urlCleanParameters = "?pipe=header(Access-Control-Allow-Origin," + location.origin + ")"; + urlCleanParameters += "|header(Access-Control-Allow-Credentials,true)"; + if (cookies) { + urlParameters += "|header(Set-Cookie,"; + urlParameters += cookies.join(",True)|header(Set-Cookie,") + ",True)"; + urlCleanParameters += "|header(Set-Cookie,"; + urlCleanParameters += cookies.join("%3B%20max-age=0,True)|header(Set-Cookie,") + "%3B%20max-age=0,True)"; + } + + var requestInit = {"credentials": credentialsMode, "mode": "cors"}; + + promise_test(function(test){ + return fetch(urlSetCookie + urlParameters, requestInit).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + //check cookies sent + return fetch(urlCheckCookies, requestInit); + }).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_false(resp.headers.has("Cookie") , "Cookie header is not exposed in response"); + if (credentialsMode === "include" && baseURL1 === baseURL2) { + assert_equals(resp.headers.get("x-request-cookie") , cookies.join("; "), "Request includes cookie(s)"); + } + else { + assert_false(resp.headers.has("x-request-cookie") , "Request should have no cookie"); + } + //clean cookies + return fetch(urlSetCookie + urlCleanParameters, {"credentials": "include"}); + }).catch(function(e) { + return fetch(urlSetCookie + urlCleanParameters, {"credentials": "include"}).then(function(resp) { + throw e; + }) + }); + }, desc); +} + +var local = get_host_info().HTTP_ORIGIN; +var remote = get_host_info().HTTP_REMOTE_ORIGIN; +// FIXME: otherRemote might not be accessible on some test environments. +var otherRemote = local.replace("http://", "http://www."); + +corsCookies("Omit mode: no cookie sent", local, local, "omit", ["g=7"]); +corsCookies("Include mode: 1 cookie", remote, remote, "include", ["a=1"]); +corsCookies("Include mode: local cookies are not sent with remote request", local, remote, "include", ["c=3"]); +corsCookies("Include mode: remote cookies are not sent with local request", remote, local, "include", ["d=4"]); +corsCookies("Same-origin mode: cookies are discarded in cors request", remote, remote, "same-origin", ["f=6"]); +corsCookies("Include mode: remote cookies are not sent with other remote request", remote, otherRemote, "include", ["e=5"]); diff --git a/test/wpt/tests/fetch/api/cors/cors-expose-star.sub.any.js b/test/wpt/tests/fetch/api/cors/cors-expose-star.sub.any.js new file mode 100644 index 0000000..340e99a --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-expose-star.sub.any.js @@ -0,0 +1,41 @@ +// META: script=../resources/utils.js + +const url = "http://{{host}}:{{ports[http][1]}}" + dirname(location.pathname) + RESOURCES_DIR + "top.txt", + sharedHeaders = "?pipe=header(Access-Control-Expose-Headers,*)|header(Test,X)|header(Set-Cookie,X)|header(*,whoa)|" + +promise_test(() => { + const headers = "header(Access-Control-Allow-Origin,*)" + return fetch(url + sharedHeaders + headers).then(resp => { + assert_equals(resp.status, 200) + assert_equals(resp.type , "cors") + assert_equals(resp.headers.get("test"), "X") + assert_equals(resp.headers.get("set-cookie"), null) + assert_equals(resp.headers.get("*"), "whoa") + }) +}, "Basic Access-Control-Expose-Headers: * support") + +promise_test(() => { + const origin = location.origin, // assuming an ASCII origin + headers = "header(Access-Control-Allow-Origin," + origin + ")|header(Access-Control-Allow-Credentials,true)" + return fetch(url + sharedHeaders + headers, { credentials:"include" }).then(resp => { + assert_equals(resp.status, 200) + assert_equals(resp.type , "cors") + assert_equals(resp.headers.get("content-type"), "text/plain") // safelisted + assert_equals(resp.headers.get("test"), null) + assert_equals(resp.headers.get("set-cookie"), null) + assert_equals(resp.headers.get("*"), "whoa") + }) +}, "* for credentialed fetches only matches literally") + +promise_test(() => { + const headers = "header(Access-Control-Allow-Origin,*)|header(Access-Control-Expose-Headers,set-cookie\\,*)" + return fetch(url + sharedHeaders + headers).then(resp => { + assert_equals(resp.status, 200) + assert_equals(resp.type , "cors") + assert_equals(resp.headers.get("test"), "X") + assert_equals(resp.headers.get("set-cookie"), null) + assert_equals(resp.headers.get("*"), "whoa") + }) +}, "* can be one of several values") + +done(); diff --git a/test/wpt/tests/fetch/api/cors/cors-filtering.sub.any.js b/test/wpt/tests/fetch/api/cors/cors-filtering.sub.any.js new file mode 100644 index 0000000..a26eacc --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-filtering.sub.any.js @@ -0,0 +1,69 @@ +// META: script=../resources/utils.js + +function corsFilter(corsUrl, headerName, headerValue, isFiltered) { + var url = corsUrl + "?pipe=header(" + headerName + "," + encodeURIComponent(headerValue) +")|header(Access-Control-Allow-Origin,*)"; + promise_test(function(test) { + return fetch(url).then(function(resp) { + assert_equals(resp.status, 200, "Fetch success with code 200"); + assert_equals(resp.type , "cors", "CORS fetch's response has cors type"); + if (!isFiltered) { + assert_equals(resp.headers.get(headerName), headerValue, + headerName + " header should be included in response with value: " + headerValue); + } else { + assert_false(resp.headers.has(headerName), "UA should exclude " + headerName + " header from response"); + } + test.done(); + }); + }, "CORS filter on " + headerName + " header"); +} + +function corsExposeFilter(corsUrl, headerName, headerValue, isForbidden, withCredentials) { + var url = corsUrl + "?pipe=header(" + headerName + "," + encodeURIComponent(headerValue) +")|" + + "header(Access-Control-Allow-Origin, http://{{host}}:{{ports[http][0]}})" + + "header(Access-Control-Allow-Credentials, true)" + + "header(Access-Control-Expose-Headers," + headerName + ")"; + + var title = "CORS filter on " + headerName + " header, header is " + (isForbidden ? "forbidden" : "exposed"); + if (withCredentials) + title+= "(credentials = include)"; + promise_test(function(test) { + return fetch(new Request(url, { credentials: withCredentials ? "include" : "omit" })).then(function(resp) { + assert_equals(resp.status, 200, "Fetch success with code 200"); + assert_equals(resp.type , "cors", "CORS fetch's response has cors type"); + if (!isForbidden) { + assert_equals(resp.headers.get(headerName), headerValue, + headerName + " header should be included in response with value: " + headerValue); + } else { + assert_false(resp.headers.has(headerName), "UA should exclude " + headerName + " header from response"); + } + test.done(); + }); + }, title); +} + +var url = "http://{{host}}:{{ports[http][1]}}" + dirname(location.pathname) + RESOURCES_DIR + "top.txt"; + +corsFilter(url, "Cache-Control", "no-cache", false); +corsFilter(url, "Content-Language", "fr", false); +corsFilter(url, "Content-Type", "text/html", false); +corsFilter(url, "Expires","04 May 1988 22:22:22 GMT" , false); +corsFilter(url, "Last-Modified", "04 May 1988 22:22:22 GMT", false); +corsFilter(url, "Pragma", "no-cache", false); +corsFilter(url, "Content-Length", "3" , false); // top.txt contains "top" + +corsFilter(url, "Age", "27", true); +corsFilter(url, "Server", "wptServe" , true); +corsFilter(url, "Warning", "Mind the gap" , true); +corsFilter(url, "Set-Cookie", "name=value" , true); +corsFilter(url, "Set-Cookie2", "name=value" , true); + +corsExposeFilter(url, "Age", "27", false); +corsExposeFilter(url, "Server", "wptServe" , false); +corsExposeFilter(url, "Warning", "Mind the gap" , false); + +corsExposeFilter(url, "Set-Cookie", "name=value" , true); +corsExposeFilter(url, "Set-Cookie2", "name=value" , true); +corsExposeFilter(url, "Set-Cookie", "name=value" , true, true); +corsExposeFilter(url, "Set-Cookie2", "name=value" , true, true); + +done(); diff --git a/test/wpt/tests/fetch/api/cors/cors-keepalive.any.js b/test/wpt/tests/fetch/api/cors/cors-keepalive.any.js new file mode 100644 index 0000000..f68d90e --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-keepalive.any.js @@ -0,0 +1,118 @@ +// META: global=window +// META: timeout=long +// META: title=Fetch API: keepalive handling +// META: script=/resources/testharness.js +// META: script=/resources/testharnessreport.js +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=../resources/keepalive-helper.js +// META: script=../resources/utils.js + +'use strict'; + +const { + HTTP_NOTSAMESITE_ORIGIN, + HTTPS_ORIGIN, + HTTP_ORIGIN_WITH_DIFFERENT_PORT, + HTTP_REMOTE_ORIGIN, + HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT, + HTTPS_REMOTE_ORIGIN, +} = get_host_info(); + +/** + * Tests to cover the basic behaviors of keepalive + cors/no-cors mode requests + * to different `origin` when the initiator document is still alive. They should + * behave the same as without setting keepalive. + */ +function keepaliveCorsBasicTest(desc, origin) { + const url = `${origin}${dirname(location.pathname)}${RESOURCES_DIR}top.txt`; + const urlAllowCors = `${url}?pipe=header(Access-Control-Allow-Origin,*)`; + + promise_test((test) => { + return fetch(urlAllowCors, {keepalive: true, 'mode': 'no-cors'}) + .then((resp) => { + assert_equals(resp.status, 0, 'Opaque filter: status is 0'); + assert_equals(resp.statusText, '', 'Opaque filter: statusText is ""'); + assert_equals( + resp.type, 'opaque', 'Opaque filter: response\'s type is opaque'); + return resp.text().then((value) => { + assert_equals( + value, '', 'Opaque response should have an empty body'); + }); + }); + }, `${desc} [no-cors mode]`); + + promise_test((test) => { + return promise_rejects_js( + test, TypeError, fetch(url, {keepalive: true, 'mode': 'cors'})); + }, `${desc} [cors mode, server forbid CORS]`); + + promise_test((test) => { + return fetch(urlAllowCors, {keepalive: true, 'mode': 'cors'}) + .then((resp) => { + assert_equals(resp.status, 200, 'Fetch\'s response\'s status is 200'); + assert_equals(resp.type, 'cors', 'CORS response\'s type is cors'); + }); + }, `${desc} [cors mode]`); +} + +keepaliveCorsBasicTest( + `[keepalive] Same domain different port`, HTTP_ORIGIN_WITH_DIFFERENT_PORT); +keepaliveCorsBasicTest( + `[keepalive] Same domain different protocol different port`, HTTPS_ORIGIN); +keepaliveCorsBasicTest( + `[keepalive] Cross domain basic usage`, HTTP_REMOTE_ORIGIN); +keepaliveCorsBasicTest( + `[keepalive] Cross domain different port`, + HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT); +keepaliveCorsBasicTest( + `[keepalive] Cross domain different protocol`, HTTPS_REMOTE_ORIGIN); + +/** + * In a same-site iframe, and in `unload` event handler, test to fetch + * a keepalive URL that involves in different cors modes. + */ +function keepaliveCorsInUnloadTest(description, origin, method) { + const evt = 'unload'; + for (const mode of ['no-cors', 'cors']) { + for (const disallowOrigin of [false, true]) { + const desc = `${description} ${method} request in ${evt} [${mode} mode` + + (disallowOrigin ? `, server forbid CORS]` : `]`); + const shouldPass = !disallowOrigin || mode === 'no-cors'; + promise_test(async (test) => { + const token1 = token(); + const iframe = document.createElement('iframe'); + iframe.src = getKeepAliveIframeUrl(token1, method, { + frameOrigin: '', + requestOrigin: origin, + sendOn: evt, + mode: mode, + disallowOrigin + }); + document.body.appendChild(iframe); + await iframeLoaded(iframe); + iframe.remove(); + assert_equals(await getTokenFromMessage(), token1); + + assertStashedTokenAsync(desc, token1, {shouldPass}); + }, `${desc}; setting up`); + } + } +} + +for (const method of ['GET', 'POST']) { + keepaliveCorsInUnloadTest( + '[keepalive] Same domain different port', HTTP_ORIGIN_WITH_DIFFERENT_PORT, + method); + keepaliveCorsInUnloadTest( + `[keepalive] Same domain different protocol different port`, HTTPS_ORIGIN, + method); + keepaliveCorsInUnloadTest( + `[keepalive] Cross domain basic usage`, HTTP_REMOTE_ORIGIN, method); + keepaliveCorsInUnloadTest( + `[keepalive] Cross domain different port`, + HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT, method); + keepaliveCorsInUnloadTest( + `[keepalive] Cross domain different protocol`, HTTPS_REMOTE_ORIGIN, + method); +} diff --git a/test/wpt/tests/fetch/api/cors/cors-multiple-origins.sub.any.js b/test/wpt/tests/fetch/api/cors/cors-multiple-origins.sub.any.js new file mode 100644 index 0000000..b3abb92 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-multiple-origins.sub.any.js @@ -0,0 +1,22 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +function corsMultipleOrigins(originList) { + var urlParameters = "?origin=" + encodeURIComponent(originList.join(", ")); + var url = "http://{{host}}:{{ports[http][1]}}" + dirname(location.pathname) + RESOURCES_DIR + "preflight.py"; + + promise_test(function(test) { + return promise_rejects_js(test, TypeError, fetch(url + urlParameters)); + }, "Listing multiple origins is illegal: " + originList); +} +/* Actual origin */ +var origin = "http://{{host}}:{{ports[http][0]}}"; + +corsMultipleOrigins(["\"\"", "http://example.com", origin]); +corsMultipleOrigins(["\"\"", "http://example.com", "*"]); +corsMultipleOrigins(["\"\"", origin, origin]); +corsMultipleOrigins(["*", "http://example.com", "*"]); +corsMultipleOrigins(["*", "http://example.com", origin]); +corsMultipleOrigins(["", "http://example.com", "https://example2.com"]); + +done(); diff --git a/test/wpt/tests/fetch/api/cors/cors-no-preflight.any.js b/test/wpt/tests/fetch/api/cors/cors-no-preflight.any.js new file mode 100644 index 0000000..7a0269a --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-no-preflight.any.js @@ -0,0 +1,41 @@ +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +function corsNoPreflight(desc, baseURL, method, headerName, headerValue) { + + var uuid_token = token(); + var url = baseURL + dirname(location.pathname) + RESOURCES_DIR + "preflight.py"; + var urlParameters = "?token=" + uuid_token + "&max_age=0"; + var requestInit = {"mode": "cors", "method": method, "headers":{}}; + if (headerName) + requestInit["headers"][headerName] = headerValue; + + promise_test(function(test) { + return fetch(RESOURCES_DIR + "clean-stash.py?token=" + uuid_token).then(function(resp) { + assert_equals(resp.status, 200, "Clean stash response's status is 200"); + return fetch(url + urlParameters, requestInit).then(function(resp) { + assert_equals(resp.status, 200, "Response's status is 200"); + assert_equals(resp.headers.get("x-did-preflight"), "0", "No preflight request has been made"); + }); + }); + }, desc); +} + +var host_info = get_host_info(); + +corsNoPreflight("Cross domain basic usage [GET]", host_info.HTTP_REMOTE_ORIGIN, "GET"); +corsNoPreflight("Same domain different port [GET]", host_info.HTTP_ORIGIN_WITH_DIFFERENT_PORT, "GET"); +corsNoPreflight("Cross domain different port [GET]", host_info.HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT, "GET"); +corsNoPreflight("Cross domain different protocol [GET]", host_info.HTTPS_REMOTE_ORIGIN, "GET"); +corsNoPreflight("Same domain different protocol different port [GET]", host_info.HTTPS_ORIGIN, "GET"); +corsNoPreflight("Cross domain [POST]", host_info.HTTP_REMOTE_ORIGIN, "POST"); +corsNoPreflight("Cross domain [HEAD]", host_info.HTTP_REMOTE_ORIGIN, "HEAD"); +corsNoPreflight("Cross domain [GET] [Accept: */*]", host_info.HTTP_REMOTE_ORIGIN, "GET" , "Accept", "*/*"); +corsNoPreflight("Cross domain [GET] [Accept-Language: fr]", host_info.HTTP_REMOTE_ORIGIN, "GET" , "Accept-Language", "fr"); +corsNoPreflight("Cross domain [GET] [Content-Language: fr]", host_info.HTTP_REMOTE_ORIGIN, "GET" , "Content-Language", "fr"); +corsNoPreflight("Cross domain [GET] [Content-Type: application/x-www-form-urlencoded]", host_info.HTTP_REMOTE_ORIGIN, "GET" , "Content-Type", "application/x-www-form-urlencoded"); +corsNoPreflight("Cross domain [GET] [Content-Type: multipart/form-data]", host_info.HTTP_REMOTE_ORIGIN, "GET" , "Content-Type", "multipart/form-data"); +corsNoPreflight("Cross domain [GET] [Content-Type: text/plain]", host_info.HTTP_REMOTE_ORIGIN, "GET" , "Content-Type", "text/plain"); +corsNoPreflight("Cross domain [GET] [Content-Type: text/plain;charset=utf-8]", host_info.HTTP_REMOTE_ORIGIN, "GET" , "Content-Type", "text/plain;charset=utf-8"); +corsNoPreflight("Cross domain [GET] [Content-Type: Text/Plain;charset=utf-8]", host_info.HTTP_REMOTE_ORIGIN, "GET" , "Content-Type", "Text/Plain;charset=utf-8"); diff --git a/test/wpt/tests/fetch/api/cors/cors-origin.any.js b/test/wpt/tests/fetch/api/cors/cors-origin.any.js new file mode 100644 index 0000000..30a02d9 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-origin.any.js @@ -0,0 +1,51 @@ +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +/* If origin is undefined, it is set to fetched url's origin*/ +function corsOrigin(desc, baseURL, method, origin, shouldPass) { + if (!origin) + origin = baseURL; + + var uuid_token = token(); + var urlParameters = "?token=" + uuid_token + "&max_age=0&origin=" + encodeURIComponent(origin) + "&allow_methods=" + method; + var url = baseURL + dirname(location.pathname) + RESOURCES_DIR + "preflight.py"; + var requestInit = {"mode": "cors", "method": method}; + + promise_test(function(test) { + return fetch(RESOURCES_DIR + "clean-stash.py?token=" + uuid_token).then(function(resp) { + assert_equals(resp.status, 200, "Clean stash response's status is 200"); + if (shouldPass) { + return fetch(url + urlParameters, requestInit).then(function(resp) { + assert_equals(resp.status, 200, "Response's status is 200"); + }); + } else { + return promise_rejects_js(test, TypeError, fetch(url + urlParameters, requestInit)); + } + }); + }, desc); + +} + +var host_info = get_host_info(); + +/* Actual origin */ +var origin = host_info.HTTP_ORIGIN; + +corsOrigin("Cross domain different subdomain [origin OK]", host_info.HTTP_REMOTE_ORIGIN, "GET", origin, true); +corsOrigin("Cross domain different subdomain [origin KO]", host_info.HTTP_REMOTE_ORIGIN, "GET", undefined, false); +corsOrigin("Same domain different port [origin OK]", host_info.HTTP_ORIGIN_WITH_DIFFERENT_PORT, "GET", origin, true); +corsOrigin("Same domain different port [origin KO]", host_info.HTTP_ORIGIN_WITH_DIFFERENT_PORT, "GET", undefined, false); +corsOrigin("Cross domain different port [origin OK]", host_info.HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT, "GET", origin, true); +corsOrigin("Cross domain different port [origin KO]", host_info.HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT, "GET", undefined, false); +corsOrigin("Cross domain different protocol [origin OK]", host_info.HTTPS_REMOTE_ORIGIN, "GET", origin, true); +corsOrigin("Cross domain different protocol [origin KO]", host_info.HTTPS_REMOTE_ORIGIN, "GET", undefined, false); +corsOrigin("Same domain different protocol different port [origin OK]", host_info.HTTPS_ORIGIN, "GET", origin, true); +corsOrigin("Same domain different protocol different port [origin KO]", host_info.HTTPS_ORIGIN, "GET", undefined, false); +corsOrigin("Cross domain [POST] [origin OK]", host_info.HTTP_REMOTE_ORIGIN, "POST", origin, true); +corsOrigin("Cross domain [POST] [origin KO]", host_info.HTTP_REMOTE_ORIGIN, "POST", undefined, false); +corsOrigin("Cross domain [HEAD] [origin OK]", host_info.HTTP_REMOTE_ORIGIN, "HEAD", origin, true); +corsOrigin("Cross domain [HEAD] [origin KO]", host_info.HTTP_REMOTE_ORIGIN, "HEAD", undefined, false); +corsOrigin("CORS preflight [PUT] [origin OK]", host_info.HTTP_REMOTE_ORIGIN, "PUT", origin, true); +corsOrigin("CORS preflight [PUT] [origin KO]", host_info.HTTP_REMOTE_ORIGIN, "PUT", undefined, false); +corsOrigin("Allowed origin: \"\" [origin KO]", host_info.HTTP_REMOTE_ORIGIN, "GET", "" , false); diff --git a/test/wpt/tests/fetch/api/cors/cors-preflight-cache.any.js b/test/wpt/tests/fetch/api/cors/cors-preflight-cache.any.js new file mode 100644 index 0000000..ce6a169 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-preflight-cache.any.js @@ -0,0 +1,46 @@ +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +var cors_url = get_host_info().HTTP_REMOTE_ORIGIN + + dirname(location.pathname) + + RESOURCES_DIR + + "preflight.py"; + +promise_test((test) => { + var uuid_token = token(); + var request_url = + cors_url + "?token=" + uuid_token + "&max_age=12000&allow_methods=POST" + + "&allow_headers=x-test-header"; + return fetch(cors_url + "?token=" + uuid_token + "&clear-stash") + .then(() => { + return fetch( + new Request(request_url, + { + mode: "cors", + method: "POST", + headers: [["x-test-header", "test1"]] + })); + }) + .then((resp) => { + assert_equals(resp.status, 200, "Response's status is 200"); + assert_equals(resp.headers.get("x-did-preflight"), "1", "Preflight request has been made"); + return fetch(cors_url + "?token=" + uuid_token + "&clear-stash"); + }) + .then((res) => res.text()) + .then((txt) => { + assert_equals(txt, "1", "Server stash must be cleared."); + return fetch( + new Request(request_url, + { + mode: "cors", + method: "POST", + headers: [["x-test-header", "test2"]] + })); + }) + .then((resp) => { + assert_equals(resp.status, 200, "Response's status is 200"); + assert_equals(resp.headers.get("x-did-preflight"), "0", "Preflight request has not been made"); + return fetch(cors_url + "?token=" + uuid_token + "&clear-stash"); + }); +}); diff --git a/test/wpt/tests/fetch/api/cors/cors-preflight-not-cors-safelisted.any.js b/test/wpt/tests/fetch/api/cors/cors-preflight-not-cors-safelisted.any.js new file mode 100644 index 0000000..b2747cc --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-preflight-not-cors-safelisted.any.js @@ -0,0 +1,19 @@ +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=resources/corspreflight.js + +const corsURL = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "preflight.py"; + +promise_test(() => fetch("resources/not-cors-safelisted.json").then(res => res.json().then(runTests)), "Loading data…"); + +function runTests(testArray) { + testArray.forEach(testItem => { + const [headerName, headerValue] = testItem; + corsPreflight("Need CORS-preflight for " + headerName + "/" + headerValue + " header", + corsURL, + "GET", + true, + [[headerName, headerValue]]); + }); +} diff --git a/test/wpt/tests/fetch/api/cors/cors-preflight-redirect.any.js b/test/wpt/tests/fetch/api/cors/cors-preflight-redirect.any.js new file mode 100644 index 0000000..15f7659 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-preflight-redirect.any.js @@ -0,0 +1,37 @@ +// META: global=window,worker +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +function corsPreflightRedirect(desc, redirectUrl, redirectLocation, redirectStatus, redirectPreflight) { + var uuid_token = token(); + var url = redirectUrl; + var urlParameters = "?token=" + uuid_token + "&max_age=0"; + urlParameters += "&redirect_status=" + redirectStatus; + urlParameters += "&location=" + encodeURIComponent(redirectLocation); + + if (redirectPreflight) + urlParameters += "&redirect_preflight"; + var requestInit = {"mode": "cors", "redirect": "follow"}; + + /* Force preflight */ + requestInit["headers"] = {"x-force-preflight": ""}; + urlParameters += "&allow_headers=x-force-preflight"; + + promise_test(function(test) { + return fetch(RESOURCES_DIR + "clean-stash.py?token=" + uuid_token).then(function(resp) { + assert_equals(resp.status, 200, "Clean stash response's status is 200"); + return promise_rejects_js(test, TypeError, fetch(url + urlParameters, requestInit)); + }); + }, desc); +} + +var redirectUrl = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "redirect.py"; +var locationUrl = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "preflight.py"; + +for (var code of [301, 302, 303, 307, 308]) { + /* preflight should not follow the redirection */ + corsPreflightRedirect("Redirection " + code + " on preflight failed", redirectUrl, locationUrl, code, true); + /* preflight is done before redirection: preflight force redirect to error */ + corsPreflightRedirect("Redirection " + code + " after preflight failed", redirectUrl, locationUrl, code, false); +} diff --git a/test/wpt/tests/fetch/api/cors/cors-preflight-referrer.any.js b/test/wpt/tests/fetch/api/cors/cors-preflight-referrer.any.js new file mode 100644 index 0000000..5df9fcf --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-preflight-referrer.any.js @@ -0,0 +1,51 @@ +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +function corsPreflightReferrer(desc, corsUrl, referrerPolicy, referrer, expectedReferrer) { + var uuid_token = token(); + var url = corsUrl; + var urlParameters = "?token=" + uuid_token + "&max_age=0"; + var requestInit = {"mode": "cors", "referrerPolicy": referrerPolicy}; + + if (referrer) + requestInit.referrer = referrer; + + /* Force preflight */ + requestInit["headers"] = {"x-force-preflight": ""}; + urlParameters += "&allow_headers=x-force-preflight"; + + promise_test(function(test) { + return fetch(RESOURCES_DIR + "clean-stash.py?token=" + uuid_token).then(function(resp) { + assert_equals(resp.status, 200, "Clean stash response's status is 200"); + return fetch(url + urlParameters, requestInit).then(function(resp) { + assert_equals(resp.status, 200, "Response's status is 200"); + assert_equals(resp.headers.get("x-did-preflight"), "1", "Preflight request has been made"); + assert_equals(resp.headers.get("x-preflight-referrer"), expectedReferrer, "Preflight's referrer is correct"); + assert_equals(resp.headers.get("x-referrer"), expectedReferrer, "Request's referrer is correct"); + assert_equals(resp.headers.get("x-control-request-headers"), "", "Access-Control-Allow-Headers value"); + }); + }); + }, desc + " and referrer: " + (referrer ? "'" + referrer + "'" : "default")); +} + +var corsUrl = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "preflight.py"; +var origin = get_host_info().HTTP_ORIGIN + "/"; + +corsPreflightReferrer("Referrer policy: no-referrer", corsUrl, "no-referrer", undefined, ""); +corsPreflightReferrer("Referrer policy: no-referrer", corsUrl, "no-referrer", "myreferrer", ""); + +corsPreflightReferrer("Referrer policy: \"\"", corsUrl, "", undefined, origin); +corsPreflightReferrer("Referrer policy: \"\"", corsUrl, "", "myreferrer", origin); + +corsPreflightReferrer("Referrer policy: no-referrer-when-downgrade", corsUrl, "no-referrer-when-downgrade", undefined, location.toString()) +corsPreflightReferrer("Referrer policy: no-referrer-when-downgrade", corsUrl, "no-referrer-when-downgrade", "myreferrer", new URL("myreferrer", location).toString()); + +corsPreflightReferrer("Referrer policy: origin", corsUrl, "origin", undefined, origin); +corsPreflightReferrer("Referrer policy: origin", corsUrl, "origin", "myreferrer", origin); + +corsPreflightReferrer("Referrer policy: origin-when-cross-origin", corsUrl, "origin-when-cross-origin", undefined, origin); +corsPreflightReferrer("Referrer policy: origin-when-cross-origin", corsUrl, "origin-when-cross-origin", "myreferrer", origin); + +corsPreflightReferrer("Referrer policy: unsafe-url", corsUrl, "unsafe-url", undefined, location.toString()); +corsPreflightReferrer("Referrer policy: unsafe-url", corsUrl, "unsafe-url", "myreferrer", new URL("myreferrer", location).toString()); diff --git a/test/wpt/tests/fetch/api/cors/cors-preflight-response-validation.any.js b/test/wpt/tests/fetch/api/cors/cors-preflight-response-validation.any.js new file mode 100644 index 0000000..718e351 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-preflight-response-validation.any.js @@ -0,0 +1,33 @@ +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +function corsPreflightResponseValidation(desc, corsUrl, allowHeaders, allowMethods) { + var uuid_token = token(); + var url = corsUrl; + var requestInit = {"mode": "cors"}; + /* Force preflight */ + requestInit["headers"] = {"x-force-preflight": ""}; + + var urlParameters = "?token=" + uuid_token + "&max_age=0"; + urlParameters += "&allow_headers=x-force-preflight"; + if (allowHeaders) + urlParameters += "," + allowHeaders; + if (allowMethods) + urlParameters += "&allow_methods="+ allowMethods; + + promise_test(function(test) { + return fetch(RESOURCES_DIR + "clean-stash.py?token=" + uuid_token).then(async function(resp) { + assert_equals(resp.status, 200, "Clean stash response's status is 200"); + await promise_rejects_js(test, TypeError, fetch(url + urlParameters, requestInit)); + + return fetch(url + urlParameters).then(function(resp) { + assert_equals(resp.headers.get("x-did-preflight"), "1", "Preflight request has been made"); + }); + }); + }, desc); +} + +var corsUrl = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "preflight.py"; +corsPreflightResponseValidation("Preflight response with a bad Access-Control-Allow-Headers", corsUrl, "Bad value", null); +corsPreflightResponseValidation("Preflight response with a bad Access-Control-Allow-Methods", corsUrl, null, "Bad value"); diff --git a/test/wpt/tests/fetch/api/cors/cors-preflight-star.any.js b/test/wpt/tests/fetch/api/cors/cors-preflight-star.any.js new file mode 100644 index 0000000..f9fb204 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-preflight-star.any.js @@ -0,0 +1,86 @@ +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +const url = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "preflight.py", + origin = location.origin // assuming an ASCII origin + +function preflightTest(succeeds, withCredentials, allowMethod, allowHeader, useMethod, useHeader) { + return promise_test(t => { + let testURL = url + "?", + requestInit = {} + if (withCredentials) { + testURL += "origin=" + origin + "&" + testURL += "credentials&" + requestInit.credentials = "include" + } + if (useMethod) { + requestInit.method = useMethod + } + if (useHeader.length > 0) { + requestInit.headers = [useHeader] + } + testURL += "allow_methods=" + allowMethod + "&" + testURL += "allow_headers=" + allowHeader + "&" + + if (succeeds) { + return fetch(testURL, requestInit).then(resp => { + assert_equals(resp.headers.get("x-origin"), origin) + }) + } else { + return promise_rejects_js(t, TypeError, fetch(testURL, requestInit)) + } + }, "CORS that " + (succeeds ? "succeeds" : "fails") + " with credentials: " + withCredentials + "; method: " + useMethod + " (allowed: " + allowMethod + "); header: " + useHeader + " (allowed: " + allowHeader + ")") +} + +// "GET" does not pass the case-sensitive method check, but in the safe list. +preflightTest(true, false, "get", "x-test", "GET", ["X-Test", "1"]) +// Headers check is case-insensitive, and "*" works as any for method. +preflightTest(true, false, "*", "x-test", "SUPER", ["X-Test", "1"]) +// "*" works as any only without credentials. +preflightTest(true, false, "*", "*", "OK", ["X-Test", "1"]) +preflightTest(false, true, "*", "*", "OK", ["X-Test", "1"]) +preflightTest(false, true, "*", "", "PUT", []) +preflightTest(false, true, "get", "*", "GET", ["X-Test", "1"]) +preflightTest(false, true, "*", "*", "GET", ["X-Test", "1"]) +// Exact character match works even for "*" with credentials. +preflightTest(true, true, "*", "*", "*", ["*", "1"]) + +// The following methods are upper-cased for init["method"] by +// https://fetch.spec.whatwg.org/#concept-method-normalize +// but not in Access-Control-Allow-Methods response. +// But they are https://fetch.spec.whatwg.org/#cors-safelisted-method, +// CORS anyway passes regardless of the cases. +for (const METHOD of ['GET', 'HEAD', 'POST']) { + const method = METHOD.toLowerCase(); + preflightTest(true, true, METHOD, "*", METHOD, []) + preflightTest(true, true, METHOD, "*", method, []) + preflightTest(true, true, method, "*", METHOD, []) + preflightTest(true, true, method, "*", method, []) +} + +// The following methods are upper-cased for init["method"] by +// https://fetch.spec.whatwg.org/#concept-method-normalize +// but not in Access-Control-Allow-Methods response. +// As they are not https://fetch.spec.whatwg.org/#cors-safelisted-method, +// Access-Control-Allow-Methods should contain upper-cased methods, +// while init["method"] can be either in upper or lower case. +for (const METHOD of ['DELETE', 'PUT']) { + const method = METHOD.toLowerCase(); + preflightTest(true, true, METHOD, "*", METHOD, []) + preflightTest(true, true, METHOD, "*", method, []) + preflightTest(false, true, method, "*", METHOD, []) + preflightTest(false, true, method, "*", method, []) +} + +// "PATCH" is NOT upper-cased in both places because it is not listed in +// https://fetch.spec.whatwg.org/#concept-method-normalize. +// So Access-Control-Allow-Methods value and init["method"] should match +// case-sensitively. +preflightTest(true, true, "PATCH", "*", "PATCH", []) +preflightTest(false, true, "PATCH", "*", "patch", []) +preflightTest(false, true, "patch", "*", "PATCH", []) +preflightTest(true, true, "patch", "*", "patch", []) + +// "Authorization" header can't be wildcarded. +preflightTest(false, false, "*", "*", "POST", ["Authorization", "123"]) +preflightTest(true, false, "*", "*, Authorization", "POST", ["Authorization", "123"]) diff --git a/test/wpt/tests/fetch/api/cors/cors-preflight-status.any.js b/test/wpt/tests/fetch/api/cors/cors-preflight-status.any.js new file mode 100644 index 0000000..a4467a6 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-preflight-status.any.js @@ -0,0 +1,37 @@ +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +/* Check preflight is ok if status is ok status (200 to 299)*/ +function corsPreflightStatus(desc, corsUrl, preflightStatus) { + var uuid_token = token(); + var url = corsUrl; + var requestInit = {"mode": "cors"}; + /* Force preflight */ + requestInit["headers"] = {"x-force-preflight": ""}; + + var urlParameters = "?token=" + uuid_token + "&max_age=0"; + urlParameters += "&allow_headers=x-force-preflight"; + urlParameters += "&preflight_status=" + preflightStatus; + + promise_test(function(test) { + return fetch(RESOURCES_DIR + "clean-stash.py?token=" + uuid_token).then(function(resp) { + assert_equals(resp.status, 200, "Clean stash response's status is 200"); + if (200 <= preflightStatus && 299 >= preflightStatus) { + return fetch(url + urlParameters, requestInit).then(function(resp) { + assert_equals(resp.status, 200, "Response's status is 200"); + assert_equals(resp.headers.get("x-did-preflight"), "1", "Preflight request has been made"); + }); + } else { + return promise_rejects_js(test, TypeError, fetch(url + urlParameters, requestInit)); + } + }); + }, desc); +} + +var corsUrl = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "preflight.py"; +for (status of [200, 201, 202, 203, 204, 205, 206, + 300, 301, 302, 303, 304, 305, 306, 307, 308, + 400, 401, 402, 403, 404, 405, + 501, 502, 503, 504, 505]) + corsPreflightStatus("Preflight answered with status " + status, corsUrl, status); diff --git a/test/wpt/tests/fetch/api/cors/cors-preflight.any.js b/test/wpt/tests/fetch/api/cors/cors-preflight.any.js new file mode 100644 index 0000000..045422f --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-preflight.any.js @@ -0,0 +1,62 @@ +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=resources/corspreflight.js + +var corsUrl = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "preflight.py"; + +corsPreflight("CORS [DELETE], server allows", corsUrl, "DELETE", true); +corsPreflight("CORS [DELETE], server refuses", corsUrl, "DELETE", false); +corsPreflight("CORS [PUT], server allows", corsUrl, "PUT", true); +corsPreflight("CORS [PUT], server allows, check preflight has user agent", corsUrl + "?checkUserAgentHeaderInPreflight", "PUT", true); +corsPreflight("CORS [PUT], server refuses", corsUrl, "PUT", false); +corsPreflight("CORS [PATCH], server allows", corsUrl, "PATCH", true); +corsPreflight("CORS [PATCH], server refuses", corsUrl, "PATCH", false); +corsPreflight("CORS [patcH], server allows", corsUrl, "patcH", true); +corsPreflight("CORS [patcH], server refuses", corsUrl, "patcH", false); +corsPreflight("CORS [NEW], server allows", corsUrl, "NEW", true); +corsPreflight("CORS [NEW], server refuses", corsUrl, "NEW", false); +corsPreflight("CORS [chicken], server allows", corsUrl, "chicken", true); +corsPreflight("CORS [chicken], server refuses", corsUrl, "chicken", false); + +corsPreflight("CORS [GET] [x-test-header: allowed], server allows", corsUrl, "GET", true, [["x-test-header1", "allowed"]]); +corsPreflight("CORS [GET] [x-test-header: refused], server refuses", corsUrl, "GET", false, [["x-test-header1", "refused"]]); + +var headers = [ + ["x-test-header1", "allowedOrRefused"], + ["x-test-header2", "allowedOrRefused"], + ["X-test-header3", "allowedOrRefused"], + ["x-test-header-b", "allowedOrRefused"], + ["x-test-header-D", "allowedOrRefused"], + ["x-test-header-C", "allowedOrRefused"], + ["x-test-header-a", "allowedOrRefused"], + ["Content-Type", "allowedOrRefused"], +]; +var safeHeaders= [ + ["Accept", "*"], + ["Accept-Language", "bzh"], + ["Content-Language", "eu"], +]; + +corsPreflight("CORS [GET] [several headers], server allows", corsUrl, "GET", true, headers, safeHeaders); +corsPreflight("CORS [GET] [several headers], server refuses", corsUrl, "GET", false, headers, safeHeaders); +corsPreflight("CORS [PUT] [several headers], server allows", corsUrl, "PUT", true, headers, safeHeaders); +corsPreflight("CORS [PUT] [several headers], server refuses", corsUrl, "PUT", false, headers, safeHeaders); + +corsPreflight("CORS [PUT] [only safe headers], server allows", corsUrl, "PUT", true, null, safeHeaders); + +promise_test(async t => { + const url = `${corsUrl}?allow_headers=*`; + await promise_rejects_js(t, TypeError, fetch(url, { + headers: { + authorization: 'foobar' + } + })); +}, '"authorization" should not be covered by the wildcard symbol'); + +promise_test(async t => { + const url = `${corsUrl}?allow_headers=authorization`; + await fetch(url, { headers: { + authorization: 'foobar' + }}); +}, '"authorization" should be covered by "authorization"'); \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/cors/cors-redirect-credentials.any.js b/test/wpt/tests/fetch/api/cors/cors-redirect-credentials.any.js new file mode 100644 index 0000000..2aff313 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-redirect-credentials.any.js @@ -0,0 +1,52 @@ +// META: timeout=long +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +function corsRedirectCredentials(desc, redirectUrl, redirectLocation, redirectStatus, locationCredentials) { + var url = redirectUrl + var urlParameters = "?redirect_status=" + redirectStatus; + urlParameters += "&location=" + redirectLocation.replace("://", "://" + locationCredentials + "@"); + + var requestInit = {"mode": "cors", "redirect": "follow"}; + + promise_test(t => { + const result = fetch(url + urlParameters, requestInit) + if(locationCredentials === "") { + return result; + } else { + return promise_rejects_js(t, TypeError, result); + } + }, desc); +} + +var redirPath = dirname(location.pathname) + RESOURCES_DIR + "redirect.py"; +var preflightPath = dirname(location.pathname) + RESOURCES_DIR + "preflight.py"; + +var host_info = get_host_info(); + +var localRedirect = host_info.HTTP_ORIGIN + redirPath; +var remoteRedirect = host_info.HTTP_ORIGIN_WITH_DIFFERENT_PORT + redirPath; + +var localLocation = host_info.HTTP_ORIGIN + preflightPath; +var remoteLocation = host_info.HTTP_ORIGIN_WITH_DIFFERENT_PORT + preflightPath; +var remoteLocation2 = host_info.HTTP_REMOTE_ORIGIN + preflightPath; + +for (var code of [301, 302, 303, 307, 308]) { + corsRedirectCredentials("Redirect " + code + " from same origin to remote without user and password", localRedirect, remoteLocation, code, ""); + + corsRedirectCredentials("Redirect " + code + " from same origin to remote with user and password", localRedirect, remoteLocation, code, "user:password"); + corsRedirectCredentials("Redirect " + code + " from same origin to remote with user", localRedirect, remoteLocation, code, "user:"); + corsRedirectCredentials("Redirect " + code + " from same origin to remote with password", localRedirect, remoteLocation, code, ":password"); + + corsRedirectCredentials("Redirect " + code + " from remote to same origin with user and password", remoteRedirect, localLocation, code, "user:password"); + corsRedirectCredentials("Redirect " + code + " from remote to same origin with user", remoteRedirect, localLocation, code, "user:"); + corsRedirectCredentials("Redirect " + code + " from remote to same origin with password", remoteRedirect, localLocation, code, ":password"); + + corsRedirectCredentials("Redirect " + code + " from remote to same remote with user and password", remoteRedirect, remoteLocation, code, "user:password"); + corsRedirectCredentials("Redirect " + code + " from remote to same remote with user", remoteRedirect, remoteLocation, code, "user:"); + corsRedirectCredentials("Redirect " + code + " from remote to same remote with password", remoteRedirect, remoteLocation, code, ":password"); + + corsRedirectCredentials("Redirect " + code + " from remote to another remote with user and password", remoteRedirect, remoteLocation2, code, "user:password"); + corsRedirectCredentials("Redirect " + code + " from remote to another remote with user", remoteRedirect, remoteLocation2, code, "user:"); + corsRedirectCredentials("Redirect " + code + " from remote to another remote with password", remoteRedirect, remoteLocation2, code, ":password"); +} diff --git a/test/wpt/tests/fetch/api/cors/cors-redirect-preflight.any.js b/test/wpt/tests/fetch/api/cors/cors-redirect-preflight.any.js new file mode 100644 index 0000000..5084817 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-redirect-preflight.any.js @@ -0,0 +1,46 @@ +// META: timeout=long +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +function corsRedirect(desc, redirectUrl, redirectLocation, redirectStatus, expectSuccess) { + var urlBaseParameters = "&redirect_status=" + redirectStatus; + var urlParametersSuccess = urlBaseParameters + "&allow_headers=x-w3c&location=" + encodeURIComponent(redirectLocation + "?allow_headers=x-w3c"); + var urlParametersFailure = urlBaseParameters + "&location=" + encodeURIComponent(redirectLocation); + + var requestInit = {"mode": "cors", "redirect": "follow", "headers" : [["x-w3c", "test"]]}; + + promise_test(function(test) { + var uuid_token = token(); + return fetch(RESOURCES_DIR + "clean-stash.py?token=" + uuid_token).then(function(resp) { + return fetch(redirectUrl + "?token=" + uuid_token + "&max_age=0" + urlParametersSuccess, requestInit).then(function(resp) { + assert_equals(resp.status, 200, "Response's status is 200"); + assert_equals(resp.headers.get("x-did-preflight"), "1", "Preflight request has been made"); + }); + }); + }, desc + " (preflight after redirection success case)"); + promise_test(function(test) { + var uuid_token = token(); + return fetch(RESOURCES_DIR + "clean-stash.py?token=" + uuid_token).then(function(resp) { + return promise_rejects_js(test, TypeError, fetch(redirectUrl + "?token=" + uuid_token + "&max_age=0" + urlParametersFailure, requestInit)); + }); + }, desc + " (preflight after redirection failure case)"); +} + +var redirPath = dirname(location.pathname) + RESOURCES_DIR + "redirect.py"; +var preflightPath = dirname(location.pathname) + RESOURCES_DIR + "preflight.py"; + +var host_info = get_host_info(); + +var localRedirect = host_info.HTTP_ORIGIN + redirPath; +var remoteRedirect = host_info.HTTP_REMOTE_ORIGIN + redirPath; + +var localLocation = host_info.HTTP_ORIGIN + preflightPath; +var remoteLocation = host_info.HTTP_REMOTE_ORIGIN + preflightPath; +var remoteLocation2 = host_info.HTTP_ORIGIN_WITH_DIFFERENT_PORT + preflightPath; + +for (var code of [301, 302, 303, 307, 308]) { + corsRedirect("Redirect " + code + ": same origin to cors", localRedirect, remoteLocation, code); + corsRedirect("Redirect " + code + ": cors to same origin", remoteRedirect, localLocation, code); + corsRedirect("Redirect " + code + ": cors to another cors", remoteRedirect, remoteLocation2, code); +} diff --git a/test/wpt/tests/fetch/api/cors/cors-redirect.any.js b/test/wpt/tests/fetch/api/cors/cors-redirect.any.js new file mode 100644 index 0000000..cdf4097 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/cors-redirect.any.js @@ -0,0 +1,42 @@ +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +function corsRedirect(desc, redirectUrl, redirectLocation, redirectStatus, expectedOrigin) { + var uuid_token = token(); + var url = redirectUrl; + var urlParameters = "?token=" + uuid_token + "&max_age=0"; + urlParameters += "&redirect_status=" + redirectStatus; + urlParameters += "&location=" + encodeURIComponent(redirectLocation); + + var requestInit = {"mode": "cors", "redirect": "follow"}; + + return promise_test(function(test) { + return fetch(RESOURCES_DIR + "clean-stash.py?token=" + uuid_token).then(function(resp) { + return fetch(url + urlParameters, requestInit).then(function(resp) { + assert_equals(resp.status, 200, "Response's status is 200"); + assert_equals(resp.headers.get("x-did-preflight"), "0", "No preflight request has been made"); + assert_equals(resp.headers.get("x-origin"), expectedOrigin, "Origin is correctly set after redirect"); + }); + }); + }, desc); +} + +var redirPath = dirname(location.pathname) + RESOURCES_DIR + "redirect.py"; +var preflightPath = dirname(location.pathname) + RESOURCES_DIR + "preflight.py"; + +var host_info = get_host_info(); + +var localRedirect = host_info.HTTP_ORIGIN + redirPath; +var remoteRedirect = host_info.HTTP_REMOTE_ORIGIN + redirPath; + +var localLocation = host_info.HTTP_ORIGIN + preflightPath; +var remoteLocation = host_info.HTTP_REMOTE_ORIGIN + preflightPath; +var remoteLocation2 = host_info.HTTP_ORIGIN_WITH_DIFFERENT_PORT + preflightPath; + +for (var code of [301, 302, 303, 307, 308]) { + corsRedirect("Redirect " + code + ": cors to same cors", remoteRedirect, remoteLocation, code, location.origin); + corsRedirect("Redirect " + code + ": cors to another cors", remoteRedirect, remoteLocation2, code, "null"); + corsRedirect("Redirect " + code + ": same origin to cors", localRedirect, remoteLocation, code, location.origin); + corsRedirect("Redirect " + code + ": cors to same origin", remoteRedirect, localLocation, code, "null"); +} diff --git a/test/wpt/tests/fetch/api/cors/data-url-iframe.html b/test/wpt/tests/fetch/api/cors/data-url-iframe.html new file mode 100644 index 0000000..217baa3 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/data-url-iframe.html @@ -0,0 +1,58 @@ + + + + + + diff --git a/test/wpt/tests/fetch/api/cors/data-url-shared-worker.html b/test/wpt/tests/fetch/api/cors/data-url-shared-worker.html new file mode 100644 index 0000000..d69748a --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/data-url-shared-worker.html @@ -0,0 +1,53 @@ + + + + + diff --git a/test/wpt/tests/fetch/api/cors/data-url-worker.html b/test/wpt/tests/fetch/api/cors/data-url-worker.html new file mode 100644 index 0000000..13113e6 --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/data-url-worker.html @@ -0,0 +1,50 @@ + + + + + diff --git a/test/wpt/tests/fetch/api/cors/resources/corspreflight.js b/test/wpt/tests/fetch/api/cors/resources/corspreflight.js new file mode 100644 index 0000000..18b8f6d --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/resources/corspreflight.js @@ -0,0 +1,58 @@ +function headerNames(headers) { + let names = []; + for (let header of headers) { + names.push(header[0].toLowerCase()); + } + return names; +} + +/* + Check preflight is done + Control if server allows method and headers and check accordingly + Check control access headers added by UA (for method and headers) +*/ +function corsPreflight(desc, corsUrl, method, allowed, headers, safeHeaders) { + return promise_test(function(test) { + var uuid_token = token(); + return fetch(RESOURCES_DIR + "clean-stash.py?token=" + uuid_token).then(function(response) { + var url = corsUrl + (corsUrl.indexOf("?") === -1 ? "?" : "&"); + var urlParameters = "token=" + uuid_token + "&max_age=0"; + var requestInit = {"mode": "cors", "method": method}; + var requestHeaders = []; + if (headers) + requestHeaders.push.apply(requestHeaders, headers); + if (safeHeaders) + requestHeaders.push.apply(requestHeaders, safeHeaders); + requestInit["headers"] = requestHeaders; + + if (allowed) { + urlParameters += "&allow_methods=" + method + "&control_request_headers"; + if (headers) { + //Make the server allow the headers + urlParameters += "&allow_headers=" + headerNames(headers).join("%20%2C"); + } + return fetch(url + urlParameters, requestInit).then(function(resp) { + assert_equals(resp.status, 200, "Response's status is 200"); + assert_equals(resp.headers.get("x-did-preflight"), "1", "Preflight request has been made"); + if (headers) { + var actualHeaders = resp.headers.get("x-control-request-headers").toLowerCase().split(","); + for (var i in actualHeaders) + actualHeaders[i] = actualHeaders[i].trim(); + for (var header of headers) + assert_in_array(header[0].toLowerCase(), actualHeaders, "Preflight asked permission for header: " + header); + + let accessControlAllowHeaders = headerNames(headers).sort().join(","); + assert_equals(resp.headers.get("x-control-request-headers"), accessControlAllowHeaders, "Access-Control-Allow-Headers value"); + return fetch(RESOURCES_DIR + "clean-stash.py?token=" + uuid_token); + } else { + assert_equals(resp.headers.get("x-control-request-headers"), null, "Access-Control-Request-Headers should be omitted") + } + }); + } else { + return promise_rejects_js(test, TypeError, fetch(url + urlParameters, requestInit)).then(function(){ + return fetch(RESOURCES_DIR + "clean-stash.py?token=" + uuid_token); + }); + } + }); + }, desc); +} diff --git a/test/wpt/tests/fetch/api/cors/resources/not-cors-safelisted.json b/test/wpt/tests/fetch/api/cors/resources/not-cors-safelisted.json new file mode 100644 index 0000000..945dc0f --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/resources/not-cors-safelisted.json @@ -0,0 +1,13 @@ +[ + ["accept", "\""], + ["accept", "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"], + ["accept-language", "\u0001"], + ["accept-language", "@"], + ["authorization", "basics"], + ["content-language", "\u0001"], + ["content-language", "@"], + ["content-type", "text/html"], + ["content-type", "text/plain; long=0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901"], + ["range", "bytes 0-"], + ["test", "hi"] +] diff --git a/test/wpt/tests/fetch/api/cors/sandboxed-iframe.html b/test/wpt/tests/fetch/api/cors/sandboxed-iframe.html new file mode 100644 index 0000000..feb9f1f --- /dev/null +++ b/test/wpt/tests/fetch/api/cors/sandboxed-iframe.html @@ -0,0 +1,14 @@ + + + + + + + diff --git a/test/wpt/tests/fetch/api/crashtests/body-window-destroy.html b/test/wpt/tests/fetch/api/crashtests/body-window-destroy.html new file mode 100644 index 0000000..646d3c5 --- /dev/null +++ b/test/wpt/tests/fetch/api/crashtests/body-window-destroy.html @@ -0,0 +1,11 @@ + + + diff --git a/test/wpt/tests/fetch/api/crashtests/request.html b/test/wpt/tests/fetch/api/crashtests/request.html new file mode 100644 index 0000000..2d21930 --- /dev/null +++ b/test/wpt/tests/fetch/api/crashtests/request.html @@ -0,0 +1,8 @@ + + + + diff --git a/test/wpt/tests/fetch/api/credentials/authentication-basic.any.js b/test/wpt/tests/fetch/api/credentials/authentication-basic.any.js new file mode 100644 index 0000000..31ccc38 --- /dev/null +++ b/test/wpt/tests/fetch/api/credentials/authentication-basic.any.js @@ -0,0 +1,17 @@ +// META: global=window,worker + +function basicAuth(desc, user, pass, mode, status) { + promise_test(function(test) { + var headers = { "Authorization": "Basic " + btoa(user + ":" + pass)}; + var requestInit = {"credentials": mode, "headers": headers}; + return fetch("../resources/authentication.py?realm=test", requestInit).then(function(resp) { + assert_equals(resp.status, status, "HTTP status is " + status); + assert_equals(resp.type , "basic", "Response's type is basic"); + }); + }, desc); +} + +basicAuth("User-added Authorization header with include mode", "user", "password", "include", 200); +basicAuth("User-added Authorization header with same-origin mode", "user", "password", "same-origin", 200); +basicAuth("User-added Authorization header with omit mode", "user", "password", "omit", 200); +basicAuth("User-added bogus Authorization header with omit mode", "notuser", "notpassword", "omit", 401); diff --git a/test/wpt/tests/fetch/api/credentials/authentication-redirection.any.js b/test/wpt/tests/fetch/api/credentials/authentication-redirection.any.js new file mode 100644 index 0000000..16656b5 --- /dev/null +++ b/test/wpt/tests/fetch/api/credentials/authentication-redirection.any.js @@ -0,0 +1,29 @@ +// META: global=window,worker +// META: script=/common/get-host-info.sub.js + +const authorizationValue = "Basic " + btoa("user:pass"); +async function getAuthorizationHeaderValue(url) +{ + const headers = { "Authorization": authorizationValue}; + const requestInit = {"headers": headers}; + const response = await fetch(url, requestInit); + return response.text(); +} + +promise_test(async test => { + const result = await getAuthorizationHeaderValue("/fetch/api/resources/dump-authorization-header.py"); + assert_equals(result, authorizationValue); +}, "getAuthorizationHeaderValue - no redirection"); + +promise_test(async test => { + result = await getAuthorizationHeaderValue("/fetch/api/resources/redirect.py?location=" + encodeURIComponent("/fetch/api/resources/dump-authorization-header.py")); + assert_equals(result, authorizationValue); + + result = await getAuthorizationHeaderValue(get_host_info().HTTPS_REMOTE_ORIGIN + "/fetch/api/resources/redirect.py?allow_headers=Authorization&location=" + encodeURIComponent(get_host_info().HTTPS_REMOTE_ORIGIN + "/fetch/api/resources/dump-authorization-header.py")); + assert_equals(result, authorizationValue); +}, "getAuthorizationHeaderValue - same origin redirection"); + +promise_test(async (test) => { + const result = await getAuthorizationHeaderValue(get_host_info().HTTPS_REMOTE_ORIGIN + "/fetch/api/resources/redirect.py?allow_headers=Authorization&location=" + encodeURIComponent(get_host_info().HTTPS_ORIGIN + "/fetch/api/resources/dump-authorization-header.py")); + assert_equals(result, "none"); +}, "getAuthorizationHeaderValue - cross origin redirection"); diff --git a/test/wpt/tests/fetch/api/credentials/cookies.any.js b/test/wpt/tests/fetch/api/credentials/cookies.any.js new file mode 100644 index 0000000..de30e47 --- /dev/null +++ b/test/wpt/tests/fetch/api/credentials/cookies.any.js @@ -0,0 +1,49 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +function cookies(desc, credentials1, credentials2 ,cookies) { + var url = RESOURCES_DIR + "top.txt" + var urlParameters = ""; + var urlCleanParameters = ""; + if (cookies) { + urlParameters +="?pipe=header(Set-Cookie,"; + urlParameters += cookies.join(",True)|header(Set-Cookie,") + ",True)"; + urlCleanParameters +="?pipe=header(Set-Cookie,"; + urlCleanParameters += cookies.join("%3B%20max-age=0,True)|header(Set-Cookie,") + "%3B%20max-age=0,True)"; + } + + var requestInit = {"credentials": credentials1} + promise_test(function(test){ + var requestInit = {"credentials": credentials1} + return fetch(url + urlParameters, requestInit).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type , "basic", "Response's type is basic"); + //check cookies sent + return fetch(RESOURCES_DIR + "inspect-headers.py?headers=cookie" , {"credentials": credentials2}); + }).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type , "basic", "Response's type is basic"); + assert_false(resp.headers.has("Cookie") , "Cookie header is not exposed in response"); + if (credentials1 != "omit" && credentials2 != "omit") { + assert_equals(resp.headers.get("x-request-cookie") , cookies.join("; "), "Request include cookie(s)"); + } + else { + assert_false(resp.headers.has("x-request-cookie") , "Request does not have cookie(s)"); + } + //clean cookies + return fetch(url + urlCleanParameters, {"credentials": "include"}); + }).catch(function(e) { + return fetch(url + urlCleanParameters, {"credentials": "include"}).then(function() { + return Promise.reject(e); + }); + }); + }, desc); +} + +cookies("Include mode: 1 cookie", "include", "include", ["a=1"]); +cookies("Include mode: 2 cookies", "include", "include", ["b=2", "c=3"]); +cookies("Omit mode: discard cookies", "omit", "omit", ["d=4"]); +cookies("Omit mode: no cookie is stored", "omit", "include", ["e=5"]); +cookies("Omit mode: no cookie is sent", "include", "omit", ["f=6"]); +cookies("Same-origin mode: 1 cookie", "same-origin", "same-origin", ["a=1"]); +cookies("Same-origin mode: 2 cookies", "same-origin", "same-origin", ["b=2", "c=3"]); diff --git a/test/wpt/tests/fetch/api/headers/header-setcookie.any.js b/test/wpt/tests/fetch/api/headers/header-setcookie.any.js new file mode 100644 index 0000000..cafb780 --- /dev/null +++ b/test/wpt/tests/fetch/api/headers/header-setcookie.any.js @@ -0,0 +1,266 @@ +// META: title=Headers set-cookie special cases +// META: global=window,worker + +const headerList = [ + ["set-cookie", "foo=bar"], + ["Set-Cookie", "fizz=buzz; domain=example.com"], +]; + +const setCookie2HeaderList = [ + ["set-cookie2", "foo2=bar2"], + ["Set-Cookie2", "fizz2=buzz2; domain=example2.com"], +]; + +function assert_nested_array_equals(actual, expected) { + assert_equals(actual.length, expected.length, "Array length is not equal"); + for (let i = 0; i < expected.length; i++) { + assert_array_equals(actual[i], expected[i]); + } +} + +test(function () { + const headers = new Headers(headerList); + assert_equals( + headers.get("set-cookie"), + "foo=bar, fizz=buzz; domain=example.com", + ); +}, "Headers.prototype.get combines set-cookie headers in order"); + +test(function () { + const headers = new Headers(headerList); + const list = [...headers]; + assert_nested_array_equals(list, [ + ["set-cookie", "foo=bar"], + ["set-cookie", "fizz=buzz; domain=example.com"], + ]); +}, "Headers iterator does not combine set-cookie headers"); + +test(function () { + const headers = new Headers(setCookie2HeaderList); + const list = [...headers]; + assert_nested_array_equals(list, [ + ["set-cookie2", "foo2=bar2, fizz2=buzz2; domain=example2.com"], + ]); +}, "Headers iterator does not special case set-cookie2 headers"); + +test(function () { + const headers = new Headers([...headerList, ...setCookie2HeaderList]); + const list = [...headers]; + assert_nested_array_equals(list, [ + ["set-cookie", "foo=bar"], + ["set-cookie", "fizz=buzz; domain=example.com"], + ["set-cookie2", "foo2=bar2, fizz2=buzz2; domain=example2.com"], + ]); +}, "Headers iterator does not combine set-cookie & set-cookie2 headers"); + +test(function () { + // Values are in non alphabetic order, and the iterator should yield in the + // headers in the exact order of the input. + const headers = new Headers([ + ["set-cookie", "z=z"], + ["set-cookie", "a=a"], + ["set-cookie", "n=n"], + ]); + const list = [...headers]; + assert_nested_array_equals(list, [ + ["set-cookie", "z=z"], + ["set-cookie", "a=a"], + ["set-cookie", "n=n"], + ]); +}, "Headers iterator preserves set-cookie ordering"); + +test( + function () { + const headers = new Headers([ + ["xylophone-header", "1"], + ["best-header", "2"], + ["set-cookie", "3"], + ["a-cool-header", "4"], + ["set-cookie", "5"], + ["a-cool-header", "6"], + ["best-header", "7"], + ]); + const list = [...headers]; + assert_nested_array_equals(list, [ + ["a-cool-header", "4, 6"], + ["best-header", "2, 7"], + ["set-cookie", "3"], + ["set-cookie", "5"], + ["xylophone-header", "1"], + ]); + }, + "Headers iterator preserves per header ordering, but sorts keys alphabetically", +); + +test( + function () { + const headers = new Headers([ + ["xylophone-header", "7"], + ["best-header", "6"], + ["set-cookie", "5"], + ["a-cool-header", "4"], + ["set-cookie", "3"], + ["a-cool-header", "2"], + ["best-header", "1"], + ]); + const list = [...headers]; + assert_nested_array_equals(list, [ + ["a-cool-header", "4, 2"], + ["best-header", "6, 1"], + ["set-cookie", "5"], + ["set-cookie", "3"], + ["xylophone-header", "7"], + ]); + }, + "Headers iterator preserves per header ordering, but sorts keys alphabetically (and ignores value ordering)", +); + +test(function () { + const headers = new Headers([["fizz", "buzz"], ["X-Header", "test"]]); + const iterator = headers[Symbol.iterator](); + assert_array_equals(iterator.next().value, ["fizz", "buzz"]); + headers.append("Set-Cookie", "a=b"); + assert_array_equals(iterator.next().value, ["set-cookie", "a=b"]); + headers.append("Accept", "text/html"); + assert_array_equals(iterator.next().value, ["set-cookie", "a=b"]); + assert_array_equals(iterator.next().value, ["x-header", "test"]); + headers.append("set-cookie", "c=d"); + assert_array_equals(iterator.next().value, ["x-header", "test"]); + assert_true(iterator.next().done); +}, "Headers iterator is correctly updated with set-cookie changes"); + +test(function () { + const headers = new Headers([ + ["set-cookie", "a"], + ["set-cookie", "b"], + ["set-cookie", "c"] + ]); + const iterator = headers[Symbol.iterator](); + assert_array_equals(iterator.next().value, ["set-cookie", "a"]); + headers.delete("set-cookie"); + headers.append("set-cookie", "d"); + headers.append("set-cookie", "e"); + headers.append("set-cookie", "f"); + assert_array_equals(iterator.next().value, ["set-cookie", "e"]); + assert_array_equals(iterator.next().value, ["set-cookie", "f"]); + assert_true(iterator.next().done); +}, "Headers iterator is correctly updated with set-cookie changes #2"); + +test(function () { + const headers = new Headers(headerList); + assert_true(headers.has("sEt-cOoKiE")); +}, "Headers.prototype.has works for set-cookie"); + +test(function () { + const headers = new Headers(setCookie2HeaderList); + headers.append("set-Cookie", "foo=bar"); + headers.append("sEt-cOoKiE", "fizz=buzz"); + const list = [...headers]; + assert_nested_array_equals(list, [ + ["set-cookie", "foo=bar"], + ["set-cookie", "fizz=buzz"], + ["set-cookie2", "foo2=bar2, fizz2=buzz2; domain=example2.com"], + ]); +}, "Headers.prototype.append works for set-cookie"); + +test(function () { + const headers = new Headers(headerList); + headers.set("set-cookie", "foo2=bar2"); + const list = [...headers]; + assert_nested_array_equals(list, [ + ["set-cookie", "foo2=bar2"], + ]); +}, "Headers.prototype.set works for set-cookie"); + +test(function () { + const headers = new Headers(headerList); + headers.delete("set-Cookie"); + const list = [...headers]; + assert_nested_array_equals(list, []); +}, "Headers.prototype.delete works for set-cookie"); + +test(function () { + const headers = new Headers(); + assert_array_equals(headers.getSetCookie(), []); +}, "Headers.prototype.getSetCookie with no headers present"); + +test(function () { + const headers = new Headers([headerList[0]]); + assert_array_equals(headers.getSetCookie(), ["foo=bar"]); +}, "Headers.prototype.getSetCookie with one header"); + +test(function () { + const headers = new Headers({ "Set-Cookie": "foo=bar" }); + assert_array_equals(headers.getSetCookie(), ["foo=bar"]); +}, "Headers.prototype.getSetCookie with one header created from an object"); + +test(function () { + const headers = new Headers(headerList); + assert_array_equals(headers.getSetCookie(), [ + "foo=bar", + "fizz=buzz; domain=example.com", + ]); +}, "Headers.prototype.getSetCookie with multiple headers"); + +test(function () { + const headers = new Headers([["set-cookie", ""]]); + assert_array_equals(headers.getSetCookie(), [""]); +}, "Headers.prototype.getSetCookie with an empty header"); + +test(function () { + const headers = new Headers([["set-cookie", "x"], ["set-cookie", "x"]]); + assert_array_equals(headers.getSetCookie(), ["x", "x"]); +}, "Headers.prototype.getSetCookie with two equal headers"); + +test(function () { + const headers = new Headers([ + ["set-cookie2", "x"], + ["set-cookie", "y"], + ["set-cookie2", "z"], + ]); + assert_array_equals(headers.getSetCookie(), ["y"]); +}, "Headers.prototype.getSetCookie ignores set-cookie2 headers"); + +test(function () { + // Values are in non alphabetic order, and the iterator should yield in the + // headers in the exact order of the input. + const headers = new Headers([ + ["set-cookie", "z=z"], + ["set-cookie", "a=a"], + ["set-cookie", "n=n"], + ]); + assert_array_equals(headers.getSetCookie(), ["z=z", "a=a", "n=n"]); +}, "Headers.prototype.getSetCookie preserves header ordering"); + +test(function () { + const headers = new Headers({"Set-Cookie": " a=b\n"}); + headers.append("set-cookie", "\n\rc=d "); + assert_nested_array_equals([...headers], [ + ["set-cookie", "a=b"], + ["set-cookie", "c=d"] + ]); + headers.set("set-cookie", "\te=f "); + assert_nested_array_equals([...headers], [["set-cookie", "e=f"]]); +}, "Adding Set-Cookie headers normalizes their value"); + +test(function () { + assert_throws_js(TypeError, () => { + new Headers({"set-cookie": "\0"}); + }); + + const headers = new Headers(); + assert_throws_js(TypeError, () => { + headers.append("Set-Cookie", "a\nb"); + }); + assert_throws_js(TypeError, () => { + headers.set("Set-Cookie", "a\rb"); + }); +}, "Adding invalid Set-Cookie headers throws"); + +test(function () { + const response = new Response(); + response.headers.append("Set-Cookie", "foo=bar"); + assert_array_equals(response.headers.getSetCookie(), []); + response.headers.append("sEt-cOokIe", "bar=baz"); + assert_array_equals(response.headers.getSetCookie(), []); +}, "Set-Cookie is a forbidden response header"); diff --git a/test/wpt/tests/fetch/api/headers/header-values-normalize.any.js b/test/wpt/tests/fetch/api/headers/header-values-normalize.any.js new file mode 100644 index 0000000..5710554 --- /dev/null +++ b/test/wpt/tests/fetch/api/headers/header-values-normalize.any.js @@ -0,0 +1,72 @@ +// META: title=Header value normalizing test +// META: global=window,worker +// META: timeout=long + +"use strict"; + +for(let i = 0; i < 0x21; i++) { + let fail = false, + strip = false + + // REMOVE 0x0B/0x0C exception once https://github.com/web-platform-tests/wpt/issues/8372 is fixed + if(i === 0x0B || i === 0x0C) + continue + + if(i === 0) { + fail = true + } + + if(i === 0x09 || i === 0x0A || i === 0x0D || i === 0x20) { + strip = true + } + + let url = "../resources/inspect-headers.py?headers=val1|val2|val3", + val = String.fromCharCode(i), + expectedVal = strip ? "" : val, + val1 = val, + expectedVal1 = expectedVal, + val2 = "x" + val, + expectedVal2 = "x" + expectedVal, + val3 = val + "x", + expectedVal3 = expectedVal + "x" + + // XMLHttpRequest is not available in service workers + if (!self.GLOBAL.isWorker()) { + async_test((t) => { + let xhr = new XMLHttpRequest() + xhr.open("POST", url) + if(fail) { + assert_throws_dom("SyntaxError", () => xhr.setRequestHeader("val1", val1)) + assert_throws_dom("SyntaxError", () => xhr.setRequestHeader("val2", val2)) + assert_throws_dom("SyntaxError", () => xhr.setRequestHeader("val3", val3)) + t.done() + } else { + xhr.setRequestHeader("val1", val1) + xhr.setRequestHeader("val2", val2) + xhr.setRequestHeader("val3", val3) + xhr.onload = t.step_func_done(() => { + assert_equals(xhr.getResponseHeader("x-request-val1"), expectedVal1) + assert_equals(xhr.getResponseHeader("x-request-val2"), expectedVal2) + assert_equals(xhr.getResponseHeader("x-request-val3"), expectedVal3) + }) + xhr.send() + } + }, "XMLHttpRequest with value " + encodeURI(val)) + } + + promise_test((t) => { + if(fail) { + return Promise.all([ + promise_rejects_js(t, TypeError, fetch(url, { headers: {"val1": val1} })), + promise_rejects_js(t, TypeError, fetch(url, { headers: {"val2": val2} })), + promise_rejects_js(t, TypeError, fetch(url, { headers: {"val3": val3} })) + ]) + } else { + return fetch(url, { headers: {"val1": val1, "val2": val2, "val3": val3} }).then((res) => { + assert_equals(res.headers.get("x-request-val1"), expectedVal1) + assert_equals(res.headers.get("x-request-val2"), expectedVal2) + assert_equals(res.headers.get("x-request-val3"), expectedVal3) + }) + } + }, "fetch() with value " + encodeURI(val)) +} diff --git a/test/wpt/tests/fetch/api/headers/header-values.any.js b/test/wpt/tests/fetch/api/headers/header-values.any.js new file mode 100644 index 0000000..bb7570c --- /dev/null +++ b/test/wpt/tests/fetch/api/headers/header-values.any.js @@ -0,0 +1,63 @@ +// META: title=Header value test +// META: global=window,worker +// META: timeout=long + +"use strict"; + +// Invalid values +[0, 0x0A, 0x0D].forEach(val => { + val = "x" + String.fromCharCode(val) + "x" + + // XMLHttpRequest is not available in service workers + if (!self.GLOBAL.isWorker()) { + test(() => { + let xhr = new XMLHttpRequest() + xhr.open("POST", "/") + assert_throws_dom("SyntaxError", () => xhr.setRequestHeader("value-test", val)) + }, "XMLHttpRequest with value " + encodeURI(val) + " needs to throw") + } + + promise_test(t => promise_rejects_js(t, TypeError, fetch("/", { headers: {"value-test": val} })), "fetch() with value " + encodeURI(val) + " needs to throw") +}) + +// Valid values +let headerValues =[] +for(let i = 0; i < 0x100; i++) { + if(i === 0 || i === 0x0A || i === 0x0D) { + continue + } + headerValues.push("x" + String.fromCharCode(i) + "x") +} +var url = "../resources/inspect-headers.py?headers=" +headerValues.forEach((_, i) => { + url += "val" + i + "|" +}) + +// XMLHttpRequest is not available in service workers +if (!self.GLOBAL.isWorker()) { + async_test((t) => { + let xhr = new XMLHttpRequest() + xhr.open("POST", url) + headerValues.forEach((val, i) => { + xhr.setRequestHeader("val" + i, val) + }) + xhr.onload = t.step_func_done(() => { + headerValues.forEach((val, i) => { + assert_equals(xhr.getResponseHeader("x-request-val" + i), val) + }) + }) + xhr.send() + }, "XMLHttpRequest with all valid values") +} + +promise_test((t) => { + const headers = new Headers + headerValues.forEach((val, i) => { + headers.append("val" + i, val) + }) + return fetch(url, { headers }).then((res) => { + headerValues.forEach((val, i) => { + assert_equals(res.headers.get("x-request-val" + i), val) + }) + }) +}, "fetch() with all valid values") diff --git a/test/wpt/tests/fetch/api/headers/headers-basic.any.js b/test/wpt/tests/fetch/api/headers/headers-basic.any.js new file mode 100644 index 0000000..ead1047 --- /dev/null +++ b/test/wpt/tests/fetch/api/headers/headers-basic.any.js @@ -0,0 +1,275 @@ +// META: title=Headers structure +// META: global=window,worker + +"use strict"; + +test(function() { + new Headers(); +}, "Create headers from no parameter"); + +test(function() { + new Headers(undefined); +}, "Create headers from undefined parameter"); + +test(function() { + new Headers({}); +}, "Create headers from empty object"); + +var parameters = [null, 1]; +parameters.forEach(function(parameter) { + test(function() { + assert_throws_js(TypeError, function() { new Headers(parameter) }); + }, "Create headers with " + parameter + " should throw"); +}); + +var headerDict = {"name1": "value1", + "name2": "value2", + "name3": "value3", + "name4": null, + "name5": undefined, + "name6": 1, + "Content-Type": "value4" +}; + +var headerSeq = []; +for (var name in headerDict) + headerSeq.push([name, headerDict[name]]); + +test(function() { + var headers = new Headers(headerSeq); + for (name in headerDict) { + assert_equals(headers.get(name), String(headerDict[name]), + "name: " + name + " has value: " + headerDict[name]); + } + assert_equals(headers.get("length"), null, "init should be treated as a sequence, not as a dictionary"); +}, "Create headers with sequence"); + +test(function() { + var headers = new Headers(headerDict); + for (name in headerDict) { + assert_equals(headers.get(name), String(headerDict[name]), + "name: " + name + " has value: " + headerDict[name]); + } +}, "Create headers with record"); + +test(function() { + var headers = new Headers(headerDict); + var headers2 = new Headers(headers); + for (name in headerDict) { + assert_equals(headers2.get(name), String(headerDict[name]), + "name: " + name + " has value: " + headerDict[name]); + } +}, "Create headers with existing headers"); + +test(function() { + var headers = new Headers() + headers[Symbol.iterator] = function *() { + yield ["test", "test"] + } + var headers2 = new Headers(headers) + assert_equals(headers2.get("test"), "test") +}, "Create headers with existing headers with custom iterator"); + +test(function() { + var headers = new Headers(); + for (name in headerDict) { + headers.append(name, headerDict[name]); + assert_equals(headers.get(name), String(headerDict[name]), + "name: " + name + " has value: " + headerDict[name]); + } +}, "Check append method"); + +test(function() { + var headers = new Headers(); + for (name in headerDict) { + headers.set(name, headerDict[name]); + assert_equals(headers.get(name), String(headerDict[name]), + "name: " + name + " has value: " + headerDict[name]); + } +}, "Check set method"); + +test(function() { + var headers = new Headers(headerDict); + for (name in headerDict) + assert_true(headers.has(name),"headers has name " + name); + + assert_false(headers.has("nameNotInHeaders"),"headers do not have header: nameNotInHeaders"); +}, "Check has method"); + +test(function() { + var headers = new Headers(headerDict); + for (name in headerDict) { + assert_true(headers.has(name),"headers have a header: " + name); + headers.delete(name) + assert_true(!headers.has(name),"headers do not have anymore a header: " + name); + } +}, "Check delete method"); + +test(function() { + var headers = new Headers(headerDict); + for (name in headerDict) + assert_equals(headers.get(name), String(headerDict[name]), + "name: " + name + " has value: " + headerDict[name]); + + assert_equals(headers.get("nameNotInHeaders"), null, "header: nameNotInHeaders has no value"); +}, "Check get method"); + +var headerEntriesDict = {"name1": "value1", + "Name2": "value2", + "name": "value3", + "content-Type": "value4", + "Content-Typ": "value5", + "Content-Types": "value6" +}; +var sortedHeaderDict = {}; +var headerValues = []; +var sortedHeaderKeys = Object.keys(headerEntriesDict).map(function(value) { + sortedHeaderDict[value.toLowerCase()] = headerEntriesDict[value]; + headerValues.push(headerEntriesDict[value]); + return value.toLowerCase(); +}).sort(); + +var iteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); +function checkIteratorProperties(iterator) { + var prototype = Object.getPrototypeOf(iterator); + assert_equals(Object.getPrototypeOf(prototype), iteratorPrototype); + + var descriptor = Object.getOwnPropertyDescriptor(prototype, "next"); + assert_true(descriptor.configurable, "configurable"); + assert_true(descriptor.enumerable, "enumerable"); + assert_true(descriptor.writable, "writable"); +} + +test(function() { + var headers = new Headers(headerEntriesDict); + var actual = headers.keys(); + checkIteratorProperties(actual); + + sortedHeaderKeys.forEach(function(key) { + const entry = actual.next(); + assert_false(entry.done); + assert_equals(entry.value, key); + }); + assert_true(actual.next().done); + assert_true(actual.next().done); + + for (const key of headers.keys()) + assert_true(sortedHeaderKeys.indexOf(key) != -1); +}, "Check keys method"); + +test(function() { + var headers = new Headers(headerEntriesDict); + var actual = headers.values(); + checkIteratorProperties(actual); + + sortedHeaderKeys.forEach(function(key) { + const entry = actual.next(); + assert_false(entry.done); + assert_equals(entry.value, sortedHeaderDict[key]); + }); + assert_true(actual.next().done); + assert_true(actual.next().done); + + for (const value of headers.values()) + assert_true(headerValues.indexOf(value) != -1); +}, "Check values method"); + +test(function() { + var headers = new Headers(headerEntriesDict); + var actual = headers.entries(); + checkIteratorProperties(actual); + + sortedHeaderKeys.forEach(function(key) { + const entry = actual.next(); + assert_false(entry.done); + assert_equals(entry.value[0], key); + assert_equals(entry.value[1], sortedHeaderDict[key]); + }); + assert_true(actual.next().done); + assert_true(actual.next().done); + + for (const entry of headers.entries()) + assert_equals(entry[1], sortedHeaderDict[entry[0]]); +}, "Check entries method"); + +test(function() { + var headers = new Headers(headerEntriesDict); + var actual = headers[Symbol.iterator](); + + sortedHeaderKeys.forEach(function(key) { + const entry = actual.next(); + assert_false(entry.done); + assert_equals(entry.value[0], key); + assert_equals(entry.value[1], sortedHeaderDict[key]); + }); + assert_true(actual.next().done); + assert_true(actual.next().done); +}, "Check Symbol.iterator method"); + +test(function() { + var headers = new Headers(headerEntriesDict); + var reference = sortedHeaderKeys[Symbol.iterator](); + headers.forEach(function(value, key, container) { + assert_equals(headers, container); + const entry = reference.next(); + assert_false(entry.done); + assert_equals(key, entry.value); + assert_equals(value, sortedHeaderDict[entry.value]); + }); + assert_true(reference.next().done); +}, "Check forEach method"); + +test(() => { + const headers = new Headers({"foo": "2", "baz": "1", "BAR": "0"}); + const actualKeys = []; + const actualValues = []; + for (const [header, value] of headers) { + actualKeys.push(header); + actualValues.push(value); + headers.delete("foo"); + } + assert_array_equals(actualKeys, ["bar", "baz"]); + assert_array_equals(actualValues, ["0", "1"]); +}, "Iteration skips elements removed while iterating"); + +test(() => { + const headers = new Headers({"foo": "2", "baz": "1", "BAR": "0", "quux": "3"}); + const actualKeys = []; + const actualValues = []; + for (const [header, value] of headers) { + actualKeys.push(header); + actualValues.push(value); + if (header === "baz") + headers.delete("bar"); + } + assert_array_equals(actualKeys, ["bar", "baz", "quux"]); + assert_array_equals(actualValues, ["0", "1", "3"]); +}, "Removing elements already iterated over causes an element to be skipped during iteration"); + +test(() => { + const headers = new Headers({"foo": "2", "baz": "1", "BAR": "0", "quux": "3"}); + const actualKeys = []; + const actualValues = []; + for (const [header, value] of headers) { + actualKeys.push(header); + actualValues.push(value); + if (header === "baz") + headers.append("X-yZ", "4"); + } + assert_array_equals(actualKeys, ["bar", "baz", "foo", "quux", "x-yz"]); + assert_array_equals(actualValues, ["0", "1", "2", "3", "4"]); +}, "Appending a value pair during iteration causes it to be reached during iteration"); + +test(() => { + const headers = new Headers({"foo": "2", "baz": "1", "BAR": "0", "quux": "3"}); + const actualKeys = []; + const actualValues = []; + for (const [header, value] of headers) { + actualKeys.push(header); + actualValues.push(value); + if (header === "baz") + headers.append("abc", "-1"); + } + assert_array_equals(actualKeys, ["bar", "baz", "baz", "foo", "quux"]); + assert_array_equals(actualValues, ["0", "1", "1", "2", "3"]); +}, "Prepending a value pair before the current element position causes it to be skipped during iteration and adds the current element a second time"); diff --git a/test/wpt/tests/fetch/api/headers/headers-casing.any.js b/test/wpt/tests/fetch/api/headers/headers-casing.any.js new file mode 100644 index 0000000..20b8a9d --- /dev/null +++ b/test/wpt/tests/fetch/api/headers/headers-casing.any.js @@ -0,0 +1,54 @@ +// META: title=Headers case management +// META: global=window,worker + +"use strict"; + +var headerDictCase = {"UPPERCASE": "value1", + "lowercase": "value2", + "mixedCase": "value3", + "Content-TYPE": "value4" + }; + +function checkHeadersCase(originalName, headersToCheck, expectedDict) { + var lowCaseName = originalName.toLowerCase(); + var upCaseName = originalName.toUpperCase(); + var expectedValue = expectedDict[originalName]; + assert_equals(headersToCheck.get(originalName), expectedValue, + "name: " + originalName + " has value: " + expectedValue); + assert_equals(headersToCheck.get(lowCaseName), expectedValue, + "name: " + lowCaseName + " has value: " + expectedValue); + assert_equals(headersToCheck.get(upCaseName), expectedValue, + "name: " + upCaseName + " has value: " + expectedValue); +} + +test(function() { + var headers = new Headers(headerDictCase); + for (const name in headerDictCase) + checkHeadersCase(name, headers, headerDictCase) +}, "Create headers, names use characters with different case"); + +test(function() { + var headers = new Headers(); + for (const name in headerDictCase) { + headers.append(name, headerDictCase[name]); + checkHeadersCase(name, headers, headerDictCase); + } +}, "Check append method, names use characters with different case"); + +test(function() { + var headers = new Headers(); + for (const name in headerDictCase) { + headers.set(name, headerDictCase[name]); + checkHeadersCase(name, headers, headerDictCase); + } +}, "Check set method, names use characters with different case"); + +test(function() { + var headers = new Headers(); + for (const name in headerDictCase) + headers.set(name, headerDictCase[name]); + for (const name in headerDictCase) + headers.delete(name.toLowerCase()); + for (const name in headerDictCase) + assert_false(headers.has(name), "header " + name + " should have been deleted"); +}, "Check delete method, names use characters with different case"); diff --git a/test/wpt/tests/fetch/api/headers/headers-combine.any.js b/test/wpt/tests/fetch/api/headers/headers-combine.any.js new file mode 100644 index 0000000..4f3b6d1 --- /dev/null +++ b/test/wpt/tests/fetch/api/headers/headers-combine.any.js @@ -0,0 +1,66 @@ +// META: title=Headers have combined (and sorted) values +// META: global=window,worker + +"use strict"; + +var headerSeqCombine = [["single", "singleValue"], + ["double", "doubleValue1"], + ["double", "doubleValue2"], + ["triple", "tripleValue1"], + ["triple", "tripleValue2"], + ["triple", "tripleValue3"] +]; +var expectedDict = {"single": "singleValue", + "double": "doubleValue1, doubleValue2", + "triple": "tripleValue1, tripleValue2, tripleValue3" +}; + +test(function() { + var headers = new Headers(headerSeqCombine); + for (const name in expectedDict) + assert_equals(headers.get(name), expectedDict[name]); +}, "Create headers using same name for different values"); + +test(function() { + var headers = new Headers(headerSeqCombine); + for (const name in expectedDict) { + assert_true(headers.has(name), "name: " + name + " has value(s)"); + headers.delete(name); + assert_false(headers.has(name), "name: " + name + " has no value(s) anymore"); + } +}, "Check delete and has methods when using same name for different values"); + +test(function() { + var headers = new Headers(headerSeqCombine); + for (const name in expectedDict) { + headers.set(name,"newSingleValue"); + assert_equals(headers.get(name), "newSingleValue", "name: " + name + " has value: newSingleValue"); + } +}, "Check set methods when called with already used name"); + +test(function() { + var headers = new Headers(headerSeqCombine); + for (const name in expectedDict) { + var value = headers.get(name); + headers.append(name,"newSingleValue"); + assert_equals(headers.get(name), (value + ", " + "newSingleValue")); + } +}, "Check append methods when called with already used name"); + +test(() => { + const headers = new Headers([["1", "a"],["1", "b"]]); + for(let header of headers) { + assert_array_equals(header, ["1", "a, b"]); + } +}, "Iterate combined values"); + +test(() => { + const headers = new Headers([["2", "a"], ["1", "b"], ["2", "b"]]), + expected = [["1", "b"], ["2", "a, b"]]; + let i = 0; + for(let header of headers) { + assert_array_equals(header, expected[i]); + i++; + } + assert_equals(i, 2); +}, "Iterate combined values in sorted order") diff --git a/test/wpt/tests/fetch/api/headers/headers-errors.any.js b/test/wpt/tests/fetch/api/headers/headers-errors.any.js new file mode 100644 index 0000000..82dadd8 --- /dev/null +++ b/test/wpt/tests/fetch/api/headers/headers-errors.any.js @@ -0,0 +1,96 @@ +// META: title=Headers errors +// META: global=window,worker + +"use strict"; + +test(function() { + assert_throws_js(TypeError, function() { new Headers([["name"]]); }); +}, "Create headers giving an array having one string as init argument"); + +test(function() { + assert_throws_js(TypeError, function() { new Headers([["invalid", "invalidValue1", "invalidValue2"]]); }); +}, "Create headers giving an array having three strings as init argument"); + +test(function() { + assert_throws_js(TypeError, function() { new Headers([["invalidÄ€", "Value1"]]); }); +}, "Create headers giving bad header name as init argument"); + +test(function() { + assert_throws_js(TypeError, function() { new Headers([["name", "invalidValueÄ€"]]); }); +}, "Create headers giving bad header value as init argument"); + +var badNames = ["invalidÄ€", {}]; +var badValues = ["invalidÄ€"]; + +badNames.forEach(function(name) { + test(function() { + var headers = new Headers(); + assert_throws_js(TypeError, function() { headers.get(name); }); + }, "Check headers get with an invalid name " + name); +}); + +badNames.forEach(function(name) { + test(function() { + var headers = new Headers(); + assert_throws_js(TypeError, function() { headers.delete(name); }); + }, "Check headers delete with an invalid name " + name); +}); + +badNames.forEach(function(name) { + test(function() { + var headers = new Headers(); + assert_throws_js(TypeError, function() { headers.has(name); }); + }, "Check headers has with an invalid name " + name); +}); + +badNames.forEach(function(name) { + test(function() { + var headers = new Headers(); + assert_throws_js(TypeError, function() { headers.set(name, "Value1"); }); + }, "Check headers set with an invalid name " + name); +}); + +badValues.forEach(function(value) { + test(function() { + var headers = new Headers(); + assert_throws_js(TypeError, function() { headers.set("name", value); }); + }, "Check headers set with an invalid value " + value); +}); + +badNames.forEach(function(name) { + test(function() { + var headers = new Headers(); + assert_throws_js(TypeError, function() { headers.append("invalidÄ€", "Value1"); }); + }, "Check headers append with an invalid name " + name); +}); + +badValues.forEach(function(value) { + test(function() { + var headers = new Headers(); + assert_throws_js(TypeError, function() { headers.append("name", value); }); + }, "Check headers append with an invalid value " + value); +}); + +test(function() { + var headers = new Headers([["name", "value"]]); + assert_throws_js(TypeError, function() { headers.forEach(); }); + assert_throws_js(TypeError, function() { headers.forEach(undefined); }); + assert_throws_js(TypeError, function() { headers.forEach(1); }); +}, "Headers forEach throws if argument is not callable"); + +test(function() { + var headers = new Headers([["name1", "value1"], ["name2", "value2"], ["name3", "value3"]]); + var counter = 0; + try { + headers.forEach(function(value, name) { + counter++; + if (name == "name2") + throw "error"; + }); + } catch (e) { + assert_equals(counter, 2); + assert_equals(e, "error"); + return; + } + assert_unreached(); +}, "Headers forEach loop should stop if callback is throwing exception"); diff --git a/test/wpt/tests/fetch/api/headers/headers-no-cors.any.js b/test/wpt/tests/fetch/api/headers/headers-no-cors.any.js new file mode 100644 index 0000000..60dbb9e --- /dev/null +++ b/test/wpt/tests/fetch/api/headers/headers-no-cors.any.js @@ -0,0 +1,59 @@ +// META: global=window,worker + +"use strict"; + +promise_test(() => fetch("../cors/resources/not-cors-safelisted.json").then(res => res.json().then(runTests)), "Loading data…"); + +const longValue = "s".repeat(127); + +[ + { + "headers": ["accept", "accept-language", "content-language"], + "values": [longValue, "", longValue] + }, + { + "headers": ["accept", "accept-language", "content-language"], + "values": ["", longValue] + }, + { + "headers": ["content-type"], + "values": ["text/plain;" + "s".repeat(116), "text/plain"] + } +].forEach(testItem => { + testItem.headers.forEach(header => { + test(() => { + const noCorsHeaders = new Request("about:blank", { mode: "no-cors" }).headers; + testItem.values.forEach((value) => { + noCorsHeaders.append(header, value); + assert_equals(noCorsHeaders.get(header), testItem.values[0], '1'); + }); + noCorsHeaders.set(header, testItem.values.join(", ")); + assert_equals(noCorsHeaders.get(header), testItem.values[0], '2'); + noCorsHeaders.delete(header); + assert_false(noCorsHeaders.has(header)); + }, "\"no-cors\" Headers object cannot have " + header + " set to " + testItem.values.join(", ")); + }); +}); + +function runTests(testArray) { + testArray = testArray.concat([ + ["dpr", "2"], + ["rtt", "1.0"], + ["downlink", "-1.0"], + ["ect", "6g"], + ["save-data", "on"], + ["viewport-width", "100"], + ["width", "100"], + ["unknown", "doesitmatter"] + ]); + testArray.forEach(testItem => { + const [headerName, headerValue] = testItem; + test(() => { + const noCorsHeaders = new Request("about:blank", { mode: "no-cors" }).headers; + noCorsHeaders.append(headerName, headerValue); + assert_false(noCorsHeaders.has(headerName)); + noCorsHeaders.set(headerName, headerValue); + assert_false(noCorsHeaders.has(headerName)); + }, "\"no-cors\" Headers object cannot have " + headerName + "/" + headerValue + " as header"); + }); +} diff --git a/test/wpt/tests/fetch/api/headers/headers-normalize.any.js b/test/wpt/tests/fetch/api/headers/headers-normalize.any.js new file mode 100644 index 0000000..68cf5b8 --- /dev/null +++ b/test/wpt/tests/fetch/api/headers/headers-normalize.any.js @@ -0,0 +1,56 @@ +// META: title=Headers normalize values +// META: global=window,worker + +"use strict"; + +const expectations = { + "name1": [" space ", "space"], + "name2": ["\ttab\t", "tab"], + "name3": [" spaceAndTab\t", "spaceAndTab"], + "name4": ["\r\n newLine", "newLine"], //obs-fold cases + "name5": ["newLine\r\n ", "newLine"], + "name6": ["\r\n\tnewLine", "newLine"], + "name7": ["\t\f\tnewLine\n", "\f\tnewLine"], + "name8": ["newLine\xa0", "newLine\xa0"], // \xa0 == non breaking space +}; + +test(function () { + const headerDict = Object.fromEntries( + Object.entries(expectations).map(([name, [actual]]) => [name, actual]), + ); + var headers = new Headers(headerDict); + for (const name in expectations) { + const expected = expectations[name][1]; + assert_equals( + headers.get(name), + expected, + "name: " + name + " has normalized value: " + expected, + ); + } +}, "Create headers with not normalized values"); + +test(function () { + var headers = new Headers(); + for (const name in expectations) { + headers.append(name, expectations[name][0]); + const expected = expectations[name][1]; + assert_equals( + headers.get(name), + expected, + "name: " + name + " has value: " + expected, + ); + } +}, "Check append method with not normalized values"); + +test(function () { + var headers = new Headers(); + for (const name in expectations) { + headers.set(name, expectations[name][0]); + const expected = expectations[name][1]; + assert_equals( + headers.get(name), + expected, + "name: " + name + " has value: " + expected, + ); + } +}, "Check set method with not normalized values"); diff --git a/test/wpt/tests/fetch/api/headers/headers-record.any.js b/test/wpt/tests/fetch/api/headers/headers-record.any.js new file mode 100644 index 0000000..fa85391 --- /dev/null +++ b/test/wpt/tests/fetch/api/headers/headers-record.any.js @@ -0,0 +1,357 @@ +// META: global=window,worker + +"use strict"; + +var log = []; +function clearLog() { + log = []; +} +function addLogEntry(name, args) { + log.push([ name, ...args ]); +} + +var loggingHandler = { +}; + +setup(function() { + for (let prop of Object.getOwnPropertyNames(Reflect)) { + loggingHandler[prop] = function(...args) { + addLogEntry(prop, args); + return Reflect[prop](...args); + } + } +}); + +test(function() { + var h = new Headers(); + assert_equals([...h].length, 0); +}, "Passing nothing to Headers constructor"); + +test(function() { + var h = new Headers(undefined); + assert_equals([...h].length, 0); +}, "Passing undefined to Headers constructor"); + +test(function() { + assert_throws_js(TypeError, function() { + var h = new Headers(null); + }); +}, "Passing null to Headers constructor"); + +test(function() { + this.add_cleanup(clearLog); + var record = { a: "b" }; + var proxy = new Proxy(record, loggingHandler); + var h = new Headers(proxy); + + assert_equals(log.length, 4); + // The first thing is the [[Get]] of Symbol.iterator to figure out whether + // we're a sequence, during overload resolution. + assert_array_equals(log[0], ["get", record, Symbol.iterator, proxy]); + // Then we have the [[OwnPropertyKeys]] from + // https://webidl.spec.whatwg.org/#es-to-record step 4. + assert_array_equals(log[1], ["ownKeys", record]); + // Then the [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[2], ["getOwnPropertyDescriptor", record, "a"]); + // Then the [[Get]] from step 5.2. + assert_array_equals(log[3], ["get", record, "a", proxy]); + + // Check the results. + assert_equals([...h].length, 1); + assert_array_equals([...h.keys()], ["a"]); + assert_true(h.has("a")); + assert_equals(h.get("a"), "b"); +}, "Basic operation with one property"); + +test(function() { + this.add_cleanup(clearLog); + var recordProto = { c: "d" }; + var record = Object.create(recordProto, { a: { value: "b", enumerable: true } }); + var proxy = new Proxy(record, loggingHandler); + var h = new Headers(proxy); + + assert_equals(log.length, 4); + // The first thing is the [[Get]] of Symbol.iterator to figure out whether + // we're a sequence, during overload resolution. + assert_array_equals(log[0], ["get", record, Symbol.iterator, proxy]); + // Then we have the [[OwnPropertyKeys]] from + // https://webidl.spec.whatwg.org/#es-to-record step 4. + assert_array_equals(log[1], ["ownKeys", record]); + // Then the [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[2], ["getOwnPropertyDescriptor", record, "a"]); + // Then the [[Get]] from step 5.2. + assert_array_equals(log[3], ["get", record, "a", proxy]); + + // Check the results. + assert_equals([...h].length, 1); + assert_array_equals([...h.keys()], ["a"]); + assert_true(h.has("a")); + assert_equals(h.get("a"), "b"); +}, "Basic operation with one property and a proto"); + +test(function() { + this.add_cleanup(clearLog); + var record = { a: "b", c: "d" }; + var proxy = new Proxy(record, loggingHandler); + var h = new Headers(proxy); + + assert_equals(log.length, 6); + // The first thing is the [[Get]] of Symbol.iterator to figure out whether + // we're a sequence, during overload resolution. + assert_array_equals(log[0], ["get", record, Symbol.iterator, proxy]); + // Then we have the [[OwnPropertyKeys]] from + // https://webidl.spec.whatwg.org/#es-to-record step 4. + assert_array_equals(log[1], ["ownKeys", record]); + // Then the [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[2], ["getOwnPropertyDescriptor", record, "a"]); + // Then the [[Get]] from step 5.2. + assert_array_equals(log[3], ["get", record, "a", proxy]); + // Then the second [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[4], ["getOwnPropertyDescriptor", record, "c"]); + // Then the second [[Get]] from step 5.2. + assert_array_equals(log[5], ["get", record, "c", proxy]); + + // Check the results. + assert_equals([...h].length, 2); + assert_array_equals([...h.keys()], ["a", "c"]); + assert_true(h.has("a")); + assert_equals(h.get("a"), "b"); + assert_true(h.has("c")); + assert_equals(h.get("c"), "d"); +}, "Correct operation ordering with two properties"); + +test(function() { + this.add_cleanup(clearLog); + var record = { a: "b", "\uFFFF": "d" }; + var proxy = new Proxy(record, loggingHandler); + assert_throws_js(TypeError, function() { + var h = new Headers(proxy); + }); + + assert_equals(log.length, 5); + // The first thing is the [[Get]] of Symbol.iterator to figure out whether + // we're a sequence, during overload resolution. + assert_array_equals(log[0], ["get", record, Symbol.iterator, proxy]); + // Then we have the [[OwnPropertyKeys]] from + // https://webidl.spec.whatwg.org/#es-to-record step 4. + assert_array_equals(log[1], ["ownKeys", record]); + // Then the [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[2], ["getOwnPropertyDescriptor", record, "a"]); + // Then the [[Get]] from step 5.2. + assert_array_equals(log[3], ["get", record, "a", proxy]); + // Then the second [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[4], ["getOwnPropertyDescriptor", record, "\uFFFF"]); + // The second [[Get]] never happens, because we convert the invalid name to a + // ByteString first and throw. +}, "Correct operation ordering with two properties one of which has an invalid name"); + +test(function() { + this.add_cleanup(clearLog); + var record = { a: "\uFFFF", c: "d" } + var proxy = new Proxy(record, loggingHandler); + assert_throws_js(TypeError, function() { + var h = new Headers(proxy); + }); + + assert_equals(log.length, 4); + // The first thing is the [[Get]] of Symbol.iterator to figure out whether + // we're a sequence, during overload resolution. + assert_array_equals(log[0], ["get", record, Symbol.iterator, proxy]); + // Then we have the [[OwnPropertyKeys]] from + // https://webidl.spec.whatwg.org/#es-to-record step 4. + assert_array_equals(log[1], ["ownKeys", record]); + // Then the [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[2], ["getOwnPropertyDescriptor", record, "a"]); + // Then the [[Get]] from step 5.2. + assert_array_equals(log[3], ["get", record, "a", proxy]); + // Nothing else after this, because converting the result of that [[Get]] to a + // ByteString throws. +}, "Correct operation ordering with two properties one of which has an invalid value"); + +test(function() { + this.add_cleanup(clearLog); + var record = {}; + Object.defineProperty(record, "a", { value: "b", enumerable: false }); + Object.defineProperty(record, "c", { value: "d", enumerable: true }); + Object.defineProperty(record, "e", { value: "f", enumerable: false }); + var proxy = new Proxy(record, loggingHandler); + var h = new Headers(proxy); + + assert_equals(log.length, 6); + // The first thing is the [[Get]] of Symbol.iterator to figure out whether + // we're a sequence, during overload resolution. + assert_array_equals(log[0], ["get", record, Symbol.iterator, proxy]); + // Then we have the [[OwnPropertyKeys]] from + // https://webidl.spec.whatwg.org/#es-to-record step 4. + assert_array_equals(log[1], ["ownKeys", record]); + // Then the [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[2], ["getOwnPropertyDescriptor", record, "a"]); + // No [[Get]] because not enumerable + // Then the second [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[3], ["getOwnPropertyDescriptor", record, "c"]); + // Then the [[Get]] from step 5.2. + assert_array_equals(log[4], ["get", record, "c", proxy]); + // Then the third [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[5], ["getOwnPropertyDescriptor", record, "e"]); + // No [[Get]] because not enumerable + + // Check the results. + assert_equals([...h].length, 1); + assert_array_equals([...h.keys()], ["c"]); + assert_true(h.has("c")); + assert_equals(h.get("c"), "d"); +}, "Correct operation ordering with non-enumerable properties"); + +test(function() { + this.add_cleanup(clearLog); + var record = {a: "b", c: "d", e: "f"}; + var lyingHandler = { + getOwnPropertyDescriptor: function(target, name) { + if (name == "a" || name == "e") { + return undefined; + } + return Reflect.getOwnPropertyDescriptor(target, name); + } + }; + var lyingProxy = new Proxy(record, lyingHandler); + var proxy = new Proxy(lyingProxy, loggingHandler); + var h = new Headers(proxy); + + assert_equals(log.length, 6); + // The first thing is the [[Get]] of Symbol.iterator to figure out whether + // we're a sequence, during overload resolution. + assert_array_equals(log[0], ["get", lyingProxy, Symbol.iterator, proxy]); + // Then we have the [[OwnPropertyKeys]] from + // https://webidl.spec.whatwg.org/#es-to-record step 4. + assert_array_equals(log[1], ["ownKeys", lyingProxy]); + // Then the [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[2], ["getOwnPropertyDescriptor", lyingProxy, "a"]); + // No [[Get]] because no descriptor + // Then the second [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[3], ["getOwnPropertyDescriptor", lyingProxy, "c"]); + // Then the [[Get]] from step 5.2. + assert_array_equals(log[4], ["get", lyingProxy, "c", proxy]); + // Then the third [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[5], ["getOwnPropertyDescriptor", lyingProxy, "e"]); + // No [[Get]] because no descriptor + + // Check the results. + assert_equals([...h].length, 1); + assert_array_equals([...h.keys()], ["c"]); + assert_true(h.has("c")); + assert_equals(h.get("c"), "d"); +}, "Correct operation ordering with undefined descriptors"); + +test(function() { + this.add_cleanup(clearLog); + var record = {a: "b", c: "d"}; + var lyingHandler = { + ownKeys: function() { + return [ "a", "c", "a", "c" ]; + }, + }; + var lyingProxy = new Proxy(record, lyingHandler); + var proxy = new Proxy(lyingProxy, loggingHandler); + + // Returning duplicate keys from ownKeys() throws a TypeError. + assert_throws_js(TypeError, + function() { var h = new Headers(proxy); }); + + assert_equals(log.length, 2); + // The first thing is the [[Get]] of Symbol.iterator to figure out whether + // we're a sequence, during overload resolution. + assert_array_equals(log[0], ["get", lyingProxy, Symbol.iterator, proxy]); + // Then we have the [[OwnPropertyKeys]] from + // https://webidl.spec.whatwg.org/#es-to-record step 4. + assert_array_equals(log[1], ["ownKeys", lyingProxy]); +}, "Correct operation ordering with repeated keys"); + +test(function() { + this.add_cleanup(clearLog); + var record = { + a: "b", + [Symbol.toStringTag]: { + // Make sure the ToString conversion of the value happens + // after the ToString conversion of the key. + toString: function () { addLogEntry("toString", [this]); return "nope"; } + }, + c: "d" }; + var proxy = new Proxy(record, loggingHandler); + assert_throws_js(TypeError, + function() { var h = new Headers(proxy); }); + + assert_equals(log.length, 7); + // The first thing is the [[Get]] of Symbol.iterator to figure out whether + // we're a sequence, during overload resolution. + assert_array_equals(log[0], ["get", record, Symbol.iterator, proxy]); + // Then we have the [[OwnPropertyKeys]] from + // https://webidl.spec.whatwg.org/#es-to-record step 4. + assert_array_equals(log[1], ["ownKeys", record]); + // Then the [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[2], ["getOwnPropertyDescriptor", record, "a"]); + // Then the [[Get]] from step 5.2. + assert_array_equals(log[3], ["get", record, "a", proxy]); + // Then the second [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[4], ["getOwnPropertyDescriptor", record, "c"]); + // Then the second [[Get]] from step 5.2. + assert_array_equals(log[5], ["get", record, "c", proxy]); + // Then the third [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[6], ["getOwnPropertyDescriptor", record, + Symbol.toStringTag]); + // Then we throw an exception converting the Symbol to a string, before we do + // the third [[Get]]. +}, "Basic operation with Symbol keys"); + +test(function() { + this.add_cleanup(clearLog); + var record = { + a: { + toString: function() { addLogEntry("toString", [this]); return "b"; } + }, + [Symbol.toStringTag]: { + toString: function () { addLogEntry("toString", [this]); return "nope"; } + }, + c: { + toString: function() { addLogEntry("toString", [this]); return "d"; } + } + }; + // Now make that Symbol-named property not enumerable. + Object.defineProperty(record, Symbol.toStringTag, { enumerable: false }); + assert_array_equals(Reflect.ownKeys(record), + ["a", "c", Symbol.toStringTag]); + + var proxy = new Proxy(record, loggingHandler); + var h = new Headers(proxy); + + assert_equals(log.length, 9); + // The first thing is the [[Get]] of Symbol.iterator to figure out whether + // we're a sequence, during overload resolution. + assert_array_equals(log[0], ["get", record, Symbol.iterator, proxy]); + // Then we have the [[OwnPropertyKeys]] from + // https://webidl.spec.whatwg.org/#es-to-record step 4. + assert_array_equals(log[1], ["ownKeys", record]); + // Then the [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[2], ["getOwnPropertyDescriptor", record, "a"]); + // Then the [[Get]] from step 5.2. + assert_array_equals(log[3], ["get", record, "a", proxy]); + // Then the ToString on the value. + assert_array_equals(log[4], ["toString", record.a]); + // Then the second [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[5], ["getOwnPropertyDescriptor", record, "c"]); + // Then the second [[Get]] from step 5.2. + assert_array_equals(log[6], ["get", record, "c", proxy]); + // Then the ToString on the value. + assert_array_equals(log[7], ["toString", record.c]); + // Then the third [[GetOwnProperty]] from step 5.1. + assert_array_equals(log[8], ["getOwnPropertyDescriptor", record, + Symbol.toStringTag]); + // No [[Get]] because not enumerable. + + // Check the results. + assert_equals([...h].length, 2); + assert_array_equals([...h.keys()], ["a", "c"]); + assert_true(h.has("a")); + assert_equals(h.get("a"), "b"); + assert_true(h.has("c")); + assert_equals(h.get("c"), "d"); +}, "Operation with non-enumerable Symbol keys"); diff --git a/test/wpt/tests/fetch/api/headers/headers-structure.any.js b/test/wpt/tests/fetch/api/headers/headers-structure.any.js new file mode 100644 index 0000000..d826bca --- /dev/null +++ b/test/wpt/tests/fetch/api/headers/headers-structure.any.js @@ -0,0 +1,20 @@ +// META: title=Headers basic +// META: global=window,worker + +"use strict"; + +var headers = new Headers(); +var methods = ["append", + "delete", + "get", + "has", + "set", + //Headers is iterable + "entries", + "keys", + "values" + ]; +for (var idx in methods) + test(function() { + assert_true(methods[idx] in headers, "headers has " + methods[idx] + " method"); + }, "Headers has " + methods[idx] + " method"); diff --git a/test/wpt/tests/fetch/api/idlharness.any.js b/test/wpt/tests/fetch/api/idlharness.any.js new file mode 100644 index 0000000..7b3c694 --- /dev/null +++ b/test/wpt/tests/fetch/api/idlharness.any.js @@ -0,0 +1,21 @@ +// META: global=window,worker +// META: script=/resources/WebIDLParser.js +// META: script=/resources/idlharness.js +// META: timeout=long + +idl_test( + ['fetch'], + ['referrer-policy', 'html', 'dom'], + idl_array => { + idl_array.add_objects({ + Headers: ["new Headers()"], + Request: ["new Request('about:blank')"], + Response: ["new Response()"], + }); + if (self.GLOBAL.isWindow()) { + idl_array.add_objects({ Window: ['window'] }); + } else if (self.GLOBAL.isWorker()) { + idl_array.add_objects({ WorkerGlobalScope: ['self'] }); + } + } +); diff --git a/test/wpt/tests/fetch/api/policies/csp-blocked-worker.html b/test/wpt/tests/fetch/api/policies/csp-blocked-worker.html new file mode 100644 index 0000000..e8660df --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/csp-blocked-worker.html @@ -0,0 +1,16 @@ + + + + + Fetch in worker: blocked by CSP + + + + + + + + + \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/policies/csp-blocked.html b/test/wpt/tests/fetch/api/policies/csp-blocked.html new file mode 100644 index 0000000..99e90df --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/csp-blocked.html @@ -0,0 +1,15 @@ + + + + + Fetch: blocked by CSP + + + + + + + + + + \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/policies/csp-blocked.html.headers b/test/wpt/tests/fetch/api/policies/csp-blocked.html.headers new file mode 100644 index 0000000..c8c1e9f --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/csp-blocked.html.headers @@ -0,0 +1 @@ +Content-Security-Policy: connect-src 'none'; \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/policies/csp-blocked.js b/test/wpt/tests/fetch/api/policies/csp-blocked.js new file mode 100644 index 0000000..28653ff --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/csp-blocked.js @@ -0,0 +1,13 @@ +if (this.document === undefined) { + importScripts("/resources/testharness.js"); + importScripts("../resources/utils.js"); +} + +//Content-Security-Policy: connect-src 'none'; cf .headers file +cspViolationUrl = RESOURCES_DIR + "top.txt"; + +promise_test(function(test) { + return promise_rejects_js(test, TypeError, fetch(cspViolationUrl)); +}, "Fetch is blocked by CSP, got a TypeError"); + +done(); diff --git a/test/wpt/tests/fetch/api/policies/csp-blocked.js.headers b/test/wpt/tests/fetch/api/policies/csp-blocked.js.headers new file mode 100644 index 0000000..c8c1e9f --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/csp-blocked.js.headers @@ -0,0 +1 @@ +Content-Security-Policy: connect-src 'none'; \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/policies/nested-policy.js b/test/wpt/tests/fetch/api/policies/nested-policy.js new file mode 100644 index 0000000..b0d1769 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/nested-policy.js @@ -0,0 +1 @@ +// empty, but referrer-policy set on this file diff --git a/test/wpt/tests/fetch/api/policies/nested-policy.js.headers b/test/wpt/tests/fetch/api/policies/nested-policy.js.headers new file mode 100644 index 0000000..7ffbf17 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/nested-policy.js.headers @@ -0,0 +1 @@ +Referrer-Policy: no-referrer diff --git a/test/wpt/tests/fetch/api/policies/referrer-no-referrer-service-worker.https.html b/test/wpt/tests/fetch/api/policies/referrer-no-referrer-service-worker.https.html new file mode 100644 index 0000000..af898aa --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-no-referrer-service-worker.https.html @@ -0,0 +1,18 @@ + + + + + Fetch in service worker: referrer with no-referrer policy + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/policies/referrer-no-referrer-worker.html b/test/wpt/tests/fetch/api/policies/referrer-no-referrer-worker.html new file mode 100644 index 0000000..dbef9bb --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-no-referrer-worker.html @@ -0,0 +1,17 @@ + + + + + Fetch in worker: referrer with no-referrer policy + + + + + + + + + + \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/policies/referrer-no-referrer.html b/test/wpt/tests/fetch/api/policies/referrer-no-referrer.html new file mode 100644 index 0000000..22a6f34 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-no-referrer.html @@ -0,0 +1,15 @@ + + + + + Fetch: referrer with no-referrer policy + + + + + + + + + + \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/policies/referrer-no-referrer.html.headers b/test/wpt/tests/fetch/api/policies/referrer-no-referrer.html.headers new file mode 100644 index 0000000..7ffbf17 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-no-referrer.html.headers @@ -0,0 +1 @@ +Referrer-Policy: no-referrer diff --git a/test/wpt/tests/fetch/api/policies/referrer-no-referrer.js b/test/wpt/tests/fetch/api/policies/referrer-no-referrer.js new file mode 100644 index 0000000..60600bf --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-no-referrer.js @@ -0,0 +1,19 @@ +if (this.document === undefined) { + importScripts("/resources/testharness.js"); + importScripts("../resources/utils.js"); +} + +var fetchedUrl = RESOURCES_DIR + "inspect-headers.py?headers=origin"; + +promise_test(function(test) { + return fetch(fetchedUrl).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type , "basic", "Response's type is basic"); + var referrer = resp.headers.get("x-request-referer"); + //Either no referrer header is sent or it is empty + if (referrer) + assert_equals(referrer, "", "request's referrer is empty"); + }); +}, "Request's referrer is empty"); + +done(); diff --git a/test/wpt/tests/fetch/api/policies/referrer-no-referrer.js.headers b/test/wpt/tests/fetch/api/policies/referrer-no-referrer.js.headers new file mode 100644 index 0000000..7ffbf17 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-no-referrer.js.headers @@ -0,0 +1 @@ +Referrer-Policy: no-referrer diff --git a/test/wpt/tests/fetch/api/policies/referrer-origin-service-worker.https.html b/test/wpt/tests/fetch/api/policies/referrer-origin-service-worker.https.html new file mode 100644 index 0000000..4018b83 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-origin-service-worker.https.html @@ -0,0 +1,18 @@ + + + + + Fetch in service worker: referrer with no-referrer policy + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin-service-worker.https.html b/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin-service-worker.https.html new file mode 100644 index 0000000..d87192e --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin-service-worker.https.html @@ -0,0 +1,17 @@ + + + + + Fetch in service worker: referrer with origin-when-cross-origin policy + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin-worker.html b/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin-worker.html new file mode 100644 index 0000000..f95ae8c --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin-worker.html @@ -0,0 +1,16 @@ + + + + + Fetch in worker: referrer with origin-when-cross-origin policy + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.html b/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.html new file mode 100644 index 0000000..5cd79e4 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.html @@ -0,0 +1,16 @@ + + + + + Fetch: referrer with origin-when-cross-origin policy + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.html.headers b/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.html.headers new file mode 100644 index 0000000..ad768e6 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.html.headers @@ -0,0 +1 @@ +Referrer-Policy: origin-when-cross-origin diff --git a/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.js b/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.js new file mode 100644 index 0000000..0adadbc --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.js @@ -0,0 +1,21 @@ +if (this.document === undefined) { + importScripts("/resources/testharness.js"); + importScripts("../resources/utils.js"); + importScripts("/common/get-host-info.sub.js"); + + // A nested importScripts() with a referrer-policy should have no effect + // on overall worker policy. + importScripts("nested-policy.js"); +} + +var referrerOrigin = location.origin + '/'; +var fetchedUrl = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "inspect-headers.py?cors&headers=referer"; + +promise_test(function(test) { + return fetch(fetchedUrl).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.headers.get("x-request-referer"), referrerOrigin, "request's referrer is " + referrerOrigin); + }); +}, "Request's referrer is origin"); + +done(); diff --git a/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.js.headers b/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.js.headers new file mode 100644 index 0000000..ad768e6 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-origin-when-cross-origin.js.headers @@ -0,0 +1 @@ +Referrer-Policy: origin-when-cross-origin diff --git a/test/wpt/tests/fetch/api/policies/referrer-origin-worker.html b/test/wpt/tests/fetch/api/policies/referrer-origin-worker.html new file mode 100644 index 0000000..bb80dd5 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-origin-worker.html @@ -0,0 +1,17 @@ + + + + + Fetch in worker: referrer with origin policy + + + + + + + + + + \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/policies/referrer-origin.html b/test/wpt/tests/fetch/api/policies/referrer-origin.html new file mode 100644 index 0000000..b164afe --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-origin.html @@ -0,0 +1,16 @@ + + + + + Fetch: referrer with origin policy + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/policies/referrer-origin.html.headers b/test/wpt/tests/fetch/api/policies/referrer-origin.html.headers new file mode 100644 index 0000000..5b29739 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-origin.html.headers @@ -0,0 +1 @@ +Referrer-Policy: origin diff --git a/test/wpt/tests/fetch/api/policies/referrer-origin.js b/test/wpt/tests/fetch/api/policies/referrer-origin.js new file mode 100644 index 0000000..918f8f2 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-origin.js @@ -0,0 +1,30 @@ +if (this.document === undefined) { + importScripts("/resources/testharness.js"); + importScripts("../resources/utils.js"); + + // A nested importScripts() with a referrer-policy should have no effect + // on overall worker policy. + importScripts("nested-policy.js"); +} + +var referrerOrigin = (new URL("/", location.href)).href; +var fetchedUrl = RESOURCES_DIR + "inspect-headers.py?headers=referer"; + +promise_test(function(test) { + return fetch(fetchedUrl).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type , "basic", "Response's type is basic"); + assert_equals(resp.headers.get("x-request-referer"), referrerOrigin, "request's referrer is " + referrerOrigin); + }); +}, "Request's referrer is origin"); + +promise_test(function(test) { + var referrerUrl = "https://{{domains[www]}}:{{ports[https][0]}}/"; + return fetch(fetchedUrl, { "referrer": referrerUrl }).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type , "basic", "Response's type is basic"); + assert_equals(resp.headers.get("x-request-referer"), referrerOrigin, "request's referrer is " + referrerOrigin); + }); +}, "Cross-origin referrer is overridden by client origin"); + +done(); diff --git a/test/wpt/tests/fetch/api/policies/referrer-origin.js.headers b/test/wpt/tests/fetch/api/policies/referrer-origin.js.headers new file mode 100644 index 0000000..5b29739 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-origin.js.headers @@ -0,0 +1 @@ +Referrer-Policy: origin diff --git a/test/wpt/tests/fetch/api/policies/referrer-unsafe-url-service-worker.https.html b/test/wpt/tests/fetch/api/policies/referrer-unsafe-url-service-worker.https.html new file mode 100644 index 0000000..634877e --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-unsafe-url-service-worker.https.html @@ -0,0 +1,18 @@ + + + + + Fetch in worker: referrer with unsafe-url policy + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/policies/referrer-unsafe-url-worker.html b/test/wpt/tests/fetch/api/policies/referrer-unsafe-url-worker.html new file mode 100644 index 0000000..4204577 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-unsafe-url-worker.html @@ -0,0 +1,17 @@ + + + + + Fetch in worker: referrer with unsafe-url policy + + + + + + + + + + \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/policies/referrer-unsafe-url.html b/test/wpt/tests/fetch/api/policies/referrer-unsafe-url.html new file mode 100644 index 0000000..10dd79e --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-unsafe-url.html @@ -0,0 +1,16 @@ + + + + + Fetch: referrer with unsafe-url policy + + + + + + + + + + + \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/policies/referrer-unsafe-url.html.headers b/test/wpt/tests/fetch/api/policies/referrer-unsafe-url.html.headers new file mode 100644 index 0000000..8e23770 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-unsafe-url.html.headers @@ -0,0 +1 @@ +Referrer-Policy: unsafe-url diff --git a/test/wpt/tests/fetch/api/policies/referrer-unsafe-url.js b/test/wpt/tests/fetch/api/policies/referrer-unsafe-url.js new file mode 100644 index 0000000..4d61172 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-unsafe-url.js @@ -0,0 +1,21 @@ +if (this.document === undefined) { + importScripts("/resources/testharness.js"); + importScripts("../resources/utils.js"); + + // A nested importScripts() with a referrer-policy should have no effect + // on overall worker policy. + importScripts("nested-policy.js"); +} + +var referrerUrl = location.href; +var fetchedUrl = RESOURCES_DIR + "inspect-headers.py?headers=referer"; + +promise_test(function(test) { + return fetch(fetchedUrl).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type , "basic", "Response's type is basic"); + assert_equals(resp.headers.get("x-request-referer"), referrerUrl, "request's referrer is " + referrerUrl); + }); +}, "Request's referrer is the full url of current document/worker"); + +done(); diff --git a/test/wpt/tests/fetch/api/policies/referrer-unsafe-url.js.headers b/test/wpt/tests/fetch/api/policies/referrer-unsafe-url.js.headers new file mode 100644 index 0000000..8e23770 --- /dev/null +++ b/test/wpt/tests/fetch/api/policies/referrer-unsafe-url.js.headers @@ -0,0 +1 @@ +Referrer-Policy: unsafe-url diff --git a/test/wpt/tests/fetch/api/redirect/redirect-back-to-original-origin.any.js b/test/wpt/tests/fetch/api/redirect/redirect-back-to-original-origin.any.js new file mode 100644 index 0000000..74d731f --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-back-to-original-origin.any.js @@ -0,0 +1,38 @@ +// META: global=window,worker +// META: script=/common/get-host-info.sub.js + +const BASE = location.href; +const IS_HTTPS = new URL(BASE).protocol === 'https:'; +const REMOTE_HOST = get_host_info()['REMOTE_HOST']; +const REMOTE_PORT = + IS_HTTPS ? get_host_info()['HTTPS_PORT'] : get_host_info()['HTTP_PORT']; + +const REMOTE_ORIGIN = + new URL(`//${REMOTE_HOST}:${REMOTE_PORT}`, BASE).origin; +const DESTINATION = new URL('../resources/cors-top.txt', BASE); + +function CreateURL(url, BASE, params) { + const u = new URL(url, BASE); + for (const {name, value} of params) { + u.searchParams.append(name, value); + } + return u; +} + +const redirect = + CreateURL('/fetch/api/resources/redirect.py', REMOTE_ORIGIN, + [{name: 'redirect_status', value: 303}, + {name: 'location', value: DESTINATION.href}]); + +promise_test(async (test) => { + const res = await fetch(redirect.href, {mode: 'no-cors'}); + // This is discussed at https://github.com/whatwg/fetch/issues/737. + assert_equals(res.type, 'opaque'); +}, 'original => remote => original with mode: "no-cors"'); + +promise_test(async (test) => { + const res = await fetch(redirect.href, {mode: 'cors'}); + assert_equals(res.type, 'cors'); +}, 'original => remote => original with mode: "cors"'); + +done(); diff --git a/test/wpt/tests/fetch/api/redirect/redirect-count.any.js b/test/wpt/tests/fetch/api/redirect/redirect-count.any.js new file mode 100644 index 0000000..420f9c0 --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-count.any.js @@ -0,0 +1,51 @@ +// META: global=window,worker +// META: script=../resources/utils.js +// META: script=/common/utils.js +// META: timeout=long + +/** + * Fetches a target that returns response with HTTP status code `statusCode` to + * redirect `maxCount` times. + */ +function redirectCountTest(maxCount, {statusCode, shouldPass = true} = {}) { + const desc = `Redirect ${statusCode} ${maxCount} times`; + + const fromUrl = `${RESOURCES_DIR}redirect.py`; + const toUrl = fromUrl; + const token1 = token(); + const url = `${fromUrl}?token=${token1}` + + `&max_age=0` + + `&redirect_status=${statusCode}` + + `&max_count=${maxCount}` + + `&location=${encodeURIComponent(toUrl)}`; + + const requestInit = {'redirect': 'follow'}; + + promise_test((test) => { + return fetch(`${RESOURCES_DIR}clean-stash.py?token=${token1}`) + .then((resp) => { + assert_equals( + resp.status, 200, 'Clean stash response\'s status is 200'); + + if (!shouldPass) + return promise_rejects_js(test, TypeError, fetch(url, requestInit)); + + return fetch(url, requestInit) + .then((resp) => { + assert_equals(resp.status, 200, 'Response\'s status is 200'); + return resp.text(); + }) + .then((body) => { + assert_equals( + body, maxCount.toString(), `Redirected ${maxCount} times`); + }); + }); + }, desc); +} + +for (const statusCode of [301, 302, 303, 307, 308]) { + redirectCountTest(20, {statusCode}); + redirectCountTest(21, {statusCode, shouldPass: false}); +} + +done(); diff --git a/test/wpt/tests/fetch/api/redirect/redirect-empty-location.any.js b/test/wpt/tests/fetch/api/redirect/redirect-empty-location.any.js new file mode 100644 index 0000000..487f4d4 --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-empty-location.any.js @@ -0,0 +1,21 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +// Tests receiving a redirect response with a Location header with an empty +// value. + +const url = RESOURCES_DIR + 'redirect-empty-location.py'; + +promise_test(t => { + return promise_rejects_js(t, TypeError, fetch(url, {redirect:'follow'})); +}, 'redirect response with empty Location, follow mode'); + +promise_test(t => { + return fetch(url, {redirect:'manual'}) + .then(resp => { + assert_equals(resp.type, 'opaqueredirect'); + assert_equals(resp.status, 0); + }); +}, 'redirect response with empty Location, manual mode'); + +done(); diff --git a/test/wpt/tests/fetch/api/redirect/redirect-keepalive.any.js b/test/wpt/tests/fetch/api/redirect/redirect-keepalive.any.js new file mode 100644 index 0000000..bcfc444 --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-keepalive.any.js @@ -0,0 +1,94 @@ +// META: global=window +// META: title=Fetch API: keepalive handling +// META: script=/resources/testharness.js +// META: script=/resources/testharnessreport.js +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=../resources/keepalive-helper.js + +'use strict'; + +const { + HTTP_NOTSAMESITE_ORIGIN, + HTTP_REMOTE_ORIGIN, + HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT +} = get_host_info(); + +/** + * In an iframe, test to fetch a keepalive URL that involves in redirect to + * another URL. + */ +function keepaliveRedirectTest( + desc, {origin1 = '', origin2 = '', withPreflight = false} = {}) { + desc = `[keepalive] ${desc}`; + promise_test(async (test) => { + const tokenToStash = token(); + const iframe = document.createElement('iframe'); + iframe.src = getKeepAliveAndRedirectIframeUrl( + tokenToStash, origin1, origin2, withPreflight); + document.body.appendChild(iframe); + await iframeLoaded(iframe); + assert_equals(await getTokenFromMessage(), tokenToStash); + iframe.remove(); + + assertStashedTokenAsync(desc, tokenToStash); + }, `${desc}; setting up`); +} + +/** + * Opens a different site window, and in `unload` event handler, test to fetch + * a keepalive URL that involves in redirect to another URL. + */ +function keepaliveRedirectInUnloadTest(desc, { + origin1 = '', + origin2 = '', + url2 = '', + withPreflight = false, + shouldPass = true +} = {}) { + desc = `[keepalive][new window][unload] ${desc}`; + + promise_test(async (test) => { + const targetUrl = + `${HTTP_NOTSAMESITE_ORIGIN}/fetch/api/resources/keepalive-redirect-window.html?` + + `origin1=${origin1}&` + + `origin2=${origin2}&` + + `url2=${url2}&` + (withPreflight ? `with-headers` : ``); + const w = window.open(targetUrl); + const token = await getTokenFromMessage(); + w.close(); + + assertStashedTokenAsync(desc, token, {shouldPass}); + }, `${desc}; setting up`); +} + +keepaliveRedirectTest(`same-origin redirect`); +keepaliveRedirectTest( + `same-origin redirect + preflight`, {withPreflight: true}); +keepaliveRedirectTest(`cross-origin redirect`, { + origin1: HTTP_REMOTE_ORIGIN, + origin2: HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT +}); +keepaliveRedirectTest(`cross-origin redirect + preflight`, { + origin1: HTTP_REMOTE_ORIGIN, + origin2: HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT, + withPreflight: true +}); + +keepaliveRedirectInUnloadTest('same-origin redirect'); +keepaliveRedirectInUnloadTest( + 'same-origin redirect + preflight', {withPreflight: true}); +keepaliveRedirectInUnloadTest('cross-origin redirect', { + origin1: HTTP_REMOTE_ORIGIN, + origin2: HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT +}); +keepaliveRedirectInUnloadTest('cross-origin redirect + preflight', { + origin1: HTTP_REMOTE_ORIGIN, + origin2: HTTP_REMOTE_ORIGIN_WITH_DIFFERENT_PORT, + withPreflight: true +}); +keepaliveRedirectInUnloadTest( + 'redirect to file URL', {url2: 'file://tmp/bar.txt', shouldPass: false}); +keepaliveRedirectInUnloadTest( + 'redirect to data URL', + {url2: 'data:text/plain;base64,cmVzcG9uc2UncyBib2R5', shouldPass: false}); diff --git a/test/wpt/tests/fetch/api/redirect/redirect-location-escape.tentative.any.js b/test/wpt/tests/fetch/api/redirect/redirect-location-escape.tentative.any.js new file mode 100644 index 0000000..779ad70 --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-location-escape.tentative.any.js @@ -0,0 +1,46 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +// See https://github.com/whatwg/fetch/issues/883 for the behavior covered by +// this test. As of writing, the Fetch spec has not been updated to cover these. + +// redirectLocation tests that a Location header of |locationHeader| is resolved +// to a URL which ends in |expectedUrlSuffix|. |locationHeader| is interpreted +// as a byte sequence via isomorphic encode, as described in [INFRA]. This +// allows the caller to specify byte sequences which are not valid UTF-8. +// However, this means, e.g., U+2603 must be passed in as "\xe2\x98\x83", its +// UTF-8 encoding, not "\u2603". +// +// [INFRA] https://infra.spec.whatwg.org/#isomorphic-encode +function redirectLocation( + desc, redirectUrl, locationHeader, expectedUrlSuffix) { + promise_test(function(test) { + // Note we use escape() instead of encodeURIComponent(), so that characters + // are escaped as bytes in the isomorphic encoding. + var url = redirectUrl + '?simple=1&location=' + escape(locationHeader); + + return fetch(url, {'redirect': 'follow'}).then(function(resp) { + assert_true( + resp.url.endsWith(expectedUrlSuffix), + resp.url + ' ends with ' + expectedUrlSuffix); + }); + }, desc); +} + +var redirUrl = RESOURCES_DIR + 'redirect.py'; +redirectLocation( + 'Redirect to escaped UTF-8', redirUrl, 'top.txt?%E2%98%83%e2%98%83', + 'top.txt?%E2%98%83%e2%98%83'); +redirectLocation( + 'Redirect to unescaped UTF-8', redirUrl, 'top.txt?\xe2\x98\x83', + 'top.txt?%E2%98%83'); +redirectLocation( + 'Redirect to escaped and unescaped UTF-8', redirUrl, + 'top.txt?\xe2\x98\x83%e2%98%83', 'top.txt?%E2%98%83%e2%98%83'); +redirectLocation( + 'Escaping produces double-percent', redirUrl, 'top.txt?%\xe2\x98\x83', + 'top.txt?%%E2%98%83'); +redirectLocation( + 'Redirect to invalid UTF-8', redirUrl, 'top.txt?\xff', 'top.txt?%FF'); + +done(); diff --git a/test/wpt/tests/fetch/api/redirect/redirect-location.any.js b/test/wpt/tests/fetch/api/redirect/redirect-location.any.js new file mode 100644 index 0000000..3d483bd --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-location.any.js @@ -0,0 +1,73 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +const VALID_URL = 'top.txt'; +const INVALID_URL = 'invalidurl:'; +const DATA_URL = 'data:text/plain;base64,cmVzcG9uc2UncyBib2R5'; + +/** + * A test to fetch a URL that returns response redirecting to `toUrl` with + * `status` as its HTTP status code. `expectStatus` can be set to test the + * status code in fetch's Promise response. + */ +function redirectLocationTest(toUrlDesc, { + toUrl = undefined, + status, + expectStatus = undefined, + mode, + shouldPass = true +} = {}) { + toUrlDesc = toUrl ? `with ${toUrlDesc}` : `without`; + const desc = `Redirect ${status} in "${mode}" mode ${toUrlDesc} location`; + const url = `${RESOURCES_DIR}redirect.py?redirect_status=${status}` + + (toUrl ? `&location=${encodeURIComponent(toUrl)}` : ''); + const requestInit = {'redirect': mode}; + if (!expectStatus) + expectStatus = status; + + promise_test((test) => { + if (mode === 'error' || !shouldPass) + return promise_rejects_js(test, TypeError, fetch(url, requestInit)); + if (mode === 'manual') + return fetch(url, requestInit).then((resp) => { + assert_equals(resp.status, 0, "Response's status is 0"); + assert_equals(resp.type, "opaqueredirect", "Response's type is opaqueredirect"); + assert_equals(resp.statusText, '', `Response's statusText is ""`); + assert_true(resp.headers.entries().next().done, "Headers should be empty"); + }); + + if (mode === 'follow') + return fetch(url, requestInit).then((resp) => { + assert_equals( + resp.status, expectStatus, `Response's status is ${expectStatus}`); + }); + assert_unreached(`${mode} is not a valid redirect mode`); + }, desc); +} + +// FIXME: We may want to mix redirect-mode and cors-mode. +for (const status of [301, 302, 303, 307, 308]) { + redirectLocationTest('without location', {status, mode: 'follow'}); + redirectLocationTest('without location', {status, mode: 'manual'}); + // FIXME: Add tests for "error" redirect-mode without location. + + // When succeeded, `follow` mode should have followed all redirects. + redirectLocationTest( + 'valid', {toUrl: VALID_URL, status, expectStatus: 200, mode: 'follow'}); + redirectLocationTest('valid', {toUrl: VALID_URL, status, mode: 'manual'}); + redirectLocationTest('valid', {toUrl: VALID_URL, status, mode: 'error'}); + + redirectLocationTest( + 'invalid', + {toUrl: INVALID_URL, status, mode: 'follow', shouldPass: false}); + redirectLocationTest('invalid', {toUrl: INVALID_URL, status, mode: 'manual'}); + redirectLocationTest('invalid', {toUrl: INVALID_URL, status, mode: 'error'}); + + redirectLocationTest( + 'data', {toUrl: DATA_URL, status, mode: 'follow', shouldPass: false}); + // FIXME: Should this pass? + redirectLocationTest('data', {toUrl: DATA_URL, status, mode: 'manual'}); + redirectLocationTest('data', {toUrl: DATA_URL, status, mode: 'error'}); +} + +done(); diff --git a/test/wpt/tests/fetch/api/redirect/redirect-method.any.js b/test/wpt/tests/fetch/api/redirect/redirect-method.any.js new file mode 100644 index 0000000..9fe086a --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-method.any.js @@ -0,0 +1,112 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +// Creates a promise_test that fetches a URL that returns a redirect response. +// +// |opts| has additional options: +// |opts.body|: the request body as a string or blob (default is empty body) +// |opts.expectedBodyAsString|: the expected response body as a string. The +// server is expected to echo the request body. The default is the empty string +// if the request after redirection isn't POST; otherwise it's |opts.body|. +// |opts.expectedRequestContentType|: the expected Content-Type of redirected +// request. +function redirectMethod(desc, redirectUrl, redirectLocation, redirectStatus, method, expectedMethod, opts) { + let url = redirectUrl; + let urlParameters = "?redirect_status=" + redirectStatus; + urlParameters += "&location=" + encodeURIComponent(redirectLocation); + + let requestHeaders = { + "Content-Encoding": "Identity", + "Content-Language": "en-US", + "Content-Location": "foo", + }; + let requestInit = {"method": method, "redirect": "follow", "headers" : requestHeaders}; + opts = opts || {}; + if (opts.body) { + requestInit.body = opts.body; + } + + promise_test(function(test) { + return fetch(url + urlParameters, requestInit).then(function(resp) { + let expectedRequestContentType = "NO"; + if (opts.expectedRequestContentType) { + expectedRequestContentType = opts.expectedRequestContentType; + } + + assert_equals(resp.status, 200, "Response's status is 200"); + assert_equals(resp.type, "basic", "Response's type basic"); + assert_equals( + resp.headers.get("x-request-method"), + expectedMethod, + "Request method after redirection is " + expectedMethod); + let hasRequestBodyHeader = true; + if (opts.expectedStripRequestBodyHeader) { + hasRequestBodyHeader = !opts.expectedStripRequestBodyHeader; + } + assert_equals( + resp.headers.get("x-request-content-type"), + expectedRequestContentType, + "Request Content-Type after redirection is " + expectedRequestContentType); + [ + "Content-Encoding", + "Content-Language", + "Content-Location" + ].forEach(header => { + let xHeader = "x-request-" + header.toLowerCase(); + let expectedValue = hasRequestBodyHeader ? requestHeaders[header] : "NO"; + assert_equals( + resp.headers.get(xHeader), + expectedValue, + "Request " + header + " after redirection is " + expectedValue); + }); + assert_true(resp.redirected); + return resp.text().then(function(text) { + let expectedBody = ""; + if (expectedMethod == "POST") { + expectedBody = opts.expectedBodyAsString || requestInit.body; + } + let expectedContentLength = expectedBody ? expectedBody.length.toString() : "NO"; + assert_equals(text, expectedBody, "request body"); + assert_equals( + resp.headers.get("x-request-content-length"), + expectedContentLength, + "Request Content-Length after redirection is " + expectedContentLength); + }); + }); + }, desc); +} + +promise_test(function(test) { + assert_false(new Response().redirected); + return fetch(RESOURCES_DIR + "method.py").then(function(resp) { + assert_equals(resp.status, 200, "Response's status is 200"); + assert_false(resp.redirected); + }); +}, "Response.redirected should be false on not-redirected responses"); + +var redirUrl = RESOURCES_DIR + "redirect.py"; +var locationUrl = "method.py"; + +const stringBody = "this is my body"; +const blobBody = new Blob(["it's me the blob!", " ", "and more blob!"]); +const blobBodyAsString = "it's me the blob! and more blob!"; + +redirectMethod("Redirect 301 with GET", redirUrl, locationUrl, 301, "GET", "GET"); +redirectMethod("Redirect 301 with POST", redirUrl, locationUrl, 301, "POST", "GET", { body: stringBody, expectedStripRequestBodyHeader: true }); +redirectMethod("Redirect 301 with HEAD", redirUrl, locationUrl, 301, "HEAD", "HEAD"); + +redirectMethod("Redirect 302 with GET", redirUrl, locationUrl, 302, "GET", "GET"); +redirectMethod("Redirect 302 with POST", redirUrl, locationUrl, 302, "POST", "GET", { body: stringBody, expectedStripRequestBodyHeader: true }); +redirectMethod("Redirect 302 with HEAD", redirUrl, locationUrl, 302, "HEAD", "HEAD"); + +redirectMethod("Redirect 303 with GET", redirUrl, locationUrl, 303, "GET", "GET"); +redirectMethod("Redirect 303 with POST", redirUrl, locationUrl, 303, "POST", "GET", { body: stringBody, expectedStripRequestBodyHeader: true }); +redirectMethod("Redirect 303 with HEAD", redirUrl, locationUrl, 303, "HEAD", "HEAD"); +redirectMethod("Redirect 303 with TESTING", redirUrl, locationUrl, 303, "TESTING", "GET", { expectedStripRequestBodyHeader: true }); + +redirectMethod("Redirect 307 with GET", redirUrl, locationUrl, 307, "GET", "GET"); +redirectMethod("Redirect 307 with POST (string body)", redirUrl, locationUrl, 307, "POST", "POST", { body: stringBody , expectedRequestContentType: "text/plain;charset=UTF-8"}); +redirectMethod("Redirect 307 with POST (blob body)", redirUrl, locationUrl, 307, "POST", "POST", { body: blobBody, expectedBodyAsString: blobBodyAsString }); +redirectMethod("Redirect 307 with HEAD", redirUrl, locationUrl, 307, "HEAD", "HEAD"); + +done(); diff --git a/test/wpt/tests/fetch/api/redirect/redirect-mode.any.js b/test/wpt/tests/fetch/api/redirect/redirect-mode.any.js new file mode 100644 index 0000000..9f1ff98 --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-mode.any.js @@ -0,0 +1,59 @@ +// META: script=/common/get-host-info.sub.js + +var redirectLocation = "cors-top.txt"; +const { ORIGIN, REMOTE_ORIGIN } = get_host_info(); + +function testRedirect(origin, redirectStatus, redirectMode, corsMode) { + var url = new URL("../resources/redirect.py", self.location); + if (origin === "cross-origin") { + url.host = get_host_info().REMOTE_HOST; + url.port = get_host_info().HTTP_PORT; + } + + var urlParameters = "?redirect_status=" + redirectStatus; + urlParameters += "&location=" + encodeURIComponent(redirectLocation); + + var requestInit = {redirect: redirectMode, mode: corsMode}; + + promise_test(function(test) { + if (redirectMode === "error" || + (corsMode === "no-cors" && redirectMode !== "follow" && origin !== "same-origin")) + return promise_rejects_js(test, TypeError, fetch(url + urlParameters, requestInit)); + if (redirectMode === "manual") + return fetch(url + urlParameters, requestInit).then(function(resp) { + assert_equals(resp.status, 0, "Response's status is 0"); + assert_equals(resp.type, "opaqueredirect", "Response's type is opaqueredirect"); + assert_equals(resp.statusText, "", "Response's statusText is \"\""); + assert_equals(resp.url, url + urlParameters, "Response URL should be the original one"); + }); + if (redirectMode === "follow") + return fetch(url + urlParameters, requestInit).then(function(resp) { + if (corsMode !== "no-cors" || origin === "same-origin") { + assert_true(new URL(resp.url).pathname.endsWith(redirectLocation), "Response's url should be the redirected one"); + assert_equals(resp.status, 200, "Response's status is 200"); + } else { + assert_equals(resp.type, "opaque", "Response is opaque"); + } + }); + assert_unreached(redirectMode + " is no a valid redirect mode"); + }, origin + " redirect " + redirectStatus + " in " + redirectMode + " redirect and " + corsMode + " mode"); +} + +for (var origin of ["same-origin", "cross-origin"]) { + for (var statusCode of [301, 302, 303, 307, 308]) { + for (var redirect of ["error", "manual", "follow"]) { + for (var mode of ["cors", "no-cors"]) + testRedirect(origin, statusCode, redirect, mode); + } + } +} + +promise_test(async (t) => { + const destination = `${ORIGIN}/common/blank.html`; + // We use /common/redirect.py intentionally, as we want a CORS error. + const url = + `${REMOTE_ORIGIN}/common/redirect.py?location=${destination}`; + await promise_rejects_js(t, TypeError, fetch(url, { redirect: "manual" })); +}, "manual redirect with a CORS error should be rejected"); + +done(); diff --git a/test/wpt/tests/fetch/api/redirect/redirect-origin.any.js b/test/wpt/tests/fetch/api/redirect/redirect-origin.any.js new file mode 100644 index 0000000..6001c50 --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-origin.any.js @@ -0,0 +1,68 @@ +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +const { + HTTP_ORIGIN, + HTTP_REMOTE_ORIGIN, +} = get_host_info(); + +/** + * Fetches `fromUrl` with 'cors' and 'follow' modes that returns response to + * redirect to `toUrl`. + */ +function testOriginAfterRedirection( + desc, method, fromUrl, toUrl, statusCode, expectedOrigin) { + desc = `[${method}] Redirect ${statusCode} ${desc}`; + const token1 = token(); + const url = `${fromUrl}?token=${token1}&max_age=0` + + `&redirect_status=${statusCode}` + + `&location=${encodeURIComponent(toUrl)}`; + + const requestInit = {method, 'mode': 'cors', 'redirect': 'follow'}; + + promise_test(function(test) { + return fetch(`${RESOURCES_DIR}clean-stash.py?token=${token1}`) + .then((cleanResponse) => { + assert_equals( + cleanResponse.status, 200, + `Clean stash response's status is 200`); + return fetch(url, requestInit).then((redirectResponse) => { + assert_equals( + redirectResponse.status, 200, + `Inspect header response's status is 200`); + assert_equals( + redirectResponse.headers.get('x-request-origin'), + expectedOrigin, 'Check origin header'); + }); + }); + }, desc); +} + +const FROM_URL = `${RESOURCES_DIR}redirect.py`; +const CORS_FROM_URL = + `${HTTP_REMOTE_ORIGIN}${dirname(location.pathname)}${FROM_URL}`; +const TO_URL = `${HTTP_ORIGIN}${dirname(location.pathname)}${ + RESOURCES_DIR}inspect-headers.py?headers=origin`; +const CORS_TO_URL = `${HTTP_REMOTE_ORIGIN}${dirname(location.pathname)}${ + RESOURCES_DIR}inspect-headers.py?cors&headers=origin`; + +for (const statusCode of [301, 302, 303, 307, 308]) { + for (const method of ['GET', 'POST']) { + testOriginAfterRedirection( + 'Same origin to same origin', method, FROM_URL, TO_URL, statusCode, + null); + testOriginAfterRedirection( + 'Same origin to other origin', method, FROM_URL, CORS_TO_URL, + statusCode, HTTP_ORIGIN); + testOriginAfterRedirection( + 'Other origin to other origin', method, CORS_FROM_URL, CORS_TO_URL, + statusCode, HTTP_ORIGIN); + // TODO(crbug.com/1432059): Fix broken tests. + testOriginAfterRedirection( + 'Other origin to same origin', method, CORS_FROM_URL, `${TO_URL}&cors`, + statusCode, 'null'); + } +} + +done(); diff --git a/test/wpt/tests/fetch/api/redirect/redirect-referrer-override.any.js b/test/wpt/tests/fetch/api/redirect/redirect-referrer-override.any.js new file mode 100644 index 0000000..56e55d7 --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-referrer-override.any.js @@ -0,0 +1,104 @@ +// META: timeout=long +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +function getExpectation(expectations, init, initScenario, redirectPolicy, redirectScenario) { + let policies = [ + expectations[initPolicy][initScenario], + expectations[redirectPolicy][redirectScenario] + ]; + + if (policies.includes("omitted")) { + return null; + } else if (policies.includes("origin")) { + return referrerOrigin; + } else { + // "stripped-referrer" + return referrerUrl; + } +} + +function testReferrerAfterRedirection(desc, redirectUrl, redirectLocation, referrerPolicy, redirectReferrerPolicy, expectedReferrer) { + var url = redirectUrl; + var urlParameters = "?location=" + encodeURIComponent(redirectLocation); + var description = desc + ", " + referrerPolicy + " init, " + redirectReferrerPolicy + " redirect header "; + + if (redirectReferrerPolicy) + urlParameters += "&redirect_referrerpolicy=" + redirectReferrerPolicy; + + var requestInit = {"redirect": "follow", "referrerPolicy": referrerPolicy}; + promise_test(function(test) { + return fetch(url + urlParameters, requestInit).then(function(response) { + assert_equals(response.status, 200, "Inspect header response's status is 200"); + assert_equals(response.headers.get("x-request-referer"), expectedReferrer ? expectedReferrer : null, "Check referrer header"); + }); + }, description); +} + +var referrerOrigin = get_host_info().HTTP_ORIGIN + "/"; +var referrerUrl = location.href; + +var redirectUrl = RESOURCES_DIR + "redirect.py"; +var locationUrl = get_host_info().HTTP_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "inspect-headers.py?headers=referer"; +var crossLocationUrl = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "inspect-headers.py?cors&headers=referer"; + +var expectations = { + "no-referrer": { + "same-origin": "omitted", + "cross-origin": "omitted" + }, + "no-referrer-when-downgrade": { + "same-origin": "stripped-referrer", + "cross-origin": "stripped-referrer" + }, + "origin": { + "same-origin": "origin", + "cross-origin": "origin" + }, + "origin-when-cross-origin": { + "same-origin": "stripped-referrer", + "cross-origin": "origin", + }, + "same-origin": { + "same-origin": "stripped-referrer", + "cross-origin": "omitted" + }, + "strict-origin": { + "same-origin": "origin", + "cross-origin": "origin" + }, + "strict-origin-when-cross-origin": { + "same-origin": "stripped-referrer", + "cross-origin": "origin" + }, + "unsafe-url": { + "same-origin": "stripped-referrer", + "cross-origin": "stripped-referrer" + } +}; + +for (var initPolicy in expectations) { + for (var redirectPolicy in expectations) { + + // Redirect to same-origin URL + testReferrerAfterRedirection( + "Same origin redirection", + redirectUrl, + locationUrl, + initPolicy, + redirectPolicy, + getExpectation(expectations, initPolicy, "same-origin", redirectPolicy, "same-origin")); + + // Redirect to cross-origin URL + testReferrerAfterRedirection( + "Cross origin redirection", + redirectUrl, + crossLocationUrl, + initPolicy, + redirectPolicy, + getExpectation(expectations, initPolicy, "same-origin", redirectPolicy, "cross-origin")); + } +} + +done(); diff --git a/test/wpt/tests/fetch/api/redirect/redirect-referrer.any.js b/test/wpt/tests/fetch/api/redirect/redirect-referrer.any.js new file mode 100644 index 0000000..99fda42 --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-referrer.any.js @@ -0,0 +1,66 @@ +// META: timeout=long +// META: script=/common/utils.js +// META: script=../resources/utils.js +// META: script=/common/get-host-info.sub.js + +function testReferrerAfterRedirection(desc, redirectUrl, redirectLocation, referrerPolicy, redirectReferrerPolicy, expectedReferrer) { + var url = redirectUrl; + var urlParameters = "?location=" + encodeURIComponent(redirectLocation); + + if (redirectReferrerPolicy) + urlParameters += "&redirect_referrerpolicy=" + redirectReferrerPolicy; + + var requestInit = {"redirect": "follow", "referrerPolicy": referrerPolicy}; + + promise_test(function(test) { + return fetch(url + urlParameters, requestInit).then(function(response) { + assert_equals(response.status, 200, "Inspect header response's status is 200"); + assert_equals(response.headers.get("x-request-referer"), expectedReferrer ? expectedReferrer : null, "Check referrer header"); + }); + }, desc); +} + +var referrerOrigin = get_host_info().HTTP_ORIGIN + "/"; +var referrerUrl = location.href; + +var redirectUrl = RESOURCES_DIR + "redirect.py"; +var locationUrl = get_host_info().HTTP_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "inspect-headers.py?headers=referer"; +var crossLocationUrl = get_host_info().HTTP_REMOTE_ORIGIN + dirname(location.pathname) + RESOURCES_DIR + "inspect-headers.py?cors&headers=referer"; + +testReferrerAfterRedirection("Same origin redirection, empty init, unsafe-url redirect header ", redirectUrl, locationUrl, "", "unsafe-url", referrerUrl); +testReferrerAfterRedirection("Same origin redirection, empty init, no-referrer-when-downgrade redirect header ", redirectUrl, locationUrl, "", "no-referrer-when-downgrade", referrerUrl); +testReferrerAfterRedirection("Same origin redirection, empty init, same-origin redirect header ", redirectUrl, locationUrl, "", "same-origin", referrerUrl); +testReferrerAfterRedirection("Same origin redirection, empty init, origin redirect header ", redirectUrl, locationUrl, "", "origin", referrerOrigin); +testReferrerAfterRedirection("Same origin redirection, empty init, origin-when-cross-origin redirect header ", redirectUrl, locationUrl, "", "origin-when-cross-origin", referrerUrl); +testReferrerAfterRedirection("Same origin redirection, empty init, no-referrer redirect header ", redirectUrl, locationUrl, "", "no-referrer", null); +testReferrerAfterRedirection("Same origin redirection, empty init, strict-origin redirect header ", redirectUrl, locationUrl, "", "strict-origin", referrerOrigin); +testReferrerAfterRedirection("Same origin redirection, empty init, strict-origin-when-cross-origin redirect header ", redirectUrl, locationUrl, "", "strict-origin-when-cross-origin", referrerUrl); + +testReferrerAfterRedirection("Same origin redirection, empty redirect header, unsafe-url init ", redirectUrl, locationUrl, "unsafe-url", "", referrerUrl); +testReferrerAfterRedirection("Same origin redirection, empty redirect header, no-referrer-when-downgrade init ", redirectUrl, locationUrl, "no-referrer-when-downgrade", "", referrerUrl); +testReferrerAfterRedirection("Same origin redirection, empty redirect header, same-origin init ", redirectUrl, locationUrl, "same-origin", "", referrerUrl); +testReferrerAfterRedirection("Same origin redirection, empty redirect header, origin init ", redirectUrl, locationUrl, "origin", "", referrerOrigin); +testReferrerAfterRedirection("Same origin redirection, empty redirect header, origin-when-cross-origin init ", redirectUrl, locationUrl, "origin-when-cross-origin", "", referrerUrl); +testReferrerAfterRedirection("Same origin redirection, empty redirect header, no-referrer init ", redirectUrl, locationUrl, "no-referrer", "", null); +testReferrerAfterRedirection("Same origin redirection, empty redirect header, strict-origin init ", redirectUrl, locationUrl, "strict-origin", "", referrerOrigin); +testReferrerAfterRedirection("Same origin redirection, empty redirect header, strict-origin-when-cross-origin init ", redirectUrl, locationUrl, "strict-origin-when-cross-origin", "", referrerUrl); + +testReferrerAfterRedirection("Cross origin redirection, empty init, unsafe-url redirect header ", redirectUrl, crossLocationUrl, "", "unsafe-url", referrerUrl); +testReferrerAfterRedirection("Cross origin redirection, empty init, no-referrer-when-downgrade redirect header ", redirectUrl, crossLocationUrl, "", "no-referrer-when-downgrade", referrerUrl); +testReferrerAfterRedirection("Cross origin redirection, empty init, same-origin redirect header ", redirectUrl, crossLocationUrl, "", "same-origin", null); +testReferrerAfterRedirection("Cross origin redirection, empty init, origin redirect header ", redirectUrl, crossLocationUrl, "", "origin", referrerOrigin); +testReferrerAfterRedirection("Cross origin redirection, empty init, origin-when-cross-origin redirect header ", redirectUrl, crossLocationUrl, "", "origin-when-cross-origin", referrerOrigin); +testReferrerAfterRedirection("Cross origin redirection, empty init, no-referrer redirect header ", redirectUrl, crossLocationUrl, "", "no-referrer", null); +testReferrerAfterRedirection("Cross origin redirection, empty init, strict-origin redirect header ", redirectUrl, crossLocationUrl, "", "strict-origin", referrerOrigin); +testReferrerAfterRedirection("Cross origin redirection, empty init, strict-origin-when-cross-origin redirect header ", redirectUrl, crossLocationUrl, "", "strict-origin-when-cross-origin", referrerOrigin); + +testReferrerAfterRedirection("Cross origin redirection, empty redirect header, unsafe-url init ", redirectUrl, crossLocationUrl, "unsafe-url", "", referrerUrl); +testReferrerAfterRedirection("Cross origin redirection, empty redirect header, no-referrer-when-downgrade init ", redirectUrl, crossLocationUrl, "no-referrer-when-downgrade", "", referrerUrl); +testReferrerAfterRedirection("Cross origin redirection, empty redirect header, same-origin init ", redirectUrl, crossLocationUrl, "same-origin", "", null); +testReferrerAfterRedirection("Cross origin redirection, empty redirect header, origin init ", redirectUrl, crossLocationUrl, "origin", "", referrerOrigin); +testReferrerAfterRedirection("Cross origin redirection, empty redirect header, origin-when-cross-origin init ", redirectUrl, crossLocationUrl, "origin-when-cross-origin", "", referrerOrigin); +testReferrerAfterRedirection("Cross origin redirection, empty redirect header, no-referrer init ", redirectUrl, crossLocationUrl, "no-referrer", "", null); +testReferrerAfterRedirection("Cross origin redirection, empty redirect header, strict-origin init ", redirectUrl, crossLocationUrl, "strict-origin", "", referrerOrigin); +testReferrerAfterRedirection("Cross origin redirection, empty redirect header, strict-origin-when-cross-origin init ", redirectUrl, crossLocationUrl, "strict-origin-when-cross-origin", "", referrerOrigin); + +done(); diff --git a/test/wpt/tests/fetch/api/redirect/redirect-schemes.any.js b/test/wpt/tests/fetch/api/redirect/redirect-schemes.any.js new file mode 100644 index 0000000..31ec124 --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-schemes.any.js @@ -0,0 +1,19 @@ +// META: title=Fetch: handling different schemes in redirects +// META: global=window,worker +// META: script=/common/get-host-info.sub.js + +// All non-HTTP(S) schemes cannot survive redirects +var url = "../resources/redirect.py?location="; +var tests = [ + url + "mailto:a@a.com", + url + "data:,HI", + url + "facetime:a@a.org", + url + "about:blank", + url + "about:unicorn", + url + "blob:djfksfjs" +]; +tests.forEach(function(url) { + promise_test(function(test) { + return promise_rejects_js(test, TypeError, fetch(url)) + }) +}) diff --git a/test/wpt/tests/fetch/api/redirect/redirect-to-dataurl.any.js b/test/wpt/tests/fetch/api/redirect/redirect-to-dataurl.any.js new file mode 100644 index 0000000..9d0f147 --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-to-dataurl.any.js @@ -0,0 +1,28 @@ +// META: global=window,worker +// META: script=/common/get-host-info.sub.js + +var dataURL = "data:text/plain;base64,cmVzcG9uc2UncyBib2R5"; +var body = "response's body"; +var contentType = "text/plain"; + +function redirectDataURL(desc, redirectUrl, mode) { + var url = redirectUrl + "?cors&location=" + encodeURIComponent(dataURL); + + var requestInit = {"mode": mode}; + + promise_test(function(test) { + return promise_rejects_js(test, TypeError, fetch(url, requestInit)); + }, desc); +} + +var redirUrl = get_host_info().HTTP_ORIGIN + "/fetch/api/resources/redirect.py"; +var corsRedirUrl = get_host_info().HTTP_REMOTE_ORIGIN + "/fetch/api/resources/redirect.py"; + +redirectDataURL("Testing data URL loading after same-origin redirection (cors mode)", redirUrl, "cors"); +redirectDataURL("Testing data URL loading after same-origin redirection (no-cors mode)", redirUrl, "no-cors"); +redirectDataURL("Testing data URL loading after same-origin redirection (same-origin mode)", redirUrl, "same-origin"); + +redirectDataURL("Testing data URL loading after cross-origin redirection (cors mode)", corsRedirUrl, "cors"); +redirectDataURL("Testing data URL loading after cross-origin redirection (no-cors mode)", corsRedirUrl, "no-cors"); + +done(); diff --git a/test/wpt/tests/fetch/api/redirect/redirect-upload.h2.any.js b/test/wpt/tests/fetch/api/redirect/redirect-upload.h2.any.js new file mode 100644 index 0000000..521bd3a --- /dev/null +++ b/test/wpt/tests/fetch/api/redirect/redirect-upload.h2.any.js @@ -0,0 +1,33 @@ +// META: global=window,worker +// META: script=../resources/utils.js +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js + +const redirectUrl = RESOURCES_DIR + "redirect.h2.py"; +const redirectLocation = "top.txt"; + +async function fetchStreamRedirect(statusCode) { + const url = RESOURCES_DIR + "redirect.h2.py" + + `?redirect_status=${statusCode}&location=${redirectLocation}`; + const requestInit = {method: "POST"}; + requestInit["body"] = new ReadableStream({start: controller => { + const encoder = new TextEncoder(); + controller.enqueue(encoder.encode("Test")); + controller.close(); + }}); + requestInit.duplex = "half"; + return fetch(url, requestInit); +} + +promise_test(async () => { + const resp = await fetchStreamRedirect(303); + assert_equals(resp.status, 200); + assert_true(new URL(resp.url).pathname.endsWith(redirectLocation), + "Response's url should be the redirected one"); +}, "Fetch upload streaming should be accepted on 303"); + +for (const statusCode of [301, 302, 307, 308]) { + promise_test(t => { + return promise_rejects_js(t, TypeError, fetchStreamRedirect(statusCode)); + }, `Fetch upload streaming should fail on ${statusCode}`); +} diff --git a/test/wpt/tests/fetch/api/request/destination/fetch-destination-frame.https.html b/test/wpt/tests/fetch/api/request/destination/fetch-destination-frame.https.html new file mode 100644 index 0000000..f3f9f78 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/destination/fetch-destination-frame.https.html @@ -0,0 +1,51 @@ + +Fetch destination tests for resources with no load event + + + + + diff --git a/test/wpt/tests/fetch/api/request/destination/fetch-destination-iframe.https.html b/test/wpt/tests/fetch/api/request/destination/fetch-destination-iframe.https.html new file mode 100644 index 0000000..1aa5a56 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/destination/fetch-destination-iframe.https.html @@ -0,0 +1,51 @@ + +Fetch destination tests for resources with no load event + + + + + diff --git a/test/wpt/tests/fetch/api/request/destination/fetch-destination-no-load-event.https.html b/test/wpt/tests/fetch/api/request/destination/fetch-destination-no-load-event.https.html new file mode 100644 index 0000000..1778bf2 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/destination/fetch-destination-no-load-event.https.html @@ -0,0 +1,124 @@ + +Fetch destination tests for resources with no load event + + + + + diff --git a/test/wpt/tests/fetch/api/request/destination/fetch-destination-prefetch.https.html b/test/wpt/tests/fetch/api/request/destination/fetch-destination-prefetch.https.html new file mode 100644 index 0000000..db99202 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/destination/fetch-destination-prefetch.https.html @@ -0,0 +1,46 @@ + +Fetch destination test for prefetching + + + + + + diff --git a/test/wpt/tests/fetch/api/request/destination/fetch-destination-worker.https.html b/test/wpt/tests/fetch/api/request/destination/fetch-destination-worker.https.html new file mode 100644 index 0000000..5935c1f --- /dev/null +++ b/test/wpt/tests/fetch/api/request/destination/fetch-destination-worker.https.html @@ -0,0 +1,60 @@ + +Fetch destination tests for resources with no load event + + + + + diff --git a/test/wpt/tests/fetch/api/request/destination/fetch-destination.https.html b/test/wpt/tests/fetch/api/request/destination/fetch-destination.https.html new file mode 100644 index 0000000..0094b0b --- /dev/null +++ b/test/wpt/tests/fetch/api/request/destination/fetch-destination.https.html @@ -0,0 +1,435 @@ + +Fetch destination tests + + + + + + diff --git a/test/wpt/tests/fetch/api/request/destination/resources/dummy b/test/wpt/tests/fetch/api/request/destination/resources/dummy new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/fetch/api/request/destination/resources/dummy.es b/test/wpt/tests/fetch/api/request/destination/resources/dummy.es new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/fetch/api/request/destination/resources/dummy.es.headers b/test/wpt/tests/fetch/api/request/destination/resources/dummy.es.headers new file mode 100644 index 0000000..9bb8bad --- /dev/null +++ b/test/wpt/tests/fetch/api/request/destination/resources/dummy.es.headers @@ -0,0 +1 @@ +Content-Type: text/event-stream diff --git a/test/wpt/tests/fetch/api/request/destination/resources/dummy.html b/test/wpt/tests/fetch/api/request/destination/resources/dummy.html new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/fetch/api/request/destination/resources/dummy.png b/test/wpt/tests/fetch/api/request/destination/resources/dummy.png new file mode 100644 index 0000000..01c9666 Binary files /dev/null and b/test/wpt/tests/fetch/api/request/destination/resources/dummy.png differ diff --git a/test/wpt/tests/fetch/api/request/destination/resources/dummy.ttf b/test/wpt/tests/fetch/api/request/destination/resources/dummy.ttf new file mode 100644 index 0000000..9023592 Binary files /dev/null and b/test/wpt/tests/fetch/api/request/destination/resources/dummy.ttf differ diff --git a/test/wpt/tests/fetch/api/request/destination/resources/dummy_audio.mp3 b/test/wpt/tests/fetch/api/request/destination/resources/dummy_audio.mp3 new file mode 100644 index 0000000..0091330 Binary files /dev/null and b/test/wpt/tests/fetch/api/request/destination/resources/dummy_audio.mp3 differ diff --git a/test/wpt/tests/fetch/api/request/destination/resources/dummy_audio.oga b/test/wpt/tests/fetch/api/request/destination/resources/dummy_audio.oga new file mode 100644 index 0000000..239ad2b Binary files /dev/null and b/test/wpt/tests/fetch/api/request/destination/resources/dummy_audio.oga differ diff --git a/test/wpt/tests/fetch/api/request/destination/resources/dummy_video.mp4 b/test/wpt/tests/fetch/api/request/destination/resources/dummy_video.mp4 new file mode 100644 index 0000000..7022e75 Binary files /dev/null and b/test/wpt/tests/fetch/api/request/destination/resources/dummy_video.mp4 differ diff --git a/test/wpt/tests/fetch/api/request/destination/resources/dummy_video.ogv b/test/wpt/tests/fetch/api/request/destination/resources/dummy_video.ogv new file mode 100644 index 0000000..de99616 Binary files /dev/null and b/test/wpt/tests/fetch/api/request/destination/resources/dummy_video.ogv differ diff --git a/test/wpt/tests/fetch/api/request/destination/resources/dummy_video.webm b/test/wpt/tests/fetch/api/request/destination/resources/dummy_video.webm new file mode 100644 index 0000000..c3d433a Binary files /dev/null and b/test/wpt/tests/fetch/api/request/destination/resources/dummy_video.webm differ diff --git a/test/wpt/tests/fetch/api/request/destination/resources/empty.https.html b/test/wpt/tests/fetch/api/request/destination/resources/empty.https.html new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker-frame.js b/test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker-frame.js new file mode 100644 index 0000000..b69de0b --- /dev/null +++ b/test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker-frame.js @@ -0,0 +1,20 @@ +self.addEventListener('fetch', function(event) { + if (event.request.url.includes('dummy')) { + event.waitUntil(async function() { + let destination = new URL(event.request.url).searchParams.get("dest"); + let clients = await self.clients.matchAll({"includeUncontrolled": true}); + clients.forEach(function(client) { + if (client.url.includes("fetch-destination-frame")) { + if (event.request.destination == destination) { + client.postMessage("PASS"); + } else { + client.postMessage("FAIL"); + } + } + }) + }()); + } + event.respondWith(fetch(event.request)); +}); + + diff --git a/test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker-iframe.js b/test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker-iframe.js new file mode 100644 index 0000000..7634583 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker-iframe.js @@ -0,0 +1,20 @@ +self.addEventListener('fetch', function(event) { + if (event.request.url.includes('dummy')) { + event.waitUntil(async function() { + let destination = new URL(event.request.url).searchParams.get("dest"); + let clients = await self.clients.matchAll({"includeUncontrolled": true}); + clients.forEach(function(client) { + if (client.url.includes("fetch-destination-iframe")) { + if (event.request.destination == destination) { + client.postMessage("PASS"); + } else { + client.postMessage("FAIL"); + } + } + }) + }()); + } + event.respondWith(fetch(event.request)); +}); + + diff --git a/test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker-no-load-event.js b/test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker-no-load-event.js new file mode 100644 index 0000000..a583b12 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker-no-load-event.js @@ -0,0 +1,20 @@ +self.addEventListener('fetch', function(event) { + const url = event.request.url; + if (url.includes('dummy') && url.includes('?')) { + event.waitUntil(async function() { + let destination = new URL(url).searchParams.get("dest"); + var result = "FAIL"; + if (event.request.destination == destination || + (event.request.destination == "empty" && destination == "")) { + result = "PASS"; + } + let cl = await clients.matchAll({includeUncontrolled: true}); + for (i = 0; i < cl.length; i++) { + cl[i].postMessage(result); + } + }()) + } + event.respondWith(fetch(event.request)); +}); + + diff --git a/test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker.js b/test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker.js new file mode 100644 index 0000000..904009c --- /dev/null +++ b/test/wpt/tests/fetch/api/request/destination/resources/fetch-destination-worker.js @@ -0,0 +1,12 @@ +self.addEventListener('fetch', function(event) { + if (event.request.url.includes('dummy')) { + let destination = new URL(event.request.url).searchParams.get("dest"); + if (event.request.destination == destination || + (event.request.destination == "empty" && destination == "")) { + event.respondWith(fetch(event.request)); + } else { + event.respondWith(Response.error()); + } + } +}); + diff --git a/test/wpt/tests/fetch/api/request/destination/resources/importer.js b/test/wpt/tests/fetch/api/request/destination/resources/importer.js new file mode 100644 index 0000000..9568474 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/destination/resources/importer.js @@ -0,0 +1 @@ +importScripts("dummy?t=importScripts&dest=script"); diff --git a/test/wpt/tests/fetch/api/request/forbidden-method.any.js b/test/wpt/tests/fetch/api/request/forbidden-method.any.js new file mode 100644 index 0000000..eb13f37 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/forbidden-method.any.js @@ -0,0 +1,13 @@ +// META: global=window,worker + +// https://fetch.spec.whatwg.org/#forbidden-method +for (const method of [ + 'CONNECT', 'TRACE', 'TRACK', + 'connect', 'trace', 'track' + ]) { + test(function() { + assert_throws_js(TypeError, + function() { new Request('./', {method: method}); } + ); + }, 'Request() with a forbidden method ' + method + ' must throw.'); +} diff --git a/test/wpt/tests/fetch/api/request/multi-globals/construct-in-detached-frame.window.js b/test/wpt/tests/fetch/api/request/multi-globals/construct-in-detached-frame.window.js new file mode 100644 index 0000000..b0d6ba5 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/multi-globals/construct-in-detached-frame.window.js @@ -0,0 +1,11 @@ +// This is a regression test for Chromium issue https://crbug.com/1427266. +test(() => { + const iframe = document.createElement('iframe'); + document.body.append(iframe); + const otherRequest = iframe.contentWindow.Request; + iframe.remove(); + const r1 = new otherRequest('resource', { method: 'POST', body: 'string' }); + const r2 = new otherRequest(r1); + assert_true(r1.bodyUsed); + assert_false(r2.bodyUsed); +}, 'creating a request from another request in a detached realm should work'); diff --git a/test/wpt/tests/fetch/api/request/multi-globals/current/current.html b/test/wpt/tests/fetch/api/request/multi-globals/current/current.html new file mode 100644 index 0000000..9bb6e0b --- /dev/null +++ b/test/wpt/tests/fetch/api/request/multi-globals/current/current.html @@ -0,0 +1,3 @@ + +Current page used as a test helper + diff --git a/test/wpt/tests/fetch/api/request/multi-globals/incumbent/incumbent.html b/test/wpt/tests/fetch/api/request/multi-globals/incumbent/incumbent.html new file mode 100644 index 0000000..a885b8a --- /dev/null +++ b/test/wpt/tests/fetch/api/request/multi-globals/incumbent/incumbent.html @@ -0,0 +1,14 @@ + +Incumbent page used as a test helper + + + + diff --git a/test/wpt/tests/fetch/api/request/multi-globals/url-parsing.html b/test/wpt/tests/fetch/api/request/multi-globals/url-parsing.html new file mode 100644 index 0000000..df60e72 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/multi-globals/url-parsing.html @@ -0,0 +1,27 @@ + +Request constructor URL parsing, with multiple globals in play + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/request/request-bad-port.any.js b/test/wpt/tests/fetch/api/request/request-bad-port.any.js new file mode 100644 index 0000000..b0684d4 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-bad-port.any.js @@ -0,0 +1,92 @@ +// META: global=window,worker + +// list of bad ports according to +// https://fetch.spec.whatwg.org/#port-blocking +var BLOCKED_PORTS_LIST = [ + 1, // tcpmux + 7, // echo + 9, // discard + 11, // systat + 13, // daytime + 15, // netstat + 17, // qotd + 19, // chargen + 20, // ftp-data + 21, // ftp + 22, // ssh + 23, // telnet + 25, // smtp + 37, // time + 42, // name + 43, // nicname + 53, // domain + 69, // tftp + 77, // priv-rjs + 79, // finger + 87, // ttylink + 95, // supdup + 101, // hostriame + 102, // iso-tsap + 103, // gppitnp + 104, // acr-nema + 109, // pop2 + 110, // pop3 + 111, // sunrpc + 113, // auth + 115, // sftp + 117, // uucp-path + 119, // nntp + 123, // ntp + 135, // loc-srv / epmap + 137, // netbios-ns + 139, // netbios-ssn + 143, // imap2 + 161, // snmp + 179, // bgp + 389, // ldap + 427, // afp (alternate) + 465, // smtp (alternate) + 512, // print / exec + 513, // login + 514, // shell + 515, // printer + 526, // tempo + 530, // courier + 531, // chat + 532, // netnews + 540, // uucp + 548, // afp + 554, // rtsp + 556, // remotefs + 563, // nntp+ssl + 587, // smtp (outgoing) + 601, // syslog-conn + 636, // ldap+ssl + 989, // ftps-data + 990, // ftps + 993, // ldap+ssl + 995, // pop3+ssl + 1719, // h323gatestat + 1720, // h323hostcall + 1723, // pptp + 2049, // nfs + 3659, // apple-sasl + 4045, // lockd + 5060, // sip + 5061, // sips + 6000, // x11 + 6566, // sane-port + 6665, // irc (alternate) + 6666, // irc (alternate) + 6667, // irc (default) + 6668, // irc (alternate) + 6669, // irc (alternate) + 6697, // irc+tls + 10080, // amanda +]; + +BLOCKED_PORTS_LIST.map(function(a){ + promise_test(function(t){ + return promise_rejects_js(t, TypeError, fetch("http://example.com:" + a)) + }, 'Request on bad port ' + a + ' should throw TypeError.'); +}); diff --git a/test/wpt/tests/fetch/api/request/request-cache-default-conditional.any.js b/test/wpt/tests/fetch/api/request/request-cache-default-conditional.any.js new file mode 100644 index 0000000..c5b2001 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-cache-default-conditional.any.js @@ -0,0 +1,170 @@ +// META: global=window,worker +// META: title=Request cache - default with conditional requests +// META: timeout=long +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=request-cache.js + +var tests = [ + { + name: 'RequestCache "default" mode with an If-Modified-Since header (following a request without additional headers) is treated similarly to "no-store"', + state: "stale", + request_cache: ["default", "default"], + request_headers: [{}, {"If-Modified-Since": now.toGMTString()}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "default" mode with an If-Modified-Since header (following a request without additional headers) is treated similarly to "no-store"', + state: "fresh", + request_cache: ["default", "default"], + request_headers: [{}, {"If-Modified-Since": now.toGMTString()}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "default" mode with an If-Modified-Since header is treated similarly to "no-store"', + state: "stale", + request_cache: ["default", "default"], + request_headers: [{"If-Modified-Since": now.toGMTString()}, {}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [true, false], + }, + { + name: 'RequestCache "default" mode with an If-Modified-Since header is treated similarly to "no-store"', + state: "fresh", + request_cache: ["default", "default"], + request_headers: [{"If-Modified-Since": now.toGMTString()}, {}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [true, false], + }, + { + name: 'RequestCache "default" mode with an If-None-Match header (following a request without additional headers) is treated similarly to "no-store"', + state: "stale", + request_cache: ["default", "default"], + request_headers: [{}, {"If-None-Match": '"foo"'}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "default" mode with an If-None-Match header (following a request without additional headers) is treated similarly to "no-store"', + state: "fresh", + request_cache: ["default", "default"], + request_headers: [{}, {"If-None-Match": '"foo"'}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "default" mode with an If-None-Match header is treated similarly to "no-store"', + state: "stale", + request_cache: ["default", "default"], + request_headers: [{"If-None-Match": '"foo"'}, {}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [true, false], + }, + { + name: 'RequestCache "default" mode with an If-None-Match header is treated similarly to "no-store"', + state: "fresh", + request_cache: ["default", "default"], + request_headers: [{"If-None-Match": '"foo"'}, {}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [true, false], + }, + { + name: 'RequestCache "default" mode with an If-Unmodified-Since header (following a request without additional headers) is treated similarly to "no-store"', + state: "stale", + request_cache: ["default", "default"], + request_headers: [{}, {"If-Unmodified-Since": now.toGMTString()}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "default" mode with an If-Unmodified-Since header (following a request without additional headers) is treated similarly to "no-store"', + state: "fresh", + request_cache: ["default", "default"], + request_headers: [{}, {"If-Unmodified-Since": now.toGMTString()}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "default" mode with an If-Unmodified-Since header is treated similarly to "no-store"', + state: "stale", + request_cache: ["default", "default"], + request_headers: [{"If-Unmodified-Since": now.toGMTString()}, {}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [true, false], + }, + { + name: 'RequestCache "default" mode with an If-Unmodified-Since header is treated similarly to "no-store"', + state: "fresh", + request_cache: ["default", "default"], + request_headers: [{"If-Unmodified-Since": now.toGMTString()}, {}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [true, false], + }, + { + name: 'RequestCache "default" mode with an If-Match header (following a request without additional headers) is treated similarly to "no-store"', + state: "stale", + request_cache: ["default", "default"], + request_headers: [{}, {"If-Match": '"foo"'}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "default" mode with an If-Match header (following a request without additional headers) is treated similarly to "no-store"', + state: "fresh", + request_cache: ["default", "default"], + request_headers: [{}, {"If-Match": '"foo"'}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "default" mode with an If-Match header is treated similarly to "no-store"', + state: "stale", + request_cache: ["default", "default"], + request_headers: [{"If-Match": '"foo"'}, {}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [true, false], + }, + { + name: 'RequestCache "default" mode with an If-Match header is treated similarly to "no-store"', + state: "fresh", + request_cache: ["default", "default"], + request_headers: [{"If-Match": '"foo"'}, {}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [true, false], + }, + { + name: 'RequestCache "default" mode with an If-Range header (following a request without additional headers) is treated similarly to "no-store"', + state: "stale", + request_cache: ["default", "default"], + request_headers: [{}, {"If-Range": '"foo"'}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "default" mode with an If-Range header (following a request without additional headers) is treated similarly to "no-store"', + state: "fresh", + request_cache: ["default", "default"], + request_headers: [{}, {"If-Range": '"foo"'}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "default" mode with an If-Range header is treated similarly to "no-store"', + state: "stale", + request_cache: ["default", "default"], + request_headers: [{"If-Range": '"foo"'}, {}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [true, false], + }, + { + name: 'RequestCache "default" mode with an If-Range header is treated similarly to "no-store"', + state: "fresh", + request_cache: ["default", "default"], + request_headers: [{"If-Range": '"foo"'}, {}], + expected_validation_headers: [false, false], + expected_no_cache_headers: [true, false], + }, +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/api/request/request-cache-default.any.js b/test/wpt/tests/fetch/api/request/request-cache-default.any.js new file mode 100644 index 0000000..dfa8369 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-cache-default.any.js @@ -0,0 +1,39 @@ +// META: global=window,worker +// META: title=Request cache - default +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=request-cache.js + +var tests = [ + { + name: 'RequestCache "default" mode checks the cache for previously cached content and goes to the network for stale responses', + state: "stale", + request_cache: ["default", "default"], + expected_validation_headers: [false, true], + expected_no_cache_headers: [false, false], + }, + { + name: 'RequestCache "default" mode checks the cache for previously cached content and avoids going to the network if a fresh response exists', + state: "fresh", + request_cache: ["default", "default"], + expected_validation_headers: [false], + expected_no_cache_headers: [false], + }, + { + name: 'Responses with the "Cache-Control: no-store" header are not stored in the cache', + state: "stale", + cache_control: "no-store", + request_cache: ["default", "default"], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, false], + }, + { + name: 'Responses with the "Cache-Control: no-store" header are not stored in the cache', + state: "fresh", + cache_control: "no-store", + request_cache: ["default", "default"], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, false], + }, +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/api/request/request-cache-force-cache.any.js b/test/wpt/tests/fetch/api/request/request-cache-force-cache.any.js new file mode 100644 index 0000000..00dce09 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-cache-force-cache.any.js @@ -0,0 +1,67 @@ +// META: global=window,worker +// META: title=Request cache - force-cache +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=request-cache.js + +var tests = [ + { + name: 'RequestCache "force-cache" mode checks the cache for previously cached content and avoid revalidation for stale responses', + state: "stale", + request_cache: ["default", "force-cache"], + expected_validation_headers: [false], + expected_no_cache_headers: [false], + }, + { + name: 'RequestCache "force-cache" mode checks the cache for previously cached content and avoid revalidation for fresh responses', + state: "fresh", + request_cache: ["default", "force-cache"], + expected_validation_headers: [false], + expected_no_cache_headers: [false], + }, + { + name: 'RequestCache "force-cache" mode checks the cache for previously cached content and goes to the network if a cached response is not found', + state: "stale", + request_cache: ["force-cache"], + expected_validation_headers: [false], + expected_no_cache_headers: [false], + }, + { + name: 'RequestCache "force-cache" mode checks the cache for previously cached content and goes to the network if a cached response is not found', + state: "fresh", + request_cache: ["force-cache"], + expected_validation_headers: [false], + expected_no_cache_headers: [false], + }, + { + name: 'RequestCache "force-cache" mode checks the cache for previously cached content and goes to the network if a cached response would vary', + state: "stale", + vary: "*", + request_cache: ["default", "force-cache"], + expected_validation_headers: [false, true], + expected_no_cache_headers: [false, false], + }, + { + name: 'RequestCache "force-cache" mode checks the cache for previously cached content and goes to the network if a cached response would vary', + state: "fresh", + vary: "*", + request_cache: ["default", "force-cache"], + expected_validation_headers: [false, true], + expected_no_cache_headers: [false, false], + }, + { + name: 'RequestCache "force-cache" stores the response in the cache if it goes to the network', + state: "stale", + request_cache: ["force-cache", "default"], + expected_validation_headers: [false, true], + expected_no_cache_headers: [false, false], + }, + { + name: 'RequestCache "force-cache" stores the response in the cache if it goes to the network', + state: "fresh", + request_cache: ["force-cache", "default"], + expected_validation_headers: [false], + expected_no_cache_headers: [false], + }, +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/api/request/request-cache-no-cache.any.js b/test/wpt/tests/fetch/api/request/request-cache-no-cache.any.js new file mode 100644 index 0000000..41fc22b --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-cache-no-cache.any.js @@ -0,0 +1,25 @@ +// META: global=window,worker +// META: title=Request cache : no-cache +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=request-cache.js + +var tests = [ + { + name: 'RequestCache "no-cache" mode revalidates stale responses found in the cache', + state: "stale", + request_cache: ["default", "no-cache"], + expected_validation_headers: [false, true], + expected_no_cache_headers: [false, false], + expected_max_age_headers: [false, true], + }, + { + name: 'RequestCache "no-cache" mode revalidates fresh responses found in the cache', + state: "fresh", + request_cache: ["default", "no-cache"], + expected_validation_headers: [false, true], + expected_no_cache_headers: [false, false], + expected_max_age_headers: [false, true], + }, +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/api/request/request-cache-no-store.any.js b/test/wpt/tests/fetch/api/request/request-cache-no-store.any.js new file mode 100644 index 0000000..9a28718 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-cache-no-store.any.js @@ -0,0 +1,37 @@ +// META: global=window,worker +// META: title=Request cache - no store +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=request-cache.js + +var tests = [ + { + name: 'RequestCache "no-store" mode does not check the cache for previously cached content and goes to the network regardless', + state: "stale", + request_cache: ["default", "no-store"], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "no-store" mode does not check the cache for previously cached content and goes to the network regardless', + state: "fresh", + request_cache: ["default", "no-store"], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "no-store" mode does not store the response in the cache', + state: "stale", + request_cache: ["no-store", "default"], + expected_validation_headers: [false, false], + expected_no_cache_headers: [true, false], + }, + { + name: 'RequestCache "no-store" mode does not store the response in the cache', + state: "fresh", + request_cache: ["no-store", "default"], + expected_validation_headers: [false, false], + expected_no_cache_headers: [true, false], + }, +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/api/request/request-cache-only-if-cached.any.js b/test/wpt/tests/fetch/api/request/request-cache-only-if-cached.any.js new file mode 100644 index 0000000..1305787 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-cache-only-if-cached.any.js @@ -0,0 +1,66 @@ +// META: global=window,dedicatedworker,sharedworker +// META: title=Request cache - only-if-cached +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=request-cache.js + +// FIXME: avoid mixed content requests to enable service worker global +var tests = [ + { + name: 'RequestCache "only-if-cached" mode checks the cache for previously cached content and avoids revalidation for stale responses', + state: "stale", + request_cache: ["default", "only-if-cached"], + expected_validation_headers: [false], + expected_no_cache_headers: [false] + }, + { + name: 'RequestCache "only-if-cached" mode checks the cache for previously cached content and avoids revalidation for fresh responses', + state: "fresh", + request_cache: ["default", "only-if-cached"], + expected_validation_headers: [false], + expected_no_cache_headers: [false] + }, + { + name: 'RequestCache "only-if-cached" mode checks the cache for previously cached content and does not go to the network if a cached response is not found', + state: "fresh", + request_cache: ["only-if-cached"], + response: ["error"], + expected_validation_headers: [], + expected_no_cache_headers: [] + }, + { + name: 'RequestCache "only-if-cached" (with "same-origin") uses cached same-origin redirects to same-origin content', + state: "fresh", + request_cache: ["default", "only-if-cached"], + redirect: "same-origin", + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, false], + }, + { + name: 'RequestCache "only-if-cached" (with "same-origin") uses cached same-origin redirects to same-origin content', + state: "stale", + request_cache: ["default", "only-if-cached"], + redirect: "same-origin", + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, false], + }, + { + name: 'RequestCache "only-if-cached" (with "same-origin") does not follow redirects across origins and rejects', + state: "fresh", + request_cache: ["default", "only-if-cached"], + redirect: "cross-origin", + response: [null, "error"], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, false], + }, + { + name: 'RequestCache "only-if-cached" (with "same-origin") does not follow redirects across origins and rejects', + state: "stale", + request_cache: ["default", "only-if-cached"], + redirect: "cross-origin", + response: [null, "error"], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, false], + }, +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/api/request/request-cache-reload.any.js b/test/wpt/tests/fetch/api/request/request-cache-reload.any.js new file mode 100644 index 0000000..c7bfffb --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-cache-reload.any.js @@ -0,0 +1,51 @@ +// META: global=window,worker +// META: title=Request cache - reload +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=request-cache.js + +var tests = [ + { + name: 'RequestCache "reload" mode does not check the cache for previously cached content and goes to the network regardless', + state: "stale", + request_cache: ["default", "reload"], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "reload" mode does not check the cache for previously cached content and goes to the network regardless', + state: "fresh", + request_cache: ["default", "reload"], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, + { + name: 'RequestCache "reload" mode does store the response in the cache', + state: "stale", + request_cache: ["reload", "default"], + expected_validation_headers: [false, true], + expected_no_cache_headers: [true, false], + }, + { + name: 'RequestCache "reload" mode does store the response in the cache', + state: "fresh", + request_cache: ["reload", "default"], + expected_validation_headers: [false], + expected_no_cache_headers: [true], + }, + { + name: 'RequestCache "reload" mode does store the response in the cache even if a previous response is already stored', + state: "stale", + request_cache: ["default", "reload", "default"], + expected_validation_headers: [false, false, true], + expected_no_cache_headers: [false, true, false], + }, + { + name: 'RequestCache "reload" mode does store the response in the cache even if a previous response is already stored', + state: "fresh", + request_cache: ["default", "reload", "default"], + expected_validation_headers: [false, false], + expected_no_cache_headers: [false, true], + }, +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/api/request/request-cache.js b/test/wpt/tests/fetch/api/request/request-cache.js new file mode 100644 index 0000000..f2fbecf --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-cache.js @@ -0,0 +1,223 @@ +/** + * Each test is run twice: once using etag/If-None-Match and once with + * date/If-Modified-Since. Each test run gets its own URL and randomized + * content and operates independently. + * + * The test steps are run with request_cache.length fetch requests issued + * and their immediate results sanity-checked. The cache.py server script + * stashes an entry containing any If-None-Match, If-Modified-Since, Pragma, + * and Cache-Control observed headers for each request it receives. When + * the test fetches have run, this state is retrieved from cache.py and the + * expected_* lists are checked, including their length. + * + * This means that if a request_* fetch is expected to hit the cache and not + * touch the network, then there will be no entry for it in the expect_* + * lists. AKA (request_cache.length - expected_validation_headers.length) + * should equal the number of cache hits that didn't touch the network. + * + * Test dictionary keys: + * - state: required string that determines whether the Expires response for + * the fetched document should be set in the future ("fresh") or past + * ("stale"). + * - vary: optional string to be passed to the server for it to quote back + * in a Vary header on the response to us. + * - cache_control: optional string to be passed to the server for it to + * quote back in a Cache-Control header on the response to us. + * - redirect: optional string "same-origin" or "cross-origin". If + * provided, the server will issue an absolute redirect to the script on + * the same or a different origin, as appropriate. The redirected + * location is the script with the redirect parameter removed, so the + * content/state/etc. will be as if you hadn't specified a redirect. + * - request_cache: required array of cache modes to use (via `cache`). + * - request_headers: optional array of explicit fetch `headers` arguments. + * If provided, the server will log an empty dictionary for each request + * instead of the request headers it would normally log. + * - response: optional array of specialized response handling. Right now, + * "error" array entries indicate a network error response is expected + * which will reject with a TypeError. + * - expected_validation_headers: required boolean array indicating whether + * the server should have seen an If-None-Match/If-Modified-Since header + * in the request. + * - expected_no_cache_headers: required boolean array indicating whether + * the server should have seen Pragma/Cache-control:no-cache headers in + * the request. + * - expected_max_age_headers: optional boolean array indicating whether + * the server should have seen a Cache-Control:max-age=0 header in the + * request. + */ + +var now = new Date(); + +function base_path() { + return location.pathname.replace(/\/[^\/]*$/, '/'); +} +function make_url(uuid, id, value, content, info) { + var dates = { + fresh: new Date(now.getFullYear() + 1, now.getMonth(), now.getDay()).toGMTString(), + stale: new Date(now.getFullYear() - 1, now.getMonth(), now.getDay()).toGMTString(), + }; + var vary = ""; + if ("vary" in info) { + vary = "&vary=" + info.vary; + } + var cache_control = ""; + if ("cache_control" in info) { + cache_control = "&cache_control=" + info.cache_control; + } + var redirect = ""; + + var ignore_request_headers = ""; + if ("request_headers" in info) { + // Ignore the request headers that we send since they may be synthesized by the test. + ignore_request_headers = "&ignore"; + } + var url_sans_redirect = "resources/cache.py?token=" + uuid + + "&content=" + content + + "&" + id + "=" + value + + "&expires=" + dates[info.state] + + vary + cache_control + ignore_request_headers; + // If there's a redirect, the target is the script without any redirect at + // either the same domain or a different domain. + if ("redirect" in info) { + var host_info = get_host_info(); + var origin; + switch (info.redirect) { + case "same-origin": + origin = host_info['HTTP_ORIGIN']; + break; + case "cross-origin": + origin = host_info['HTTP_REMOTE_ORIGIN']; + break; + } + var redirected_url = origin + base_path() + url_sans_redirect; + return url_sans_redirect + "&redirect=" + encodeURIComponent(redirected_url); + } else { + return url_sans_redirect; + } +} +function expected_status(type, identifier, init) { + if (type == "date" && + init.headers && + init.headers["If-Modified-Since"] == identifier) { + // The server will respond with a 304 in this case. + return [304, "Not Modified"]; + } + return [200, "OK"]; +} +function expected_response_text(type, identifier, init, content) { + if (type == "date" && + init.headers && + init.headers["If-Modified-Since"] == identifier) { + // The server will respond with a 304 in this case. + return ""; + } + return content; +} +function server_state(uuid) { + return fetch("resources/cache.py?querystate&token=" + uuid) + .then(function(response) { + return response.text(); + }).then(function(text) { + // null will be returned if the server never received any requests + // for the given uuid. Normalize that to an empty list consistent + // with our representation. + return JSON.parse(text) || []; + }); +} +function make_test(type, info) { + return function(test) { + var uuid = token(); + var identifier = (type == "tag" ? Math.random() : now.toGMTString()); + var content = Math.random().toString(); + var url = make_url(uuid, type, identifier, content, info); + var fetch_functions = []; + for (var i = 0; i < info.request_cache.length; ++i) { + fetch_functions.push(function(idx) { + var init = {cache: info.request_cache[idx]}; + if ("request_headers" in info) { + init.headers = info.request_headers[idx]; + } + if (init.cache === "only-if-cached") { + // only-if-cached requires we use same-origin mode. + init.mode = "same-origin"; + } + return fetch(url, init) + .then(function(response) { + if ("response" in info && info.response[idx] === "error") { + assert_true(false, "fetch should have been an error"); + return; + } + assert_array_equals([response.status, response.statusText], + expected_status(type, identifier, init)); + return response.text(); + }).then(function(text) { + assert_equals(text, expected_response_text(type, identifier, init, content)); + }, function(reason) { + if ("response" in info && info.response[idx] === "error") { + assert_throws_js(TypeError, function() { throw reason; }); + } else { + throw reason; + } + }); + }); + } + var i = 0; + function run_next_step() { + if (fetch_functions.length) { + return fetch_functions.shift()(i++) + .then(run_next_step); + } else { + return Promise.resolve(); + } + } + return run_next_step() + .then(function() { + // Now, query the server state + return server_state(uuid); + }).then(function(state) { + var expectedState = []; + info.expected_validation_headers.forEach(function (validate) { + if (validate) { + if (type == "tag") { + expectedState.push({"If-None-Match": '"' + identifier + '"'}); + } else { + expectedState.push({"If-Modified-Since": identifier}); + } + } else { + expectedState.push({}); + } + }); + for (var i = 0; i < info.expected_no_cache_headers.length; ++i) { + if (info.expected_no_cache_headers[i]) { + expectedState[i]["Pragma"] = "no-cache"; + expectedState[i]["Cache-Control"] = "no-cache"; + } + } + if ("expected_max_age_headers" in info) { + for (var i = 0; i < info.expected_max_age_headers.length; ++i) { + if (info.expected_max_age_headers[i]) { + expectedState[i]["Cache-Control"] = "max-age=0"; + } + } + } + assert_equals(state.length, expectedState.length); + for (var i = 0; i < state.length; ++i) { + for (var header in state[i]) { + assert_equals(state[i][header], expectedState[i][header]); + delete expectedState[i][header]; + } + for (var header in expectedState[i]) { + assert_false(header in state[i]); + } + } + }); + }; +} + +function run_tests(tests) +{ + tests.forEach(function(info) { + promise_test(make_test("tag", info), info.name + " with Etag and " + info.state + " response"); + promise_test(make_test("date", info), info.name + " with Last-Modified and " + info.state + " response"); + }); +} diff --git a/test/wpt/tests/fetch/api/request/request-clone.sub.html b/test/wpt/tests/fetch/api/request/request-clone.sub.html new file mode 100644 index 0000000..c690bb3 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-clone.sub.html @@ -0,0 +1,63 @@ + + + + + Request clone + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/request/request-consume-empty.any.js b/test/wpt/tests/fetch/api/request/request-consume-empty.any.js new file mode 100644 index 0000000..034a860 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-consume-empty.any.js @@ -0,0 +1,101 @@ +// META: global=window,worker +// META: title=Request consume empty bodies + +function checkBodyText(test, request) { + return request.text().then(function(bodyAsText) { + assert_equals(bodyAsText, "", "Resolved value should be empty"); + assert_false(request.bodyUsed); + }); +} + +function checkBodyBlob(test, request) { + return request.blob().then(function(bodyAsBlob) { + var promise = new Promise(function(resolve, reject) { + var reader = new FileReader(); + reader.onload = function(evt) { + resolve(reader.result) + }; + reader.onerror = function() { + reject("Blob's reader failed"); + }; + reader.readAsText(bodyAsBlob); + }); + return promise.then(function(body) { + assert_equals(body, "", "Resolved value should be empty"); + assert_false(request.bodyUsed); + }); + }); +} + +function checkBodyArrayBuffer(test, request) { + return request.arrayBuffer().then(function(bodyAsArrayBuffer) { + assert_equals(bodyAsArrayBuffer.byteLength, 0, "Resolved value should be empty"); + assert_false(request.bodyUsed); + }); +} + +function checkBodyJSON(test, request) { + return request.json().then( + function(bodyAsJSON) { + assert_unreached("JSON parsing should fail"); + }, + function() { + assert_false(request.bodyUsed); + }); +} + +function checkBodyFormData(test, request) { + return request.formData().then(function(bodyAsFormData) { + assert_true(bodyAsFormData instanceof FormData, "Should receive a FormData"); + assert_false(request.bodyUsed); + }); +} + +function checkBodyFormDataError(test, request) { + return promise_rejects_js(test, TypeError, request.formData()).then(function() { + assert_false(request.bodyUsed); + }); +} + +function checkRequestWithNoBody(bodyType, checkFunction, headers = []) { + promise_test(function(test) { + var request = new Request("", {"method": "POST", "headers": headers}); + assert_false(request.bodyUsed); + return checkFunction(test, request); + }, "Consume request's body as " + bodyType); +} + +checkRequestWithNoBody("text", checkBodyText); +checkRequestWithNoBody("blob", checkBodyBlob); +checkRequestWithNoBody("arrayBuffer", checkBodyArrayBuffer); +checkRequestWithNoBody("json (error case)", checkBodyJSON); +checkRequestWithNoBody("formData with correct multipart type (error case)", checkBodyFormDataError, [["Content-Type", 'multipart/form-data; boundary="boundary"']]); +checkRequestWithNoBody("formData with correct urlencoded type", checkBodyFormData, [["Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"]]); +checkRequestWithNoBody("formData without correct type (error case)", checkBodyFormDataError); + +function checkRequestWithEmptyBody(bodyType, body, asText) { + promise_test(function(test) { + var request = new Request("", {"method": "POST", "body": body}); + assert_false(request.bodyUsed, "bodyUsed is false at init"); + if (asText) { + return request.text().then(function(bodyAsString) { + assert_equals(bodyAsString.length, 0, "Resolved value should be empty"); + assert_true(request.bodyUsed, "bodyUsed is true after being consumed"); + }); + } + return request.arrayBuffer().then(function(bodyAsArrayBuffer) { + assert_equals(bodyAsArrayBuffer.byteLength, 0, "Resolved value should be empty"); + assert_true(request.bodyUsed, "bodyUsed is true after being consumed"); + }); + }, "Consume empty " + bodyType + " request body as " + (asText ? "text" : "arrayBuffer")); +} + +// FIXME: Add BufferSource, FormData and URLSearchParams. +checkRequestWithEmptyBody("blob", new Blob([], { "type" : "text/plain" }), false); +checkRequestWithEmptyBody("text", "", false); +checkRequestWithEmptyBody("blob", new Blob([], { "type" : "text/plain" }), true); +checkRequestWithEmptyBody("text", "", true); +checkRequestWithEmptyBody("URLSearchParams", new URLSearchParams(""), true); +// FIXME: This test assumes that the empty string be returned but it is not clear whether that is right. See https://github.com/web-platform-tests/wpt/pull/3950. +checkRequestWithEmptyBody("FormData", new FormData(), true); +checkRequestWithEmptyBody("ArrayBuffer", new ArrayBuffer(), true); diff --git a/test/wpt/tests/fetch/api/request/request-consume.any.js b/test/wpt/tests/fetch/api/request/request-consume.any.js new file mode 100644 index 0000000..aff5d65 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-consume.any.js @@ -0,0 +1,145 @@ +// META: global=window,worker +// META: title=Request consume +// META: script=../resources/utils.js + +function checkBodyText(request, expectedBody) { + return request.text().then(function(bodyAsText) { + assert_equals(bodyAsText, expectedBody, "Retrieve and verify request's body"); + assert_true(request.bodyUsed, "body as text: bodyUsed turned true"); + }); +} + +function checkBodyBlob(request, expectedBody, checkContentType) { + return request.blob().then(function(bodyAsBlob) { + if (checkContentType) + assert_equals(bodyAsBlob.type, "text/plain", "Blob body type should be computed from the request Content-Type"); + + var promise = new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onload = function(evt) { + resolve(reader.result) + }; + reader.onerror = function() { + reject("Blob's reader failed"); + }; + reader.readAsText(bodyAsBlob); + }); + return promise.then(function(body) { + assert_equals(body, expectedBody, "Retrieve and verify request's body"); + assert_true(request.bodyUsed, "body as blob: bodyUsed turned true"); + }); + }); +} + +function checkBodyArrayBuffer(request, expectedBody) { + return request.arrayBuffer().then(function(bodyAsArrayBuffer) { + validateBufferFromString(bodyAsArrayBuffer, expectedBody, "Retrieve and verify request's body"); + assert_true(request.bodyUsed, "body as arrayBuffer: bodyUsed turned true"); + }); +} + +function checkBodyJSON(request, expectedBody) { + return request.json().then(function(bodyAsJSON) { + var strBody = JSON.stringify(bodyAsJSON) + assert_equals(strBody, expectedBody, "Retrieve and verify request's body"); + assert_true(request.bodyUsed, "body as json: bodyUsed turned true"); + }); +} + +function checkBodyFormData(request, expectedBody) { + return request.formData().then(function(bodyAsFormData) { + assert_true(bodyAsFormData instanceof FormData, "Should receive a FormData"); + assert_true(request.bodyUsed, "body as formData: bodyUsed turned true"); + }); +} + +function checkRequestBody(body, expected, bodyType) { + promise_test(function(test) { + var request = new Request("", {"method": "POST", "body": body, "headers": [["Content-Type", "text/PLAIN"]] }); + assert_false(request.bodyUsed, "bodyUsed is false at init"); + return checkBodyText(request, expected); + }, "Consume " + bodyType + " request's body as text"); + promise_test(function(test) { + var request = new Request("", {"method": "POST", "body": body }); + assert_false(request.bodyUsed, "bodyUsed is false at init"); + return checkBodyBlob(request, expected); + }, "Consume " + bodyType + " request's body as blob"); + promise_test(function(test) { + var request = new Request("", {"method": "POST", "body": body }); + assert_false(request.bodyUsed, "bodyUsed is false at init"); + return checkBodyArrayBuffer(request, expected); + }, "Consume " + bodyType + " request's body as arrayBuffer"); + promise_test(function(test) { + var request = new Request("", {"method": "POST", "body": body }); + assert_false(request.bodyUsed, "bodyUsed is false at init"); + return checkBodyJSON(request, expected); + }, "Consume " + bodyType + " request's body as JSON"); +} + +var textData = JSON.stringify("This is response's body"); +var blob = new Blob([textData], { "type" : "text/plain" }); + +checkRequestBody(textData, textData, "String"); + +var string = "\"123456\""; +function getArrayBuffer() { + var arrayBuffer = new ArrayBuffer(8); + var int8Array = new Int8Array(arrayBuffer); + for (var cptr = 0; cptr < 8; cptr++) + int8Array[cptr] = string.charCodeAt(cptr); + return arrayBuffer; +} + +function getArrayBufferWithZeros() { + var arrayBuffer = new ArrayBuffer(10); + var int8Array = new Int8Array(arrayBuffer); + for (var cptr = 0; cptr < 8; cptr++) + int8Array[cptr + 1] = string.charCodeAt(cptr); + return arrayBuffer; +} + +checkRequestBody(getArrayBuffer(), string, "ArrayBuffer"); +checkRequestBody(new Uint8Array(getArrayBuffer()), string, "Uint8Array"); +checkRequestBody(new Int8Array(getArrayBufferWithZeros(), 1, 8), string, "Int8Array"); +checkRequestBody(new Float32Array(getArrayBuffer()), string, "Float32Array"); +checkRequestBody(new DataView(getArrayBufferWithZeros(), 1, 8), string, "DataView"); + +promise_test(function(test) { + var formData = new FormData(); + formData.append("name", "value") + var request = new Request("", {"method": "POST", "body": formData }); + assert_false(request.bodyUsed, "bodyUsed is false at init"); + return checkBodyFormData(request, formData); +}, "Consume FormData request's body as FormData"); + +function checkBlobResponseBody(blobBody, blobData, bodyType, checkFunction) { + promise_test(function(test) { + var response = new Response(blobBody); + assert_false(response.bodyUsed, "bodyUsed is false at init"); + return checkFunction(response, blobData); + }, "Consume blob response's body as " + bodyType); +} + +checkBlobResponseBody(blob, textData, "blob", checkBodyBlob); +checkBlobResponseBody(blob, textData, "text", checkBodyText); +checkBlobResponseBody(blob, textData, "json", checkBodyJSON); +checkBlobResponseBody(blob, textData, "arrayBuffer", checkBodyArrayBuffer); +checkBlobResponseBody(new Blob([""]), "", "blob (empty blob as input)", checkBodyBlob); + +var goodJSONValues = ["null", "1", "true", "\"string\""]; +goodJSONValues.forEach(function(value) { + promise_test(function(test) { + var request = new Request("", {"method": "POST", "body": value}); + return request.json().then(function(v) { + assert_equals(v, JSON.parse(value)); + }); + }, "Consume JSON from text: '" + JSON.stringify(value) + "'"); +}); + +var badJSONValues = ["undefined", "{", "a", "["]; +badJSONValues.forEach(function(value) { + promise_test(function(test) { + var request = new Request("", {"method": "POST", "body": value}); + return promise_rejects_js(test, SyntaxError, request.json()); + }, "Trying to consume bad JSON text as JSON: '" + value + "'"); +}); diff --git a/test/wpt/tests/fetch/api/request/request-disturbed.any.js b/test/wpt/tests/fetch/api/request/request-disturbed.any.js new file mode 100644 index 0000000..8a11de7 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-disturbed.any.js @@ -0,0 +1,109 @@ +// META: global=window,worker +// META: title=Request disturbed +// META: script=../resources/utils.js + +var initValuesDict = {"method" : "POST", + "body" : "Request's body" +}; + +var noBodyConsumed = new Request(""); +var bodyConsumed = new Request("", initValuesDict); + +test(() => { + assert_equals(noBodyConsumed.body, null, "body's default value is null"); + assert_false(noBodyConsumed.bodyUsed , "bodyUsed is false when request is not disturbed"); + assert_not_equals(bodyConsumed.body, null, "non-null body"); + assert_true(bodyConsumed.body instanceof ReadableStream, "non-null body type"); + assert_false(noBodyConsumed.bodyUsed, "bodyUsed is false when request is not disturbed"); +}, "Request's body: initial state"); + +noBodyConsumed.blob(); +bodyConsumed.blob(); + +test(function() { + assert_false(noBodyConsumed.bodyUsed , "bodyUsed is false when request is not disturbed"); + try { + noBodyConsumed.clone(); + } catch (e) { + assert_unreached("Can use request not disturbed for creating or cloning request"); + } +}, "Request without body cannot be disturbed"); + +test(function() { + assert_true(bodyConsumed.bodyUsed , "bodyUsed is true when request is disturbed"); + assert_throws_js(TypeError, function() { bodyConsumed.clone(); }); +}, "Check cloning a disturbed request"); + +test(function() { + assert_true(bodyConsumed.bodyUsed , "bodyUsed is true when request is disturbed"); + assert_throws_js(TypeError, function() { new Request(bodyConsumed); }); +}, "Check creating a new request from a disturbed request"); + +promise_test(function() { + assert_true(bodyConsumed.bodyUsed , "bodyUsed is true when request is disturbed"); + const originalBody = bodyConsumed.body; + const bodyReplaced = new Request(bodyConsumed, { body: "Replaced body" }); + assert_not_equals(bodyReplaced.body, originalBody, "new request's body is new"); + assert_false(bodyReplaced.bodyUsed, "bodyUsed is false when request is not disturbed"); + return bodyReplaced.text().then(text => { + assert_equals(text, "Replaced body"); + }); +}, "Check creating a new request with a new body from a disturbed request"); + +promise_test(function() { + var bodyRequest = new Request("", initValuesDict); + const originalBody = bodyRequest.body; + assert_false(bodyRequest.bodyUsed , "bodyUsed is false when request is not disturbed"); + var requestFromRequest = new Request(bodyRequest); + assert_true(bodyRequest.bodyUsed , "bodyUsed is true when request is disturbed"); + assert_equals(bodyRequest.body, originalBody, "body should not change"); + assert_not_equals(originalBody, undefined, "body should not be undefined"); + assert_not_equals(originalBody, null, "body should not be null"); + assert_not_equals(requestFromRequest.body, originalBody, "new request's body is new"); + return requestFromRequest.text().then(text => { + assert_equals(text, "Request's body"); + }); +}, "Input request used for creating new request became disturbed"); + +promise_test(() => { + const bodyRequest = new Request("", initValuesDict); + const originalBody = bodyRequest.body; + assert_false(bodyRequest.bodyUsed , "bodyUsed is false when request is not disturbed"); + const requestFromRequest = new Request(bodyRequest, { body : "init body" }); + assert_true(bodyRequest.bodyUsed , "bodyUsed is true when request is disturbed"); + assert_equals(bodyRequest.body, originalBody, "body should not change"); + assert_not_equals(originalBody, undefined, "body should not be undefined"); + assert_not_equals(originalBody, null, "body should not be null"); + assert_not_equals(requestFromRequest.body, originalBody, "new request's body is new"); + + return requestFromRequest.text().then(text => { + assert_equals(text, "init body"); + }); +}, "Input request used for creating new request became disturbed even if body is not used"); + +promise_test(function(test) { + assert_true(bodyConsumed.bodyUsed , "bodyUsed is true when request is disturbed"); + return promise_rejects_js(test, TypeError, bodyConsumed.blob()); +}, "Check consuming a disturbed request"); + +test(function() { + var req = new Request(URL, {method: 'POST', body: 'hello'}); + assert_false(req.bodyUsed, + 'Request should not be flagged as used if it has not been ' + + 'consumed.'); + assert_throws_js(TypeError, + function() { new Request(req, {method: 'GET'}); }, + 'A get request may not have body.'); + + assert_false(req.bodyUsed, 'After the GET case'); + + assert_throws_js(TypeError, + function() { new Request(req, {method: 'CONNECT'}); }, + 'Request() with a forbidden method must throw.'); + + assert_false(req.bodyUsed, 'After the forbidden method case'); + + var req2 = new Request(req); + assert_true(req.bodyUsed, + 'Request should be flagged as used if it has been consumed.'); +}, 'Request construction failure should not set "bodyUsed"'); diff --git a/test/wpt/tests/fetch/api/request/request-error.any.js b/test/wpt/tests/fetch/api/request/request-error.any.js new file mode 100644 index 0000000..9ec8015 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-error.any.js @@ -0,0 +1,56 @@ +// META: global=window,worker +// META: title=Request error +// META: script=request-error.js + +// badRequestArgTests is from response-error.js +for (const { args, testName } of badRequestArgTests) { + test(() => { + assert_throws_js( + TypeError, + () => new Request(...args), + "Expect TypeError exception" + ); + }, testName); +} + +test(function() { + assert_throws_js( + TypeError, + () => Request("about:blank"), + "Calling Request constructor without 'new' must throw" + ); +}); + +test(function() { + var initialHeaders = new Headers([["Content-Type", "potato"]]); + var initialRequest = new Request("", {"headers" : initialHeaders}); + var request = new Request(initialRequest); + assert_equals(request.headers.get("Content-Type"), "potato"); +}, "Request should get its content-type from the init request"); + +test(function() { + var initialHeaders = new Headers([["Content-Type", "potato"]]); + var initialRequest = new Request("", {"headers" : initialHeaders}); + var headers = new Headers([]); + var request = new Request(initialRequest, {"headers" : headers}); + assert_false(request.headers.has("Content-Type")); +}, "Request should not get its content-type from the init request if init headers are provided"); + +test(function() { + var initialHeaders = new Headers([["Content-Type-Extra", "potato"]]); + var initialRequest = new Request("", {"headers" : initialHeaders, "body" : "this is my plate", "method" : "POST"}); + var request = new Request(initialRequest); + assert_equals(request.headers.get("Content-Type"), "text/plain;charset=UTF-8"); +}, "Request should get its content-type from the body if none is provided"); + +test(function() { + var initialHeaders = new Headers([["Content-Type", "potato"]]); + var initialRequest = new Request("", {"headers" : initialHeaders, "body" : "this is my plate", "method" : "POST"}); + var request = new Request(initialRequest); + assert_equals(request.headers.get("Content-Type"), "potato"); +}, "Request should get its content-type from init headers if one is provided"); + +test(function() { + var options = {"cache": "only-if-cached", "mode": "same-origin"}; + new Request("test", options); +}, "Request with cache mode: only-if-cached and fetch mode: same-origin"); diff --git a/test/wpt/tests/fetch/api/request/request-error.js b/test/wpt/tests/fetch/api/request/request-error.js new file mode 100644 index 0000000..cf77313 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-error.js @@ -0,0 +1,57 @@ +const badRequestArgTests = [ + { + args: ["", { "window": "http://test.url" }], + testName: "RequestInit's window is not null" + }, + { + args: ["http://:not a valid URL"], + testName: "Input URL is not valid" + }, + { + args: ["http://user:pass@test.url"], + testName: "Input URL has credentials" + }, + { + args: ["", { "mode": "navigate" }], + testName: "RequestInit's mode is navigate" + }, + { + args: ["", { "referrer": "http://:not a valid URL" }], + testName: "RequestInit's referrer is invalid" + }, + { + args: ["", { "method": "IN VALID" }], + testName: "RequestInit's method is invalid" + }, + { + args: ["", { "method": "TRACE" }], + testName: "RequestInit's method is forbidden" + }, + { + args: ["", { "mode": "no-cors", "method": "PUT" }], + testName: "RequestInit's mode is no-cors and method is not simple" + }, + { + args: ["", { "mode": "cors", "cache": "only-if-cached" }], + testName: "RequestInit's cache mode is only-if-cached and mode is not same-origin" + }, + { + args: ["test", { "cache": "only-if-cached", "mode": "cors" }], + testName: "Request with cache mode: only-if-cached and fetch mode cors" + }, + { + args: ["test", { "cache": "only-if-cached", "mode": "no-cors" }], + testName: "Request with cache mode: only-if-cached and fetch mode no-cors" + } +]; + +badRequestArgTests.push( + ...["referrerPolicy", "mode", "credentials", "cache", "redirect"].map(optionProp => { + const options = {}; + options[optionProp] = "BAD"; + return { + args: ["", options], + testName: `Bad ${optionProp} init parameter value` + }; + }) +); diff --git a/test/wpt/tests/fetch/api/request/request-headers.any.js b/test/wpt/tests/fetch/api/request/request-headers.any.js new file mode 100644 index 0000000..22925e0 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-headers.any.js @@ -0,0 +1,178 @@ +// META: global=window,worker +// META: title=Request Headers + +var validRequestHeaders = [ + ["Content-Type", "OK"], + ["Potato", "OK"], + ["proxy", "OK"], + ["proxya", "OK"], + ["sec", "OK"], + ["secb", "OK"], + ["Set-Cookie2", "OK"], + ["User-Agent", "OK"], +]; +var invalidRequestHeaders = [ + ["Accept-Charset", "KO"], + ["accept-charset", "KO"], + ["ACCEPT-ENCODING", "KO"], + ["Accept-Encoding", "KO"], + ["Access-Control-Request-Headers", "KO"], + ["Access-Control-Request-Method", "KO"], + ["Access-Control-Request-Private-Network", "KO"], + ["Connection", "KO"], + ["Content-Length", "KO"], + ["Cookie", "KO"], + ["Cookie2", "KO"], + ["Date", "KO"], + ["DNT", "KO"], + ["Expect", "KO"], + ["Host", "KO"], + ["Keep-Alive", "KO"], + ["Origin", "KO"], + ["Referer", "KO"], + ["Set-Cookie", "KO"], + ["TE", "KO"], + ["Trailer", "KO"], + ["Transfer-Encoding", "KO"], + ["Upgrade", "KO"], + ["Via", "KO"], + ["Proxy-", "KO"], + ["proxy-a", "KO"], + ["Sec-", "KO"], + ["sec-b", "KO"], +]; + +var validRequestNoCorsHeaders = [ + ["Accept", "OK"], + ["Accept-Language", "OK"], + ["content-language", "OK"], + ["content-type", "application/x-www-form-urlencoded"], + ["content-type", "application/x-www-form-urlencoded;charset=UTF-8"], + ["content-type", "multipart/form-data"], + ["content-type", "multipart/form-data;charset=UTF-8"], + ["content-TYPE", "text/plain"], + ["CONTENT-type", "text/plain;charset=UTF-8"], +]; +var invalidRequestNoCorsHeaders = [ + ["Content-Type", "KO"], + ["Potato", "KO"], + ["proxy", "KO"], + ["proxya", "KO"], + ["sec", "KO"], + ["secb", "KO"], + ["Empty-Value", ""], +]; + +validRequestHeaders.forEach(function(header) { + test(function() { + var request = new Request(""); + request.headers.set(header[0], header[1]); + assert_equals(request.headers.get(header[0]), header[1]); + }, "Adding valid request header \"" + header[0] + ": " + header[1] + "\""); +}); +invalidRequestHeaders.forEach(function(header) { + test(function() { + var request = new Request(""); + request.headers.set(header[0], header[1]); + assert_equals(request.headers.get(header[0]), null); + }, "Adding invalid request header \"" + header[0] + ": " + header[1] + "\""); +}); + +validRequestNoCorsHeaders.forEach(function(header) { + test(function() { + var requestNoCors = new Request("", {"mode": "no-cors"}); + requestNoCors.headers.set(header[0], header[1]); + assert_equals(requestNoCors.headers.get(header[0]), header[1]); + }, "Adding valid no-cors request header \"" + header[0] + ": " + header[1] + "\""); +}); +invalidRequestNoCorsHeaders.forEach(function(header) { + test(function() { + var requestNoCors = new Request("", {"mode": "no-cors"}); + requestNoCors.headers.set(header[0], header[1]); + assert_equals(requestNoCors.headers.get(header[0]), null); + }, "Adding invalid no-cors request header \"" + header[0] + ": " + header[1] + "\""); +}); + +test(function() { + var headers = new Headers([["Cookie2", "potato"]]); + var request = new Request("", {"headers": headers}); + assert_equals(request.headers.get("Cookie2"), null); +}, "Check that request constructor is filtering headers provided as init parameter"); + +test(function() { + var headers = new Headers([["Content-Type", "potato"]]); + var request = new Request("", {"headers": headers, "mode": "no-cors"}); + assert_equals(request.headers.get("Content-Type"), null); +}, "Check that no-cors request constructor is filtering headers provided as init parameter"); + +test(function() { + var headers = new Headers([["Content-Type", "potato"]]); + var initialRequest = new Request("", {"headers": headers}); + var request = new Request(initialRequest, {"mode": "no-cors"}); + assert_equals(request.headers.get("Content-Type"), null); +}, "Check that no-cors request constructor is filtering headers provided as part of request parameter"); + +test(function() { + var initialHeaders = new Headers([["Content-Type", "potato"]]); + var initialRequest = new Request("", {"headers" : initialHeaders}); + var request = new Request(initialRequest); + assert_equals(request.headers.get("Content-Type"), "potato"); +}, "Request should get its content-type from the init request"); + +test(function() { + var initialHeaders = new Headers([["Content-Type", "potato"]]); + var initialRequest = new Request("", {"headers" : initialHeaders}); + var headers = new Headers([]); + var request = new Request(initialRequest, {"headers" : headers}); + assert_false(request.headers.has("Content-Type")); +}, "Request should not get its content-type from the init request if init headers are provided"); + +test(function() { + var initialHeaders = new Headers([["Content-Type-Extra", "potato"]]); + var initialRequest = new Request("", {"headers" : initialHeaders, "body" : "this is my plate", "method" : "POST"}); + var request = new Request(initialRequest); + assert_equals(request.headers.get("Content-Type"), "text/plain;charset=UTF-8"); +}, "Request should get its content-type from the body if none is provided"); + +test(function() { + var initialHeaders = new Headers([["Content-Type", "potato"]]); + var initialRequest = new Request("", {"headers" : initialHeaders, "body" : "this is my plate", "method" : "POST"}); + var request = new Request(initialRequest); + assert_equals(request.headers.get("Content-Type"), "potato"); +}, "Request should get its content-type from init headers if one is provided"); + +test(function() { + var array = [["hello", "worldAHH"]]; + var object = {"hello": 'worldOOH'}; + var headers = new Headers(array); + + assert_equals(headers.get("hello"), "worldAHH"); + + var request1 = new Request("", {"headers": headers}); + var request2 = new Request("", {"headers": array}); + var request3 = new Request("", {"headers": object}); + + assert_equals(request1.headers.get("hello"), "worldAHH"); + assert_equals(request2.headers.get("hello"), "worldAHH"); + assert_equals(request3.headers.get("hello"), "worldOOH"); +}, "Testing request header creations with various objects"); + +promise_test(function(test) { + var request = new Request("", {"headers" : [["Content-Type", ""]], "body" : "this is my plate", "method" : "POST"}); + return request.blob().then(function(blob) { + assert_equals(blob.type, "", "Blob type should be the empty string"); + }); +}, "Testing empty Request Content-Type header"); + +test(function() { + const request1 = new Request(""); + assert_equals(request1.headers, request1.headers); + + const request2 = new Request("", {"headers": {"X-Foo": "bar"}}); + assert_equals(request2.headers, request2.headers); + const headers = request2.headers; + request2.headers.set("X-Foo", "quux"); + assert_equals(headers, request2.headers); + headers.set("X-Other-Header", "baz"); + assert_equals(headers, request2.headers); +}, "Test that Request.headers has the [SameObject] extended attribute"); diff --git a/test/wpt/tests/fetch/api/request/request-init-001.sub.html b/test/wpt/tests/fetch/api/request/request-init-001.sub.html new file mode 100644 index 0000000..cc495a6 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-init-001.sub.html @@ -0,0 +1,112 @@ + + + + + Request init: simple cases + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/request/request-init-002.any.js b/test/wpt/tests/fetch/api/request/request-init-002.any.js new file mode 100644 index 0000000..abb6689 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-init-002.any.js @@ -0,0 +1,60 @@ +// META: global=window,worker +// META: title=Request init: headers and body + +test(function() { + var headerDict = {"name1": "value1", + "name2": "value2", + "name3": "value3" + }; + var headers = new Headers(headerDict); + var request = new Request("", { "headers" : headers }) + for (var name in headerDict) { + assert_equals(request.headers.get(name), headerDict[name], + "request's headers has " + name + " : " + headerDict[name]); + } +}, "Initialize Request with headers values"); + +function makeRequestInit(body, method) { + return {"method": method, "body": body}; +} + +function checkRequestInit(body, bodyType, expectedTextBody) { + promise_test(function(test) { + var request = new Request("", makeRequestInit(body, "POST")); + if (body) { + assert_throws_js(TypeError, function() { new Request("", makeRequestInit(body, "GET")); }); + assert_throws_js(TypeError, function() { new Request("", makeRequestInit(body, "HEAD")); }); + } else { + new Request("", makeRequestInit(body, "GET")); // should not throw + } + var reqHeaders = request.headers; + var mime = reqHeaders.get("Content-Type"); + assert_true(!body || (mime && mime.search(bodyType) > -1), "Content-Type header should be \"" + bodyType + "\", not \"" + mime + "\""); + return request.text().then(function(bodyAsText) { + //not equals: cannot guess formData exact value + assert_true( bodyAsText.search(expectedTextBody) > -1, "Retrieve and verify request body"); + }); + }, `Initialize Request's body with "${body}", ${bodyType}`); +} + +var blob = new Blob(["This is a blob"], {type: "application/octet-binary"}); +var formaData = new FormData(); +formaData.append("name", "value"); +var usvString = "This is a USVString" + +checkRequestInit(undefined, undefined, ""); +checkRequestInit(null, null, ""); +checkRequestInit(blob, "application/octet-binary", "This is a blob"); +checkRequestInit(formaData, "multipart/form-data", "name=\"name\"\r\n\r\nvalue"); +checkRequestInit(usvString, "text/plain;charset=UTF-8", "This is a USVString"); +checkRequestInit({toString: () => "hi!"}, "text/plain;charset=UTF-8", "hi!"); + +// Ensure test does not time out in case of missing URLSearchParams support. +if (self.URLSearchParams) { + var urlSearchParams = new URLSearchParams("name=value"); + checkRequestInit(urlSearchParams, "application/x-www-form-urlencoded;charset=UTF-8", "name=value"); +} else { + promise_test(function(test) { + return Promise.reject("URLSearchParams not supported"); + }, "Initialize Request's body with application/x-www-form-urlencoded;charset=UTF-8"); +} diff --git a/test/wpt/tests/fetch/api/request/request-init-003.sub.html b/test/wpt/tests/fetch/api/request/request-init-003.sub.html new file mode 100644 index 0000000..79c91cd --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-init-003.sub.html @@ -0,0 +1,84 @@ + + + + + Request: init with request or url + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/request/request-init-contenttype.any.js b/test/wpt/tests/fetch/api/request/request-init-contenttype.any.js new file mode 100644 index 0000000..18a6969 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-init-contenttype.any.js @@ -0,0 +1,141 @@ +function requestFromBody(body) { + return new Request( + "https://example.com", + { + method: "POST", + body, + duplex: "half", + }, + ); +} + +test(() => { + const request = requestFromBody(undefined); + assert_equals(request.headers.get("Content-Type"), null); +}, "Default Content-Type for Request with empty body"); + +test(() => { + const blob = new Blob([]); + const request = requestFromBody(blob); + assert_equals(request.headers.get("Content-Type"), null); +}, "Default Content-Type for Request with Blob body (no type set)"); + +test(() => { + const blob = new Blob([], { type: "" }); + const request = requestFromBody(blob); + assert_equals(request.headers.get("Content-Type"), null); +}, "Default Content-Type for Request with Blob body (empty type)"); + +test(() => { + const blob = new Blob([], { type: "a/b; c=d" }); + const request = requestFromBody(blob); + assert_equals(request.headers.get("Content-Type"), "a/b; c=d"); +}, "Default Content-Type for Request with Blob body (set type)"); + +test(() => { + const buffer = new Uint8Array(); + const request = requestFromBody(buffer); + assert_equals(request.headers.get("Content-Type"), null); +}, "Default Content-Type for Request with buffer source body"); + +promise_test(async () => { + const formData = new FormData(); + formData.append("a", "b"); + const request = requestFromBody(formData); + const boundary = (await request.text()).split("\r\n")[0].slice(2); + assert_equals( + request.headers.get("Content-Type"), + `multipart/form-data; boundary=${boundary}`, + ); +}, "Default Content-Type for Request with FormData body"); + +test(() => { + const usp = new URLSearchParams(); + const request = requestFromBody(usp); + assert_equals( + request.headers.get("Content-Type"), + "application/x-www-form-urlencoded;charset=UTF-8", + ); +}, "Default Content-Type for Request with URLSearchParams body"); + +test(() => { + const request = requestFromBody(""); + assert_equals( + request.headers.get("Content-Type"), + "text/plain;charset=UTF-8", + ); +}, "Default Content-Type for Request with string body"); + +test(() => { + const stream = new ReadableStream(); + const request = requestFromBody(stream); + assert_equals(request.headers.get("Content-Type"), null); +}, "Default Content-Type for Request with ReadableStream body"); + +// ----------------------------------------------------------------------------- + +const OVERRIDE_MIME = "test/only; mime=type"; + +function requestFromBodyWithOverrideMime(body) { + return new Request( + "https://example.com", + { + method: "POST", + body, + headers: { "Content-Type": OVERRIDE_MIME }, + duplex: "half", + }, + ); +} + +test(() => { + const request = requestFromBodyWithOverrideMime(undefined); + assert_equals(request.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Request with empty body"); + +test(() => { + const blob = new Blob([]); + const request = requestFromBodyWithOverrideMime(blob); + assert_equals(request.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Request with Blob body (no type set)"); + +test(() => { + const blob = new Blob([], { type: "" }); + const request = requestFromBodyWithOverrideMime(blob); + assert_equals(request.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Request with Blob body (empty type)"); + +test(() => { + const blob = new Blob([], { type: "a/b; c=d" }); + const request = requestFromBodyWithOverrideMime(blob); + assert_equals(request.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Request with Blob body (set type)"); + +test(() => { + const buffer = new Uint8Array(); + const request = requestFromBodyWithOverrideMime(buffer); + assert_equals(request.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Request with buffer source body"); + +test(() => { + const formData = new FormData(); + const request = requestFromBodyWithOverrideMime(formData); + assert_equals(request.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Request with FormData body"); + +test(() => { + const usp = new URLSearchParams(); + const request = requestFromBodyWithOverrideMime(usp); + assert_equals(request.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Request with URLSearchParams body"); + +test(() => { + const request = requestFromBodyWithOverrideMime(""); + assert_equals(request.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Request with string body"); + +test(() => { + const stream = new ReadableStream(); + const request = requestFromBodyWithOverrideMime(stream); + assert_equals(request.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Request with ReadableStream body"); diff --git a/test/wpt/tests/fetch/api/request/request-init-priority.any.js b/test/wpt/tests/fetch/api/request/request-init-priority.any.js new file mode 100644 index 0000000..eb5073c --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-init-priority.any.js @@ -0,0 +1,26 @@ +var priorities = ["high", + "low", + "auto" + ]; + +for (idx in priorities) { + test(() => { + new Request("", {priority: priorities[idx]}); + }, "new Request() with a '" + priorities[idx] + "' priority does not throw an error"); +} + +test(() => { + assert_throws_js(TypeError, () => { + new Request("", {priority: 'invalid'}); + }, "a new Request() must throw a TypeError if RequestInit's priority is an invalid value"); +}, "new Request() throws a TypeError if any of RequestInit's members' values are invalid"); + +for (idx in priorities) { + promise_test(function(t) { + return fetch('hello.txt', { priority: priorities[idx] }); + }, "fetch() with a '" + priorities[idx] + "' priority completes successfully"); +} + +promise_test(function(t) { + return promise_rejects_js(t, TypeError, fetch('hello.txt', { priority: 'invalid' })); +}, "fetch() with an invalid priority returns a rejected promise with a TypeError"); diff --git a/test/wpt/tests/fetch/api/request/request-init-stream.any.js b/test/wpt/tests/fetch/api/request/request-init-stream.any.js new file mode 100644 index 0000000..f0ae441 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-init-stream.any.js @@ -0,0 +1,147 @@ +// META: global=window,worker + +"use strict"; + +const duplex = "half"; +const method = "POST"; + +test(() => { + const body = new ReadableStream(); + const request = new Request("...", { method, body, duplex }); + assert_equals(request.body, body); +}, "Constructing a Request with a stream holds the original object."); + +test((t) => { + const body = new ReadableStream(); + body.getReader(); + assert_throws_js(TypeError, + () => new Request("...", { method, body, duplex })); +}, "Constructing a Request with a stream on which getReader() is called"); + +test((t) => { + const body = new ReadableStream(); + body.getReader().read(); + assert_throws_js(TypeError, + () => new Request("...", { method, body, duplex })); +}, "Constructing a Request with a stream on which read() is called"); + +promise_test(async (t) => { + const body = new ReadableStream({ pull: c => c.enqueue(new Uint8Array()) }); + const reader = body.getReader(); + await reader.read(); + reader.releaseLock(); + assert_throws_js(TypeError, + () => new Request("...", { method, body, duplex })); +}, "Constructing a Request with a stream on which read() and releaseLock() are called"); + +test((t) => { + const request = new Request("...", { method: "POST", body: "..." }); + request.body.getReader(); + assert_throws_js(TypeError, () => new Request(request)); + // This doesn't throw. + new Request(request, { body: "..." }); +}, "Constructing a Request with a Request on which body.getReader() is called"); + +test((t) => { + const request = new Request("...", { method: "POST", body: "..." }); + request.body.getReader().read(); + assert_throws_js(TypeError, () => new Request(request)); + // This doesn't throw. + new Request(request, { body: "..." }); +}, "Constructing a Request with a Request on which body.getReader().read() is called"); + +promise_test(async (t) => { + const request = new Request("...", { method: "POST", body: "..." }); + const reader = request.body.getReader(); + await reader.read(); + reader.releaseLock(); + assert_throws_js(TypeError, () => new Request(request)); + // This doesn't throw. + new Request(request, { body: "..." }); +}, "Constructing a Request with a Request on which read() and releaseLock() are called"); + +test((t) => { + new Request("...", { method, body: null }); +}, "It is OK to omit .duplex when the body is null."); + +test((t) => { + new Request("...", { method, body: "..." }); +}, "It is OK to omit .duplex when the body is a string."); + +test((t) => { + new Request("...", { method, body: new Uint8Array(3) }); +}, "It is OK to omit .duplex when the body is a Uint8Array."); + +test((t) => { + new Request("...", { method, body: new Blob([]) }); +}, "It is OK to omit .duplex when the body is a Blob."); + +test((t) => { + const body = new ReadableStream(); + assert_throws_js(TypeError, + () => new Request("...", { method, body })); +}, "It is error to omit .duplex when the body is a ReadableStream."); + +test((t) => { + new Request("...", { method, body: null, duplex: "half" }); +}, "It is OK to set .duplex = 'half' when the body is null."); + +test((t) => { + new Request("...", { method, body: "...", duplex: "half" }); +}, "It is OK to set .duplex = 'half' when the body is a string."); + +test((t) => { + new Request("...", { method, body: new Uint8Array(3), duplex: "half" }); +}, "It is OK to set .duplex = 'half' when the body is a Uint8Array."); + +test((t) => { + new Request("...", { method, body: new Blob([]), duplex: "half" }); +}, "It is OK to set .duplex = 'half' when the body is a Blob."); + +test((t) => { + const body = new ReadableStream(); + new Request("...", { method, body, duplex: "half" }); +}, "It is OK to set .duplex = 'half' when the body is a ReadableStream."); + +test((t) => { + const body = null; + const duplex = "full"; + assert_throws_js(TypeError, + () => new Request("...", { method, body, duplex })); +}, "It is error to set .duplex = 'full' when the body is null."); + +test((t) => { + const body = "..."; + const duplex = "full"; + assert_throws_js(TypeError, + () => new Request("...", { method, body, duplex })); +}, "It is error to set .duplex = 'full' when the body is a string."); + +test((t) => { + const body = new Uint8Array(3); + const duplex = "full"; + assert_throws_js(TypeError, + () => new Request("...", { method, body, duplex })); +}, "It is error to set .duplex = 'full' when the body is a Uint8Array."); + +test((t) => { + const body = new Blob([]); + const duplex = "full"; + assert_throws_js(TypeError, + () => new Request("...", { method, body, duplex })); +}, "It is error to set .duplex = 'full' when the body is a Blob."); + +test((t) => { + const body = new ReadableStream(); + const duplex = "full"; + assert_throws_js(TypeError, + () => new Request("...", { method, body, duplex })); +}, "It is error to set .duplex = 'full' when the body is a ReadableStream."); + +test((t) => { + const body = new ReadableStream(); + const duplex = "half"; + const req1 = new Request("...", { method, body, duplex }); + const req2 = new Request(req1); +}, "It is OK to omit duplex when init.body is not given and input.body is given."); + diff --git a/test/wpt/tests/fetch/api/request/request-keepalive-quota.html b/test/wpt/tests/fetch/api/request/request-keepalive-quota.html new file mode 100644 index 0000000..548ab38 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-keepalive-quota.html @@ -0,0 +1,97 @@ + + + + + Request Keepalive Quota Tests + + + + + + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/request/request-keepalive.any.js b/test/wpt/tests/fetch/api/request/request-keepalive.any.js new file mode 100644 index 0000000..cb4506d --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-keepalive.any.js @@ -0,0 +1,17 @@ +// META: global=window,worker +// META: title=Request keepalive +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js + +test(() => { + assert_false(new Request('/').keepalive, 'default'); + assert_true(new Request('/', {keepalive: true}).keepalive, 'true'); + assert_false(new Request('/', {keepalive: false}).keepalive, 'false'); + assert_true(new Request('/', {keepalive: 1}).keepalive, 'truish'); + assert_false(new Request('/', {keepalive: 0}).keepalive, 'falsy'); +}, 'keepalive flag'); + +test(() => { + const init = {method: 'POST', keepalive: true, body: new ReadableStream()}; + assert_throws_js(TypeError, () => {new Request('/', init)}); +}, 'keepalive flag with stream body'); diff --git a/test/wpt/tests/fetch/api/request/request-reset-attributes.https.html b/test/wpt/tests/fetch/api/request/request-reset-attributes.https.html new file mode 100644 index 0000000..7be3608 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-reset-attributes.https.html @@ -0,0 +1,96 @@ + + + + + + + diff --git a/test/wpt/tests/fetch/api/request/request-structure.any.js b/test/wpt/tests/fetch/api/request/request-structure.any.js new file mode 100644 index 0000000..5e78553 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/request-structure.any.js @@ -0,0 +1,143 @@ +// META: global=window,worker +// META: title=Request structure + +var request = new Request(""); +var methods = ["clone", + //Request implements Body + "arrayBuffer", + "blob", + "formData", + "json", + "text" + ]; +var attributes = ["method", + "url", + "headers", + "destination", + "referrer", + "referrerPolicy", + "mode", + "credentials", + "cache", + "redirect", + "integrity", + "isReloadNavigation", + "isHistoryNavigation", + "duplex", + //Request implements Body + "bodyUsed" + ]; +var internalAttributes = ["priority", + "internalpriority", + "blocking" + ]; + +function isReadOnly(request, attributeToCheck) { + var defaultValue = undefined; + var newValue = undefined; + switch (attributeToCheck) { + case "method": + defaultValue = "GET"; + newValue = "POST"; + break; + + case "url": + //default value is base url + //i.e http://example.com/fetch/api/request-structure.html + newValue = "http://url.test"; + break; + + case "headers": + request.headers = new Headers ({"name":"value"}); + assert_false(request.headers.has("name"), "Headers attribute is read only"); + return; + + case "destination": + defaultValue = ""; + newValue = "worker"; + break; + + case "referrer": + defaultValue = "about:client"; + newValue = "http://url.test"; + break; + + case "referrerPolicy": + defaultValue = ""; + newValue = "unsafe-url"; + break; + + case "mode": + defaultValue = "cors"; + newValue = "navigate"; + break; + + case "credentials": + defaultValue = "same-origin"; + newValue = "cors"; + break; + + case "cache": + defaultValue = "default"; + newValue = "reload"; + break; + + case "redirect": + defaultValue = "follow"; + newValue = "manual"; + break; + + case "integrity": + newValue = "CannotWriteIntegrity"; + break; + + case "bodyUsed": + defaultValue = false; + newValue = true; + break; + + case "isReloadNavigation": + defaultValue = false; + newValue = true; + break; + + case "isHistoryNavigation": + defaultValue = false; + newValue = true; + break; + + case "duplex": + defaultValue = "half"; + newValue = "full"; + break; + + default: + return; + } + + request[attributeToCheck] = newValue; + if (defaultValue === undefined) + assert_not_equals(request[attributeToCheck], newValue, "Attribute " + attributeToCheck + " is read only"); + else + assert_equals(request[attributeToCheck], defaultValue, + "Attribute " + attributeToCheck + " is read only. Default value is " + defaultValue); +} + +for (var idx in methods) { + test(function() { + assert_true(methods[idx] in request, "request has " + methods[idx] + " method"); + }, "Request has " + methods[idx] + " method"); +} + +for (var idx in attributes) { + test(function() { + assert_true(attributes[idx] in request, "request has " + attributes[idx] + " attribute"); + isReadOnly(request, attributes[idx]); + }, "Check " + attributes[idx] + " attribute"); +} + +for (var idx in internalAttributes) { + test(function() { + assert_false(internalAttributes[idx] in request, "request does not expose " + internalAttributes[idx] + " attribute"); + }, "Request does not expose " + internalAttributes[idx] + " attribute"); +} \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/request/resources/cache.py b/test/wpt/tests/fetch/api/request/resources/cache.py new file mode 100644 index 0000000..ca0bd64 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/resources/cache.py @@ -0,0 +1,67 @@ +from wptserve.utils import isomorphic_decode + +def main(request, response): + token = request.GET.first(b"token", None) + if b"querystate" in request.GET: + from json import JSONEncoder + response.headers.set(b"Content-Type", b"text/plain") + return JSONEncoder().encode(request.server.stash.take(token)) + content = request.GET.first(b"content", None) + tag = request.GET.first(b"tag", None) + date = request.GET.first(b"date", None) + expires = request.GET.first(b"expires", None) + vary = request.GET.first(b"vary", None) + cc = request.GET.first(b"cache_control", None) + redirect = request.GET.first(b"redirect", None) + inm = request.headers.get(b"If-None-Match", None) + ims = request.headers.get(b"If-Modified-Since", None) + pragma = request.headers.get(b"Pragma", None) + cache_control = request.headers.get(b"Cache-Control", None) + ignore = b"ignore" in request.GET + + if tag: + tag = b'"%s"' % tag + + server_state = request.server.stash.take(token) + if not server_state: + server_state = [] + state = dict() + if not ignore: + if inm: + state[u"If-None-Match"] = isomorphic_decode(inm) + if ims: + state[u"If-Modified-Since"] = isomorphic_decode(ims) + if pragma: + state[u"Pragma"] = isomorphic_decode(pragma) + if cache_control: + state[u"Cache-Control"] = isomorphic_decode(cache_control) + server_state.append(state) + request.server.stash.put(token, server_state) + + if tag: + response.headers.set(b"ETag", b'%s' % tag) + elif date: + response.headers.set(b"Last-Modified", date) + if expires: + response.headers.set(b"Expires", expires) + if vary: + response.headers.set(b"Vary", vary) + if cc: + response.headers.set(b"Cache-Control", cc) + + # The only-if-cached redirect tests wants CORS to be okay, the other tests + # are all same-origin anyways and don't care. + response.headers.set(b"Access-Control-Allow-Origin", b"*") + + if redirect: + response.headers.set(b"Location", redirect) + response.status = (302, b"Redirect") + return b"" + elif ((inm is not None and inm == tag) or + (ims is not None and ims == date)): + response.status = (304, b"Not Modified") + return b"" + else: + response.status = (200, b"OK") + response.headers.set(b"Content-Type", b"text/plain") + return content diff --git a/test/wpt/tests/fetch/api/request/resources/hello.txt b/test/wpt/tests/fetch/api/request/resources/hello.txt new file mode 100644 index 0000000..ce01362 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/resources/hello.txt @@ -0,0 +1 @@ +hello diff --git a/test/wpt/tests/fetch/api/request/resources/request-reset-attributes-worker.js b/test/wpt/tests/fetch/api/request/resources/request-reset-attributes-worker.js new file mode 100644 index 0000000..4b264ca --- /dev/null +++ b/test/wpt/tests/fetch/api/request/resources/request-reset-attributes-worker.js @@ -0,0 +1,19 @@ +self.addEventListener('fetch', (event) => { + const params = new URL(event.request.url).searchParams; + if (params.has('ignore')) { + return; + } + if (!params.has('name')) { + event.respondWith(Promise.reject(TypeError('No name is provided.'))); + return; + } + + const name = params.get('name'); + const old_attribute = event.request[name]; + // If any of |init|'s member is present... + const init = {cache: 'no-store'} + const new_attribute = (new Request(event.request, init))[name]; + + event.respondWith( + new Response(`old: ${old_attribute}, new: ${new_attribute}`)); + }); diff --git a/test/wpt/tests/fetch/api/request/url-encoding.html b/test/wpt/tests/fetch/api/request/url-encoding.html new file mode 100644 index 0000000..31c1ed3 --- /dev/null +++ b/test/wpt/tests/fetch/api/request/url-encoding.html @@ -0,0 +1,25 @@ + + +Fetch: URL encoding + + + diff --git a/test/wpt/tests/fetch/api/resources/authentication.py b/test/wpt/tests/fetch/api/resources/authentication.py new file mode 100644 index 0000000..8b6b00b --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/authentication.py @@ -0,0 +1,14 @@ +def main(request, response): + user = request.auth.username + password = request.auth.password + + if user == b"user" and password == b"password": + return b"Authentication done" + + realm = b"test" + if b"realm" in request.GET: + realm = request.GET.first(b"realm") + + return ((401, b"Unauthorized"), + [(b"WWW-Authenticate", b'Basic realm="' + realm + b'"')], + b"Please login with credentials 'user' and 'password'") diff --git a/test/wpt/tests/fetch/api/resources/bad-chunk-encoding.py b/test/wpt/tests/fetch/api/resources/bad-chunk-encoding.py new file mode 100644 index 0000000..94a77ad --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/bad-chunk-encoding.py @@ -0,0 +1,13 @@ +import time + +def main(request, response): + delay = float(request.GET.first(b"ms", 1000)) / 1E3 + count = int(request.GET.first(b"count", 50)) + time.sleep(delay) + response.headers.set(b"Transfer-Encoding", b"chunked") + response.write_status_headers() + time.sleep(delay) + for i in range(count): + response.writer.write_content(b"a\r\nTEST_CHUNK\r\n") + time.sleep(delay) + response.writer.write_content(b"garbage") diff --git a/test/wpt/tests/fetch/api/resources/basic.html b/test/wpt/tests/fetch/api/resources/basic.html new file mode 100644 index 0000000..e23afd4 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/basic.html @@ -0,0 +1,5 @@ + + diff --git a/test/wpt/tests/fetch/api/resources/cache.py b/test/wpt/tests/fetch/api/resources/cache.py new file mode 100644 index 0000000..4de751e --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/cache.py @@ -0,0 +1,18 @@ +ETAG = b'"123abc"' +CONTENT_TYPE = b"text/plain" +CONTENT = b"lorem ipsum dolor sit amet" + + +def main(request, response): + # let caching kick in if possible (conditional GET) + etag = request.headers.get(b"If-None-Match", None) + if etag == ETAG: + response.headers.set(b"X-HTTP-STATUS", 304) + response.status = (304, b"Not Modified") + return b"" + + # cache miss, so respond with the actual content + response.status = (200, b"OK") + response.headers.set(b"ETag", ETAG) + response.headers.set(b"Content-Type", CONTENT_TYPE) + return CONTENT diff --git a/test/wpt/tests/fetch/api/resources/clean-stash.py b/test/wpt/tests/fetch/api/resources/clean-stash.py new file mode 100644 index 0000000..ee8c69a --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/clean-stash.py @@ -0,0 +1,6 @@ +def main(request, response): + token = request.GET.first(b"token") + if request.server.stash.take(token) is not None: + return b"1" + else: + return b"0" diff --git a/test/wpt/tests/fetch/api/resources/cors-top.txt b/test/wpt/tests/fetch/api/resources/cors-top.txt new file mode 100644 index 0000000..83a3157 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/cors-top.txt @@ -0,0 +1 @@ +top \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/resources/cors-top.txt.headers b/test/wpt/tests/fetch/api/resources/cors-top.txt.headers new file mode 100644 index 0000000..cb762ef --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/cors-top.txt.headers @@ -0,0 +1 @@ +Access-Control-Allow-Origin: * diff --git a/test/wpt/tests/fetch/api/resources/data.json b/test/wpt/tests/fetch/api/resources/data.json new file mode 100644 index 0000000..76519fa --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/data.json @@ -0,0 +1 @@ +{"key": "value"} diff --git a/test/wpt/tests/fetch/api/resources/dump-authorization-header.py b/test/wpt/tests/fetch/api/resources/dump-authorization-header.py new file mode 100644 index 0000000..a651aeb --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/dump-authorization-header.py @@ -0,0 +1,14 @@ +def main(request, response): + headers = [(b"Content-Type", "text/html"), + (b"Cache-Control", b"no-cache")] + + if b"Origin" in request.headers: + headers.append((b"Access-Control-Allow-Origin", request.headers.get(b"Origin", b""))) + headers.append((b"Access-Control-Allow-Credentials", b"true")) + else: + headers.append((b"Access-Control-Allow-Origin", b"*")) + headers.append((b"Access-Control-Allow-Headers", b'Authorization')) + + if b"authorization" in request.headers: + return 200, headers, request.headers.get(b"Authorization") + return 200, headers, "none" diff --git a/test/wpt/tests/fetch/api/resources/echo-content.h2.py b/test/wpt/tests/fetch/api/resources/echo-content.h2.py new file mode 100644 index 0000000..0be3ece --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/echo-content.h2.py @@ -0,0 +1,7 @@ +def handle_headers(frame, request, response): + response.status = 200 + response.headers.update([('Content-Type', 'text/plain')]) + response.write_status_headers() + +def handle_data(frame, request, response): + response.writer.write_data(frame.data) diff --git a/test/wpt/tests/fetch/api/resources/echo-content.py b/test/wpt/tests/fetch/api/resources/echo-content.py new file mode 100644 index 0000000..5e137e1 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/echo-content.py @@ -0,0 +1,12 @@ +from wptserve.utils import isomorphic_encode + +def main(request, response): + + headers = [(b"X-Request-Method", isomorphic_encode(request.method)), + (b"X-Request-Content-Length", request.headers.get(b"Content-Length", b"NO")), + (b"X-Request-Content-Type", request.headers.get(b"Content-Type", b"NO")), + # Avoid any kind of content sniffing on the response. + (b"Content-Type", b"text/plain")] + content = request.body + + return headers, content diff --git a/test/wpt/tests/fetch/api/resources/empty.txt b/test/wpt/tests/fetch/api/resources/empty.txt new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/fetch/api/resources/infinite-slow-response.py b/test/wpt/tests/fetch/api/resources/infinite-slow-response.py new file mode 100644 index 0000000..a26cd80 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/infinite-slow-response.py @@ -0,0 +1,35 @@ +import time + + +def url_dir(request): + return u'/'.join(request.url_parts.path.split(u'/')[:-1]) + u'/' + + +def stash_write(request, key, value): + """Write to the stash, overwriting any previous value""" + request.server.stash.take(key, url_dir(request)) + request.server.stash.put(key, value, url_dir(request)) + + +def main(request, response): + stateKey = request.GET.first(b"stateKey", b"") + abortKey = request.GET.first(b"abortKey", b"") + + if stateKey: + stash_write(request, stateKey, 'open') + + response.headers.set(b"Content-type", b"text/plain") + response.write_status_headers() + + # Writing an initial 2k so browsers realise it's there. *shrug* + response.writer.write(b"." * 2048) + + while True: + if not response.writer.write(b"."): + break + if abortKey and request.server.stash.take(abortKey, url_dir(request)): + break + time.sleep(0.01) + + if stateKey: + stash_write(request, stateKey, 'closed') diff --git a/test/wpt/tests/fetch/api/resources/inspect-headers.py b/test/wpt/tests/fetch/api/resources/inspect-headers.py new file mode 100644 index 0000000..9ed566e --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/inspect-headers.py @@ -0,0 +1,24 @@ +def main(request, response): + headers = [] + if b"headers" in request.GET: + checked_headers = request.GET.first(b"headers").split(b"|") + for header in checked_headers: + if header in request.headers: + headers.append((b"x-request-" + header, request.headers.get(header, b""))) + + if b"cors" in request.GET: + if b"Origin" in request.headers: + headers.append((b"Access-Control-Allow-Origin", request.headers.get(b"Origin", b""))) + else: + headers.append((b"Access-Control-Allow-Origin", b"*")) + headers.append((b"Access-Control-Allow-Credentials", b"true")) + headers.append((b"Access-Control-Allow-Methods", b"GET, POST, HEAD")) + exposed_headers = [b"x-request-" + header for header in checked_headers] + headers.append((b"Access-Control-Expose-Headers", b", ".join(exposed_headers))) + if b"allow_headers" in request.GET: + headers.append((b"Access-Control-Allow-Headers", request.GET[b'allow_headers'])) + else: + headers.append((b"Access-Control-Allow-Headers", b", ".join(request.headers))) + + headers.append((b"content-type", b"text/plain")) + return headers, b"" diff --git a/test/wpt/tests/fetch/api/resources/keepalive-helper.js b/test/wpt/tests/fetch/api/resources/keepalive-helper.js new file mode 100644 index 0000000..ad1d4b2 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/keepalive-helper.js @@ -0,0 +1,99 @@ +// Utility functions to help testing keepalive requests. + +// Returns a URL to an iframe that loads a keepalive URL on iframe loaded. +// +// The keepalive URL points to a target that stores `token`. The token will then +// be posted back on iframe loaded to the parent document. +// `method` defaults to GET. +// `frameOrigin` to specify the origin of the iframe to load. If not set, +// default to a different site origin. +// `requestOrigin` to specify the origin of the fetch request target. +// `sendOn` to specify the name of the event when the keepalive request should +// be sent instead of the default 'load'. +// `mode` to specify the fetch request's CORS mode. +// `disallowOrigin` to ask the iframe to set up a server that forbids CORS +// requests. +function getKeepAliveIframeUrl(token, method, { + frameOrigin = 'DEFAULT', + requestOrigin = '', + sendOn = 'load', + mode = 'cors', + disallowOrigin = false +} = {}) { + const https = location.protocol.startsWith('https'); + frameOrigin = frameOrigin === 'DEFAULT' ? + get_host_info()[https ? 'HTTPS_NOTSAMESITE_ORIGIN' : 'HTTP_NOTSAMESITE_ORIGIN'] : + frameOrigin; + return `${frameOrigin}/fetch/api/resources/keepalive-iframe.html?` + + `token=${token}&` + + `method=${method}&` + + `sendOn=${sendOn}&` + + `mode=${mode}&` + (disallowOrigin ? `disallowOrigin=1&` : ``) + + `origin=${requestOrigin}`; +} + +// Returns a different-site URL to an iframe that loads a keepalive URL. +// +// By default, the keepalive URL points to a target that redirects to another +// same-origin destination storing `token`. The token will then be posted back +// to parent document. +// +// The URL redirects can be customized from `origin1` to `origin2` if provided. +// Sets `withPreflight` to true to get URL enabling preflight. +function getKeepAliveAndRedirectIframeUrl( + token, origin1, origin2, withPreflight) { + const https = location.protocol.startsWith('https'); + const frameOrigin = + get_host_info()[https ? 'HTTPS_NOTSAMESITE_ORIGIN' : 'HTTP_NOTSAMESITE_ORIGIN']; + return `${frameOrigin}/fetch/api/resources/keepalive-redirect-iframe.html?` + + `token=${token}&` + + `origin1=${origin1}&` + + `origin2=${origin2}&` + (withPreflight ? `with-headers` : ``); +} + +async function iframeLoaded(iframe) { + return new Promise((resolve) => iframe.addEventListener('load', resolve)); +} + +// Obtains the token from the message posted by iframe after loading +// `getKeepAliveAndRedirectIframeUrl()`. +async function getTokenFromMessage() { + return new Promise((resolve) => { + window.addEventListener('message', (event) => { + resolve(event.data); + }, {once: true}); + }); +} + +// Tells if `token` has been stored in the server. +async function queryToken(token) { + const response = await fetch(`../resources/stash-take.py?key=${token}`); + const json = await response.json(); + return json; +} + +// In order to parallelize the work, we are going to have an async_test +// for the rest of the work. Note that we want the serialized behavior +// for the steps so far, so we don't want to make the entire test case +// an async_test. +function assertStashedTokenAsync(testName, token, {shouldPass = true} = {}) { + async_test((test) => { + new Promise((resolve) => test.step_timeout(resolve, 3000)) + .then(() => { + return queryToken(token); + }) + .then((result) => { + assert_equals(result, 'on'); + }) + .then(() => { + test.done(); + }) + .catch(test.step_func((e) => { + if (shouldPass) { + assert_unreached(e); + } else { + test.done(); + } + })); + }, testName); +} diff --git a/test/wpt/tests/fetch/api/resources/keepalive-iframe.html b/test/wpt/tests/fetch/api/resources/keepalive-iframe.html new file mode 100644 index 0000000..335a1f8 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/keepalive-iframe.html @@ -0,0 +1,21 @@ + + + + + diff --git a/test/wpt/tests/fetch/api/resources/keepalive-redirect-iframe.html b/test/wpt/tests/fetch/api/resources/keepalive-redirect-iframe.html new file mode 100644 index 0000000..fdee00f --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/keepalive-redirect-iframe.html @@ -0,0 +1,23 @@ + + + + + diff --git a/test/wpt/tests/fetch/api/resources/keepalive-redirect-window.html b/test/wpt/tests/fetch/api/resources/keepalive-redirect-window.html new file mode 100644 index 0000000..c186507 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/keepalive-redirect-window.html @@ -0,0 +1,42 @@ + + + + + + + diff --git a/test/wpt/tests/fetch/api/resources/method.py b/test/wpt/tests/fetch/api/resources/method.py new file mode 100644 index 0000000..c1a111b --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/method.py @@ -0,0 +1,18 @@ +from wptserve.utils import isomorphic_encode + +def main(request, response): + headers = [] + if b"cors" in request.GET: + headers.append((b"Access-Control-Allow-Origin", b"*")) + headers.append((b"Access-Control-Allow-Credentials", b"true")) + headers.append((b"Access-Control-Allow-Methods", b"GET, POST, PUT, FOO")) + headers.append((b"Access-Control-Allow-Headers", b"x-test, x-foo")) + headers.append((b"Access-Control-Expose-Headers", b"x-request-method")) + + headers.append((b"x-request-method", isomorphic_encode(request.method))) + headers.append((b"x-request-content-type", request.headers.get(b"Content-Type", b"NO"))) + headers.append((b"x-request-content-length", request.headers.get(b"Content-Length", b"NO"))) + headers.append((b"x-request-content-encoding", request.headers.get(b"Content-Encoding", b"NO"))) + headers.append((b"x-request-content-language", request.headers.get(b"Content-Language", b"NO"))) + headers.append((b"x-request-content-location", request.headers.get(b"Content-Location", b"NO"))) + return headers, request.body diff --git a/test/wpt/tests/fetch/api/resources/preflight.py b/test/wpt/tests/fetch/api/resources/preflight.py new file mode 100644 index 0000000..f983ef9 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/preflight.py @@ -0,0 +1,78 @@ +def main(request, response): + headers = [(b"Content-Type", b"text/plain")] + stashed_data = {b'control_request_headers': b"", b'preflight': b"0", b'preflight_referrer': b""} + + token = None + if b"token" in request.GET: + token = request.GET.first(b"token") + + if b"origin" in request.GET: + for origin in request.GET[b'origin'].split(b", "): + headers.append((b"Access-Control-Allow-Origin", origin)) + else: + headers.append((b"Access-Control-Allow-Origin", b"*")) + + if b"clear-stash" in request.GET: + if request.server.stash.take(token) is not None: + return headers, b"1" + else: + return headers, b"0" + + if b"credentials" in request.GET: + headers.append((b"Access-Control-Allow-Credentials", b"true")) + + if request.method == u"OPTIONS": + if not b"Access-Control-Request-Method" in request.headers: + response.set_error(400, u"No Access-Control-Request-Method header") + return b"ERROR: No access-control-request-method in preflight!" + + if request.headers.get(b"Accept", b"") != b"*/*": + response.set_error(400, u"Request does not have 'Accept: */*' header") + return b"ERROR: Invalid access in preflight!" + + if b"control_request_headers" in request.GET: + stashed_data[b'control_request_headers'] = request.headers.get(b"Access-Control-Request-Headers", None) + + if b"max_age" in request.GET: + headers.append((b"Access-Control-Max-Age", request.GET[b'max_age'])) + + if b"allow_headers" in request.GET: + headers.append((b"Access-Control-Allow-Headers", request.GET[b'allow_headers'])) + + if b"allow_methods" in request.GET: + headers.append((b"Access-Control-Allow-Methods", request.GET[b'allow_methods'])) + + preflight_status = 200 + if b"preflight_status" in request.GET: + preflight_status = int(request.GET.first(b"preflight_status")) + + stashed_data[b'preflight'] = b"1" + stashed_data[b'preflight_referrer'] = request.headers.get(b"Referer", b"") + stashed_data[b'preflight_user_agent'] = request.headers.get(b"User-Agent", b"") + if token: + request.server.stash.put(token, stashed_data) + + return preflight_status, headers, b"" + + + if token: + data = request.server.stash.take(token) + if data: + stashed_data = data + + if b"checkUserAgentHeaderInPreflight" in request.GET and request.headers.get(b"User-Agent") != stashed_data[b'preflight_user_agent']: + return 400, headers, b"ERROR: No user-agent header in preflight" + + #use x-* headers for returning value to bodyless responses + headers.append((b"Access-Control-Expose-Headers", b"x-did-preflight, x-control-request-headers, x-referrer, x-preflight-referrer, x-origin")) + headers.append((b"x-did-preflight", stashed_data[b'preflight'])) + if stashed_data[b'control_request_headers'] != None: + headers.append((b"x-control-request-headers", stashed_data[b'control_request_headers'])) + headers.append((b"x-preflight-referrer", stashed_data[b'preflight_referrer'])) + headers.append((b"x-referrer", request.headers.get(b"Referer", b""))) + headers.append((b"x-origin", request.headers.get(b"Origin", b""))) + + if token: + request.server.stash.put(token, stashed_data) + + return headers, b"" diff --git a/test/wpt/tests/fetch/api/resources/redirect-empty-location.py b/test/wpt/tests/fetch/api/resources/redirect-empty-location.py new file mode 100644 index 0000000..1a5f7fe --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/redirect-empty-location.py @@ -0,0 +1,3 @@ +def main(request, response): + headers = [(b"Location", b"")] + return 302, headers, b"" diff --git a/test/wpt/tests/fetch/api/resources/redirect.h2.py b/test/wpt/tests/fetch/api/resources/redirect.h2.py new file mode 100644 index 0000000..6937014 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/redirect.h2.py @@ -0,0 +1,14 @@ +from wptserve.utils import isomorphic_decode, isomorphic_encode + +def handle_headers(frame, request, response): + status = 302 + if b'redirect_status' in request.GET: + status = int(request.GET[b'redirect_status']) + response.status = status + + if b'location' in request.GET: + url = isomorphic_decode(request.GET[b'location']) + response.headers[b'Location'] = isomorphic_encode(url) + + response.headers.update([('Content-Type', 'text/plain')]) + response.write_status_headers() diff --git a/test/wpt/tests/fetch/api/resources/redirect.py b/test/wpt/tests/fetch/api/resources/redirect.py new file mode 100644 index 0000000..d52ab5f --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/redirect.py @@ -0,0 +1,73 @@ +import time + +from urllib.parse import urlencode, urlparse + +from wptserve.utils import isomorphic_decode, isomorphic_encode + +def main(request, response): + stashed_data = {b'count': 0, b'preflight': b"0"} + status = 302 + headers = [(b"Content-Type", b"text/plain"), + (b"Cache-Control", b"no-cache"), + (b"Pragma", b"no-cache")] + if b"Origin" in request.headers: + headers.append((b"Access-Control-Allow-Origin", request.headers.get(b"Origin", b""))) + headers.append((b"Access-Control-Allow-Credentials", b"true")) + else: + headers.append((b"Access-Control-Allow-Origin", b"*")) + + token = None + if b"token" in request.GET: + token = request.GET.first(b"token") + data = request.server.stash.take(token) + if data: + stashed_data = data + + if request.method == u"OPTIONS": + if b"allow_headers" in request.GET: + headers.append((b"Access-Control-Allow-Headers", request.GET[b'allow_headers'])) + stashed_data[b'preflight'] = b"1" + #Preflight is not redirected: return 200 + if not b"redirect_preflight" in request.GET: + if token: + request.server.stash.put(request.GET.first(b"token"), stashed_data) + return 200, headers, u"" + + if b"redirect_status" in request.GET: + status = int(request.GET[b'redirect_status']) + elif b"redirect_status" in request.POST: + status = int(request.POST[b'redirect_status']) + + stashed_data[b'count'] += 1 + + if b"location" in request.GET: + url = isomorphic_decode(request.GET[b'location']) + if b"simple" not in request.GET: + scheme = urlparse(url).scheme + if scheme == u"" or scheme == u"http" or scheme == u"https": + url += u"&" if u'?' in url else u"?" + #keep url parameters in location + url_parameters = {} + for item in request.GET.items(): + url_parameters[isomorphic_decode(item[0])] = isomorphic_decode(item[1][0]) + url += urlencode(url_parameters) + #make sure location changes during redirection loop + url += u"&count=" + str(stashed_data[b'count']) + headers.append((b"Location", isomorphic_encode(url))) + + if b"redirect_referrerpolicy" in request.GET: + headers.append((b"Referrer-Policy", request.GET[b'redirect_referrerpolicy'])) + + if b"delay" in request.GET: + time.sleep(float(request.GET.first(b"delay", 0)) / 1E3) + + if token: + request.server.stash.put(request.GET.first(b"token"), stashed_data) + if b"max_count" in request.GET: + max_count = int(request.GET[b'max_count']) + #stop redirecting and return count + if stashed_data[b'count'] > max_count: + # -1 because the last is not a redirection + return str(stashed_data[b'count'] - 1) + + return status, headers, u"" diff --git a/test/wpt/tests/fetch/api/resources/sandboxed-iframe.html b/test/wpt/tests/fetch/api/resources/sandboxed-iframe.html new file mode 100644 index 0000000..6e5d506 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/sandboxed-iframe.html @@ -0,0 +1,34 @@ + + + + diff --git a/test/wpt/tests/fetch/api/resources/script-with-header.py b/test/wpt/tests/fetch/api/resources/script-with-header.py new file mode 100644 index 0000000..9a9c70e --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/script-with-header.py @@ -0,0 +1,7 @@ +def main(request, response): + headers = [(b"Content-type", request.GET.first(b"mime"))] + if b"content" in request.GET and request.GET.first(b"content") == b"empty": + content = b'' + else: + content = b"console.log('Script loaded')" + return 200, headers, content diff --git a/test/wpt/tests/fetch/api/resources/stash-put.py b/test/wpt/tests/fetch/api/resources/stash-put.py new file mode 100644 index 0000000..0530e1b --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/stash-put.py @@ -0,0 +1,19 @@ +from wptserve.utils import isomorphic_decode + +def main(request, response): + if request.method == u'OPTIONS': + # CORS preflight + response.headers.set(b'Access-Control-Allow-Origin', b'*') + response.headers.set(b'Access-Control-Allow-Methods', b'*') + response.headers.set(b'Access-Control-Allow-Headers', b'*') + return 'done' + + url_dir = u'/'.join(request.url_parts.path.split(u'/')[:-1]) + u'/' + key = request.GET.first(b'key') + value = request.GET.first(b'value') + # value here must be a text string. It will be json.dump()'ed in stash-take.py. + request.server.stash.put(key, isomorphic_decode(value), url_dir) + + if b'disallow_origin' not in request.GET: + response.headers.set(b'Access-Control-Allow-Origin', b'*') + return 'done' diff --git a/test/wpt/tests/fetch/api/resources/stash-take.py b/test/wpt/tests/fetch/api/resources/stash-take.py new file mode 100644 index 0000000..e6db80d --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/stash-take.py @@ -0,0 +1,9 @@ +from wptserve.handlers import json_handler + + +@json_handler +def main(request, response): + dir = u'/'.join(request.url_parts.path.split(u'/')[:-1]) + u'/' + key = request.GET.first(b"key") + response.headers.set(b'Access-Control-Allow-Origin', b'*') + return request.server.stash.take(key, dir) diff --git a/test/wpt/tests/fetch/api/resources/status.py b/test/wpt/tests/fetch/api/resources/status.py new file mode 100644 index 0000000..05a59d5 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/status.py @@ -0,0 +1,11 @@ +from wptserve.utils import isomorphic_encode + +def main(request, response): + code = int(request.GET.first(b"code", 200)) + text = request.GET.first(b"text", b"OMG") + content = request.GET.first(b"content", b"") + type = request.GET.first(b"type", b"") + status = (code, text) + headers = [(b"Content-Type", type), + (b"X-Request-Method", isomorphic_encode(request.method))] + return status, headers, content diff --git a/test/wpt/tests/fetch/api/resources/sw-intercept-abort.js b/test/wpt/tests/fetch/api/resources/sw-intercept-abort.js new file mode 100644 index 0000000..19d4b18 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/sw-intercept-abort.js @@ -0,0 +1,19 @@ +async function messageClient(clientId, message) { + const client = await clients.get(clientId); + client.postMessage(message); +} + +addEventListener('fetch', event => { + let resolve; + const promise = new Promise(r => resolve = r); + + function onAborted() { + messageClient(event.clientId, event.request.signal.reason); + resolve(); + } + + messageClient(event.clientId, 'fetch event has arrived'); + + event.respondWith(promise.then(() => new Response('hello'))); + event.request.signal.addEventListener('abort', onAborted); +}); diff --git a/test/wpt/tests/fetch/api/resources/sw-intercept.js b/test/wpt/tests/fetch/api/resources/sw-intercept.js new file mode 100644 index 0000000..b8166b6 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/sw-intercept.js @@ -0,0 +1,10 @@ +async function broadcast(msg) { + for (const client of await clients.matchAll()) { + client.postMessage(msg); + } +} + +addEventListener('fetch', event => { + event.waitUntil(broadcast(event.request.url)); + event.respondWith(fetch(event.request)); +}); diff --git a/test/wpt/tests/fetch/api/resources/top.txt b/test/wpt/tests/fetch/api/resources/top.txt new file mode 100644 index 0000000..83a3157 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/top.txt @@ -0,0 +1 @@ +top \ No newline at end of file diff --git a/test/wpt/tests/fetch/api/resources/trickle.py b/test/wpt/tests/fetch/api/resources/trickle.py new file mode 100644 index 0000000..99833f1 --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/trickle.py @@ -0,0 +1,15 @@ +import time + +def main(request, response): + delay = float(request.GET.first(b"ms", 500)) / 1E3 + count = int(request.GET.first(b"count", 50)) + # Read request body + request.body + time.sleep(delay) + if not b"notype" in request.GET: + response.headers.set(b"Content-type", b"text/plain") + response.write_status_headers() + time.sleep(delay) + for i in range(count): + response.writer.write_content(b"TEST_TRICKLE\n") + time.sleep(delay) diff --git a/test/wpt/tests/fetch/api/resources/utils.js b/test/wpt/tests/fetch/api/resources/utils.js new file mode 100644 index 0000000..3b20ecc --- /dev/null +++ b/test/wpt/tests/fetch/api/resources/utils.js @@ -0,0 +1,105 @@ +var RESOURCES_DIR = "../resources/"; + +function dirname(path) { + return path.replace(/\/[^\/]*$/, '/') +} + +function checkRequest(request, ExpectedValuesDict) { + for (var attribute in ExpectedValuesDict) { + switch(attribute) { + case "headers": + for (var key in ExpectedValuesDict["headers"].keys()) { + assert_equals(request["headers"].get(key), ExpectedValuesDict["headers"].get(key), + "Check headers attribute has " + key + ":" + ExpectedValuesDict["headers"].get(key)); + } + break; + + case "body": + //for checking body's content, a dedicated asyncronous/promise test should be used + assert_true(request["headers"].has("Content-Type") , "Check request has body using Content-Type header") + break; + + case "method": + case "referrer": + case "referrerPolicy": + case "credentials": + case "cache": + case "redirect": + case "integrity": + case "url": + case "destination": + assert_equals(request[attribute], ExpectedValuesDict[attribute], "Check " + attribute + " attribute") + break; + + default: + break; + } + } +} + +function stringToArray(str) { + var array = new Uint8Array(str.length); + for (var i=0, strLen = str.length; i < strLen; i++) + array[i] = str.charCodeAt(i); + return array; +} + +function encode_utf8(str) +{ + if (self.TextEncoder) + return (new TextEncoder).encode(str); + return stringToArray(unescape(encodeURIComponent(str))); +} + +function validateBufferFromString(buffer, expectedValue, message) +{ + return assert_array_equals(new Uint8Array(buffer !== undefined ? buffer : []), stringToArray(expectedValue), message); +} + +function validateStreamFromString(reader, expectedValue, retrievedArrayBuffer) { + // Passing Uint8Array for byte streams; non-byte streams will simply ignore it + return reader.read(new Uint8Array(64)).then(function(data) { + if (!data.done) { + assert_true(data.value instanceof Uint8Array, "Fetch ReadableStream chunks should be Uint8Array"); + var newBuffer; + if (retrievedArrayBuffer) { + newBuffer = new Uint8Array(data.value.length + retrievedArrayBuffer.length); + newBuffer.set(retrievedArrayBuffer, 0); + newBuffer.set(data.value, retrievedArrayBuffer.length); + } else { + newBuffer = data.value; + } + return validateStreamFromString(reader, expectedValue, newBuffer); + } + validateBufferFromString(retrievedArrayBuffer, expectedValue, "Retrieve and verify stream"); + }); +} + +function validateStreamFromPartialString(reader, expectedValue, retrievedArrayBuffer) { + // Passing Uint8Array for byte streams; non-byte streams will simply ignore it + return reader.read(new Uint8Array(64)).then(function(data) { + if (!data.done) { + assert_true(data.value instanceof Uint8Array, "Fetch ReadableStream chunks should be Uint8Array"); + var newBuffer; + if (retrievedArrayBuffer) { + newBuffer = new Uint8Array(data.value.length + retrievedArrayBuffer.length); + newBuffer.set(retrievedArrayBuffer, 0); + newBuffer.set(data.value, retrievedArrayBuffer.length); + } else { + newBuffer = data.value; + } + return validateStreamFromPartialString(reader, expectedValue, newBuffer); + } + + var string = new TextDecoder("utf-8").decode(retrievedArrayBuffer); + return assert_true(string.search(expectedValue) != -1, "Retrieve and verify stream"); + }); +} + +// From streams tests +function delay(milliseconds) +{ + return new Promise(function(resolve) { + step_timeout(resolve, milliseconds); + }); +} diff --git a/test/wpt/tests/fetch/api/response/json.any.js b/test/wpt/tests/fetch/api/response/json.any.js new file mode 100644 index 0000000..15f050e --- /dev/null +++ b/test/wpt/tests/fetch/api/response/json.any.js @@ -0,0 +1,14 @@ +// See also /xhr/json.any.js + +promise_test(async t => { + const response = await fetch(`data:,\uFEFF{ "b": 1, "a": 2, "b": 3 }`); + const json = await response.json(); + assert_array_equals(Object.keys(json), ["b", "a"]); + assert_equals(json.a, 2); + assert_equals(json.b, 3); +}, "Ensure the correct JSON parser is used"); + +promise_test(async t => { + const response = await fetch("/xhr/resources/utf16-bom.json"); + return promise_rejects_js(t, SyntaxError, response.json()); +}, "Ensure UTF-16 results in an error"); diff --git a/test/wpt/tests/fetch/api/response/many-empty-chunks-crash.html b/test/wpt/tests/fetch/api/response/many-empty-chunks-crash.html new file mode 100644 index 0000000..fe5e7d4 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/many-empty-chunks-crash.html @@ -0,0 +1,14 @@ + + + diff --git a/test/wpt/tests/fetch/api/response/multi-globals/current/current.html b/test/wpt/tests/fetch/api/response/multi-globals/current/current.html new file mode 100644 index 0000000..9bb6e0b --- /dev/null +++ b/test/wpt/tests/fetch/api/response/multi-globals/current/current.html @@ -0,0 +1,3 @@ + +Current page used as a test helper + diff --git a/test/wpt/tests/fetch/api/response/multi-globals/incumbent/incumbent.html b/test/wpt/tests/fetch/api/response/multi-globals/incumbent/incumbent.html new file mode 100644 index 0000000..f63372e --- /dev/null +++ b/test/wpt/tests/fetch/api/response/multi-globals/incumbent/incumbent.html @@ -0,0 +1,16 @@ + +Incumbent page used as a test helper + + + + + diff --git a/test/wpt/tests/fetch/api/response/multi-globals/relevant/relevant.html b/test/wpt/tests/fetch/api/response/multi-globals/relevant/relevant.html new file mode 100644 index 0000000..44f42ed --- /dev/null +++ b/test/wpt/tests/fetch/api/response/multi-globals/relevant/relevant.html @@ -0,0 +1,2 @@ + +Relevant page used as a test helper diff --git a/test/wpt/tests/fetch/api/response/multi-globals/url-parsing.html b/test/wpt/tests/fetch/api/response/multi-globals/url-parsing.html new file mode 100644 index 0000000..5f2f42a --- /dev/null +++ b/test/wpt/tests/fetch/api/response/multi-globals/url-parsing.html @@ -0,0 +1,27 @@ + +Response.redirect URL parsing, with multiple globals in play + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/response/response-body-read-task-handling.html b/test/wpt/tests/fetch/api/response/response-body-read-task-handling.html new file mode 100644 index 0000000..64b0755 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-body-read-task-handling.html @@ -0,0 +1,86 @@ + + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/response/response-cancel-stream.any.js b/test/wpt/tests/fetch/api/response/response-cancel-stream.any.js new file mode 100644 index 0000000..91140d1 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-cancel-stream.any.js @@ -0,0 +1,64 @@ +// META: global=window,worker +// META: title=Response consume blob and http bodies +// META: script=../resources/utils.js + +promise_test(function(test) { + return new Response(new Blob([], { "type" : "text/plain" })).body.cancel(); +}, "Cancelling a starting blob Response stream"); + +promise_test(function(test) { + var response = new Response(new Blob(["This is data"], { "type" : "text/plain" })); + var reader = response.body.getReader(); + reader.read(); + return reader.cancel(); +}, "Cancelling a loading blob Response stream"); + +promise_test(function(test) { + var response = new Response(new Blob(["T"], { "type" : "text/plain" })); + var reader = response.body.getReader(); + + var closedPromise = reader.closed.then(function() { + return reader.cancel(); + }); + reader.read().then(function readMore({done, value}) { + if (!done) return reader.read().then(readMore); + }); + return closedPromise; +}, "Cancelling a closed blob Response stream"); + +promise_test(function(test) { + return fetch(RESOURCES_DIR + "trickle.py?ms=30&count=100").then(function(response) { + return response.body.cancel(); + }); +}, "Cancelling a starting Response stream"); + +promise_test(function() { + return fetch(RESOURCES_DIR + "trickle.py?ms=30&count=100").then(function(response) { + var reader = response.body.getReader(); + return reader.read().then(function() { + return reader.cancel(); + }); + }); +}, "Cancelling a loading Response stream"); + +promise_test(function() { + async function readAll(reader) { + while (true) { + const {value, done} = await reader.read(); + if (done) + return; + } + } + + return fetch(RESOURCES_DIR + "top.txt").then(function(response) { + var reader = response.body.getReader(); + return readAll(reader).then(() => reader.cancel()); + }); +}, "Cancelling a closed Response stream"); + +promise_test(async () => { + const response = await fetch(RESOURCES_DIR + "top.txt"); + const { body } = response; + await body.cancel(); + assert_equals(body, response.body, ".body should not change after cancellation"); +}, "Accessing .body after canceling it"); diff --git a/test/wpt/tests/fetch/api/response/response-clone-iframe.window.js b/test/wpt/tests/fetch/api/response/response-clone-iframe.window.js new file mode 100644 index 0000000..da54616 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-clone-iframe.window.js @@ -0,0 +1,32 @@ +// Verify that calling Response clone() in a detached iframe doesn't crash. +// Regression test for https://crbug.com/1082688. + +'use strict'; + +promise_test(async () => { + // Wait for the document body to be available. + await new Promise(resolve => { + onload = resolve; + }); + + window.iframe = document.createElement('iframe'); + document.body.appendChild(iframe); + iframe.srcdoc = ` + +`; + + await new Promise(resolve => { + onmessage = evt => { + if (evt.data === 'okay') { + resolve(); + } + }; + }); + + // If it got here without crashing, the test passed. +}, 'clone within removed iframe should not crash'); diff --git a/test/wpt/tests/fetch/api/response/response-clone.any.js b/test/wpt/tests/fetch/api/response/response-clone.any.js new file mode 100644 index 0000000..f5cda75 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-clone.any.js @@ -0,0 +1,140 @@ +// META: global=window,worker +// META: title=Response clone +// META: script=../resources/utils.js + +var defaultValues = { "type" : "default", + "url" : "", + "ok" : true, + "status" : 200, + "statusText" : "" +}; + +var response = new Response(); +var clonedResponse = response.clone(); +test(function() { + for (var attributeName in defaultValues) { + var expectedValue = defaultValues[attributeName]; + assert_equals(clonedResponse[attributeName], expectedValue, + "Expect default response." + attributeName + " is " + expectedValue); + } +}, "Check Response's clone with default values, without body"); + +var body = "This is response body"; +var headersInit = { "name" : "value" }; +var responseInit = { "status" : 200, + "statusText" : "GOOD", + "headers" : headersInit +}; +var response = new Response(body, responseInit); +var clonedResponse = response.clone(); +test(function() { + assert_equals(clonedResponse.status, responseInit["status"], + "Expect response.status is " + responseInit["status"]); + assert_equals(clonedResponse.statusText, responseInit["statusText"], + "Expect response.statusText is " + responseInit["statusText"]); + assert_equals(clonedResponse.headers.get("name"), "value", + "Expect response.headers has name:value header"); +}, "Check Response's clone has the expected attribute values"); + +promise_test(function(test) { + return validateStreamFromString(response.body.getReader(), body); +}, "Check orginal response's body after cloning"); + +promise_test(function(test) { + return validateStreamFromString(clonedResponse.body.getReader(), body); +}, "Check cloned response's body"); + +promise_test(function(test) { + var disturbedResponse = new Response("data"); + return disturbedResponse.text().then(function() { + assert_true(disturbedResponse.bodyUsed, "response is disturbed"); + assert_throws_js(TypeError, function() { disturbedResponse.clone(); }, + "Expect TypeError exception"); + }); +}, "Cannot clone a disturbed response"); + +promise_test(function(t) { + var clone; + var result; + var response; + return fetch('../resources/trickle.py?count=2&delay=100').then(function(res) { + clone = res.clone(); + response = res; + return clone.text(); + }).then(function(r) { + assert_equals(r.length, 26); + result = r; + return response.text(); + }).then(function(r) { + assert_equals(r, result, "cloned responses should provide the same data"); + }); + }, 'Cloned responses should provide the same data'); + +promise_test(function(t) { + var clone; + return fetch('../resources/trickle.py?count=2&delay=100').then(function(res) { + clone = res.clone(); + res.body.cancel(); + assert_true(res.bodyUsed); + assert_false(clone.bodyUsed); + return clone.arrayBuffer(); + }).then(function(r) { + assert_equals(r.byteLength, 26); + assert_true(clone.bodyUsed); + }); +}, 'Cancelling stream should not affect cloned one'); + +function testReadableStreamClone(initialBuffer, bufferType) +{ + promise_test(function(test) { + var response = new Response(new ReadableStream({start : function(controller) { + controller.enqueue(initialBuffer); + controller.close(); + }})); + + var clone = response.clone(); + var stream1 = response.body; + var stream2 = clone.body; + + var buffer; + return stream1.getReader().read().then(function(data) { + assert_false(data.done); + assert_equals(data.value, initialBuffer, "Buffer of being-cloned response stream is the same as the original buffer"); + return stream2.getReader().read(); + }).then(function(data) { + assert_false(data.done); + if (initialBuffer instanceof ArrayBuffer) { + assert_true(data.value instanceof ArrayBuffer, "Cloned buffer is ArrayBufer"); + assert_equals(initialBuffer.byteLength, data.value.byteLength, "Length equal"); + assert_array_equals(new Uint8Array(data.value), new Uint8Array(initialBuffer), "Cloned buffer chunks have the same content"); + } else if (initialBuffer instanceof DataView) { + assert_true(data.value instanceof DataView, "Cloned buffer is DataView"); + assert_equals(initialBuffer.byteLength, data.value.byteLength, "Lengths equal"); + assert_equals(initialBuffer.byteOffset, data.value.byteOffset, "Offsets equal"); + for (let i = 0; i < initialBuffer.byteLength; ++i) { + assert_equals( + data.value.getUint8(i), initialBuffer.getUint8(i), "Mismatch at byte ${i}"); + } + } else { + assert_array_equals(data.value, initialBuffer, "Cloned buffer chunks have the same content"); + } + assert_equals(Object.getPrototypeOf(data.value), Object.getPrototypeOf(initialBuffer), "Cloned buffers have the same type"); + assert_not_equals(data.value, initialBuffer, "Buffer of cloned response stream is a clone of the original buffer"); + }); + }, "Check response clone use structureClone for teed ReadableStreams (" + bufferType + "chunk)"); +} + +var arrayBuffer = new ArrayBuffer(16); +testReadableStreamClone(new Int8Array(arrayBuffer, 1), "Int8Array"); +testReadableStreamClone(new Int16Array(arrayBuffer, 2, 2), "Int16Array"); +testReadableStreamClone(new Int32Array(arrayBuffer), "Int32Array"); +testReadableStreamClone(arrayBuffer, "ArrayBuffer"); +testReadableStreamClone(new Uint8Array(arrayBuffer), "Uint8Array"); +testReadableStreamClone(new Uint8ClampedArray(arrayBuffer), "Uint8ClampedArray"); +testReadableStreamClone(new Uint16Array(arrayBuffer, 2), "Uint16Array"); +testReadableStreamClone(new Uint32Array(arrayBuffer), "Uint32Array"); +testReadableStreamClone(typeof BigInt64Array === "function" ? new BigInt64Array(arrayBuffer) : undefined, "BigInt64Array"); +testReadableStreamClone(typeof BigUint64Array === "function" ? new BigUint64Array(arrayBuffer) : undefined, "BigUint64Array"); +testReadableStreamClone(new Float32Array(arrayBuffer), "Float32Array"); +testReadableStreamClone(new Float64Array(arrayBuffer), "Float64Array"); +testReadableStreamClone(new DataView(arrayBuffer, 2, 8), "DataView"); diff --git a/test/wpt/tests/fetch/api/response/response-consume-empty.any.js b/test/wpt/tests/fetch/api/response/response-consume-empty.any.js new file mode 100644 index 0000000..0fa85ec --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-consume-empty.any.js @@ -0,0 +1,99 @@ +// META: global=window,worker +// META: title=Response consume empty bodies + +function checkBodyText(test, response) { + return response.text().then(function(bodyAsText) { + assert_equals(bodyAsText, "", "Resolved value should be empty"); + assert_false(response.bodyUsed); + }); +} + +function checkBodyBlob(test, response) { + return response.blob().then(function(bodyAsBlob) { + var promise = new Promise(function(resolve, reject) { + var reader = new FileReader(); + reader.onload = function(evt) { + resolve(reader.result) + }; + reader.onerror = function() { + reject("Blob's reader failed"); + }; + reader.readAsText(bodyAsBlob); + }); + return promise.then(function(body) { + assert_equals(body, "", "Resolved value should be empty"); + assert_false(response.bodyUsed); + }); + }); +} + +function checkBodyArrayBuffer(test, response) { + return response.arrayBuffer().then(function(bodyAsArrayBuffer) { + assert_equals(bodyAsArrayBuffer.byteLength, 0, "Resolved value should be empty"); + assert_false(response.bodyUsed); + }); +} + +function checkBodyJSON(test, response) { + return response.json().then( + function(bodyAsJSON) { + assert_unreached("JSON parsing should fail"); + }, + function() { + assert_false(response.bodyUsed); + }); +} + +function checkBodyFormData(test, response) { + return response.formData().then(function(bodyAsFormData) { + assert_true(bodyAsFormData instanceof FormData, "Should receive a FormData"); + assert_false(response.bodyUsed); + }); +} + +function checkBodyFormDataError(test, response) { + return promise_rejects_js(test, TypeError, response.formData()).then(function() { + assert_false(response.bodyUsed); + }); +} + +function checkResponseWithNoBody(bodyType, checkFunction, headers = []) { + promise_test(function(test) { + var response = new Response(undefined, { "headers": headers }); + assert_false(response.bodyUsed); + return checkFunction(test, response); + }, "Consume response's body as " + bodyType); +} + +checkResponseWithNoBody("text", checkBodyText); +checkResponseWithNoBody("blob", checkBodyBlob); +checkResponseWithNoBody("arrayBuffer", checkBodyArrayBuffer); +checkResponseWithNoBody("json (error case)", checkBodyJSON); +checkResponseWithNoBody("formData with correct multipart type (error case)", checkBodyFormDataError, [["Content-Type", 'multipart/form-data; boundary="boundary"']]); +checkResponseWithNoBody("formData with correct urlencoded type", checkBodyFormData, [["Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"]]); +checkResponseWithNoBody("formData without correct type (error case)", checkBodyFormDataError); + +function checkResponseWithEmptyBody(bodyType, body, asText) { + promise_test(function(test) { + var response = new Response(body); + assert_false(response.bodyUsed, "bodyUsed is false at init"); + if (asText) { + return response.text().then(function(bodyAsString) { + assert_equals(bodyAsString.length, 0, "Resolved value should be empty"); + assert_true(response.bodyUsed, "bodyUsed is true after being consumed"); + }); + } + return response.arrayBuffer().then(function(bodyAsArrayBuffer) { + assert_equals(bodyAsArrayBuffer.byteLength, 0, "Resolved value should be empty"); + assert_true(response.bodyUsed, "bodyUsed is true after being consumed"); + }); + }, "Consume empty " + bodyType + " response body as " + (asText ? "text" : "arrayBuffer")); +} + +checkResponseWithEmptyBody("blob", new Blob([], { "type" : "text/plain" }), false); +checkResponseWithEmptyBody("text", "", false); +checkResponseWithEmptyBody("blob", new Blob([], { "type" : "text/plain" }), true); +checkResponseWithEmptyBody("text", "", true); +checkResponseWithEmptyBody("URLSearchParams", new URLSearchParams(""), true); +checkResponseWithEmptyBody("FormData", new FormData(), true); +checkResponseWithEmptyBody("ArrayBuffer", new ArrayBuffer(), true); diff --git a/test/wpt/tests/fetch/api/response/response-consume-stream.any.js b/test/wpt/tests/fetch/api/response/response-consume-stream.any.js new file mode 100644 index 0000000..befce62 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-consume-stream.any.js @@ -0,0 +1,61 @@ +// META: global=window,worker +// META: title=Response consume +// META: script=../resources/utils.js + +promise_test(function(test) { + var body = ""; + var response = new Response(""); + return validateStreamFromString(response.body.getReader(), ""); +}, "Read empty text response's body as readableStream"); + +promise_test(function(test) { + var response = new Response(new Blob([], { "type" : "text/plain" })); + return validateStreamFromString(response.body.getReader(), ""); +}, "Read empty blob response's body as readableStream"); + +var formData = new FormData(); +formData.append("name", "value"); +var textData = JSON.stringify("This is response's body"); +var blob = new Blob([textData], { "type" : "text/plain" }); +var urlSearchParamsData = "name=value"; +var urlSearchParams = new URLSearchParams(urlSearchParamsData); + +for (const mode of [undefined, "byob"]) { + promise_test(function(test) { + var response = new Response(blob); + return validateStreamFromString(response.body.getReader({ mode }), textData); + }, `Read blob response's body as readableStream with mode=${mode}`); + + promise_test(function(test) { + var response = new Response(textData); + return validateStreamFromString(response.body.getReader({ mode }), textData); + }, `Read text response's body as readableStream with mode=${mode}`); + + promise_test(function(test) { + var response = new Response(urlSearchParams); + return validateStreamFromString(response.body.getReader({ mode }), urlSearchParamsData); + }, `Read URLSearchParams response's body as readableStream with mode=${mode}`); + + promise_test(function(test) { + var arrayBuffer = new ArrayBuffer(textData.length); + var int8Array = new Int8Array(arrayBuffer); + for (var cptr = 0; cptr < textData.length; cptr++) + int8Array[cptr] = textData.charCodeAt(cptr); + + return validateStreamFromString(new Response(arrayBuffer).body.getReader({ mode }), textData); + }, `Read array buffer response's body as readableStream with mode=${mode}`); + + promise_test(function(test) { + var response = new Response(formData); + return validateStreamFromPartialString(response.body.getReader({ mode }), + "Content-Disposition: form-data; name=\"name\"\r\n\r\nvalue"); + }, `Read form data response's body as readableStream with mode=${mode}`); +} + +test(function() { + assert_equals(Response.error().body, null); +}, "Getting an error Response stream"); + +test(function() { + assert_equals(Response.redirect("/").body, null); +}, "Getting a redirect Response stream"); diff --git a/test/wpt/tests/fetch/api/response/response-consume.html b/test/wpt/tests/fetch/api/response/response-consume.html new file mode 100644 index 0000000..89fc49f --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-consume.html @@ -0,0 +1,317 @@ + + + + + Response consume + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/api/response/response-error-from-stream.any.js b/test/wpt/tests/fetch/api/response/response-error-from-stream.any.js new file mode 100644 index 0000000..118eb7d --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-error-from-stream.any.js @@ -0,0 +1,59 @@ +// META: global=window,worker +// META: title=Response Receives Propagated Error from ReadableStream + +function newStreamWithStartError() { + var err = new Error("Start error"); + return [new ReadableStream({ + start(controller) { + controller.error(err); + } + }), + err] +} + +function newStreamWithPullError() { + var err = new Error("Pull error"); + return [new ReadableStream({ + pull(controller) { + controller.error(err); + } + }), + err] +} + +function runRequestPromiseTest([stream, err], responseReaderMethod, testDescription) { + promise_test(test => { + return promise_rejects_exactly( + test, + err, + new Response(stream)[responseReaderMethod](), + 'CustomTestError should propagate' + ) + }, testDescription) +} + + +promise_test(test => { + var [stream, err] = newStreamWithStartError(); + return promise_rejects_exactly(test, err, stream.getReader().read(), 'CustomTestError should propagate') +}, "ReadableStreamDefaultReader Promise receives ReadableStream start() Error") + +promise_test(test => { + var [stream, err] = newStreamWithPullError(); + return promise_rejects_exactly(test, err, stream.getReader().read(), 'CustomTestError should propagate') +}, "ReadableStreamDefaultReader Promise receives ReadableStream pull() Error") + + +// test start() errors for all Body reader methods +runRequestPromiseTest(newStreamWithStartError(), 'arrayBuffer', 'ReadableStream start() Error propagates to Response.arrayBuffer() Promise'); +runRequestPromiseTest(newStreamWithStartError(), 'blob', 'ReadableStream start() Error propagates to Response.blob() Promise'); +runRequestPromiseTest(newStreamWithStartError(), 'formData', 'ReadableStream start() Error propagates to Response.formData() Promise'); +runRequestPromiseTest(newStreamWithStartError(), 'json', 'ReadableStream start() Error propagates to Response.json() Promise'); +runRequestPromiseTest(newStreamWithStartError(), 'text', 'ReadableStream start() Error propagates to Response.text() Promise'); + +// test pull() errors for all Body reader methods +runRequestPromiseTest(newStreamWithPullError(), 'arrayBuffer', 'ReadableStream pull() Error propagates to Response.arrayBuffer() Promise'); +runRequestPromiseTest(newStreamWithPullError(), 'blob', 'ReadableStream pull() Error propagates to Response.blob() Promise'); +runRequestPromiseTest(newStreamWithPullError(), 'formData', 'ReadableStream pull() Error propagates to Response.formData() Promise'); +runRequestPromiseTest(newStreamWithPullError(), 'json', 'ReadableStream pull() Error propagates to Response.json() Promise'); +runRequestPromiseTest(newStreamWithPullError(), 'text', 'ReadableStream pull() Error propagates to Response.text() Promise'); diff --git a/test/wpt/tests/fetch/api/response/response-error.any.js b/test/wpt/tests/fetch/api/response/response-error.any.js new file mode 100644 index 0000000..a76bc43 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-error.any.js @@ -0,0 +1,27 @@ +// META: global=window,worker +// META: title=Response error + +var invalidStatus = [0, 100, 199, 600, 1000]; +invalidStatus.forEach(function(status) { + test(function() { + assert_throws_js(RangeError, function() { new Response("", { "status" : status }); }, + "Expect RangeError exception when status is " + status); + },"Throws RangeError when responseInit's status is " + status); +}); + +var invalidStatusText = ["\n", "Ä€"]; +invalidStatusText.forEach(function(statusText) { + test(function() { + assert_throws_js(TypeError, function() { new Response("", { "statusText" : statusText }); }, + "Expect TypeError exception " + statusText); + },"Throws TypeError when responseInit's statusText is " + statusText); +}); + +var nullBodyStatus = [204, 205, 304]; +nullBodyStatus.forEach(function(status) { + test(function() { + assert_throws_js(TypeError, + function() { new Response("body", {"status" : status }); }, + "Expect TypeError exception "); + },"Throws TypeError when building a response with body and a body status of " + status); +}); diff --git a/test/wpt/tests/fetch/api/response/response-from-stream.any.js b/test/wpt/tests/fetch/api/response/response-from-stream.any.js new file mode 100644 index 0000000..ea5192b --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-from-stream.any.js @@ -0,0 +1,23 @@ +// META: global=window,worker + +"use strict"; + +test(() => { + const stream = new ReadableStream(); + stream.getReader(); + assert_throws_js(TypeError, () => new Response(stream)); +}, "Constructing a Response with a stream on which getReader() is called"); + +test(() => { + const stream = new ReadableStream(); + stream.getReader().read(); + assert_throws_js(TypeError, () => new Response(stream)); +}, "Constructing a Response with a stream on which read() is called"); + +promise_test(async () => { + const stream = new ReadableStream({ pull: c => c.enqueue(new Uint8Array()) }), + reader = stream.getReader(); + await reader.read(); + reader.releaseLock(); + assert_throws_js(TypeError, () => new Response(stream)); +}, "Constructing a Response with a stream on which read() and releaseLock() are called"); diff --git a/test/wpt/tests/fetch/api/response/response-init-001.any.js b/test/wpt/tests/fetch/api/response/response-init-001.any.js new file mode 100644 index 0000000..559e49a --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-init-001.any.js @@ -0,0 +1,64 @@ +// META: global=window,worker +// META: title=Response init: simple cases + +var defaultValues = { "type" : "default", + "url" : "", + "ok" : true, + "status" : 200, + "statusText" : "", + "body" : null +}; + +var statusCodes = { "givenValues" : [200, 300, 400, 500, 599], + "expectedValues" : [200, 300, 400, 500, 599] +}; +var statusTexts = { "givenValues" : ["", "OK", "with space", String.fromCharCode(0x80)], + "expectedValues" : ["", "OK", "with space", String.fromCharCode(0x80)] +}; +var initValuesDict = { "status" : statusCodes, + "statusText" : statusTexts +}; + +function isOkStatus(status) { + return 200 <= status && 299 >= status; +} + +var response = new Response(); +for (var attributeName in defaultValues) { + test(function() { + var expectedValue = defaultValues[attributeName]; + assert_equals(response[attributeName], expectedValue, + "Expect default response." + attributeName + " is " + expectedValue); + }, "Check default value for " + attributeName + " attribute"); +} + +for (var attributeName in initValuesDict) { + test(function() { + var valuesToTest = initValuesDict[attributeName]; + for (var valueIdx in valuesToTest["givenValues"]) { + var givenValue = valuesToTest["givenValues"][valueIdx]; + var expectedValue = valuesToTest["expectedValues"][valueIdx]; + var responseInit = {}; + responseInit[attributeName] = givenValue; + var response = new Response("", responseInit); + assert_equals(response[attributeName], expectedValue, + "Expect response." + attributeName + " is " + expectedValue + + " when initialized with " + givenValue); + assert_equals(response.ok, isOkStatus(response.status), + "Expect response.ok is " + isOkStatus(response.status)); + } + }, "Check " + attributeName + " init values and associated getter"); +} + +test(function() { + const response1 = new Response(""); + assert_equals(response1.headers, response1.headers); + + const response2 = new Response("", {"headers": {"X-Foo": "bar"}}); + assert_equals(response2.headers, response2.headers); + const headers = response2.headers; + response2.headers.set("X-Foo", "quux"); + assert_equals(headers, response2.headers); + headers.set("X-Other-Header", "baz"); + assert_equals(headers, response2.headers); +}, "Test that Response.headers has the [SameObject] extended attribute"); diff --git a/test/wpt/tests/fetch/api/response/response-init-002.any.js b/test/wpt/tests/fetch/api/response/response-init-002.any.js new file mode 100644 index 0000000..6c0a46e --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-init-002.any.js @@ -0,0 +1,61 @@ +// META: global=window,worker +// META: title=Response init: body and headers +// META: script=../resources/utils.js + +test(function() { + var headerDict = {"name1": "value1", + "name2": "value2", + "name3": "value3" + }; + var headers = new Headers(headerDict); + var response = new Response("", { "headers" : headers }) + for (var name in headerDict) { + assert_equals(response.headers.get(name), headerDict[name], + "response's headers has " + name + " : " + headerDict[name]); + } +}, "Initialize Response with headers values"); + +function checkResponseInit(body, bodyType, expectedTextBody) { + promise_test(function(test) { + var response = new Response(body); + var resHeaders = response.headers; + var mime = resHeaders.get("Content-Type"); + assert_true(mime && mime.search(bodyType) > -1, "Content-Type header should be \"" + bodyType + "\" "); + return response.text().then(function(bodyAsText) { + //not equals: cannot guess formData exact value + assert_true(bodyAsText.search(expectedTextBody) > -1, "Retrieve and verify response body"); + }); + }, "Initialize Response's body with " + bodyType); +} + +var blob = new Blob(["This is a blob"], {type: "application/octet-binary"}); +var formaData = new FormData(); +formaData.append("name", "value"); +var urlSearchParams = "URLSearchParams are not supported"; +//avoid test timeout if not implemented +if (self.URLSearchParams) + urlSearchParams = new URLSearchParams("name=value"); +var usvString = "This is a USVString" + +checkResponseInit(blob, "application/octet-binary", "This is a blob"); +checkResponseInit(formaData, "multipart/form-data", "name=\"name\"\r\n\r\nvalue"); +checkResponseInit(urlSearchParams, "application/x-www-form-urlencoded;charset=UTF-8", "name=value"); +checkResponseInit(usvString, "text/plain;charset=UTF-8", "This is a USVString"); + +promise_test(function(test) { + var body = "This is response body"; + var response = new Response(body); + return validateStreamFromString(response.body.getReader(), body); +}, "Read Response's body as readableStream"); + +promise_test(function(test) { + var response = new Response("This is my fork", {"headers" : [["Content-Type", ""]]}); + return response.blob().then(function(blob) { + assert_equals(blob.type, "", "Blob type should be the empty string"); + }); +}, "Testing empty Response Content-Type header"); + +test(function() { + var response = new Response(null, {status: 204}); + assert_equals(response.body, null); +}, "Testing null Response body"); diff --git a/test/wpt/tests/fetch/api/response/response-init-contenttype.any.js b/test/wpt/tests/fetch/api/response/response-init-contenttype.any.js new file mode 100644 index 0000000..3a7744c --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-init-contenttype.any.js @@ -0,0 +1,125 @@ +test(() => { + const response = new Response(); + assert_equals(response.headers.get("Content-Type"), null); +}, "Default Content-Type for Response with empty body"); + +test(() => { + const blob = new Blob([]); + const response = new Response(blob); + assert_equals(response.headers.get("Content-Type"), null); +}, "Default Content-Type for Response with Blob body (no type set)"); + +test(() => { + const blob = new Blob([], { type: "" }); + const response = new Response(blob); + assert_equals(response.headers.get("Content-Type"), null); +}, "Default Content-Type for Response with Blob body (empty type)"); + +test(() => { + const blob = new Blob([], { type: "a/b; c=d" }); + const response = new Response(blob); + assert_equals(response.headers.get("Content-Type"), "a/b; c=d"); +}, "Default Content-Type for Response with Blob body (set type)"); + +test(() => { + const buffer = new Uint8Array(); + const response = new Response(buffer); + assert_equals(response.headers.get("Content-Type"), null); +}, "Default Content-Type for Response with buffer source body"); + +promise_test(async () => { + const formData = new FormData(); + formData.append("a", "b"); + const response = new Response(formData); + const boundary = (await response.text()).split("\r\n")[0].slice(2); + assert_equals( + response.headers.get("Content-Type"), + `multipart/form-data; boundary=${boundary}`, + ); +}, "Default Content-Type for Response with FormData body"); + +test(() => { + const usp = new URLSearchParams(); + const response = new Response(usp); + assert_equals( + response.headers.get("Content-Type"), + "application/x-www-form-urlencoded;charset=UTF-8", + ); +}, "Default Content-Type for Response with URLSearchParams body"); + +test(() => { + const response = new Response(""); + assert_equals( + response.headers.get("Content-Type"), + "text/plain;charset=UTF-8", + ); +}, "Default Content-Type for Response with string body"); + +test(() => { + const stream = new ReadableStream(); + const response = new Response(stream); + assert_equals(response.headers.get("Content-Type"), null); +}, "Default Content-Type for Response with ReadableStream body"); + +// ----------------------------------------------------------------------------- + +const OVERRIDE_MIME = "test/only; mime=type"; + +function responseWithOverrideMime(body) { + return new Response( + body, + { headers: { "Content-Type": OVERRIDE_MIME } }, + ); +} + +test(() => { + const response = responseWithOverrideMime(undefined); + assert_equals(response.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Response with empty body"); + +test(() => { + const blob = new Blob([]); + const response = responseWithOverrideMime(blob); + assert_equals(response.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Response with Blob body (no type set)"); + +test(() => { + const blob = new Blob([], { type: "" }); + const response = responseWithOverrideMime(blob); + assert_equals(response.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Response with Blob body (empty type)"); + +test(() => { + const blob = new Blob([], { type: "a/b; c=d" }); + const response = responseWithOverrideMime(blob); + assert_equals(response.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Response with Blob body (set type)"); + +test(() => { + const buffer = new Uint8Array(); + const response = responseWithOverrideMime(buffer); + assert_equals(response.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Response with buffer source body"); + +test(() => { + const formData = new FormData(); + const response = responseWithOverrideMime(formData); + assert_equals(response.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Response with FormData body"); + +test(() => { + const usp = new URLSearchParams(); + const response = responseWithOverrideMime(usp); + assert_equals(response.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Response with URLSearchParams body"); + +test(() => { + const response = responseWithOverrideMime(""); + assert_equals(response.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Response with string body"); + +test(() => { + const stream = new ReadableStream(); + const response = responseWithOverrideMime(stream); + assert_equals(response.headers.get("Content-Type"), OVERRIDE_MIME); +}, "Can override Content-Type for Response with ReadableStream body"); diff --git a/test/wpt/tests/fetch/api/response/response-static-error.any.js b/test/wpt/tests/fetch/api/response/response-static-error.any.js new file mode 100644 index 0000000..1f8c49a --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-static-error.any.js @@ -0,0 +1,34 @@ +// META: global=window,worker +// META: title=Response: error static method + +test(function() { + var responseError = Response.error(); + assert_equals(responseError.type, "error", "Network error response's type is error"); + assert_equals(responseError.status, 0, "Network error response's status is 0"); + assert_equals(responseError.statusText, "", "Network error response's statusText is empty"); + assert_equals(responseError.body, null, "Network error response's body is null"); + + assert_true(responseError.headers.entries().next().done, "Headers should be empty"); +}, "Check response returned by static method error()"); + +promise_test (async function() { + let response = await fetch("../resources/data.json"); + + try { + response.headers.append('name', 'value'); + } catch (e) { + assert_equals(e.constructor.name, "TypeError"); + } + + assert_not_equals(response.headers.get("name"), "value", "response headers should be immutable"); +}, "Ensure response headers are immutable"); + +test(function() { + const headers = Response.error().headers; + + // Avoid false positives if expected API is not available + assert_true(!!headers); + assert_equals(typeof headers.append, 'function'); + + assert_throws_js(TypeError, function () { headers.append('name', 'value'); }); +}, "the 'guard' of the Headers instance should be immutable"); diff --git a/test/wpt/tests/fetch/api/response/response-static-json.any.js b/test/wpt/tests/fetch/api/response/response-static-json.any.js new file mode 100644 index 0000000..5ec79e6 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-static-json.any.js @@ -0,0 +1,96 @@ +// META: global=window,worker +// META: title=Response: json static method + +const APPLICATION_JSON = "application/json"; +const FOO_BAR = "foo/bar"; + +const INIT_TESTS = [ + [undefined, 200, "", APPLICATION_JSON, {}], + [{ status: 400 }, 400, "", APPLICATION_JSON, {}], + [{ statusText: "foo" }, 200, "foo", APPLICATION_JSON, {}], + [{ headers: {} }, 200, "", APPLICATION_JSON, {}], + [{ headers: { "content-type": FOO_BAR } }, 200, "", FOO_BAR, {}], + [{ headers: { "x-foo": "bar" } }, 200, "", APPLICATION_JSON, { "x-foo": "bar" }], +]; + +for (const [init, expectedStatus, expectedStatusText, expectedContentType, expectedHeaders] of INIT_TESTS) { + promise_test(async function () { + const response = Response.json("hello world", init); + assert_equals(response.type, "default", "Response's type is default"); + assert_equals(response.status, expectedStatus, "Response's status is " + expectedStatus); + assert_equals(response.statusText, expectedStatusText, "Response's statusText is " + JSON.stringify(expectedStatusText)); + assert_equals(response.headers.get("content-type"), expectedContentType, "Response's content-type is " + expectedContentType); + for (const key in expectedHeaders) { + assert_equals(response.headers.get(key), expectedHeaders[key], "Response's header " + key + " is " + JSON.stringify(expectedHeaders[key])); + } + + const data = await response.json(); + assert_equals(data, "hello world", "Response's body is 'hello world'"); + }, `Check response returned by static json() with init ${JSON.stringify(init)}`); +} + +const nullBodyStatus = [204, 205, 304]; +for (const status of nullBodyStatus) { + test(function () { + assert_throws_js( + TypeError, + function () { + Response.json("hello world", { status: status }); + }, + ); + }, `Throws TypeError when calling static json() with a status of ${status}`); +} + +promise_test(async function () { + const response = Response.json({ foo: "bar" }); + const data = await response.json(); + assert_equals(typeof data, "object", "Response's json body is an object"); + assert_equals(data.foo, "bar", "Response's json body is { foo: 'bar' }"); +}, "Check static json() encodes JSON objects correctly"); + +test(function () { + assert_throws_js( + TypeError, + function () { + Response.json(Symbol("foo")); + }, + ); +}, "Check static json() throws when data is not encodable"); + +test(function () { + const a = { b: 1 }; + a.a = a; + assert_throws_js( + TypeError, + function () { + Response.json(a); + }, + ); +}, "Check static json() throws when data is circular"); + +promise_test(async function () { + class CustomError extends Error { + name = "CustomError"; + } + assert_throws_js( + CustomError, + function () { + Response.json({ get foo() { throw new CustomError("bar") }}); + } + ) +}, "Check static json() propagates JSON serializer errors"); + +const encodingChecks = [ + ["ðŒ†", [34, 240, 157, 140, 134, 34]], + ["\uDF06\uD834", [34, 92, 117, 100, 102, 48, 54, 92, 117, 100, 56, 51, 52, 34]], + ["\uDEAD", [34, 92, 117, 100, 101, 97, 100, 34]], +]; + +for (const [input, expected] of encodingChecks) { + promise_test(async function () { + const response = Response.json(input); + const buffer = await response.arrayBuffer(); + const data = new Uint8Array(buffer); + assert_array_equals(data, expected); + }, `Check response returned by static json() with input ${input}`); +} diff --git a/test/wpt/tests/fetch/api/response/response-static-redirect.any.js b/test/wpt/tests/fetch/api/response/response-static-redirect.any.js new file mode 100644 index 0000000..b16c56d --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-static-redirect.any.js @@ -0,0 +1,40 @@ +// META: global=window,worker +// META: title=Response: redirect static method + +var url = "http://test.url:1234/"; +test(function() { + const redirectResponse = Response.redirect(url); + assert_equals(redirectResponse.type, "default"); + assert_false(redirectResponse.redirected); + assert_false(redirectResponse.ok); + assert_equals(redirectResponse.status, 302, "Default redirect status is 302"); + assert_equals(redirectResponse.headers.get("Location"), url, + "redirected response has Location header with the correct url"); + assert_equals(redirectResponse.statusText, ""); +}, "Check default redirect response"); + +[301, 302, 303, 307, 308].forEach(function(status) { + test(function() { + const redirectResponse = Response.redirect(url, status); + assert_equals(redirectResponse.type, "default"); + assert_false(redirectResponse.redirected); + assert_false(redirectResponse.ok); + assert_equals(redirectResponse.status, status, "Redirect status is " + status); + assert_equals(redirectResponse.headers.get("Location"), url); + assert_equals(redirectResponse.statusText, ""); + }, "Check response returned by static method redirect(), status = " + status); +}); + +test(function() { + var invalidUrl = "http://:This is not an url"; + assert_throws_js(TypeError, function() { Response.redirect(invalidUrl); }, + "Expect TypeError exception"); +}, "Check error returned when giving invalid url to redirect()"); + +var invalidRedirectStatus = [200, 309, 400, 500]; +invalidRedirectStatus.forEach(function(invalidStatus) { + test(function() { + assert_throws_js(RangeError, function() { Response.redirect(url, invalidStatus); }, + "Expect RangeError exception"); + }, "Check error returned when giving invalid status to redirect(), status = " + invalidStatus); +}); diff --git a/test/wpt/tests/fetch/api/response/response-stream-bad-chunk.any.js b/test/wpt/tests/fetch/api/response/response-stream-bad-chunk.any.js new file mode 100644 index 0000000..d3d92e1 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-stream-bad-chunk.any.js @@ -0,0 +1,24 @@ +// META: global=window,worker +// META: title=Response causes TypeError from bad chunk type + +function runChunkTest(responseReaderMethod, testDescription) { + promise_test(test => { + let stream = new ReadableStream({ + start(controller) { + controller.enqueue("not Uint8Array"); + controller.close(); + } + }); + + return promise_rejects_js(test, TypeError, + new Response(stream)[responseReaderMethod](), + 'TypeError should propagate' + ) + }, testDescription) +} + +runChunkTest('arrayBuffer', 'ReadableStream with non-Uint8Array chunk passed to Response.arrayBuffer() causes TypeError'); +runChunkTest('blob', 'ReadableStream with non-Uint8Array chunk passed to Response.blob() causes TypeError'); +runChunkTest('formData', 'ReadableStream with non-Uint8Array chunk passed to Response.formData() causes TypeError'); +runChunkTest('json', 'ReadableStream with non-Uint8Array chunk passed to Response.json() causes TypeError'); +runChunkTest('text', 'ReadableStream with non-Uint8Array chunk passed to Response.text() causes TypeError'); diff --git a/test/wpt/tests/fetch/api/response/response-stream-disturbed-1.any.js b/test/wpt/tests/fetch/api/response/response-stream-disturbed-1.any.js new file mode 100644 index 0000000..64f65f1 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-stream-disturbed-1.any.js @@ -0,0 +1,44 @@ +// META: global=window,worker +// META: title=Consuming Response body after getting a ReadableStream +// META: script=./response-stream-disturbed-util.js + +async function createResponseWithReadableStream(bodySource, callback) { + const response = await responseFromBodySource(bodySource); + const reader = response.body.getReader(); + reader.releaseLock(); + return callback(response); +} + +for (const bodySource of ["fetch", "stream", "string"]) { + promise_test(function() { + return createResponseWithReadableStream(bodySource, function(response) { + return response.blob().then(function(blob) { + assert_true(blob instanceof Blob); + }); + }); + }, `Getting blob after getting the Response body - not disturbed, not locked (body source: ${bodySource})`); + + promise_test(function() { + return createResponseWithReadableStream(bodySource, function(response) { + return response.text().then(function(text) { + assert_true(text.length > 0); + }); + }); + }, `Getting text after getting the Response body - not disturbed, not locked (body source: ${bodySource})`); + + promise_test(function() { + return createResponseWithReadableStream(bodySource, function(response) { + return response.json().then(function(json) { + assert_equals(typeof json, "object"); + }); + }); + }, `Getting json after getting the Response body - not disturbed, not locked (body source: ${bodySource})`); + + promise_test(function() { + return createResponseWithReadableStream(bodySource, function(response) { + return response.arrayBuffer().then(function(arrayBuffer) { + assert_true(arrayBuffer.byteLength > 0); + }); + }); + }, `Getting arrayBuffer after getting the Response body - not disturbed, not locked (body source: ${bodySource})`); +} diff --git a/test/wpt/tests/fetch/api/response/response-stream-disturbed-2.any.js b/test/wpt/tests/fetch/api/response/response-stream-disturbed-2.any.js new file mode 100644 index 0000000..c46a180 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-stream-disturbed-2.any.js @@ -0,0 +1,35 @@ +// META: global=window,worker +// META: title=Consuming Response body after getting a ReadableStream +// META: script=./response-stream-disturbed-util.js + +async function createResponseWithLockedReadableStream(bodySource, callback) { + const response = await responseFromBodySource(bodySource); + response.body.getReader(); + return callback(response); +} + +for (const bodySource of ["fetch", "stream", "string"]) { + promise_test(function(test) { + return createResponseWithLockedReadableStream(bodySource, function(response) { + return promise_rejects_js(test, TypeError, response.blob()); + }); + }, `Getting blob after getting a locked Response body (body source: ${bodySource})`); + + promise_test(function(test) { + return createResponseWithLockedReadableStream(bodySource, function(response) { + return promise_rejects_js(test, TypeError, response.text()); + }); + }, `Getting text after getting a locked Response body (body source: ${bodySource})`); + + promise_test(function(test) { + return createResponseWithLockedReadableStream(bodySource, function(response) { + return promise_rejects_js(test, TypeError, response.json()); + }); + }, `Getting json after getting a locked Response body (body source: ${bodySource})`); + + promise_test(function(test) { + return createResponseWithLockedReadableStream(bodySource, function(response) { + return promise_rejects_js(test, TypeError, response.arrayBuffer()); + }); + }, `Getting arrayBuffer after getting a locked Response body (body source: ${bodySource})`); +} diff --git a/test/wpt/tests/fetch/api/response/response-stream-disturbed-3.any.js b/test/wpt/tests/fetch/api/response/response-stream-disturbed-3.any.js new file mode 100644 index 0000000..35fb086 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-stream-disturbed-3.any.js @@ -0,0 +1,36 @@ +// META: global=window,worker +// META: title=Consuming Response body after getting a ReadableStream +// META: script=./response-stream-disturbed-util.js + +async function createResponseWithDisturbedReadableStream(bodySource, callback) { + const response = await responseFromBodySource(bodySource); + const reader = response.body.getReader(); + reader.read(); + return callback(response); +} + +for (const bodySource of ["fetch", "stream", "string"]) { + promise_test(function(test) { + return createResponseWithDisturbedReadableStream(bodySource, function(response) { + return promise_rejects_js(test, TypeError, response.blob()); + }); + }, `Getting blob after reading the Response body (body source: ${bodySource})`); + + promise_test(function(test) { + return createResponseWithDisturbedReadableStream(bodySource, function(response) { + return promise_rejects_js(test, TypeError, response.text()); + }); + }, `Getting text after reading the Response body (body source: ${bodySource})`); + + promise_test(function(test) { + return createResponseWithDisturbedReadableStream(bodySource, function(response) { + return promise_rejects_js(test, TypeError, response.json()); + }); + }, `Getting json after reading the Response body (body source: ${bodySource})`); + + promise_test(function(test) { + return createResponseWithDisturbedReadableStream(bodySource, function(response) { + return promise_rejects_js(test, TypeError, response.arrayBuffer()); + }); + }, `Getting arrayBuffer after reading the Response body (body source: ${bodySource})`); +} diff --git a/test/wpt/tests/fetch/api/response/response-stream-disturbed-4.any.js b/test/wpt/tests/fetch/api/response/response-stream-disturbed-4.any.js new file mode 100644 index 0000000..490672f --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-stream-disturbed-4.any.js @@ -0,0 +1,35 @@ +// META: global=window,worker +// META: title=Consuming Response body after getting a ReadableStream +// META: script=./response-stream-disturbed-util.js + +async function createResponseWithCancelledReadableStream(bodySource, callback) { + const response = await responseFromBodySource(bodySource); + response.body.cancel(); + return callback(response); +} + +for (const bodySource of ["fetch", "stream", "string"]) { + promise_test(function(test) { + return createResponseWithCancelledReadableStream(bodySource, function(response) { + return promise_rejects_js(test, TypeError, response.blob()); + }); + }, `Getting blob after cancelling the Response body (body source: ${bodySource})`); + + promise_test(function(test) { + return createResponseWithCancelledReadableStream(bodySource, function(response) { + return promise_rejects_js(test, TypeError, response.text()); + }); + }, `Getting text after cancelling the Response body (body source: ${bodySource})`); + + promise_test(function(test) { + return createResponseWithCancelledReadableStream(bodySource, function(response) { + return promise_rejects_js(test, TypeError, response.json()); + }); + }, `Getting json after cancelling the Response body (body source: ${bodySource})`); + + promise_test(function(test) { + return createResponseWithCancelledReadableStream(bodySource, function(response) { + return promise_rejects_js(test, TypeError, response.arrayBuffer()); + }); + }, `Getting arrayBuffer after cancelling the Response body (body source: ${bodySource})`); +} diff --git a/test/wpt/tests/fetch/api/response/response-stream-disturbed-5.any.js b/test/wpt/tests/fetch/api/response/response-stream-disturbed-5.any.js new file mode 100644 index 0000000..348fc39 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-stream-disturbed-5.any.js @@ -0,0 +1,19 @@ +// META: global=window,worker +// META: title=Consuming Response body after getting a ReadableStream +// META: script=./response-stream-disturbed-util.js + +for (const bodySource of ["fetch", "stream", "string"]) { + for (const consumeAs of ["blob", "text", "json", "arrayBuffer"]) { + promise_test( + async () => { + const response = await responseFromBodySource(bodySource); + response[consumeAs](); + assert_not_equals(response.body, null); + assert_throws_js(TypeError, function () { + response.body.getReader(); + }); + }, + `Getting a body reader after consuming as ${consumeAs} (body source: ${bodySource})`, + ); + } +} diff --git a/test/wpt/tests/fetch/api/response/response-stream-disturbed-6.any.js b/test/wpt/tests/fetch/api/response/response-stream-disturbed-6.any.js new file mode 100644 index 0000000..61d8544 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-stream-disturbed-6.any.js @@ -0,0 +1,76 @@ +// META: global=window,worker +// META: title=ReadableStream disturbed tests, via Response's bodyUsed property + +"use strict"; + +test(() => { + const stream = new ReadableStream(); + const response = new Response(stream); + assert_false(response.bodyUsed, "On construction"); + + const reader = stream.getReader(); + assert_false(response.bodyUsed, "After getting a reader"); + + reader.read(); + assert_true(response.bodyUsed, "After calling stream.read()"); +}, "A non-closed stream on which read() has been called"); + +test(() => { + const stream = new ReadableStream(); + const response = new Response(stream); + assert_false(response.bodyUsed, "On construction"); + + const reader = stream.getReader(); + assert_false(response.bodyUsed, "After getting a reader"); + + reader.cancel(); + assert_true(response.bodyUsed, "After calling stream.cancel()"); +}, "A non-closed stream on which cancel() has been called"); + +test(() => { + const stream = new ReadableStream({ + start(c) { + c.close(); + } + }); + const response = new Response(stream); + assert_false(response.bodyUsed, "On construction"); + + const reader = stream.getReader(); + assert_false(response.bodyUsed, "After getting a reader"); + + reader.read(); + assert_true(response.bodyUsed, "After calling stream.read()"); +}, "A closed stream on which read() has been called"); + +test(() => { + const stream = new ReadableStream({ + start(c) { + c.error(new Error("some error")); + } + }); + const response = new Response(stream); + assert_false(response.bodyUsed, "On construction"); + + const reader = stream.getReader(); + assert_false(response.bodyUsed, "After getting a reader"); + + reader.read().then(() => { }, () => { }); + assert_true(response.bodyUsed, "After calling stream.read()"); +}, "An errored stream on which read() has been called"); + +test(() => { + const stream = new ReadableStream({ + start(c) { + c.error(new Error("some error")); + } + }); + const response = new Response(stream); + assert_false(response.bodyUsed, "On construction"); + + const reader = stream.getReader(); + assert_false(response.bodyUsed, "After getting a reader"); + + reader.cancel().then(() => { }, () => { }); + assert_true(response.bodyUsed, "After calling stream.cancel()"); +}, "An errored stream on which cancel() has been called"); diff --git a/test/wpt/tests/fetch/api/response/response-stream-disturbed-by-pipe.any.js b/test/wpt/tests/fetch/api/response/response-stream-disturbed-by-pipe.any.js new file mode 100644 index 0000000..5341b75 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-stream-disturbed-by-pipe.any.js @@ -0,0 +1,17 @@ +// META: global=window,worker + +test(() => { + const r = new Response(new ReadableStream()); + // highWaterMark: 0 means that nothing will actually be read from the body. + r.body.pipeTo(new WritableStream({}, {highWaterMark: 0})); + assert_true(r.bodyUsed, 'bodyUsed should be true'); +}, 'using pipeTo on Response body should disturb it synchronously'); + +test(() => { + const r = new Response(new ReadableStream()); + r.body.pipeThrough({ + writable: new WritableStream({}, {highWaterMark: 0}), + readable: new ReadableStream() + }); + assert_true(r.bodyUsed, 'bodyUsed should be true'); +}, 'using pipeThrough on Response body should disturb it synchronously'); diff --git a/test/wpt/tests/fetch/api/response/response-stream-disturbed-util.js b/test/wpt/tests/fetch/api/response/response-stream-disturbed-util.js new file mode 100644 index 0000000..50bb586 --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-stream-disturbed-util.js @@ -0,0 +1,17 @@ +const BODY = '{"key": "value"}'; + +function responseFromBodySource(bodySource) { + if (bodySource === "fetch") { + return fetch("../resources/data.json"); + } else if (bodySource === "stream") { + const stream = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode(BODY)); + controller.close(); + }, + }); + return new Response(stream); + } else { + return new Response(BODY); + } +} diff --git a/test/wpt/tests/fetch/api/response/response-stream-with-broken-then.any.js b/test/wpt/tests/fetch/api/response/response-stream-with-broken-then.any.js new file mode 100644 index 0000000..8fef66c --- /dev/null +++ b/test/wpt/tests/fetch/api/response/response-stream-with-broken-then.any.js @@ -0,0 +1,117 @@ +// META: global=window,worker +// META: script=../resources/utils.js + +promise_test(async () => { + // t.add_cleanup doesn't work when Object.prototype.then is overwritten, so + // these tests use add_completion_callback for cleanup instead. + add_completion_callback(() => delete Object.prototype.then); + const hello = new TextEncoder().encode('hello'); + const bye = new TextEncoder().encode('bye'); + const rs = new ReadableStream({ + start(controller) { + controller.enqueue(hello); + controller.close(); + } + }); + const resp = new Response(rs); + Object.prototype.then = (onFulfilled) => { + delete Object.prototype.then; + onFulfilled({done: false, value: bye}); + }; + const text = await resp.text(); + delete Object.prototype.then; + assert_equals(text, 'hello', 'The value should be "hello".'); +}, 'Attempt to inject {done: false, value: bye} via Object.prototype.then.'); + +promise_test(async (t) => { + add_completion_callback(() => delete Object.prototype.then); + const hello = new TextEncoder().encode('hello'); + const rs = new ReadableStream({ + start(controller) { + controller.enqueue(hello); + controller.close(); + } + }); + const resp = new Response(rs); + Object.prototype.then = (onFulfilled) => { + delete Object.prototype.then; + onFulfilled({done: false, value: undefined}); + }; + const text = await resp.text(); + delete Object.prototype.then; + assert_equals(text, 'hello', 'The value should be "hello".'); +}, 'Attempt to inject value: undefined via Object.prototype.then.'); + +promise_test(async (t) => { + add_completion_callback(() => delete Object.prototype.then); + const hello = new TextEncoder().encode('hello'); + const rs = new ReadableStream({ + start(controller) { + controller.enqueue(hello); + controller.close(); + } + }); + const resp = new Response(rs); + Object.prototype.then = (onFulfilled) => { + delete Object.prototype.then; + onFulfilled(undefined); + }; + const text = await resp.text(); + delete Object.prototype.then; + assert_equals(text, 'hello', 'The value should be "hello".'); +}, 'Attempt to inject undefined via Object.prototype.then.'); + +promise_test(async (t) => { + add_completion_callback(() => delete Object.prototype.then); + const hello = new TextEncoder().encode('hello'); + const rs = new ReadableStream({ + start(controller) { + controller.enqueue(hello); + controller.close(); + } + }); + const resp = new Response(rs); + Object.prototype.then = (onFulfilled) => { + delete Object.prototype.then; + onFulfilled(8.2); + }; + const text = await resp.text(); + delete Object.prototype.then; + assert_equals(text, 'hello', 'The value should be "hello".'); +}, 'Attempt to inject 8.2 via Object.prototype.then.'); + +promise_test(async () => { + add_completion_callback(() => delete Object.prototype.then); + const hello = new TextEncoder().encode('hello'); + const bye = new TextEncoder().encode('bye'); + const resp = new Response(hello); + Object.prototype.then = (onFulfilled) => { + delete Object.prototype.then; + onFulfilled({done: false, value: bye}); + }; + const text = await resp.text(); + delete Object.prototype.then; + assert_equals(text, 'hello', 'The value should be "hello".'); +}, 'intercepting arraybuffer to text conversion via Object.prototype.then ' + + 'should not be possible'); + +promise_test(async () => { + add_completion_callback(() => delete Object.prototype.then); + const u8a123 = new Uint8Array([1, 2, 3]); + const u8a456 = new Uint8Array([4, 5, 6]); + const resp = new Response(u8a123); + const writtenBytes = []; + const ws = new WritableStream({ + write(chunk) { + writtenBytes.push(...Array.from(chunk)); + } + }); + Object.prototype.then = (onFulfilled) => { + delete Object.prototype.then; + onFulfilled({done: false, value: u8a456}); + }; + await resp.body.pipeTo(ws); + delete Object.prototype.then; + assert_array_equals(writtenBytes, u8a123, 'The value should be [1, 2, 3]'); +}, 'intercepting arraybuffer to body readable stream conversion via ' + + 'Object.prototype.then should not be possible'); diff --git a/test/wpt/tests/fetch/connection-pool/network-partition-key.html b/test/wpt/tests/fetch/connection-pool/network-partition-key.html new file mode 100644 index 0000000..60a784c --- /dev/null +++ b/test/wpt/tests/fetch/connection-pool/network-partition-key.html @@ -0,0 +1,264 @@ + + + + + Connection partitioning by site + + + + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/connection-pool/resources/network-partition-about-blank-checker.html b/test/wpt/tests/fetch/connection-pool/resources/network-partition-about-blank-checker.html new file mode 100644 index 0000000..7a8b613 --- /dev/null +++ b/test/wpt/tests/fetch/connection-pool/resources/network-partition-about-blank-checker.html @@ -0,0 +1,35 @@ + + + + + about:blank Network Partition Checker + + + + + + + diff --git a/test/wpt/tests/fetch/connection-pool/resources/network-partition-checker.html b/test/wpt/tests/fetch/connection-pool/resources/network-partition-checker.html new file mode 100644 index 0000000..b058f61 --- /dev/null +++ b/test/wpt/tests/fetch/connection-pool/resources/network-partition-checker.html @@ -0,0 +1,30 @@ + + + + + Network Partition Checker + + + + + + + + + + diff --git a/test/wpt/tests/fetch/connection-pool/resources/network-partition-iframe-checker.html b/test/wpt/tests/fetch/connection-pool/resources/network-partition-iframe-checker.html new file mode 100644 index 0000000..f76ed18 --- /dev/null +++ b/test/wpt/tests/fetch/connection-pool/resources/network-partition-iframe-checker.html @@ -0,0 +1,22 @@ + + + + + Iframe Network Partition Checker + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/connection-pool/resources/network-partition-key.js b/test/wpt/tests/fetch/connection-pool/resources/network-partition-key.js new file mode 100644 index 0000000..bd66109 --- /dev/null +++ b/test/wpt/tests/fetch/connection-pool/resources/network-partition-key.js @@ -0,0 +1,47 @@ +// Runs multiple fetches that validate connections see only a single partition_id. +// Requests are run in parallel so that they use multiple connections to maximize the +// chance of exercising all matching connections in the connection pool. Only returns +// once all requests have completed to make cleaning up server state non-racy. +function check_partition_ids(location) { + const NUM_FETCHES = 20; + + var base_url = 'SUBRESOURCE_PREFIX:&dispatch=check_partition'; + + // Not a perfect parse of the query string, but good enough for this test. + var include_credentials = base_url.search('include_credentials=true') != -1; + var exclude_credentials = base_url.search('include_credentials=false') != -1; + if (include_credentials != !exclude_credentials) + throw new Exception('Credentials mode not specified'); + + + // Run NUM_FETCHES in parallel. + var fetches = []; + for (i = 0; i < NUM_FETCHES; ++i) { + var fetch_params = { + credentials: 'omit', + mode: 'cors', + headers: { + 'Header-To-Force-CORS': 'cors' + }, + }; + + // Use a unique URL for each request, in case the caching layer serializes multiple + // requests for the same URL. + var url = `${base_url}&${token()}`; + + fetches.push(fetch(url, fetch_params).then( + function (response) { + return response.text().then(function(text) { + assert_equals(text, 'ok', `Socket unexpectedly reused`); + }); + })); + } + + // Wait for all promises to complete. + return Promise.allSettled(fetches).then(function (results) { + results.forEach(function (result) { + if (result.status != 'fulfilled') + throw result.reason; + }); + }); +} diff --git a/test/wpt/tests/fetch/connection-pool/resources/network-partition-key.py b/test/wpt/tests/fetch/connection-pool/resources/network-partition-key.py new file mode 100644 index 0000000..32fe499 --- /dev/null +++ b/test/wpt/tests/fetch/connection-pool/resources/network-partition-key.py @@ -0,0 +1,130 @@ +import mimetypes +import os + +from wptserve.utils import isomorphic_decode, isomorphic_encode + +# Test server that tracks the last partition_id was used with each connection for each uuid, and +# lets consumers query if multiple different partition_ids have been been used for any socket. +# +# Server assumes that ports aren't reused, so a client address and a server port uniquely identify +# a connection. If that constraint is ever violated, the test will be flaky. No sockets being +# closed for the duration of the test is sufficient to ensure that, though even if sockets are +# closed, the OS should generally prefer to use new ports for new connections, if any are +# available. +def main(request, response): + response.headers.set(b"Cache-Control", b"no-store") + dispatch = request.GET.first(b"dispatch", None) + uuid = request.GET.first(b"uuid", None) + partition_id = request.GET.first(b"partition_id", None) + + if not uuid or not dispatch or not partition_id: + return simple_response(request, response, 404, b"Not found", b"Invalid query parameters") + + # Unless nocheck_partition is true, check partition_id against server_state, and update server_state. + stash = request.server.stash + test_failed = False + request_count = 0; + connection_count = 0; + if request.GET.first(b"nocheck_partition", None) != b"True": + # Need to grab the lock to access the Stash, since requests are made in parallel. + with stash.lock: + # Don't use server hostname here, since H2 allows multiple hosts to reuse a connection. + # Server IP is not currently available, unfortunately. + address_key = isomorphic_encode(str(request.client_address) + u"|" + str(request.url_parts.port)) + server_state = stash.take(uuid) or {b"test_failed": False, + b"request_count": 0, b"connection_count": 0} + request_count = server_state[b"request_count"] + request_count += 1 + server_state[b"request_count"] = request_count + if address_key in server_state: + if server_state[address_key] != partition_id: + server_state[b"test_failed"] = True + else: + connection_count = server_state[b"connection_count"] + connection_count += 1 + server_state[b"connection_count"] = connection_count + server_state[address_key] = partition_id + test_failed = server_state[b"test_failed"] + stash.put(uuid, server_state) + + origin = request.headers.get(b"Origin") + if origin: + response.headers.set(b"Access-Control-Allow-Origin", origin) + response.headers.set(b"Access-Control-Allow-Credentials", b"true") + + if request.method == u"OPTIONS": + return handle_preflight(request, response) + + if dispatch == b"fetch_file": + return handle_fetch_file(request, response, partition_id, uuid) + + if dispatch == b"check_partition": + status = request.GET.first(b"status", 200) + if test_failed: + return simple_response(request, response, status, b"OK", b"Multiple partition IDs used on a socket") + body = b"ok" + if request.GET.first(b"addcounter", False): + body += (". Request was sent " + str(request_count) + " times. " + + str(connection_count) + " connections were created.").encode('utf-8') + return simple_response(request, response, status, b"OK", body) + + if dispatch == b"clean_up": + stash.take(uuid) + if test_failed: + return simple_response(request, response, 200, b"OK", b"Test failed, but cleanup completed.") + return simple_response(request, response, 200, b"OK", b"cleanup complete") + + return simple_response(request, response, 404, b"Not Found", b"Unrecognized dispatch parameter: " + dispatch) + +def handle_preflight(request, response): + response.status = (200, b"OK") + response.headers.set(b"Access-Control-Allow-Methods", b"GET") + response.headers.set(b"Access-Control-Allow-Headers", b"header-to-force-cors") + response.headers.set(b"Access-Control-Max-Age", b"86400") + return b"Preflight request" + +def simple_response(request, response, status_code, status_message, body, content_type=b"text/plain"): + response.status = (status_code, status_message) + response.headers.set(b"Content-Type", content_type) + return body + +def handle_fetch_file(request, response, partition_id, uuid): + subresource_origin = request.GET.first(b"subresource_origin", None) + rel_path = request.GET.first(b"path", None) + + # This needs to be passed on to subresources so they all have access to it. + include_credentials = request.GET.first(b"include_credentials", None) + if not subresource_origin or not rel_path or not include_credentials: + return simple_response(request, response, 404, b"Not found", b"Invalid query parameters") + + cur_path = os.path.realpath(isomorphic_decode(__file__)) + base_path = os.path.abspath(os.path.join(os.path.dirname(cur_path), os.pardir, os.pardir, os.pardir)) + path = os.path.abspath(os.path.join(base_path, isomorphic_decode(rel_path))) + + # Basic security check. + if not path.startswith(base_path): + return simple_response(request, response, 404, b"Not found", b"Invalid path") + + sandbox = request.GET.first(b"sandbox", None) + if sandbox == b"true": + response.headers.set(b"Content-Security-Policy", b"sandbox allow-scripts") + + file = open(path, mode="rb") + body = file.read() + file.close() + + subresource_path = b"/" + isomorphic_encode(os.path.relpath(isomorphic_decode(__file__), base_path)).replace(b'\\', b'/') + subresource_params = b"?partition_id=" + partition_id + b"&uuid=" + uuid + b"&subresource_origin=" + subresource_origin + b"&include_credentials=" + include_credentials + body = body.replace(b"SUBRESOURCE_PREFIX:", subresource_origin + subresource_path + subresource_params) + + other_origin = request.GET.first(b"other_origin", None) + if other_origin: + body = body.replace(b"OTHER_PREFIX:", other_origin + subresource_path + subresource_params) + + mimetypes.init() + mimetype_pair = mimetypes.guess_type(path) + mimetype = mimetype_pair[0] + + if mimetype == None or mimetype_pair[1] != None: + return simple_response(request, response, 500, b"Server Error", b"Unknown MIME type") + return simple_response(request, response, 200, b"OK", body, mimetype) diff --git a/test/wpt/tests/fetch/connection-pool/resources/network-partition-worker-checker.html b/test/wpt/tests/fetch/connection-pool/resources/network-partition-worker-checker.html new file mode 100644 index 0000000..e6b7ea7 --- /dev/null +++ b/test/wpt/tests/fetch/connection-pool/resources/network-partition-worker-checker.html @@ -0,0 +1,24 @@ + + + + + Worker Network Partition Checker + + + + + + + + + + diff --git a/test/wpt/tests/fetch/connection-pool/resources/network-partition-worker.js b/test/wpt/tests/fetch/connection-pool/resources/network-partition-worker.js new file mode 100644 index 0000000..1745edf --- /dev/null +++ b/test/wpt/tests/fetch/connection-pool/resources/network-partition-worker.js @@ -0,0 +1,15 @@ +// This tests the partition key of fetches to subresouce_origin made by the worker and +// imported scripts from subresource_origin. +importScripts('SUBRESOURCE_PREFIX:&dispatch=fetch_file&path=common/utils.js'); +importScripts('SUBRESOURCE_PREFIX:&dispatch=fetch_file&path=resources/testharness.js'); +importScripts('SUBRESOURCE_PREFIX:&dispatch=fetch_file&path=fetch/connection-pool/resources/network-partition-key.js'); + +async function fetch_and_reply() { + try { + await check_partition_ids(); + self.postMessage({result: 'success'}); + } catch (e) { + self.postMessage({result: 'error', details: e.message}); + } +} +fetch_and_reply(); diff --git a/test/wpt/tests/fetch/content-encoding/bad-gzip-body.any.js b/test/wpt/tests/fetch/content-encoding/bad-gzip-body.any.js new file mode 100644 index 0000000..17bc126 --- /dev/null +++ b/test/wpt/tests/fetch/content-encoding/bad-gzip-body.any.js @@ -0,0 +1,22 @@ +// META: global=window,worker + +promise_test((test) => { + return fetch("resources/bad-gzip-body.py").then(res => { + assert_equals(res.status, 200); + }); +}, "Fetching a resource with bad gzip content should still resolve"); + +[ + "arrayBuffer", + "blob", + "formData", + "json", + "text" +].forEach(method => { + promise_test(t => { + return fetch("resources/bad-gzip-body.py").then(res => { + assert_equals(res.status, 200); + return promise_rejects_js(t, TypeError, res[method]()); + }); + }, "Consuming the body of a resource with bad gzip content with " + method + "() should reject"); +}); diff --git a/test/wpt/tests/fetch/content-encoding/gzip-body.any.js b/test/wpt/tests/fetch/content-encoding/gzip-body.any.js new file mode 100644 index 0000000..37758b7 --- /dev/null +++ b/test/wpt/tests/fetch/content-encoding/gzip-body.any.js @@ -0,0 +1,16 @@ +// META: global=window,worker + +const expectedDecompressedSize = 10500; +[ + "text", + "octetstream" +].forEach(contentType => { + promise_test(async t => { + let response = await fetch(`resources/foo.${contentType}.gz`); + assert_true(response.ok); + let arrayBuffer = await response.arrayBuffer() + let u8 = new Uint8Array(arrayBuffer); + assert_equals(u8.length, expectedDecompressedSize); + }, `fetched gzip data with content type ${contentType} should be decompressed.`); +}); + diff --git a/test/wpt/tests/fetch/content-encoding/resources/bad-gzip-body.py b/test/wpt/tests/fetch/content-encoding/resources/bad-gzip-body.py new file mode 100644 index 0000000..a79b94e --- /dev/null +++ b/test/wpt/tests/fetch/content-encoding/resources/bad-gzip-body.py @@ -0,0 +1,3 @@ +def main(request, response): + headers = [(b"Content-Encoding", b"gzip")] + return headers, b"not actually gzip" diff --git a/test/wpt/tests/fetch/content-encoding/resources/foo.octetstream.gz b/test/wpt/tests/fetch/content-encoding/resources/foo.octetstream.gz new file mode 100644 index 0000000..f3df4cb Binary files /dev/null and b/test/wpt/tests/fetch/content-encoding/resources/foo.octetstream.gz differ diff --git a/test/wpt/tests/fetch/content-encoding/resources/foo.octetstream.gz.headers b/test/wpt/tests/fetch/content-encoding/resources/foo.octetstream.gz.headers new file mode 100644 index 0000000..27d4f40 --- /dev/null +++ b/test/wpt/tests/fetch/content-encoding/resources/foo.octetstream.gz.headers @@ -0,0 +1,2 @@ +Content-type: application/octet-stream +Content-Encoding: gzip diff --git a/test/wpt/tests/fetch/content-encoding/resources/foo.text.gz b/test/wpt/tests/fetch/content-encoding/resources/foo.text.gz new file mode 100644 index 0000000..05a5cce Binary files /dev/null and b/test/wpt/tests/fetch/content-encoding/resources/foo.text.gz differ diff --git a/test/wpt/tests/fetch/content-encoding/resources/foo.text.gz.headers b/test/wpt/tests/fetch/content-encoding/resources/foo.text.gz.headers new file mode 100644 index 0000000..7def3dd --- /dev/null +++ b/test/wpt/tests/fetch/content-encoding/resources/foo.text.gz.headers @@ -0,0 +1,2 @@ +Content-type: text/plain +Content-Encoding: gzip diff --git a/test/wpt/tests/fetch/content-length/api-and-duplicate-headers.any.js b/test/wpt/tests/fetch/content-length/api-and-duplicate-headers.any.js new file mode 100644 index 0000000..8015289 --- /dev/null +++ b/test/wpt/tests/fetch/content-length/api-and-duplicate-headers.any.js @@ -0,0 +1,23 @@ +promise_test(async t => { + const response = await fetch("resources/identical-duplicates.asis"); + assert_equals(response.statusText, "BLAH"); + assert_equals(response.headers.get("test"), "x, x"); + assert_equals(response.headers.get("content-type"), "text/plain, text/plain"); + assert_equals(response.headers.get("content-length"), "6, 6"); + const text = await response.text(); + assert_equals(text, "Test.\n"); +}, "fetch() and duplicate Content-Length/Content-Type headers"); + +async_test(t => { + const xhr = new XMLHttpRequest(); + xhr.open("GET", "resources/identical-duplicates.asis"); + xhr.send(); + xhr.onload = t.step_func_done(() => { + assert_equals(xhr.statusText, "BLAH"); + assert_equals(xhr.getResponseHeader("test"), "x, x"); + assert_equals(xhr.getResponseHeader("content-type"), "text/plain, text/plain"); + assert_equals(xhr.getResponseHeader("content-length"), "6, 6"); + assert_equals(xhr.getAllResponseHeaders(), "content-length: 6, 6\r\ncontent-type: text/plain, text/plain\r\ntest: x, x\r\n"); + assert_equals(xhr.responseText, "Test.\n"); + }); +}, "XMLHttpRequest and duplicate Content-Length/Content-Type headers"); diff --git a/test/wpt/tests/fetch/content-length/content-length.html b/test/wpt/tests/fetch/content-length/content-length.html new file mode 100644 index 0000000..cda9b5b --- /dev/null +++ b/test/wpt/tests/fetch/content-length/content-length.html @@ -0,0 +1,14 @@ + + +Content-Length Test + + + +PASS +but FAIL if this is in the body. \ No newline at end of file diff --git a/test/wpt/tests/fetch/content-length/content-length.html.headers b/test/wpt/tests/fetch/content-length/content-length.html.headers new file mode 100644 index 0000000..25389b7 --- /dev/null +++ b/test/wpt/tests/fetch/content-length/content-length.html.headers @@ -0,0 +1 @@ +Content-Length: 403 diff --git a/test/wpt/tests/fetch/content-length/parsing.window.js b/test/wpt/tests/fetch/content-length/parsing.window.js new file mode 100644 index 0000000..5028ad9 --- /dev/null +++ b/test/wpt/tests/fetch/content-length/parsing.window.js @@ -0,0 +1,18 @@ +promise_test(() => { + return fetch("resources/content-lengths.json").then(res => res.json()).then(runTests); +}, "Loading JSON…"); + +function runTests(testUnits) { + testUnits.forEach(({ input, output }) => { + promise_test(t => { + const result = fetch(`resources/content-length.py?length=${encodeURIComponent(input)}`); + if (output === null) { + return promise_rejects_js(t, TypeError, result); + } else { + return result.then(res => res.text()).then(text => { + assert_equals(text.length, output); + }); + } + }, `Input: ${format_value(input)}. Expected: ${output === null ? "network error" : output}.`); + }); +} diff --git a/test/wpt/tests/fetch/content-length/resources/content-length.py b/test/wpt/tests/fetch/content-length/resources/content-length.py new file mode 100644 index 0000000..92cfade --- /dev/null +++ b/test/wpt/tests/fetch/content-length/resources/content-length.py @@ -0,0 +1,10 @@ +def main(request, response): + response.add_required_headers = False + output = b"HTTP/1.1 200 OK\r\n" + output += b"Content-Type: text/plain;charset=UTF-8\r\n" + output += b"Connection: close\r\n" + output += request.GET.first(b"length") + b"\r\n" + output += b"\r\n" + output += b"Fact: this is really forty-two bytes long." + response.writer.write(output) + response.close_connection = True diff --git a/test/wpt/tests/fetch/content-length/resources/content-lengths.json b/test/wpt/tests/fetch/content-length/resources/content-lengths.json new file mode 100644 index 0000000..ac6f1a2 --- /dev/null +++ b/test/wpt/tests/fetch/content-length/resources/content-lengths.json @@ -0,0 +1,142 @@ +[ + { + "input": "Content-Length: 42", + "output": 42 + }, + { + "input": "Content-Length: 42,42", + "output": 42 + }, + { + "input": "Content-Length: 42\r\nContent-Length: 42", + "output": 42 + }, + { + "input": "Content-Length: 42\r\nContent-Length: 42,42", + "output": 42 + }, + { + "input": "Content-Length: 30", + "output": 30 + }, + { + "input": "Content-Length: 30,30", + "output": 30 + }, + { + "input": "Content-Length: 30\r\nContent-Length: 30", + "output": 30 + }, + { + "input": "Content-Length: 30\r\nContent-Length: 30,30", + "output": 30 + }, + { + "input": "Content-Length: 30,30\r\nContent-Length: 30,30", + "output": 30 + }, + { + "input": "Content-Length: 30,30, 30 \r\nContent-Length: 30 ", + "output": 30 + }, + { + "input": "Content-Length: 30,42\r\nContent-Length: 30", + "output": null + }, + { + "input": "Content-Length: 30,42\r\nContent-Length: 30,42", + "output": null + }, + { + "input": "Content-Length: 42,30", + "output": null + }, + { + "input": "Content-Length: 30,42", + "output": null + }, + { + "input": "Content-Length: 42\r\nContent-Length: 30", + "output": null + }, + { + "input": "Content-Length: 30\r\nContent-Length: 42", + "output": null + }, + { + "input": "Content-Length: 30,", + "output": null + }, + { + "input": "Content-Length: ,30", + "output": null + }, + { + "input": "Content-Length: 30\r\nContent-Length: \t", + "output": null + }, + { + "input": "Content-Length: \r\nContent-Length: 30", + "output": null + }, + { + "input": "Content-Length: aaaah\r\nContent-Length: nah", + "output": null + }, + { + "input": "Content-Length: aaaah, nah", + "output": null + }, + { + "input": "Content-Length: aaaah\r\nContent-Length: aaaah", + "output": 42 + }, + { + "input": "Content-Length: aaaah, aaaah", + "output": 42 + }, + { + "input": "Content-Length: aaaah", + "output": 42 + }, + { + "input": "Content-Length: 42s", + "output": 42 + }, + { + "input": "Content-Length: 30s", + "output": 42 + }, + { + "input": "Content-Length: -1", + "output": 42 + }, + { + "input": "Content-Length: 0x20", + "output": 42 + }, + { + "input": "Content-Length: 030", + "output": 30 + }, + { + "input": "Content-Length: 030\r\nContent-Length: 30", + "output": null + }, + { + "input": "Content-Length: 030, 30", + "output": null + }, + { + "input": "Content-Length: \"30\"", + "output": 42 + }, + { + "input": "Content-Length:30\r\nContent-Length:,\r\nContent-Length:30", + "output": null + }, + { + "input": "Content-Length: ", + "output": 42 + } +] diff --git a/test/wpt/tests/fetch/content-length/resources/identical-duplicates.asis b/test/wpt/tests/fetch/content-length/resources/identical-duplicates.asis new file mode 100644 index 0000000..f38c9a4 --- /dev/null +++ b/test/wpt/tests/fetch/content-length/resources/identical-duplicates.asis @@ -0,0 +1,9 @@ +HTTP/1.1 200 BLAH +Test: x +Test: x +Content-Type: text/plain +Content-Type: text/plain +Content-Length: 6 +Content-Length: 6 + +Test. diff --git a/test/wpt/tests/fetch/content-length/too-long.window.js b/test/wpt/tests/fetch/content-length/too-long.window.js new file mode 100644 index 0000000..f8cefaa --- /dev/null +++ b/test/wpt/tests/fetch/content-length/too-long.window.js @@ -0,0 +1,4 @@ +promise_test(async t => { + const result = await fetch(`resources/content-length.py?length=${encodeURIComponent("Content-Length: 50")}`); + await promise_rejects_js(t, TypeError, result.text()); +}, "Content-Length header value of network response exceeds response body"); diff --git a/test/wpt/tests/fetch/content-type/README.md b/test/wpt/tests/fetch/content-type/README.md new file mode 100644 index 0000000..f553b7e --- /dev/null +++ b/test/wpt/tests/fetch/content-type/README.md @@ -0,0 +1,20 @@ +# `resources/content-types.json` + +An array of tests. Each test has these fields: + +* `contentType`: an array of values for the `Content-Type` header. A harness needs to run the test twice if there are multiple values. One time with the values concatenated with `,` followed by a space and one time with multiple `Content-Type` declarations, each on their own line with one of the values, in order. +* `encoding`: the expected encoding, null for the default. +* `mimeType`: the result of extracting a MIME type and serializing it. +* `documentContentType`: the MIME type expected to be exposed in DOM documents. + +(These tests are currently somewhat geared towards browser use, but could be generalized easily enough if someone wanted to contribute tests for MIME types that would cause downloads in the browser or some such.) + +# `resources/script-content-types.json` + +An array of tests, surprise. Each test has these fields: + +* `contentType`: see above. +* `executes`: whether the script is expected to execute. +* `encoding`: how the script is expected to be decoded. + +These tests are expected to be loaded through ` + +
+ diff --git a/test/wpt/tests/fetch/corb/img-png-mislabeled-as-html-nosniff.tentative.sub-ref.html b/test/wpt/tests/fetch/corb/img-png-mislabeled-as-html-nosniff.tentative.sub-ref.html new file mode 100644 index 0000000..a771ed6 --- /dev/null +++ b/test/wpt/tests/fetch/corb/img-png-mislabeled-as-html-nosniff.tentative.sub-ref.html @@ -0,0 +1,4 @@ + + + + diff --git a/test/wpt/tests/fetch/corb/img-png-mislabeled-as-html-nosniff.tentative.sub.html b/test/wpt/tests/fetch/corb/img-png-mislabeled-as-html-nosniff.tentative.sub.html new file mode 100644 index 0000000..82adc47 --- /dev/null +++ b/test/wpt/tests/fetch/corb/img-png-mislabeled-as-html-nosniff.tentative.sub.html @@ -0,0 +1,11 @@ + + + + + + + diff --git a/test/wpt/tests/fetch/corb/img-png-mislabeled-as-html.sub-ref.html b/test/wpt/tests/fetch/corb/img-png-mislabeled-as-html.sub-ref.html new file mode 100644 index 0000000..ebb337d --- /dev/null +++ b/test/wpt/tests/fetch/corb/img-png-mislabeled-as-html.sub-ref.html @@ -0,0 +1,4 @@ + + + + diff --git a/test/wpt/tests/fetch/corb/img-png-mislabeled-as-html.sub.html b/test/wpt/tests/fetch/corb/img-png-mislabeled-as-html.sub.html new file mode 100644 index 0000000..1ae4cfc --- /dev/null +++ b/test/wpt/tests/fetch/corb/img-png-mislabeled-as-html.sub.html @@ -0,0 +1,10 @@ + + + + + + + diff --git a/test/wpt/tests/fetch/corb/img-svg-doctype-html-mimetype-empty.sub.html b/test/wpt/tests/fetch/corb/img-svg-doctype-html-mimetype-empty.sub.html new file mode 100644 index 0000000..3219fed --- /dev/null +++ b/test/wpt/tests/fetch/corb/img-svg-doctype-html-mimetype-empty.sub.html @@ -0,0 +1,7 @@ + + + + + diff --git a/test/wpt/tests/fetch/corb/img-svg-doctype-html-mimetype-svg.sub.html b/test/wpt/tests/fetch/corb/img-svg-doctype-html-mimetype-svg.sub.html new file mode 100644 index 0000000..efcfaa2 --- /dev/null +++ b/test/wpt/tests/fetch/corb/img-svg-doctype-html-mimetype-svg.sub.html @@ -0,0 +1,11 @@ + + + + + diff --git a/test/wpt/tests/fetch/corb/img-svg-invalid.sub-ref.html b/test/wpt/tests/fetch/corb/img-svg-invalid.sub-ref.html new file mode 100644 index 0000000..484cd0a --- /dev/null +++ b/test/wpt/tests/fetch/corb/img-svg-invalid.sub-ref.html @@ -0,0 +1,5 @@ + + + + diff --git a/test/wpt/tests/fetch/corb/img-svg-labeled-as-dash.sub.html b/test/wpt/tests/fetch/corb/img-svg-labeled-as-dash.sub.html new file mode 100644 index 0000000..0578b83 --- /dev/null +++ b/test/wpt/tests/fetch/corb/img-svg-labeled-as-dash.sub.html @@ -0,0 +1,6 @@ + + + + + diff --git a/test/wpt/tests/fetch/corb/img-svg-labeled-as-svg-xml.sub.html b/test/wpt/tests/fetch/corb/img-svg-labeled-as-svg-xml.sub.html new file mode 100644 index 0000000..30a2eb3 --- /dev/null +++ b/test/wpt/tests/fetch/corb/img-svg-labeled-as-svg-xml.sub.html @@ -0,0 +1,6 @@ + + + + + diff --git a/test/wpt/tests/fetch/corb/img-svg-xml-decl.sub.html b/test/wpt/tests/fetch/corb/img-svg-xml-decl.sub.html new file mode 100644 index 0000000..0d3aeaf --- /dev/null +++ b/test/wpt/tests/fetch/corb/img-svg-xml-decl.sub.html @@ -0,0 +1,6 @@ + + + + + diff --git a/test/wpt/tests/fetch/corb/img-svg.sub-ref.html b/test/wpt/tests/fetch/corb/img-svg.sub-ref.html new file mode 100644 index 0000000..5462f68 --- /dev/null +++ b/test/wpt/tests/fetch/corb/img-svg.sub-ref.html @@ -0,0 +1,5 @@ + + + + diff --git a/test/wpt/tests/fetch/corb/preload-image-png-mislabeled-as-html-nosniff.tentative.sub.html b/test/wpt/tests/fetch/corb/preload-image-png-mislabeled-as-html-nosniff.tentative.sub.html new file mode 100644 index 0000000..cea80f2 --- /dev/null +++ b/test/wpt/tests/fetch/corb/preload-image-png-mislabeled-as-html-nosniff.tentative.sub.html @@ -0,0 +1,24 @@ + + + + + +
+ + + + + diff --git a/test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html-nosniff.css b/test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html-nosniff.css new file mode 100644 index 0000000..afd2b92 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html-nosniff.css @@ -0,0 +1 @@ +#header { color: red; } diff --git a/test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html-nosniff.css.headers b/test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html-nosniff.css.headers new file mode 100644 index 0000000..0f228f9 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html-nosniff.css.headers @@ -0,0 +1,2 @@ +Content-Type: text/html +X-Content-Type-Options: nosniff diff --git a/test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html.css b/test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html.css new file mode 100644 index 0000000..afd2b92 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html.css @@ -0,0 +1 @@ +#header { color: red; } diff --git a/test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html.css.headers b/test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html.css.headers new file mode 100644 index 0000000..156209f --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/css-mislabeled-as-html.css.headers @@ -0,0 +1 @@ +Content-Type: text/html diff --git a/test/wpt/tests/fetch/corb/resources/css-with-json-parser-breaker.css b/test/wpt/tests/fetch/corb/resources/css-with-json-parser-breaker.css new file mode 100644 index 0000000..7db6f5c --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/css-with-json-parser-breaker.css @@ -0,0 +1,3 @@ +)]}' +{} +#header { color: red; } diff --git a/test/wpt/tests/fetch/corb/resources/empty-labeled-as-png.png b/test/wpt/tests/fetch/corb/resources/empty-labeled-as-png.png new file mode 100644 index 0000000..e69de29 diff --git a/test/wpt/tests/fetch/corb/resources/empty-labeled-as-png.png.headers b/test/wpt/tests/fetch/corb/resources/empty-labeled-as-png.png.headers new file mode 100644 index 0000000..e7be84a --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/empty-labeled-as-png.png.headers @@ -0,0 +1 @@ +Content-Type: image/png diff --git a/test/wpt/tests/fetch/corb/resources/html-correctly-labeled.html b/test/wpt/tests/fetch/corb/resources/html-correctly-labeled.html new file mode 100644 index 0000000..7bad71b --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/html-correctly-labeled.html @@ -0,0 +1,10 @@ + + + + + Page Title + + +

Page body

+ + diff --git a/test/wpt/tests/fetch/corb/resources/html-correctly-labeled.html.headers b/test/wpt/tests/fetch/corb/resources/html-correctly-labeled.html.headers new file mode 100644 index 0000000..156209f --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/html-correctly-labeled.html.headers @@ -0,0 +1 @@ +Content-Type: text/html diff --git a/test/wpt/tests/fetch/corb/resources/html-js-polyglot.js b/test/wpt/tests/fetch/corb/resources/html-js-polyglot.js new file mode 100644 index 0000000..db45bb4 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/html-js-polyglot.js @@ -0,0 +1,9 @@ + diff --git a/test/wpt/tests/fetch/corb/resources/html-js-polyglot.js.headers b/test/wpt/tests/fetch/corb/resources/html-js-polyglot.js.headers new file mode 100644 index 0000000..156209f --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/html-js-polyglot.js.headers @@ -0,0 +1 @@ +Content-Type: text/html diff --git a/test/wpt/tests/fetch/corb/resources/html-js-polyglot2.js b/test/wpt/tests/fetch/corb/resources/html-js-polyglot2.js new file mode 100644 index 0000000..faae1b7 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/html-js-polyglot2.js @@ -0,0 +1,10 @@ + diff --git a/test/wpt/tests/fetch/corb/resources/html-js-polyglot2.js.headers b/test/wpt/tests/fetch/corb/resources/html-js-polyglot2.js.headers new file mode 100644 index 0000000..156209f --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/html-js-polyglot2.js.headers @@ -0,0 +1 @@ +Content-Type: text/html diff --git a/test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html-nosniff.js b/test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html-nosniff.js new file mode 100644 index 0000000..a880a5b --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html-nosniff.js @@ -0,0 +1 @@ +window.has_executed_script = true; diff --git a/test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html-nosniff.js.headers b/test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html-nosniff.js.headers new file mode 100644 index 0000000..0f228f9 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html-nosniff.js.headers @@ -0,0 +1,2 @@ +Content-Type: text/html +X-Content-Type-Options: nosniff diff --git a/test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html.js b/test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html.js new file mode 100644 index 0000000..a880a5b --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html.js @@ -0,0 +1 @@ +window.has_executed_script = true; diff --git a/test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html.js.headers b/test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html.js.headers new file mode 100644 index 0000000..156209f --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/js-mislabeled-as-html.js.headers @@ -0,0 +1 @@ +Content-Type: text/html diff --git a/test/wpt/tests/fetch/corb/resources/png-correctly-labeled.png b/test/wpt/tests/fetch/corb/resources/png-correctly-labeled.png new file mode 100644 index 0000000..820f8ca Binary files /dev/null and b/test/wpt/tests/fetch/corb/resources/png-correctly-labeled.png differ diff --git a/test/wpt/tests/fetch/corb/resources/png-correctly-labeled.png.headers b/test/wpt/tests/fetch/corb/resources/png-correctly-labeled.png.headers new file mode 100644 index 0000000..e7be84a --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/png-correctly-labeled.png.headers @@ -0,0 +1 @@ +Content-Type: image/png diff --git a/test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html-nosniff.png b/test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html-nosniff.png new file mode 100644 index 0000000..820f8ca Binary files /dev/null and b/test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html-nosniff.png differ diff --git a/test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html-nosniff.png.headers b/test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html-nosniff.png.headers new file mode 100644 index 0000000..0f228f9 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html-nosniff.png.headers @@ -0,0 +1,2 @@ +Content-Type: text/html +X-Content-Type-Options: nosniff diff --git a/test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html.png b/test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html.png new file mode 100644 index 0000000..820f8ca Binary files /dev/null and b/test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html.png differ diff --git a/test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html.png.headers b/test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html.png.headers new file mode 100644 index 0000000..156209f --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/png-mislabeled-as-html.png.headers @@ -0,0 +1 @@ +Content-Type: text/html diff --git a/test/wpt/tests/fetch/corb/resources/response_block_probe.js b/test/wpt/tests/fetch/corb/resources/response_block_probe.js new file mode 100644 index 0000000..9c3b87b --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/response_block_probe.js @@ -0,0 +1 @@ +alert(1); // Arbitrary JavaScript. Details don't matter for the test. diff --git a/test/wpt/tests/fetch/corb/resources/response_block_probe.js.headers b/test/wpt/tests/fetch/corb/resources/response_block_probe.js.headers new file mode 100644 index 0000000..0d848b0 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/response_block_probe.js.headers @@ -0,0 +1 @@ +Content-Type: text/csv diff --git a/test/wpt/tests/fetch/corb/resources/sniffable-resource.py b/test/wpt/tests/fetch/corb/resources/sniffable-resource.py new file mode 100644 index 0000000..f815093 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/sniffable-resource.py @@ -0,0 +1,11 @@ +def main(request, response): + body = request.GET.first(b"body", None) + type = request.GET.first(b"type", None) + + response.add_required_headers = False + response.writer.write_status(200) + response.writer.write_header(b"content-length", len(body)) + response.writer.write_header(b"content-type", type) + response.writer.end_headers() + + response.writer.write(body) diff --git a/test/wpt/tests/fetch/corb/resources/subframe-that-posts-html-containing-blob-url-to-parent.html b/test/wpt/tests/fetch/corb/resources/subframe-that-posts-html-containing-blob-url-to-parent.html new file mode 100644 index 0000000..67b3ad5 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/subframe-that-posts-html-containing-blob-url-to-parent.html @@ -0,0 +1,16 @@ + + + diff --git a/test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-empty.svg b/test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-empty.svg new file mode 100644 index 0000000..fa2d29b --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-empty.svg @@ -0,0 +1,4 @@ + + + + diff --git a/test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-empty.svg.headers b/test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-empty.svg.headers new file mode 100644 index 0000000..29515ee --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-empty.svg.headers @@ -0,0 +1 @@ +Content-Type: diff --git a/test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-svg.svg b/test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-svg.svg new file mode 100644 index 0000000..fa2d29b --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-svg.svg @@ -0,0 +1,4 @@ + + + + diff --git a/test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-svg.svg.headers b/test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-svg.svg.headers new file mode 100644 index 0000000..070de35 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/svg-doctype-html-mimetype-svg.svg.headers @@ -0,0 +1 @@ +Content-Type: image/svg+xml diff --git a/test/wpt/tests/fetch/corb/resources/svg-labeled-as-dash.svg b/test/wpt/tests/fetch/corb/resources/svg-labeled-as-dash.svg new file mode 100644 index 0000000..2b7d101 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/svg-labeled-as-dash.svg @@ -0,0 +1,3 @@ + + + diff --git a/test/wpt/tests/fetch/corb/resources/svg-labeled-as-dash.svg.headers b/test/wpt/tests/fetch/corb/resources/svg-labeled-as-dash.svg.headers new file mode 100644 index 0000000..43ce612 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/svg-labeled-as-dash.svg.headers @@ -0,0 +1 @@ +Content-Type: application/dash+xml diff --git a/test/wpt/tests/fetch/corb/resources/svg-labeled-as-svg-xml.svg b/test/wpt/tests/fetch/corb/resources/svg-labeled-as-svg-xml.svg new file mode 100644 index 0000000..2b7d101 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/svg-labeled-as-svg-xml.svg @@ -0,0 +1,3 @@ + + + diff --git a/test/wpt/tests/fetch/corb/resources/svg-labeled-as-svg-xml.svg.headers b/test/wpt/tests/fetch/corb/resources/svg-labeled-as-svg-xml.svg.headers new file mode 100644 index 0000000..070de35 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/svg-labeled-as-svg-xml.svg.headers @@ -0,0 +1 @@ +Content-Type: image/svg+xml diff --git a/test/wpt/tests/fetch/corb/resources/svg-xml-decl.svg b/test/wpt/tests/fetch/corb/resources/svg-xml-decl.svg new file mode 100644 index 0000000..3b39aff --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/svg-xml-decl.svg @@ -0,0 +1,4 @@ + + + + diff --git a/test/wpt/tests/fetch/corb/resources/svg.svg b/test/wpt/tests/fetch/corb/resources/svg.svg new file mode 100644 index 0000000..2b7d101 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/svg.svg @@ -0,0 +1,3 @@ + + + diff --git a/test/wpt/tests/fetch/corb/resources/svg.svg.headers b/test/wpt/tests/fetch/corb/resources/svg.svg.headers new file mode 100644 index 0000000..070de35 --- /dev/null +++ b/test/wpt/tests/fetch/corb/resources/svg.svg.headers @@ -0,0 +1 @@ +Content-Type: image/svg+xml diff --git a/test/wpt/tests/fetch/corb/response_block.tentative.https.html b/test/wpt/tests/fetch/corb/response_block.tentative.https.html new file mode 100644 index 0000000..6b11600 --- /dev/null +++ b/test/wpt/tests/fetch/corb/response_block.tentative.https.html @@ -0,0 +1,50 @@ + + + + + + diff --git a/test/wpt/tests/fetch/corb/script-html-correctly-labeled.tentative.sub.html b/test/wpt/tests/fetch/corb/script-html-correctly-labeled.tentative.sub.html new file mode 100644 index 0000000..6d1947c --- /dev/null +++ b/test/wpt/tests/fetch/corb/script-html-correctly-labeled.tentative.sub.html @@ -0,0 +1,32 @@ + + + + + +
+ diff --git a/test/wpt/tests/fetch/corb/script-html-js-polyglot.sub.html b/test/wpt/tests/fetch/corb/script-html-js-polyglot.sub.html new file mode 100644 index 0000000..9a272d6 --- /dev/null +++ b/test/wpt/tests/fetch/corb/script-html-js-polyglot.sub.html @@ -0,0 +1,32 @@ + + + + + +
+ diff --git a/test/wpt/tests/fetch/corb/script-html-via-cross-origin-blob-url.sub.html b/test/wpt/tests/fetch/corb/script-html-via-cross-origin-blob-url.sub.html new file mode 100644 index 0000000..c8a90c7 --- /dev/null +++ b/test/wpt/tests/fetch/corb/script-html-via-cross-origin-blob-url.sub.html @@ -0,0 +1,38 @@ + + + + + +
+ diff --git a/test/wpt/tests/fetch/corb/script-js-mislabeled-as-html-nosniff.sub.html b/test/wpt/tests/fetch/corb/script-js-mislabeled-as-html-nosniff.sub.html new file mode 100644 index 0000000..b6bc909 --- /dev/null +++ b/test/wpt/tests/fetch/corb/script-js-mislabeled-as-html-nosniff.sub.html @@ -0,0 +1,33 @@ + + + + + +
+ + + + + + + diff --git a/test/wpt/tests/fetch/corb/script-js-mislabeled-as-html.sub.html b/test/wpt/tests/fetch/corb/script-js-mislabeled-as-html.sub.html new file mode 100644 index 0000000..44cb1f8 --- /dev/null +++ b/test/wpt/tests/fetch/corb/script-js-mislabeled-as-html.sub.html @@ -0,0 +1,25 @@ + + + + + +
+ + + + + + + diff --git a/test/wpt/tests/fetch/corb/script-resource-with-json-parser-breaker.tentative.sub.html b/test/wpt/tests/fetch/corb/script-resource-with-json-parser-breaker.tentative.sub.html new file mode 100644 index 0000000..f0eb1f0 --- /dev/null +++ b/test/wpt/tests/fetch/corb/script-resource-with-json-parser-breaker.tentative.sub.html @@ -0,0 +1,85 @@ + + + + + +
+ diff --git a/test/wpt/tests/fetch/corb/script-resource-with-nonsniffable-types.tentative.sub.html b/test/wpt/tests/fetch/corb/script-resource-with-nonsniffable-types.tentative.sub.html new file mode 100644 index 0000000..6d490d5 --- /dev/null +++ b/test/wpt/tests/fetch/corb/script-resource-with-nonsniffable-types.tentative.sub.html @@ -0,0 +1,84 @@ + + + + + + +
+ diff --git a/test/wpt/tests/fetch/corb/style-css-mislabeled-as-html-nosniff.sub.html b/test/wpt/tests/fetch/corb/style-css-mislabeled-as-html-nosniff.sub.html new file mode 100644 index 0000000..8fef0dc --- /dev/null +++ b/test/wpt/tests/fetch/corb/style-css-mislabeled-as-html-nosniff.sub.html @@ -0,0 +1,42 @@ + + + +CSS is not applied (because of nosniff + non-text/css headers) + + + + + + + + + + + +

Header example

+

Paragraph body

+ + + diff --git a/test/wpt/tests/fetch/corb/style-css-mislabeled-as-html.sub.html b/test/wpt/tests/fetch/corb/style-css-mislabeled-as-html.sub.html new file mode 100644 index 0000000..4f0b4c2 --- /dev/null +++ b/test/wpt/tests/fetch/corb/style-css-mislabeled-as-html.sub.html @@ -0,0 +1,36 @@ + + + +CSS is not applied (because of strict content-type enforcement for cross-origin stylesheets) + + + + + + + + + + + +

Header example

+

Paragraph body

+ + + diff --git a/test/wpt/tests/fetch/corb/style-css-with-json-parser-breaker.sub.html b/test/wpt/tests/fetch/corb/style-css-with-json-parser-breaker.sub.html new file mode 100644 index 0000000..29ed586 --- /dev/null +++ b/test/wpt/tests/fetch/corb/style-css-with-json-parser-breaker.sub.html @@ -0,0 +1,38 @@ + + + +CORB doesn't block a stylesheet that has a proper Content-Type and begins with a JSON parser breaker + + + + + + + + + + + +

Header example

+

Paragraph body

+ + + diff --git a/test/wpt/tests/fetch/corb/style-html-correctly-labeled.sub.html b/test/wpt/tests/fetch/corb/style-html-correctly-labeled.sub.html new file mode 100644 index 0000000..cdefcd2 --- /dev/null +++ b/test/wpt/tests/fetch/corb/style-html-correctly-labeled.sub.html @@ -0,0 +1,41 @@ + + + +CSS is not applied (because of mismatched Content-Type header) + + + + + + + + + + + +

Header example

+

Paragraph body

+ + + diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/fetch-in-iframe.html b/test/wpt/tests/fetch/cross-origin-resource-policy/fetch-in-iframe.html new file mode 100644 index 0000000..cc6a3a8 --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/fetch-in-iframe.html @@ -0,0 +1,67 @@ + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/fetch.any.js b/test/wpt/tests/fetch/cross-origin-resource-policy/fetch.any.js new file mode 100644 index 0000000..64a7bfe --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/fetch.any.js @@ -0,0 +1,76 @@ +// META: timeout=long +// META: global=window,dedicatedworker,sharedworker +// META: script=/common/get-host-info.sub.js + +const host = get_host_info(); +const path = "/fetch/cross-origin-resource-policy/"; +const localBaseURL = host.HTTP_ORIGIN + path; +const sameSiteBaseURL = "http://" + host.ORIGINAL_HOST + ":" + host.HTTP_PORT2 + path; +const notSameSiteBaseURL = host.HTTP_NOTSAMESITE_ORIGIN + path; +const httpsBaseURL = host.HTTPS_ORIGIN + path; + +promise_test(async () => { + const response = await fetch("./resources/hello.py?corp=same-origin"); + assert_equals(await response.text(), "hello"); +}, "Same-origin fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header."); + +promise_test(async () => { + const response = await fetch("./resources/hello.py?corp=same-site"); + assert_equals(await response.text(), "hello"); +}, "Same-origin fetch with a 'Cross-Origin-Resource-Policy: same-site' response header."); + +promise_test(async (test) => { + const response = await fetch(notSameSiteBaseURL + "resources/hello.py?corp=same-origin"); + assert_equals(await response.text(), "hello"); +}, "Cross-origin cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header."); + +promise_test(async (test) => { + const response = await fetch(notSameSiteBaseURL + "resources/hello.py?corp=same-site"); + assert_equals(await response.text(), "hello"); +}, "Cross-origin cors fetch with a 'Cross-Origin-Resource-Policy: same-site' response header."); + +promise_test((test) => { + const remoteURL = notSameSiteBaseURL + "resources/hello.py?corp=same-origin"; + return promise_rejects_js(test, TypeError, fetch(remoteURL, { mode : "no-cors" })); +}, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header."); + +promise_test((test) => { + const remoteURL = notSameSiteBaseURL + "resources/hello.py?corp=same-site"; + return promise_rejects_js(test, TypeError, fetch(remoteURL, { mode: "no-cors" })); +}, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-site' response header."); + +promise_test((test) => { + const remoteURL = httpsBaseURL + "resources/hello.py?corp=same-site"; + return promise_rejects_js(test, TypeError, fetch(remoteURL, { mode: "no-cors" })); +}, "Cross-scheme (HTTP to HTTPS) no-cors fetch to a same-site URL with a 'Cross-Origin-Resource-Policy: same-site' response header."); + +promise_test((test) => { + const remoteURL = httpsBaseURL + "resources/hello.py?corp=same-origin"; + return promise_rejects_js(test, TypeError, fetch(remoteURL, { mode : "no-cors" })); +}, "Cross-origin no-cors fetch to a same-site URL with a 'Cross-Origin-Resource-Policy: same-origin' response header."); + +promise_test(async (test) => { + const remoteSameSiteURL = sameSiteBaseURL + "resources/hello.py?corp=same-site"; + + await fetch(remoteSameSiteURL, { mode: "no-cors" }); + + return promise_rejects_js(test, TypeError, fetch(sameSiteBaseURL + "resources/hello.py?corp=same-origin", { mode: "no-cors" })); +}, "Valid cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-site' response header."); + +promise_test((test) => { + const finalURL = notSameSiteBaseURL + "resources/hello.py?corp=same-origin"; + return promise_rejects_js(test, TypeError, fetch("resources/redirect.py?redirectTo=" + encodeURIComponent(finalURL), { mode: "no-cors" })); +}, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header after a redirection."); + +promise_test((test) => { + const finalURL = localBaseURL + "resources/hello.py?corp=same-origin"; + return fetch(notSameSiteBaseURL + "resources/redirect.py?redirectTo=" + encodeURIComponent(finalURL), { mode: "no-cors" }); +}, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header after a cross-origin redirection."); + +promise_test(async (test) => { + const finalURL = localBaseURL + "resources/hello.py?corp=same-origin"; + + await fetch(finalURL, { mode: "no-cors" }); + + return promise_rejects_js(test, TypeError, fetch(notSameSiteBaseURL + "resources/redirect.py?corp=same-origin&redirectTo=" + encodeURIComponent(finalURL), { mode: "no-cors" })); +}, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' redirect response header."); diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/fetch.https.any.js b/test/wpt/tests/fetch/cross-origin-resource-policy/fetch.https.any.js new file mode 100644 index 0000000..c9b5b75 --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/fetch.https.any.js @@ -0,0 +1,56 @@ +// META: timeout=long +// META: global=window,worker +// META: script=/common/get-host-info.sub.js + +const host = get_host_info(); +const path = "/fetch/cross-origin-resource-policy/"; +const localBaseURL = host.HTTPS_ORIGIN + path; +const notSameSiteBaseURL = host.HTTPS_NOTSAMESITE_ORIGIN + path; + +promise_test(async () => { + const response = await fetch("./resources/hello.py?corp=same-origin"); + assert_equals(await response.text(), "hello"); +}, "Same-origin fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header."); + +promise_test(async () => { + const response = await fetch("./resources/hello.py?corp=same-site"); + assert_equals(await response.text(), "hello"); +}, "Same-origin fetch with a 'Cross-Origin-Resource-Policy: same-site' response header."); + +promise_test(async (test) => { + const response = await fetch(notSameSiteBaseURL + "resources/hello.py?corp=same-origin"); + assert_equals(await response.text(), "hello"); +}, "Cross-origin cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header."); + +promise_test(async (test) => { + const response = await fetch(notSameSiteBaseURL + "resources/hello.py?corp=same-site"); + assert_equals(await response.text(), "hello"); +}, "Cross-origin cors fetch with a 'Cross-Origin-Resource-Policy: same-site' response header."); + +promise_test((test) => { + const remoteURL = notSameSiteBaseURL + "resources/hello.py?corp=same-origin"; + return promise_rejects_js(test, TypeError, fetch(remoteURL, { mode : "no-cors" })); +}, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header."); + +promise_test((test) => { + const remoteURL = notSameSiteBaseURL + "resources/hello.py?corp=same-site"; + return promise_rejects_js(test, TypeError, fetch(remoteURL, { mode: "no-cors" })); +}, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-site' response header."); + +promise_test((test) => { + const finalURL = notSameSiteBaseURL + "resources/hello.py?corp=same-origin"; + return promise_rejects_js(test, TypeError, fetch("resources/redirect.py?redirectTo=" + encodeURIComponent(finalURL), { mode: "no-cors" })); +}, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header after a redirection."); + +promise_test((test) => { + const finalURL = localBaseURL + "resources/hello.py?corp=same-origin"; + return fetch(notSameSiteBaseURL + "resources/redirect.py?redirectTo=" + encodeURIComponent(finalURL), { mode: "no-cors" }); +}, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header after a cross-origin redirection."); + +promise_test(async (test) => { + const finalURL = localBaseURL + "resources/hello.py?corp=same-origin"; + + await fetch(finalURL, { mode: "no-cors" }); + + return promise_rejects_js(test, TypeError, fetch(notSameSiteBaseURL + "resources/redirect.py?corp=same-origin&redirectTo=" + encodeURIComponent(finalURL), { mode: "no-cors" })); +}, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' redirect response header."); diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/iframe-loads.html b/test/wpt/tests/fetch/cross-origin-resource-policy/iframe-loads.html new file mode 100644 index 0000000..63902c3 --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/iframe-loads.html @@ -0,0 +1,46 @@ + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/image-loads.html b/test/wpt/tests/fetch/cross-origin-resource-policy/image-loads.html new file mode 100644 index 0000000..060b755 --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/image-loads.html @@ -0,0 +1,54 @@ + + + + + + + + +
+ + + diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/resources/green.png b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/green.png new file mode 100644 index 0000000..28a1faa Binary files /dev/null and b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/green.png differ diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/resources/hello.py b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/hello.py new file mode 100644 index 0000000..2b1cb84 --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/hello.py @@ -0,0 +1,6 @@ +def main(request, response): + headers = [(b"Cross-Origin-Resource-Policy", request.GET[b'corp'])] + if b'origin' in request.headers: + headers.append((b'Access-Control-Allow-Origin', request.headers[b'origin'])) + + return 200, headers, b"hello" diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/resources/iframe.py b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/iframe.py new file mode 100644 index 0000000..815ecf5 --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/iframe.py @@ -0,0 +1,5 @@ +def main(request, response): + headers = [(b"Content-Type", b"text/html"), + (b"Cross-Origin-Resource-Policy", request.GET[b'corp'])] + return 200, headers, b"

The iframe

" + diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/resources/iframeFetch.html b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/iframeFetch.html new file mode 100644 index 0000000..2571858 --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/iframeFetch.html @@ -0,0 +1,19 @@ + + + + + + +

The iframe making a same origin fetch call.

+ + diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/resources/image.py b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/image.py new file mode 100644 index 0000000..2a779cf --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/image.py @@ -0,0 +1,22 @@ +import os.path + +from wptserve.utils import isomorphic_decode + +def main(request, response): + type = request.GET.first(b"type", None) + + body = open(os.path.join(os.path.dirname(isomorphic_decode(__file__)), u"green.png"), u"rb").read() + + response.add_required_headers = False + response.writer.write_status(200) + + if b'corp' in request.GET: + response.writer.write_header(b"cross-origin-resource-policy", request.GET[b'corp']) + if b'acao' in request.GET: + response.writer.write_header(b"access-control-allow-origin", request.GET[b'acao']) + response.writer.write_header(b"content-length", len(body)) + if(type != None): + response.writer.write_header(b"content-type", type) + response.writer.end_headers() + + response.writer.write(body) diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/resources/redirect.py b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/redirect.py new file mode 100644 index 0000000..0dad4dd --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/redirect.py @@ -0,0 +1,6 @@ +def main(request, response): + headers = [(b"Location", request.GET[b'redirectTo'])] + if b'corp' in request.GET: + headers.append((b'Cross-Origin-Resource-Policy', request.GET[b'corp'])) + + return 302, headers, b"" diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/resources/script.py b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/script.py new file mode 100644 index 0000000..58f8d34 --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/resources/script.py @@ -0,0 +1,6 @@ +def main(request, response): + headers = [(b"Cross-Origin-Resource-Policy", request.GET[b'corp'])] + if b'origin' in request.headers: + headers.append((b'Access-Control-Allow-Origin', request.headers[b'origin'])) + + return 200, headers, b"" diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/scheme-restriction.any.js b/test/wpt/tests/fetch/cross-origin-resource-policy/scheme-restriction.any.js new file mode 100644 index 0000000..8f63381 --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/scheme-restriction.any.js @@ -0,0 +1,7 @@ +// META: script=/common/get-host-info.sub.js + +promise_test(t => { + return promise_rejects_js(t, + TypeError, + fetch(get_host_info().HTTPS_REMOTE_ORIGIN + "/fetch/cross-origin-resource-policy/resources/hello.py?corp=same-site", { mode: "no-cors" })); +}, "Cross-Origin-Resource-Policy: same-site blocks retrieving HTTPS from HTTP"); diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/scheme-restriction.https.window.js b/test/wpt/tests/fetch/cross-origin-resource-policy/scheme-restriction.https.window.js new file mode 100644 index 0000000..4c74571 --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/scheme-restriction.https.window.js @@ -0,0 +1,13 @@ +// META: script=/common/get-host-info.sub.js + +promise_test(t => { + const img = new Image(); + img.src = get_host_info().HTTP_REMOTE_ORIGIN + "/fetch/cross-origin-resource-policy/resources/image.py?corp=same-site"; + return new Promise((resolve, reject) => { + img.onload = resolve; + img.onerror = reject; + document.body.appendChild(img); + }).finally(() => { + img.remove(); + }); +}, "Cross-Origin-Resource-Policy does not block Mixed Content "); diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/script-loads.html b/test/wpt/tests/fetch/cross-origin-resource-policy/script-loads.html new file mode 100644 index 0000000..a9690fc --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/script-loads.html @@ -0,0 +1,52 @@ + + + + + + + + +
+ + + diff --git a/test/wpt/tests/fetch/cross-origin-resource-policy/syntax.any.js b/test/wpt/tests/fetch/cross-origin-resource-policy/syntax.any.js new file mode 100644 index 0000000..dc87497 --- /dev/null +++ b/test/wpt/tests/fetch/cross-origin-resource-policy/syntax.any.js @@ -0,0 +1,19 @@ +// META: script=/common/get-host-info.sub.js + +const crossOriginURL = get_host_info().HTTP_REMOTE_ORIGIN + "/fetch/cross-origin-resource-policy/resources/hello.py?corp="; + +[ + "same", + "same, same-origin", + "SAME-ORIGIN", + "Same-Origin", + "same-origin, <>", + "same-origin, same-origin", + "https://www.example.com", // See https://github.com/whatwg/fetch/issues/760 +].forEach(incorrectHeaderValue => { + // Note: an incorrect value results in a successful load, so this test is only meaningful in + // implementations with support for the header. + promise_test(t => { + return fetch(crossOriginURL + encodeURIComponent(incorrectHeaderValue), { mode: "no-cors" }); + }, "Parsing Cross-Origin-Resource-Policy: " + incorrectHeaderValue); +}); diff --git a/test/wpt/tests/fetch/data-urls/README.md b/test/wpt/tests/fetch/data-urls/README.md new file mode 100644 index 0000000..1ce5b18 --- /dev/null +++ b/test/wpt/tests/fetch/data-urls/README.md @@ -0,0 +1,11 @@ +## data: URLs + +`resources/data-urls.json` contains `data:` URL tests. The tests are encoded as a JSON array. Each value in the array is an array of two or three values. The first value describes the input, the second value describes the expected MIME type, null if the input is expected to fail somehow, or the empty string if the expected value is `text/plain;charset=US-ASCII`. The third value, if present, describes the expected body as an array of integers representing bytes. + +These tests are used for `data:` URLs in this directory (see `processing.any.js`). + +## Forgiving-base64 decode + +`resources/base64.json` contains [forgiving-base64 decode](https://infra.spec.whatwg.org/#forgiving-base64-decode) tests. The tests are encoded as a JSON array. Each value in the array is an array of two values. The first value describes the input, the second value describes the output as an array of integers representing bytes or null if the input cannot be decoded. + +These tests are used for `data:` URLs in this directory (see `base64.any.js`) and `window.atob()` in `../../html/webappapis/atob/base64.html`. diff --git a/test/wpt/tests/fetch/data-urls/base64.any.js b/test/wpt/tests/fetch/data-urls/base64.any.js new file mode 100644 index 0000000..83f34db --- /dev/null +++ b/test/wpt/tests/fetch/data-urls/base64.any.js @@ -0,0 +1,18 @@ +// META: global=window,worker + +promise_test(() => fetch("resources/base64.json").then(res => res.json()).then(runBase64Tests), "Setup."); +function runBase64Tests(tests) { + for(let i = 0; i < tests.length; i++) { + const input = tests[i][0], + output = tests[i][1], + dataURL = "data:;base64," + input; + promise_test(t => { + if(output === null) { + return promise_rejects_js(t, TypeError, fetch(dataURL)); + } + return fetch(dataURL).then(res => res.arrayBuffer()).then(body => { + assert_array_equals(new Uint8Array(body), output); + }); + }, "data: URL base64 handling: " + format_value(input)); + } +} diff --git a/test/wpt/tests/fetch/data-urls/navigate.window.js b/test/wpt/tests/fetch/data-urls/navigate.window.js new file mode 100644 index 0000000..b532a00 --- /dev/null +++ b/test/wpt/tests/fetch/data-urls/navigate.window.js @@ -0,0 +1,75 @@ +// META: timeout=long +// +// Test some edge cases around navigation to data: URLs to ensure they use the same code path + +[ + { + input: "data:text/html,", + result: 1, + name: "Nothing fancy", + }, + { + input: "data:text/html;base64,PHNjcmlwdD5wYXJlbnQucG9zdE1lc3NhZ2UoMiwgJyonKTwvc2NyaXB0Pg==", + result: 2, + name: "base64", + }, + { + input: "data:text/html;base64,PHNjcmlwdD5wYXJlbnQucG9zdE1lc3NhZ2UoNCwgJyonKTwvc2NyaXB0Pr+/", + result: 4, + name: "base64 with code points that differ from base64url" + }, + { + input: "data:text/html;base64,PHNjcml%09%20%20%0A%0C%0DwdD5wYXJlbnQucG9zdE1lc3NhZ2UoNiwgJyonKTwvc2NyaXB0Pg==", + result: 6, + name: "ASCII whitespace in the input is removed" + } +].forEach(({ input, result, name }) => { + // Use promise_test so they go sequentially + promise_test(async t => { + const event = await new Promise((resolve, reject) => { + self.addEventListener("message", t.step_func(resolve), { once: true }); + const frame = document.body.appendChild(document.createElement("iframe")); + t.add_cleanup(() => frame.remove()); + + // The assumption is that postMessage() is quicker + t.step_timeout(reject, 500); + frame.src = input; + }); + assert_equals(event.data, result); + }, name); +}); + +// Failure cases +[ + { + input: "data:text/html;base64,PHNjcmlwdD5wYXJlbnQucG9zdE1lc3NhZ2UoMywgJyonKTwvc2NyaXB0Pg=", + name: "base64 with incorrect padding", + }, + { + input: "data:text/html;base64,PHNjcmlwdD5wYXJlbnQucG9zdE1lc3NhZ2UoNSwgJyonKTwvc2NyaXB0Pr-_", + name: "base64url is not supported" + }, + { + input: "data:text/html;base64,%0BPHNjcmlwdD5wYXJlbnQucG9zdE1lc3NhZ2UoNywgJyonKTwvc2NyaXB0Pg==", + name: "Vertical tab in the input leads to an error" + } +].forEach(({ input, name }) => { + // Continue to use promise_test so they go sequentially + promise_test(async t => { + const event = await new Promise((resolve, reject) => { + self.addEventListener("message", t.step_func(reject), { once: true }); + const frame = document.body.appendChild(document.createElement("iframe")); + t.add_cleanup(() => frame.remove()); + + // The assumption is that postMessage() is quicker + t.step_timeout(resolve, 500); + frame.src = input; + }); + }, name); +}); + +// I found some of the interesting code point cases above through brute force: +// +// for (i = 0; i < 256; i++) { +// w(btoa("This is a document." diff --git a/test/wpt/tests/fetch/h1-parsing/resources/message.py b/test/wpt/tests/fetch/h1-parsing/resources/message.py new file mode 100644 index 0000000..640080c --- /dev/null +++ b/test/wpt/tests/fetch/h1-parsing/resources/message.py @@ -0,0 +1,3 @@ +def main(request, response): + response.writer.write(request.GET.first(b"message")) + response.close_connection = True diff --git a/test/wpt/tests/fetch/h1-parsing/resources/script-with-0x00-in-header.py b/test/wpt/tests/fetch/h1-parsing/resources/script-with-0x00-in-header.py new file mode 100644 index 0000000..39f58d8 --- /dev/null +++ b/test/wpt/tests/fetch/h1-parsing/resources/script-with-0x00-in-header.py @@ -0,0 +1,4 @@ +def main(request, response): + response.headers.set(b"Content-Type", b"text/javascript") + response.headers.set(b"Custom", b"\0") + return b"var thisIsJavaScript = 0" diff --git a/test/wpt/tests/fetch/h1-parsing/resources/status-code.py b/test/wpt/tests/fetch/h1-parsing/resources/status-code.py new file mode 100644 index 0000000..5421893 --- /dev/null +++ b/test/wpt/tests/fetch/h1-parsing/resources/status-code.py @@ -0,0 +1,6 @@ +def main(request, response): + output = b"HTTP/1.1 " + output += request.GET.first(b"input") + output += b"\nheader-parsing: is sad\n" + response.writer.write(output) + response.close_connection = True diff --git a/test/wpt/tests/fetch/h1-parsing/status-code.window.js b/test/wpt/tests/fetch/h1-parsing/status-code.window.js new file mode 100644 index 0000000..5776cf4 --- /dev/null +++ b/test/wpt/tests/fetch/h1-parsing/status-code.window.js @@ -0,0 +1,98 @@ +[ + { + input: "", + expected: null + }, + { + input: "BLAH", + expected: null + }, + { + input: "0 OK", + expected: { + status: 0, + statusText: "OK" + } + }, + { + input: "1 OK", + expected: { + status: 1, + statusText: "OK" + } + }, + { + input: "99 NOT OK", + expected: { + status: 99, + statusText: "NOT OK" + } + }, + { + input: "077 77", + expected: { + status: 77, + statusText: "77" + } + }, + { + input: "099 HELLO", + expected: { + status: 99, + statusText: "HELLO" + } + }, + { + input: "200", + expected: { + status: 200, + statusText: "" + } + }, + { + input: "999 DOES IT MATTER", + expected: { + status: 999, + statusText: "DOES IT MATTER" + } + }, + { + input: "1000 BOO", + expected: null + }, + { + input: "0200 BOO", + expected: null + }, + { + input: "65736 NOT 200 OR SOME SUCH", + expected: null + }, + { + input: "131072 HI", + expected: null + }, + { + input: "-200 TEST", + expected: null + }, + { + input: "0xA", + expected: null + }, + { + input: "C8", + expected: null + } +].forEach(({ description, input, expected }) => { + promise_test(async t => { + if (expected !== null) { + const response = await fetch("resources/status-code.py?input=" + input); + assert_equals(response.status, expected.status); + assert_equals(response.statusText, expected.statusText); + assert_equals(response.headers.get("header-parsing"), "is sad"); + } else { + await promise_rejects_js(t, TypeError, fetch("resources/status-code.py?input=" + input)); + } + }, `HTTP/1.1 ${input} ${expected === null ? "(network error)" : ""}`); +}); diff --git a/test/wpt/tests/fetch/http-cache/304-update.any.js b/test/wpt/tests/fetch/http-cache/304-update.any.js new file mode 100644 index 0000000..15484f0 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/304-update.any.js @@ -0,0 +1,146 @@ +// META: global=window,worker +// META: title=HTTP Cache - 304 Updates +// META: timeout=long +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=http-cache.js + +var tests = [ + { + name: "HTTP cache updates returned headers from a Last-Modified 304", + requests: [ + { + response_headers: [ + ["Expires", -5000], + ["Last-Modified", -3000], + ["Test-Header", "A"] + ] + }, + { + response_headers: [ + ["Expires", -3000], + ["Last-Modified", -3000], + ["Test-Header", "B"] + ], + expected_type: "lm_validated", + expected_response_headers: [ + ["Test-Header", "B"] + ] + } + ] + }, + { + name: "HTTP cache updates stored headers from a Last-Modified 304", + requests: [ + { + response_headers: [ + ["Expires", -5000], + ["Last-Modified", -3000], + ["Test-Header", "A"] + ] + }, + { + response_headers: [ + ["Expires", 3000], + ["Last-Modified", -3000], + ["Test-Header", "B"] + ], + expected_type: "lm_validated", + expected_response_headers: [ + ["Test-Header", "B"] + ], + pause_after: true + }, + { + expected_type: "cached", + expected_response_headers: [ + ["Test-Header", "B"] + ] + } + ] + }, + { + name: "HTTP cache updates returned headers from a ETag 304", + requests: [ + { + response_headers: [ + ["Expires", -5000], + ["ETag", "ABC"], + ["Test-Header", "A"] + ] + }, + { + response_headers: [ + ["Expires", -3000], + ["ETag", "ABC"], + ["Test-Header", "B"] + ], + expected_type: "etag_validated", + expected_response_headers: [ + ["Test-Header", "B"] + ] + } + ] + }, + { + name: "HTTP cache updates stored headers from a ETag 304", + requests: [ + { + response_headers: [ + ["Expires", -5000], + ["ETag", "DEF"], + ["Test-Header", "A"] + ] + }, + { + response_headers: [ + ["Expires", 3000], + ["ETag", "DEF"], + ["Test-Header", "B"] + ], + expected_type: "etag_validated", + expected_response_headers: [ + ["Test-Header", "B"] + ], + pause_after: true + }, + { + expected_type: "cached", + expected_response_headers: [ + ["Test-Header", "B"] + ] + } + ] + }, + { + name: "Content-* header", + requests: [ + { + response_headers: [ + ["Expires", -5000], + ["ETag", "GHI"], + ["Content-Test-Header", "A"] + ] + }, + { + response_headers: [ + ["Expires", 3000], + ["ETag", "GHI"], + ["Content-Test-Header", "B"] + ], + expected_type: "etag_validated", + expected_response_headers: [ + ["Content-Test-Header", "B"] + ], + pause_after: true + }, + { + expected_type: "cached", + expected_response_headers: [ + ["Content-Test-Header", "B"] + ] + } + ] + }, +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/http-cache/README.md b/test/wpt/tests/fetch/http-cache/README.md new file mode 100644 index 0000000..512c422 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/README.md @@ -0,0 +1,72 @@ +## HTTP Caching Tests + +These tests cover HTTP-specified behaviours for caches, primarily from +[RFC9111](https://www.rfc-editor.org/rfc/rfc9111.html), but as seen through the +lens of Fetch. + +A few notes: + +* By its nature, [caching is entirely optional]( + https://www.rfc-editor.org/rfc/rfc9111.html#section-2-2); + some tests expecting a response to be + cached might fail because the client chose not to cache it, or chose to + race the cache with a network request. + +* Likewise, some tests might fail because there is a separate document-level + cache that's not well defined; see [this + issue](https://github.com/whatwg/fetch/issues/354). + +* [Partial content tests](partial.any.js) (a.k.a. Range requests) are not specified + in Fetch; tests are included here for interest only. + +* Some browser caches will behave differently when reloading / + shift-reloading, despite the `cache mode` staying the same. + +* [cache-tests.fyi](https://cache-tests.fyi/) is another test suite of HTTP caching + which also caters to server/CDN implementations. + +## Test Format + +Each test run gets its own URL and randomized content and operates independently. + +Each test is an an array of objects, with the following members: + +- `name` - The name of the test. +- `requests` - a list of request objects (see below). + +Possible members of a request object: + +- template - A template object for the request, by name. +- request_method - A string containing the HTTP method to be used. +- request_headers - An array of `[header_name_string, header_value_string]` arrays to + emit in the request. +- request_body - A string to use as the request body. +- mode - The mode string to pass to `fetch()`. +- credentials - The credentials string to pass to `fetch()`. +- cache - The cache string to pass to `fetch()`. +- pause_after - Boolean controlling a 3-second pause after the request completes. +- response_status - A `[number, string]` array containing the HTTP status code + and phrase to return. +- response_headers - An array of `[header_name_string, header_value_string]` arrays to + emit in the response. These values will also be checked like + expected_response_headers, unless there is a third value that is + `false`. See below for special handling considerations. +- response_body - String to send as the response body. If not set, it will contain + the test identifier. +- expected_type - One of `["cached", "not_cached", "lm_validate", "etag_validate", "error"]` +- expected_status - A number representing a HTTP status code to check the response for. + If not set, the value of `response_status[0]` will be used; if that + is not set, 200 will be used. +- expected_request_headers - An array of `[header_name_string, header_value_string]` representing + headers to check the request for. +- expected_response_headers - An array of `[header_name_string, header_value_string]` representing + headers to check the response for. See also response_headers. +- expected_response_text - A string to check the response body against. If not present, `response_body` will be checked if present and non-null; otherwise the response body will be checked for the test uuid (unless the status code disallows a body). Set to `null` to disable all response body checking. + +Some headers in `response_headers` are treated specially: + +* For date-carrying headers, if the value is a number, it will be interpreted as a delta to the time of the first request at the server. +* For URL-carrying headers, the value will be appended as a query parameter for `target`. + +See the source for exact details. + diff --git a/test/wpt/tests/fetch/http-cache/basic-auth-cache-test-ref.html b/test/wpt/tests/fetch/http-cache/basic-auth-cache-test-ref.html new file mode 100644 index 0000000..905facd --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/basic-auth-cache-test-ref.html @@ -0,0 +1,6 @@ + + + + + + diff --git a/test/wpt/tests/fetch/http-cache/basic-auth-cache-test.html b/test/wpt/tests/fetch/http-cache/basic-auth-cache-test.html new file mode 100644 index 0000000..a8979ba --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/basic-auth-cache-test.html @@ -0,0 +1,27 @@ + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/http-cache/cache-mode.any.js b/test/wpt/tests/fetch/http-cache/cache-mode.any.js new file mode 100644 index 0000000..8f406d5 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/cache-mode.any.js @@ -0,0 +1,61 @@ +// META: global=window,worker +// META: title=Fetch - Cache Mode +// META: timeout=long +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=http-cache.js + +var tests = [ + { + name: "Fetch sends Cache-Control: max-age=0 when cache mode is no-cache", + requests: [ + { + cache: "no-cache", + expected_request_headers: [['cache-control', 'max-age=0']] + } + ] + }, + { + name: "Fetch doesn't touch Cache-Control when cache mode is no-cache and Cache-Control is already present", + requests: [ + { + cache: "no-cache", + request_headers: [['cache-control', 'foo']], + expected_request_headers: [['cache-control', 'foo']] + } + ] + }, + { + name: "Fetch sends Cache-Control: no-cache and Pragma: no-cache when cache mode is no-store", + requests: [ + { + cache: "no-store", + expected_request_headers: [ + ['cache-control', 'no-cache'], + ['pragma', 'no-cache'] + ] + } + ] + }, + { + name: "Fetch doesn't touch Cache-Control when cache mode is no-store and Cache-Control is already present", + requests: [ + { + cache: "no-store", + request_headers: [['cache-control', 'foo']], + expected_request_headers: [['cache-control', 'foo']] + } + ] + }, + { + name: "Fetch doesn't touch Pragma when cache mode is no-store and Pragma is already present", + requests: [ + { + cache: "no-store", + request_headers: [['pragma', 'foo']], + expected_request_headers: [['pragma', 'foo']] + } + ] + } +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/http-cache/cc-request.any.js b/test/wpt/tests/fetch/http-cache/cc-request.any.js new file mode 100644 index 0000000..d556566 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/cc-request.any.js @@ -0,0 +1,202 @@ +// META: global=window,worker +// META: title=HTTP Cache - Cache-Control Request Directives +// META: timeout=long +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=http-cache.js + +var tests = [ + { + name: "HTTP cache doesn't use aged but fresh response when request contains Cache-Control: max-age=0", + requests: [ + { + template: "fresh", + pause_after: true + }, + { + request_headers: [ + ["Cache-Control", "max-age=0"] + ], + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache doesn't use aged but fresh response when request contains Cache-Control: max-age=1", + requests: [ + { + template: "fresh", + pause_after: true + }, + { + request_headers: [ + ["Cache-Control", "max-age=1"] + ], + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache doesn't use fresh response with Age header when request contains Cache-Control: max-age that is greater than remaining freshness", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"], + ["Age", "1800"] + ] + }, + { + request_headers: [ + ["Cache-Control", "max-age=600"] + ], + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache does use aged stale response when request contains Cache-Control: max-stale that permits its use", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=1"] + ], + pause_after: true + }, + { + request_headers: [ + ["Cache-Control", "max-stale=1000"] + ], + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache does reuse stale response with Age header when request contains Cache-Control: max-stale that permits its use", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=1500"], + ["Age", "2000"] + ] + }, + { + request_headers: [ + ["Cache-Control", "max-stale=1000"] + ], + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache doesn't reuse fresh response when request contains Cache-Control: min-fresh that wants it fresher", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=1500"] + ] + }, + { + request_headers: [ + ["Cache-Control", "min-fresh=2000"] + ], + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache doesn't reuse fresh response with Age header when request contains Cache-Control: min-fresh that wants it fresher", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=1500"], + ["Age", "1000"] + ] + }, + { + request_headers: [ + ["Cache-Control", "min-fresh=1000"] + ], + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache doesn't reuse fresh response when request contains Cache-Control: no-cache", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"] + ] + }, + { + request_headers: [ + ["Cache-Control", "no-cache"] + ], + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache validates fresh response with Last-Modified when request contains Cache-Control: no-cache", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"], + ["Last-Modified", -10000] + ] + }, + { + request_headers: [ + ["Cache-Control", "no-cache"] + ], + expected_type: "lm_validate" + } + ] + }, + { + name: "HTTP cache validates fresh response with ETag when request contains Cache-Control: no-cache", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"], + ["ETag", http_content("abc")] + ] + }, + { + request_headers: [ + ["Cache-Control", "no-cache"] + ], + expected_type: "etag_validate" + } + ] + }, + { + name: "HTTP cache doesn't reuse fresh response when request contains Cache-Control: no-store", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"] + ] + }, + { + request_headers: [ + ["Cache-Control", "no-store"] + ], + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache generates 504 status code when nothing is in cache and request contains Cache-Control: only-if-cached", + requests: [ + { + request_headers: [ + ["Cache-Control", "only-if-cached"] + ], + expected_status: 504, + expected_response_text: null + } + ] + } +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/http-cache/credentials.tentative.any.js b/test/wpt/tests/fetch/http-cache/credentials.tentative.any.js new file mode 100644 index 0000000..3177092 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/credentials.tentative.any.js @@ -0,0 +1,62 @@ +// META: global=window,worker +// META: title=HTTP Cache - Content +// META: timeout=long +// META: script=/common/utils.js +// META: script=http-cache.js + +// This is a tentative test. +// Firefox behavior is used as expectations. +// +// whatwg/fetch issue: +// https://github.com/whatwg/fetch/issues/1253 +// +// Chrome design doc: +// https://docs.google.com/document/d/1lvbiy4n-GM5I56Ncw304sgvY5Td32R6KHitjRXvkZ6U/edit# + +const request_cacheable = { + request_headers: [], + response_headers: [ + ['Cache-Control', 'max-age=3600'], + ], + // TODO(arthursonzogni): The behavior is tested only for same-origin requests. + // It must behave similarly for cross-site and cross-origin requests. The + // problems is the http-cache.js infrastructure returns the + // "Server-Request-Count" as HTTP response headers, which aren't readable for + // CORS requests. + base_url: location.href.replace(/\/[^\/]*$/, '/'), +}; + +const request_credentialled = { ...request_cacheable, credentials: 'include', }; +const request_anonymous = { ...request_cacheable, credentials: 'omit', }; + +const responseIndex = count => { + return { + expected_response_headers: [ + ['Server-Request-Count', count.toString()], + ], + } +}; + +var tests = [ + { + name: 'same-origin: 2xAnonymous, 2xCredentialled, 1xAnonymous', + requests: [ + { ...request_anonymous , ...responseIndex(1)} , + { ...request_anonymous , ...responseIndex(1)} , + { ...request_credentialled , ...responseIndex(2)} , + { ...request_credentialled , ...responseIndex(2)} , + { ...request_anonymous , ...responseIndex(1)} , + ] + }, + { + name: 'same-origin: 2xCredentialled, 2xAnonymous, 1xCredentialled', + requests: [ + { ...request_credentialled , ...responseIndex(1)} , + { ...request_credentialled , ...responseIndex(1)} , + { ...request_anonymous , ...responseIndex(2)} , + { ...request_anonymous , ...responseIndex(2)} , + { ...request_credentialled , ...responseIndex(1)} , + ] + }, +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/http-cache/freshness.any.js b/test/wpt/tests/fetch/http-cache/freshness.any.js new file mode 100644 index 0000000..6b97c82 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/freshness.any.js @@ -0,0 +1,215 @@ +// META: global=window,worker +// META: title=HTTP Cache - Freshness +// META: timeout=long +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=http-cache.js + +var tests = [ + // response directives + { + name: "HTTP cache reuses a response with a future Expires", + requests: [ + { + response_headers: [ + ["Expires", (30 * 24 * 60 * 60)] + ] + }, + { + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache does not reuse a response with a past Expires", + requests: [ + { + response_headers: [ + ["Expires", (-30 * 24 * 60 * 60)] + ] + }, + { + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache does not reuse a response with a present Expires", + requests: [ + { + response_headers: [ + ["Expires", 0] + ] + }, + { + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache does not reuse a response with an invalid Expires", + requests: [ + { + response_headers: [ + ["Expires", "0"] + ] + }, + { + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache reuses a response with positive Cache-Control: max-age", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"] + ] + }, + { + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache does not reuse a response with Cache-Control: max-age=0", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=0"] + ] + }, + { + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache reuses a response with positive Cache-Control: max-age and a past Expires", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"], + ["Expires", -10000] + ] + }, + { + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache reuses a response with positive Cache-Control: max-age and an invalid Expires", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"], + ["Expires", "0"] + ] + }, + { + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache does not reuse a response with Cache-Control: max-age=0 and a future Expires", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=0"], + ["Expires", 10000] + ] + }, + { + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache does not prefer Cache-Control: s-maxage over Cache-Control: max-age", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=1, s-maxage=3600"] + ], + pause_after: true, + }, + { + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache does not reuse a response when the Age header is greater than its freshness lifetime", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"], + ["Age", "12000"] + ], + }, + { + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache does not store a response with Cache-Control: no-store", + requests: [ + { + response_headers: [ + ["Cache-Control", "no-store"] + ] + }, + { + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache does not store a response with Cache-Control: no-store, even with max-age and Expires", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=10000, no-store"], + ["Expires", 10000] + ] + }, + { + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache stores a response with Cache-Control: no-cache, but revalidates upon use", + requests: [ + { + response_headers: [ + ["Cache-Control", "no-cache"], + ["ETag", "abcd"] + ] + }, + { + expected_type: "etag_validated" + } + ] + }, + { + name: "HTTP cache stores a response with Cache-Control: no-cache, but revalidates upon use, even with max-age and Expires", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=10000, no-cache"], + ["Expires", 10000], + ["ETag", "abcd"] + ] + }, + { + expected_type: "etag_validated" + } + ] + }, +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/http-cache/heuristic.any.js b/test/wpt/tests/fetch/http-cache/heuristic.any.js new file mode 100644 index 0000000..d846131 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/heuristic.any.js @@ -0,0 +1,93 @@ +// META: global=window,worker +// META: title=HTTP Cache - Heuristic Freshness +// META: timeout=long +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=http-cache.js + +var tests = [ + { + name: "HTTP cache reuses an unknown response with Last-Modified based upon heuristic freshness when Cache-Control: public is present", + requests: [ + { + response_status: [299, "Whatever"], + response_headers: [ + ["Last-Modified", (-3 * 100)], + ["Cache-Control", "public"] + ], + }, + { + expected_type: "cached", + response_status: [299, "Whatever"] + } + ] + }, + { + name: "HTTP cache does not reuse an unknown response with Last-Modified based upon heuristic freshness when Cache-Control: public is not present", + requests: [ + { + response_status: [299, "Whatever"], + response_headers: [ + ["Last-Modified", (-3 * 100)] + ], + }, + { + expected_type: "not_cached" + } + ] + } +]; + +function check_status(status) { + var succeed = status[0]; + var code = status[1]; + var phrase = status[2]; + var body = status[3]; + if (body === undefined) { + body = http_content(code); + } + var expected_type = "not_cached"; + var desired = "does not use" + if (succeed === true) { + expected_type = "cached"; + desired = "reuses"; + } + tests.push( + { + name: "HTTP cache " + desired + " a " + code + " " + phrase + " response with Last-Modified based upon heuristic freshness", + requests: [ + { + response_status: [code, phrase], + response_headers: [ + ["Last-Modified", (-3 * 100)] + ], + response_body: body + }, + { + expected_type: expected_type, + response_status: [code, phrase], + response_body: body + } + ] + } + ) +} +[ + [true, 200, "OK"], + [true, 203, "Non-Authoritative Information"], + [true, 204, "No Content", ""], + [true, 404, "Not Found"], + [true, 405, "Method Not Allowed"], + [true, 410, "Gone"], + [true, 414, "URI Too Long"], + [true, 501, "Not Implemented"] +].forEach(check_status); +[ + [false, 201, "Created"], + [false, 202, "Accepted"], + [false, 403, "Forbidden"], + [false, 502, "Bad Gateway"], + [false, 503, "Service Unavailable"], + [false, 504, "Gateway Timeout"], +].forEach(check_status); +run_tests(tests); diff --git a/test/wpt/tests/fetch/http-cache/http-cache.js b/test/wpt/tests/fetch/http-cache/http-cache.js new file mode 100644 index 0000000..19f1ca9 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/http-cache.js @@ -0,0 +1,274 @@ +/* global btoa fetch token promise_test step_timeout */ +/* global assert_equals assert_true assert_own_property assert_throws_js assert_less_than */ + +const templates = { + 'fresh': { + 'response_headers': [ + ['Expires', 100000], + ['Last-Modified', 0] + ] + }, + 'stale': { + 'response_headers': [ + ['Expires', -5000], + ['Last-Modified', -100000] + ] + }, + 'lcl_response': { + 'response_headers': [ + ['Location', 'location_target'], + ['Content-Location', 'content_location_target'] + ] + }, + 'location': { + 'query_arg': 'location_target', + 'response_headers': [ + ['Expires', 100000], + ['Last-Modified', 0] + ] + }, + 'content_location': { + 'query_arg': 'content_location_target', + 'response_headers': [ + ['Expires', 100000], + ['Last-Modified', 0] + ] + } +} + +const noBodyStatus = new Set([204, 304]) + +function makeTest (test) { + return function () { + var uuid = token() + var requests = expandTemplates(test) + var fetchFunctions = makeFetchFunctions(requests, uuid) + return runTest(fetchFunctions, requests, uuid) + } +} + +function makeFetchFunctions(requests, uuid) { + var fetchFunctions = [] + for (let i = 0; i < requests.length; ++i) { + fetchFunctions.push({ + code: function (idx) { + var config = requests[idx] + var url = makeTestUrl(uuid, config) + var init = fetchInit(requests, config) + return fetch(url, init) + .then(makeCheckResponse(idx, config)) + .then(makeCheckResponseBody(config, uuid), function (reason) { + if ('expected_type' in config && config.expected_type === 'error') { + assert_throws_js(TypeError, function () { throw reason }) + } else { + throw reason + } + }) + }, + pauseAfter: 'pause_after' in requests[i] + }) + } + return fetchFunctions +} + +function runTest(fetchFunctions, requests, uuid) { + var idx = 0 + function runNextStep () { + if (fetchFunctions.length) { + var nextFetchFunction = fetchFunctions.shift() + if (nextFetchFunction.pauseAfter === true) { + return nextFetchFunction.code(idx++) + .then(pause) + .then(runNextStep) + } else { + return nextFetchFunction.code(idx++) + .then(runNextStep) + } + } else { + return Promise.resolve() + } + } + + return runNextStep() + .then(function () { + return getServerState(uuid) + }).then(function (testState) { + checkRequests(requests, testState) + return Promise.resolve() + }) +} + +function expandTemplates (test) { + var rawRequests = test.requests + var requests = [] + for (let i = 0; i < rawRequests.length; i++) { + var request = rawRequests[i] + request.name = test.name + if ('template' in request) { + var template = templates[request['template']] + for (let member in template) { + if (!request.hasOwnProperty(member)) { + request[member] = template[member] + } + } + } + requests.push(request) + } + return requests +} + +function fetchInit (requests, config) { + var init = { + 'headers': [] + } + if ('request_method' in config) init.method = config['request_method'] + // Note: init.headers must be a copy of config['request_headers'] array, + // because new elements are added later. + if ('request_headers' in config) init.headers = [...config['request_headers']]; + if ('name' in config) init.headers.push(['Test-Name', config.name]) + if ('request_body' in config) init.body = config['request_body'] + if ('mode' in config) init.mode = config['mode'] + if ('credentials' in config) init.credentials = config['credentials'] + if ('cache' in config) init.cache = config['cache'] + init.headers.push(['Test-Requests', btoa(JSON.stringify(requests))]) + return init +} + +function makeCheckResponse (idx, config) { + return function checkResponse (response) { + var reqNum = idx + 1 + var resNum = parseInt(response.headers.get('Server-Request-Count')) + if ('expected_type' in config) { + if (config.expected_type === 'error') { + assert_true(false, `Request ${reqNum} doesn't throw an error`) + return response.text() + } + if (config.expected_type === 'cached') { + assert_less_than(resNum, reqNum, `Response ${reqNum} does not come from cache`) + } + if (config.expected_type === 'not_cached') { + assert_equals(resNum, reqNum, `Response ${reqNum} comes from cache`) + } + } + if ('expected_status' in config) { + assert_equals(response.status, config.expected_status, + `Response ${reqNum} status is ${response.status}, not ${config.expected_status}`) + } else if ('response_status' in config) { + assert_equals(response.status, config.response_status[0], + `Response ${reqNum} status is ${response.status}, not ${config.response_status[0]}`) + } else { + assert_equals(response.status, 200, `Response ${reqNum} status is ${response.status}, not 200`) + } + if ('response_headers' in config) { + config.response_headers.forEach(function (header) { + if (header.len < 3 || header[2] === true) { + assert_equals(response.headers.get(header[0]), header[1], + `Response ${reqNum} header ${header[0]} is "${response.headers.get(header[0])}", not "${header[1]}"`) + } + }) + } + if ('expected_response_headers' in config) { + config.expected_response_headers.forEach(function (header) { + assert_equals(response.headers.get(header[0]), header[1], + `Response ${reqNum} header ${header[0]} is "${response.headers.get(header[0])}", not "${header[1]}"`) + }) + } + return response.text() + } +} + +function makeCheckResponseBody (config, uuid) { + return function checkResponseBody (resBody) { + var statusCode = 200 + if ('response_status' in config) { + statusCode = config.response_status[0] + } + if ('expected_response_text' in config) { + if (config.expected_response_text !== null) { + assert_equals(resBody, config.expected_response_text, + `Response body is "${resBody}", not expected "${config.expected_response_text}"`) + } + } else if ('response_body' in config && config.response_body !== null) { + assert_equals(resBody, config.response_body, + `Response body is "${resBody}", not sent "${config.response_body}"`) + } else if (!noBodyStatus.has(statusCode)) { + assert_equals(resBody, uuid, `Response body is "${resBody}", not default "${uuid}"`) + } + } +} + +function checkRequests (requests, testState) { + var testIdx = 0 + for (let i = 0; i < requests.length; ++i) { + var expectedValidatingHeaders = [] + var config = requests[i] + var serverRequest = testState[testIdx] + var reqNum = i + 1 + if ('expected_type' in config) { + if (config.expected_type === 'cached') continue // the server will not see the request + if (config.expected_type === 'etag_validated') { + expectedValidatingHeaders.push('if-none-match') + } + if (config.expected_type === 'lm_validated') { + expectedValidatingHeaders.push('if-modified-since') + } + } + testIdx++ + expectedValidatingHeaders.forEach(vhdr => { + assert_own_property(serverRequest.request_headers, vhdr, + `request ${reqNum} doesn't have ${vhdr} header`) + }) + if ('expected_request_headers' in config) { + config.expected_request_headers.forEach(expectedHdr => { + assert_equals(serverRequest.request_headers[expectedHdr[0].toLowerCase()], expectedHdr[1], + `request ${reqNum} header ${expectedHdr[0]} value is "${serverRequest.request_headers[expectedHdr[0].toLowerCase()]}", not "${expectedHdr[1]}"`) + }) + } + } +} + +function pause () { + return new Promise(function (resolve, reject) { + step_timeout(function () { + return resolve() + }, 3000) + }) +} + +function makeTestUrl (uuid, config) { + var arg = '' + var base_url = '' + if ('base_url' in config) { + base_url = config.base_url + } + if ('query_arg' in config) { + arg = `&target=${config.query_arg}` + } + return `${base_url}resources/http-cache.py?dispatch=test&uuid=${uuid}${arg}` +} + +function getServerState (uuid) { + return fetch(`resources/http-cache.py?dispatch=state&uuid=${uuid}`) + .then(function (response) { + return response.text() + }).then(function (text) { + return JSON.parse(text) || [] + }) +} + +function run_tests (tests) { + tests.forEach(function (test) { + promise_test(makeTest(test), test.name) + }) +} + +var contentStore = {} +function http_content (csKey) { + if (csKey in contentStore) { + return contentStore[csKey] + } else { + var content = btoa(Math.random() * Date.now()) + contentStore[csKey] = content + return content + } +} diff --git a/test/wpt/tests/fetch/http-cache/invalidate.any.js b/test/wpt/tests/fetch/http-cache/invalidate.any.js new file mode 100644 index 0000000..9f8090a --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/invalidate.any.js @@ -0,0 +1,235 @@ +// META: global=window,worker +// META: title=HTTP Cache - Invalidation +// META: timeout=long +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=http-cache.js + +var tests = [ + { + name: 'HTTP cache invalidates after a successful response from a POST', + requests: [ + { + template: "fresh" + }, { + request_method: "POST", + request_body: "abc" + }, { + expected_type: "not_cached" + } + ] + }, + { + name: 'HTTP cache does not invalidate after a failed response from an unsafe request', + requests: [ + { + template: "fresh" + }, { + request_method: "POST", + request_body: "abc", + response_status: [500, "Internal Server Error"] + }, { + expected_type: "cached" + } + ] + }, + { + name: 'HTTP cache invalidates after a successful response from a PUT', + requests: [ + { + template: "fresh" + }, { + template: "fresh", + request_method: "PUT", + request_body: "abc" + }, { + expected_type: "not_cached" + } + ] + }, + { + name: 'HTTP cache invalidates after a successful response from a DELETE', + requests: [ + { + template: "fresh" + }, { + request_method: "DELETE", + request_body: "abc" + }, { + expected_type: "not_cached" + } + ] + }, + { + name: 'HTTP cache invalidates after a successful response from an unknown method', + requests: [ + { + template: "fresh" + }, { + request_method: "FOO", + request_body: "abc" + }, { + expected_type: "not_cached" + } + ] + }, + + + { + name: 'HTTP cache invalidates Location URL after a successful response from a POST', + requests: [ + { + template: "location" + }, { + request_method: "POST", + request_body: "abc", + template: "lcl_response" + }, { + template: "location", + expected_type: "not_cached" + } + ] + }, + { + name: 'HTTP cache does not invalidate Location URL after a failed response from an unsafe request', + requests: [ + { + template: "location" + }, { + template: "lcl_response", + request_method: "POST", + request_body: "abc", + response_status: [500, "Internal Server Error"] + }, { + template: "location", + expected_type: "cached" + } + ] + }, + { + name: 'HTTP cache invalidates Location URL after a successful response from a PUT', + requests: [ + { + template: "location" + }, { + template: "lcl_response", + request_method: "PUT", + request_body: "abc" + }, { + template: "location", + expected_type: "not_cached" + } + ] + }, + { + name: 'HTTP cache invalidates Location URL after a successful response from a DELETE', + requests: [ + { + template: "location" + }, { + template: "lcl_response", + request_method: "DELETE", + request_body: "abc" + }, { + template: "location", + expected_type: "not_cached" + } + ] + }, + { + name: 'HTTP cache invalidates Location URL after a successful response from an unknown method', + requests: [ + { + template: "location" + }, { + template: "lcl_response", + request_method: "FOO", + request_body: "abc" + }, { + template: "location", + expected_type: "not_cached" + } + ] + }, + + + + { + name: 'HTTP cache invalidates Content-Location URL after a successful response from a POST', + requests: [ + { + template: "content_location" + }, { + request_method: "POST", + request_body: "abc", + template: "lcl_response" + }, { + template: "content_location", + expected_type: "not_cached" + } + ] + }, + { + name: 'HTTP cache does not invalidate Content-Location URL after a failed response from an unsafe request', + requests: [ + { + template: "content_location" + }, { + template: "lcl_response", + request_method: "POST", + request_body: "abc", + response_status: [500, "Internal Server Error"] + }, { + template: "content_location", + expected_type: "cached" + } + ] + }, + { + name: 'HTTP cache invalidates Content-Location URL after a successful response from a PUT', + requests: [ + { + template: "content_location" + }, { + template: "lcl_response", + request_method: "PUT", + request_body: "abc" + }, { + template: "content_location", + expected_type: "not_cached" + } + ] + }, + { + name: 'HTTP cache invalidates Content-Location URL after a successful response from a DELETE', + requests: [ + { + template: "content_location" + }, { + template: "lcl_response", + request_method: "DELETE", + request_body: "abc" + }, { + template: "content_location", + expected_type: "not_cached" + } + ] + }, + { + name: 'HTTP cache invalidates Content-Location URL after a successful response from an unknown method', + requests: [ + { + template: "content_location" + }, { + template: "lcl_response", + request_method: "FOO", + request_body: "abc" + }, { + template: "content_location", + expected_type: "not_cached" + } + ] + } + +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/http-cache/partial.any.js b/test/wpt/tests/fetch/http-cache/partial.any.js new file mode 100644 index 0000000..3f23b59 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/partial.any.js @@ -0,0 +1,208 @@ +// META: global=window,worker +// META: title=HTTP Cache - Partial Content +// META: timeout=long +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=http-cache.js + +var tests = [ + { + name: "HTTP cache stores partial content and reuses it", + requests: [ + { + request_headers: [ + ['Range', "bytes=-5"] + ], + response_status: [206, "Partial Content"], + response_headers: [ + ["Cache-Control", "max-age=3600"], + ["Content-Range", "bytes 4-9/10"] + ], + response_body: "01234", + expected_request_headers: [ + ["Range", "bytes=-5"] + ] + }, + { + request_headers: [ + ["Range", "bytes=-5"] + ], + expected_type: "cached", + expected_status: 206, + expected_response_text: "01234" + } + ] + }, + { + name: "HTTP cache stores complete response and serves smaller ranges from it (byte-range-spec)", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"] + ], + response_body: "01234567890" + }, + { + request_headers: [ + ['Range', "bytes=0-1"] + ], + expected_type: "cached", + expected_status: 206, + expected_response_text: "01" + }, + ] + }, + { + name: "HTTP cache stores complete response and serves smaller ranges from it (absent last-byte-pos)", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"], + ], + response_body: "01234567890" + }, + { + request_headers: [ + ['Range', "bytes=1-"] + ], + expected_type: "cached", + expected_status: 206, + expected_response_text: "1234567890" + } + ] + }, + { + name: "HTTP cache stores complete response and serves smaller ranges from it (suffix-byte-range-spec)", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"], + ], + response_body: "0123456789A" + }, + { + request_headers: [ + ['Range', "bytes=-1"] + ], + expected_type: "cached", + expected_status: 206, + expected_response_text: "A" + } + ] + }, + { + name: "HTTP cache stores complete response and serves smaller ranges from it with only-if-cached", + requests: [ + { + response_headers: [ + ["Cache-Control", "max-age=3600"] + ], + response_body: "01234567890" + }, + { + request_headers: [ + ['Range', "bytes=0-1"] + ], + mode: "same-origin", + cache: "only-if-cached", + expected_type: "cached", + expected_status: 206, + expected_response_text: "01" + }, + ] + }, + { + name: "HTTP cache stores partial response and serves smaller ranges from it (byte-range-spec)", + requests: [ + { + request_headers: [ + ['Range', "bytes=-5"] + ], + response_status: [206, "Partial Content"], + response_headers: [ + ["Cache-Control", "max-age=3600"], + ["Content-Range", "bytes 4-9/10"] + ], + response_body: "01234" + }, + { + request_headers: [ + ['Range', "bytes=6-8"] + ], + expected_type: "cached", + expected_status: 206, + expected_response_text: "234" + } + ] + }, + { + name: "HTTP cache stores partial response and serves smaller ranges from it (absent last-byte-pos)", + requests: [ + { + request_headers: [ + ['Range', "bytes=-5"] + ], + response_status: [206, "Partial Content"], + response_headers: [ + ["Cache-Control", "max-age=3600"], + ["Content-Range", "bytes 4-9/10"] + ], + response_body: "01234" + }, + { + request_headers: [ + ["Range", "bytes=6-"] + ], + expected_type: "cached", + expected_status: 206, + expected_response_text: "234" + } + ] + }, + { + name: "HTTP cache stores partial response and serves smaller ranges from it (suffix-byte-range-spec)", + requests: [ + { + request_headers: [ + ['Range', "bytes=-5"] + ], + response_status: [206, "Partial Content"], + response_headers: [ + ["Cache-Control", "max-age=3600"], + ["Content-Range", "bytes 4-9/10"] + ], + response_body: "01234" + }, + { + request_headers: [ + ['Range', "bytes=-1"] + ], + expected_type: "cached", + expected_status: 206, + expected_response_text: "4" + } + ] + }, + { + name: "HTTP cache stores partial content and completes it", + requests: [ + { + request_headers: [ + ['Range', "bytes=-5"] + ], + response_status: [206, "Partial Content"], + response_headers: [ + ["Cache-Control", "max-age=3600"], + ["Content-Range", "bytes 0-4/10"] + ], + response_body: "01234" + }, + { + expected_request_headers: [ + ["range", "bytes=5-"] + ] + } + ] + }, +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/http-cache/post-patch.any.js b/test/wpt/tests/fetch/http-cache/post-patch.any.js new file mode 100644 index 0000000..0a69baa --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/post-patch.any.js @@ -0,0 +1,46 @@ +// META: global=window,worker +// META: title=HTTP Cache - Caching POST and PATCH responses +// META: timeout=long +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=http-cache.js + +var tests = [ + { + name: "HTTP cache uses content after PATCH request with response containing Content-Location and cache-allowing header", + requests: [ + { + request_method: "PATCH", + request_body: "abc", + response_status: [200, "OK"], + response_headers: [ + ['Cache-Control', "private, max-age=1000"], + ['Content-Location', ""] + ], + response_body: "abc" + }, + { + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache uses content after POST request with response containing Content-Location and cache-allowing header", + requests: [ + { + request_method: "POST", + request_body: "abc", + response_status: [200, "OK"], + response_headers: [ + ['Cache-Control', "private, max-age=1000"], + ['Content-Location', ""] + ], + response_body: "abc" + }, + { + expected_type: "cached" + } + ] + } +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/http-cache/resources/http-cache.py b/test/wpt/tests/fetch/http-cache/resources/http-cache.py new file mode 100644 index 0000000..3ab610d --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/resources/http-cache.py @@ -0,0 +1,124 @@ +import datetime +import json +import time +from base64 import b64decode + +from wptserve.utils import isomorphic_decode, isomorphic_encode + +NOTEHDRS = set([u'content-type', u'access-control-allow-origin', u'last-modified', u'etag']) +NOBODYSTATUS = set([204, 304]) +LOCATIONHDRS = set([u'location', u'content-location']) +DATEHDRS = set([u'date', u'expires', u'last-modified']) + +def main(request, response): + dispatch = request.GET.first(b"dispatch", None) + uuid = request.GET.first(b"uuid", None) + response.headers.set(b"Access-Control-Allow-Credentials", b"true") + + if request.method == u"OPTIONS": + return handle_preflight(uuid, request, response) + if not uuid: + response.status = (404, b"Not Found") + response.headers.set(b"Content-Type", b"text/plain") + return b"UUID not found" + if dispatch == b'test': + return handle_test(uuid, request, response) + elif dispatch == b'state': + return handle_state(uuid, request, response) + response.status = (404, b"Not Found") + response.headers.set(b"Content-Type", b"text/plain") + return b"Fallthrough" + +def handle_preflight(uuid, request, response): + response.status = (200, b"OK") + response.headers.set(b"Access-Control-Allow-Origin", request.headers.get(b"origin") or '*') + response.headers.set(b"Access-Control-Allow-Methods", b"GET") + response.headers.set(b"Access-Control-Allow-Headers", request.headers.get(b"Access-Control-Request-Headers") or "*") + response.headers.set(b"Access-Control-Max-Age", b"86400") + return b"Preflight request" + +def handle_state(uuid, request, response): + response.headers.set(b"Content-Type", b"text/plain") + return json.dumps(request.server.stash.take(uuid)) + +def handle_test(uuid, request, response): + server_state = request.server.stash.take(uuid) or [] + try: + requests = json.loads(b64decode(request.headers.get(b'Test-Requests', b""))) + except: + response.status = (400, b"Bad Request") + response.headers.set(b"Content-Type", b"text/plain") + return b"No or bad Test-Requests request header" + config = requests[len(server_state)] + if not config: + response.status = (404, b"Not Found") + response.headers.set(b"Content-Type", b"text/plain") + return b"Config not found" + noted_headers = {} + now = time.time() + for header in config.get(u'response_headers', []): + if header[0].lower() in LOCATIONHDRS: # magic locations + if (len(header[1]) > 0): + header[1] = u"%s&target=%s" % (request.url, header[1]) + else: + header[1] = request.url + if header[0].lower() in DATEHDRS and isinstance(header[1], int): # magic dates + header[1] = http_date(now, header[1]) + response.headers.set(isomorphic_encode(header[0]), isomorphic_encode(header[1])) + if header[0].lower() in NOTEHDRS: + noted_headers[header[0].lower()] = header[1] + state = { + u'now': now, + u'request_method': request.method, + u'request_headers': dict([[isomorphic_decode(h.lower()), isomorphic_decode(request.headers[h])] for h in request.headers]), + u'response_headers': noted_headers + } + server_state.append(state) + request.server.stash.put(uuid, server_state) + + if u"access-control-allow-origin" not in noted_headers: + response.headers.set(b"Access-Control-Allow-Origin", b"*") + if u"content-type" not in noted_headers: + response.headers.set(b"Content-Type", b"text/plain") + response.headers.set(b"Server-Request-Count", len(server_state)) + + code, phrase = config.get(u"response_status", [200, b"OK"]) + if config.get(u"expected_type", u"").endswith(u'validated'): + ref_hdrs = server_state[0][u'response_headers'] + previous_lm = ref_hdrs.get(u'last-modified', False) + if previous_lm and request.headers.get(b"If-Modified-Since", False) == isomorphic_encode(previous_lm): + code, phrase = [304, b"Not Modified"] + previous_etag = ref_hdrs.get(u'etag', False) + if previous_etag and request.headers.get(b"If-None-Match", False) == isomorphic_encode(previous_etag): + code, phrase = [304, b"Not Modified"] + if code != 304: + code, phrase = [999, b'304 Not Generated'] + response.status = (code, phrase) + + content = config.get(u"response_body", uuid) + if code in NOBODYSTATUS: + return b"" + return content + + +def get_header(headers, header_name): + result = None + for header in headers: + if header[0].lower() == header_name.lower(): + result = header[1] + return result + +WEEKDAYS = [u'Mon', u'Tue', u'Wed', u'Thu', u'Fri', u'Sat', u'Sun'] +MONTHS = [None, u'Jan', u'Feb', u'Mar', u'Apr', u'May', u'Jun', u'Jul', + u'Aug', u'Sep', u'Oct', u'Nov', u'Dec'] + +def http_date(now, delta_secs=0): + date = datetime.datetime.utcfromtimestamp(now + delta_secs) + return u"%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT" % ( + WEEKDAYS[date.weekday()], + date.day, + MONTHS[date.month], + date.year, + date.hour, + date.minute, + date.second) diff --git a/test/wpt/tests/fetch/http-cache/resources/securedimage.py b/test/wpt/tests/fetch/http-cache/resources/securedimage.py new file mode 100644 index 0000000..cac9cfe --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/resources/securedimage.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 - + +from wptserve.utils import isomorphic_decode, isomorphic_encode + +def main(request, response): + image_url = str.replace(request.url, u"fetch/http-cache/resources/securedimage.py", u"images/green.png") + + if b"authorization" not in request.headers: + response.status = 401 + response.headers.set(b"WWW-Authenticate", b"Basic") + return + else: + auth = request.headers.get(b"Authorization") + if auth != b"Basic dGVzdHVzZXI6dGVzdHBhc3M=": + response.set_error(403, u"Invalid username or password - " + isomorphic_decode(auth)) + return + + response.status = 301 + response.headers.set(b"Location", isomorphic_encode(image_url)) diff --git a/test/wpt/tests/fetch/http-cache/resources/split-cache-popup-with-iframe.html b/test/wpt/tests/fetch/http-cache/resources/split-cache-popup-with-iframe.html new file mode 100644 index 0000000..48b1618 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/resources/split-cache-popup-with-iframe.html @@ -0,0 +1,34 @@ + + + + + HTTP Cache - helper + + + + + + + + + diff --git a/test/wpt/tests/fetch/http-cache/resources/split-cache-popup.html b/test/wpt/tests/fetch/http-cache/resources/split-cache-popup.html new file mode 100644 index 0000000..edb5794 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/resources/split-cache-popup.html @@ -0,0 +1,28 @@ + + + + + HTTP Cache - helper + + + + + + + + + diff --git a/test/wpt/tests/fetch/http-cache/split-cache.html b/test/wpt/tests/fetch/http-cache/split-cache.html new file mode 100644 index 0000000..fe93d2e --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/split-cache.html @@ -0,0 +1,158 @@ + + + + + HTTP Cache - Partioning by site + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/http-cache/status.any.js b/test/wpt/tests/fetch/http-cache/status.any.js new file mode 100644 index 0000000..10c83a2 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/status.any.js @@ -0,0 +1,60 @@ +// META: global=window,worker +// META: title=HTTP Cache - Status Codes +// META: timeout=long +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=http-cache.js + +var tests = []; +function check_status(status) { + var code = status[0]; + var phrase = status[1]; + var body = status[2]; + if (body === undefined) { + body = http_content(code); + } + tests.push({ + name: "HTTP cache goes to the network if it has a stale " + code + " response", + requests: [ + { + template: "stale", + response_status: [code, phrase], + response_body: body + }, { + expected_type: "not_cached", + response_status: [code, phrase], + response_body: body + } + ] + }) + tests.push({ + name: "HTTP cache avoids going to the network if it has a fresh " + code + " response", + requests: [ + { + template: "fresh", + response_status: [code, phrase], + response_body: body + }, { + expected_type: "cached", + response_status: [code, phrase], + response_body: body + } + ] + }) +} +[ + [200, "OK"], + [203, "Non-Authoritative Information"], + [204, "No Content", null], + [299, "Whatever"], + [400, "Bad Request"], + [404, "Not Found"], + [410, "Gone"], + [499, "Whatever"], + [500, "Internal Server Error"], + [502, "Bad Gateway"], + [503, "Service Unavailable"], + [504, "Gateway Timeout"], + [599, "Whatever"] +].forEach(check_status); +run_tests(tests); diff --git a/test/wpt/tests/fetch/http-cache/vary.any.js b/test/wpt/tests/fetch/http-cache/vary.any.js new file mode 100644 index 0000000..2cfd226 --- /dev/null +++ b/test/wpt/tests/fetch/http-cache/vary.any.js @@ -0,0 +1,313 @@ +// META: global=window,worker +// META: title=HTTP Cache - Vary +// META: timeout=long +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=http-cache.js + +var tests = [ + { + name: "HTTP cache reuses Vary response when request matches", + requests: [ + { + request_headers: [ + ["Foo", "1"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo"] + ] + }, + { + request_headers: [ + ["Foo", "1"] + ], + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache doesn't use Vary response when request doesn't match", + requests: [ + { + request_headers: [ + ["Foo", "1"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo"] + ] + }, + { + request_headers: [ + ["Foo", "2"] + ], + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache doesn't use Vary response when request omits variant header", + requests: [ + { + request_headers: [ + ["Foo", "1"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo"] + ] + }, + { + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache doesn't invalidate existing Vary response", + requests: [ + { + request_headers: [ + ["Foo", "1"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo"] + ], + response_body: http_content('foo_1') + }, + { + request_headers: [ + ["Foo", "2"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo"] + ], + expected_type: "not_cached", + response_body: http_content('foo_2'), + }, + { + request_headers: [ + ["Foo", "1"] + ], + response_body: http_content('foo_1'), + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache doesn't pay attention to headers not listed in Vary", + requests: [ + { + request_headers: [ + ["Foo", "1"], + ["Other", "2"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo"] + ], + }, + { + request_headers: [ + ["Foo", "1"], + ["Other", "3"] + ], + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache reuses two-way Vary response when request matches", + requests: [ + { + request_headers: [ + ["Foo", "1"], + ["Bar", "abc"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo, Bar"] + ] + }, + { + request_headers: [ + ["Foo", "1"], + ["Bar", "abc"] + ], + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache doesn't use two-way Vary response when request doesn't match", + requests: [ + { + request_headers: [ + ["Foo", "1"], + ["Bar", "abc"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo, Bar"] + ] + }, + { + request_headers: [ + ["Foo", "2"], + ["Bar", "abc"] + ], + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache doesn't use two-way Vary response when request omits variant header", + requests: [ + { + request_headers: [ + ["Foo", "1"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo, Bar"] + ] + }, + { + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache reuses three-way Vary response when request matches", + requests: [ + { + request_headers: [ + ["Foo", "1"], + ["Bar", "abc"], + ["Baz", "789"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo, Bar, Baz"] + ] + }, + { + request_headers: [ + ["Foo", "1"], + ["Bar", "abc"], + ["Baz", "789"] + ], + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache doesn't use three-way Vary response when request doesn't match", + requests: [ + { + request_headers: [ + ["Foo", "1"], + ["Bar", "abc"], + ["Baz", "789"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo, Bar, Baz"] + ] + }, + { + request_headers: [ + ["Foo", "2"], + ["Bar", "abc"], + ["Baz", "789"] + ], + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache doesn't use three-way Vary response when request doesn't match, regardless of header order", + requests: [ + { + request_headers: [ + ["Foo", "1"], + ["Bar", "abc4"], + ["Baz", "789"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo, Bar, Baz"] + ] + }, + { + request_headers: [ + ["Foo", "1"], + ["Bar", "abc"], + ["Baz", "789"] + ], + expected_type: "not_cached" + } + ] + }, + { + name: "HTTP cache uses three-way Vary response when both request and the original request omited a variant header", + requests: [ + { + request_headers: [ + ["Foo", "1"], + ["Baz", "789"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "Foo, Bar, Baz"] + ] + }, + { + request_headers: [ + ["Foo", "1"], + ["Baz", "789"] + ], + expected_type: "cached" + } + ] + }, + { + name: "HTTP cache doesn't use Vary response with a field value of '*'", + requests: [ + { + request_headers: [ + ["Foo", "1"], + ["Baz", "789"] + ], + response_headers: [ + ["Expires", 5000], + ["Last-Modified", -3000], + ["Vary", "*"] + ] + }, + { + request_headers: [ + ["*", "1"], + ["Baz", "789"] + ], + expected_type: "not_cached" + } + ] + } +]; +run_tests(tests); diff --git a/test/wpt/tests/fetch/images/canvas-remote-read-remote-image-redirect.html b/test/wpt/tests/fetch/images/canvas-remote-read-remote-image-redirect.html new file mode 100644 index 0000000..4a887f3 --- /dev/null +++ b/test/wpt/tests/fetch/images/canvas-remote-read-remote-image-redirect.html @@ -0,0 +1,28 @@ + + +Load a no-cors image from a same-origin URL that redirects to a cross-origin URL that redirects to the initial origin + + + + diff --git a/test/wpt/tests/fetch/metadata/META.yml b/test/wpt/tests/fetch/metadata/META.yml new file mode 100644 index 0000000..85f0a7d --- /dev/null +++ b/test/wpt/tests/fetch/metadata/META.yml @@ -0,0 +1,4 @@ +spec: https://w3c.github.io/webappsec-fetch-metadata/ +suggested_reviewers: + - mikewest + - iVanlIsh diff --git a/test/wpt/tests/fetch/metadata/README.md b/test/wpt/tests/fetch/metadata/README.md new file mode 100644 index 0000000..34864d4 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/README.md @@ -0,0 +1,9 @@ +Fetch Metadata Tests +==================== + +This directory contains tests related to the Fetch Metadata proposal: + +: Explainer +:: +: "Spec" +:: diff --git a/test/wpt/tests/fetch/metadata/audio-worklet.https.html b/test/wpt/tests/fetch/metadata/audio-worklet.https.html new file mode 100644 index 0000000..3b768ef --- /dev/null +++ b/test/wpt/tests/fetch/metadata/audio-worklet.https.html @@ -0,0 +1,20 @@ + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/embed.https.sub.tentative.html b/test/wpt/tests/fetch/metadata/embed.https.sub.tentative.html new file mode 100644 index 0000000..1900dbd --- /dev/null +++ b/test/wpt/tests/fetch/metadata/embed.https.sub.tentative.html @@ -0,0 +1,63 @@ + + + + + + + + + +

Relevant issue: +<embed> should support loading random HTML documents, like <object> +

+ + diff --git a/test/wpt/tests/fetch/metadata/fetch-preflight.https.sub.any.js b/test/wpt/tests/fetch/metadata/fetch-preflight.https.sub.any.js new file mode 100644 index 0000000..d524743 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/fetch-preflight.https.sub.any.js @@ -0,0 +1,29 @@ +// META: global=window,worker +// META: script=/fetch/metadata/resources/helper.js + +// Site +promise_test(t => { + return validate_expectations_custom_url("https://{{hosts[][www]}}:{{ports[https][0]}}/fetch/metadata/resources/echo-as-json.py", + { + mode: "cors", + headers: { 'x-test': 'testing' } + }, { + "site": "same-site", + "user": "", + "mode": "cors", + "dest": "empty" + }, "Same-site fetch with preflight"); +}, "Same-site fetch with preflight"); + +promise_test(t => { + return validate_expectations_custom_url("https://{{hosts[alt][www]}}:{{ports[https][0]}}/fetch/metadata/resources/echo-as-json.py", + { + mode: "cors", + headers: { 'x-test': 'testing' } + }, { + "site": "cross-site", + "user": "", + "mode": "cors", + "dest": "empty" + }, "Cross-site fetch with preflight"); +}, "Cross-site fetch with preflight"); diff --git a/test/wpt/tests/fetch/metadata/fetch.https.sub.any.js b/test/wpt/tests/fetch/metadata/fetch.https.sub.any.js new file mode 100644 index 0000000..aeec5cd --- /dev/null +++ b/test/wpt/tests/fetch/metadata/fetch.https.sub.any.js @@ -0,0 +1,58 @@ +// META: global=window,worker +// META: script=/fetch/metadata/resources/helper.js + +// Site +promise_test(t => { + return validate_expectations_custom_url("https://{{host}}:{{ports[https][0]}}/fetch/metadata/resources/echo-as-json.py", {}, { + "site": "same-origin", + "user": "", + "mode": "cors", + "dest": "empty" + }, "Same-origin fetch"); +}, "Same-origin fetch"); + +promise_test(t => { + return validate_expectations_custom_url("https://{{hosts[][www]}}:{{ports[https][0]}}/fetch/metadata/resources/echo-as-json.py", {}, { + "site": "same-site", + "user": "", + "mode": "cors", + "dest": "empty" + }, "Same-site fetch"); +}, "Same-site fetch"); + +promise_test(t => { + return validate_expectations_custom_url("https://{{hosts[alt][www]}}:{{ports[https][0]}}/fetch/metadata/resources/echo-as-json.py", {}, { + "site": "cross-site", + "user": "", + "mode": "cors", + "dest": "empty" + }, "Cross-site fetch"); +}, "Cross-site fetch"); + +// Mode +promise_test(t => { + return validate_expectations_custom_url("https://{{host}}:{{ports[https][0]}}/fetch/metadata/resources/echo-as-json.py", {mode: "same-origin"}, { + "site": "same-origin", + "user": "", + "mode": "same-origin", + "dest": "empty" + }, "Same-origin mode"); +}, "Same-origin mode"); + +promise_test(t => { + return validate_expectations_custom_url("https://{{host}}:{{ports[https][0]}}/fetch/metadata/resources/echo-as-json.py", {mode: "cors"}, { + "site": "same-origin", + "user": "", + "mode": "cors", + "dest": "empty" + }, "CORS mode"); +}, "CORS mode"); + +promise_test(t => { + return validate_expectations_custom_url("https://{{host}}:{{ports[https][0]}}/fetch/metadata/resources/echo-as-json.py", {mode: "no-cors"}, { + "site": "same-origin", + "user": "", + "mode": "no-cors", + "dest": "empty" + }, "no-CORS mode"); +}, "no-CORS mode"); diff --git a/test/wpt/tests/fetch/metadata/generated/appcache-manifest.https.sub.html b/test/wpt/tests/fetch/metadata/generated/appcache-manifest.https.sub.html new file mode 100644 index 0000000..cf322fd --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/appcache-manifest.https.sub.html @@ -0,0 +1,341 @@ + + + + + HTTP headers on request for Appcache manifest + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/audioworklet.https.sub.html b/test/wpt/tests/fetch/metadata/generated/audioworklet.https.sub.html new file mode 100644 index 0000000..64fb760 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/audioworklet.https.sub.html @@ -0,0 +1,271 @@ + + + + + HTTP headers on request for AudioWorklet module + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/css-font-face.https.sub.tentative.html b/test/wpt/tests/fetch/metadata/generated/css-font-face.https.sub.tentative.html new file mode 100644 index 0000000..332effe --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/css-font-face.https.sub.tentative.html @@ -0,0 +1,230 @@ + + + + + HTTP headers on request for CSS font-face + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/css-font-face.sub.tentative.html b/test/wpt/tests/fetch/metadata/generated/css-font-face.sub.tentative.html new file mode 100644 index 0000000..8a0b90c --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/css-font-face.sub.tentative.html @@ -0,0 +1,196 @@ + + + + + HTTP headers on request for CSS font-face + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/css-images.https.sub.tentative.html b/test/wpt/tests/fetch/metadata/generated/css-images.https.sub.tentative.html new file mode 100644 index 0000000..3fa2401 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/css-images.https.sub.tentative.html @@ -0,0 +1,1384 @@ + + + + + + HTTP headers on request for CSS image-accepting properties + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/css-images.sub.tentative.html b/test/wpt/tests/fetch/metadata/generated/css-images.sub.tentative.html new file mode 100644 index 0000000..f1ef27c --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/css-images.sub.tentative.html @@ -0,0 +1,1099 @@ + + + + + + HTTP headers on request for CSS image-accepting properties + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-a.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-a.https.sub.html new file mode 100644 index 0000000..dffd36c --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-a.https.sub.html @@ -0,0 +1,482 @@ + + + + + + HTTP headers on request for HTML "a" element navigation + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-a.sub.html b/test/wpt/tests/fetch/metadata/generated/element-a.sub.html new file mode 100644 index 0000000..0661de3 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-a.sub.html @@ -0,0 +1,342 @@ + + + + + + HTTP headers on request for HTML "a" element navigation + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-area.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-area.https.sub.html new file mode 100644 index 0000000..be3f5f9 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-area.https.sub.html @@ -0,0 +1,482 @@ + + + + + + HTTP headers on request for HTML "area" element navigation + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-area.sub.html b/test/wpt/tests/fetch/metadata/generated/element-area.sub.html new file mode 100644 index 0000000..5f5c338 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-area.sub.html @@ -0,0 +1,342 @@ + + + + + + HTTP headers on request for HTML "area" element navigation + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-audio.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-audio.https.sub.html new file mode 100644 index 0000000..a9d9512 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-audio.https.sub.html @@ -0,0 +1,325 @@ + + + + + HTTP headers on request for HTML "audio" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-audio.sub.html b/test/wpt/tests/fetch/metadata/generated/element-audio.sub.html new file mode 100644 index 0000000..2b62632 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-audio.sub.html @@ -0,0 +1,229 @@ + + + + + HTTP headers on request for HTML "audio" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-embed.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-embed.https.sub.html new file mode 100644 index 0000000..819bed8 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-embed.https.sub.html @@ -0,0 +1,224 @@ + + + + + HTTP headers on request for HTML "embed" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-embed.sub.html b/test/wpt/tests/fetch/metadata/generated/element-embed.sub.html new file mode 100644 index 0000000..b6e14a5 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-embed.sub.html @@ -0,0 +1,190 @@ + + + + + HTTP headers on request for HTML "embed" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-frame.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-frame.https.sub.html new file mode 100644 index 0000000..17504ff --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-frame.https.sub.html @@ -0,0 +1,309 @@ + + + + + HTTP headers on request for HTML "frame" element source + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-frame.sub.html b/test/wpt/tests/fetch/metadata/generated/element-frame.sub.html new file mode 100644 index 0000000..2d9a7ec --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-frame.sub.html @@ -0,0 +1,250 @@ + + + + + HTTP headers on request for HTML "frame" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-iframe.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-iframe.https.sub.html new file mode 100644 index 0000000..fba1c8b --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-iframe.https.sub.html @@ -0,0 +1,309 @@ + + + + + HTTP headers on request for HTML "frame" element source + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-iframe.sub.html b/test/wpt/tests/fetch/metadata/generated/element-iframe.sub.html new file mode 100644 index 0000000..6f71cc0 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-iframe.sub.html @@ -0,0 +1,250 @@ + + + + + HTTP headers on request for HTML "frame" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-img-environment-change.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-img-environment-change.https.sub.html new file mode 100644 index 0000000..a19aa11 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-img-environment-change.https.sub.html @@ -0,0 +1,357 @@ + + + + + HTTP headers on image request triggered by change to environment + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-img-environment-change.sub.html b/test/wpt/tests/fetch/metadata/generated/element-img-environment-change.sub.html new file mode 100644 index 0000000..9665872 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-img-environment-change.sub.html @@ -0,0 +1,270 @@ + + + + + HTTP headers on image request triggered by change to environment + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-img.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-img.https.sub.html new file mode 100644 index 0000000..51d6e08 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-img.https.sub.html @@ -0,0 +1,645 @@ + + + + + HTTP headers on request for HTML "img" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-img.sub.html b/test/wpt/tests/fetch/metadata/generated/element-img.sub.html new file mode 100644 index 0000000..5a4b152 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-img.sub.html @@ -0,0 +1,456 @@ + + + + + HTTP headers on request for HTML "img" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-input-image.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-input-image.https.sub.html new file mode 100644 index 0000000..7fa6740 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-input-image.https.sub.html @@ -0,0 +1,229 @@ + + + + + HTTP headers on request for HTML "input" element with type="button" + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-input-image.sub.html b/test/wpt/tests/fetch/metadata/generated/element-input-image.sub.html new file mode 100644 index 0000000..fb2a146 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-input-image.sub.html @@ -0,0 +1,184 @@ + + + + + HTTP headers on request for HTML "input" element with type="button" + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-link-icon.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-link-icon.https.sub.html new file mode 100644 index 0000000..b244960 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-link-icon.https.sub.html @@ -0,0 +1,371 @@ + + + + + + HTTP headers on request for HTML "link" element with rel="icon" + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-link-icon.sub.html b/test/wpt/tests/fetch/metadata/generated/element-link-icon.sub.html new file mode 100644 index 0000000..e9226c1 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-link-icon.sub.html @@ -0,0 +1,279 @@ + + + + + + HTTP headers on request for HTML "link" element with rel="icon" + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-link-prefetch.https.optional.sub.html b/test/wpt/tests/fetch/metadata/generated/element-link-prefetch.https.optional.sub.html new file mode 100644 index 0000000..bdd684a --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-link-prefetch.https.optional.sub.html @@ -0,0 +1,559 @@ + + + + + + HTTP headers on request for HTML "link" element with rel="prefetch" + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-link-prefetch.optional.sub.html b/test/wpt/tests/fetch/metadata/generated/element-link-prefetch.optional.sub.html new file mode 100644 index 0000000..c224488 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-link-prefetch.optional.sub.html @@ -0,0 +1,275 @@ + + + + + + HTTP headers on request for HTML "link" element with rel="prefetch" + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-meta-refresh.https.optional.sub.html b/test/wpt/tests/fetch/metadata/generated/element-meta-refresh.https.optional.sub.html new file mode 100644 index 0000000..3a1a8eb --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-meta-refresh.https.optional.sub.html @@ -0,0 +1,276 @@ + + + + + HTTP headers on request for HTML "meta" element with http-equiv="refresh" + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-meta-refresh.optional.sub.html b/test/wpt/tests/fetch/metadata/generated/element-meta-refresh.optional.sub.html new file mode 100644 index 0000000..df3e92e --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-meta-refresh.optional.sub.html @@ -0,0 +1,225 @@ + + + + + HTTP headers on request for HTML "meta" element with http-equiv="refresh" + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-picture.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-picture.https.sub.html new file mode 100644 index 0000000..ba6636a --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-picture.https.sub.html @@ -0,0 +1,997 @@ + + + + + HTTP headers on request for HTML "picture" element source + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-picture.sub.html b/test/wpt/tests/fetch/metadata/generated/element-picture.sub.html new file mode 100644 index 0000000..64f851c --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-picture.sub.html @@ -0,0 +1,721 @@ + + + + + HTTP headers on request for HTML "picture" element source + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-script.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-script.https.sub.html new file mode 100644 index 0000000..dcdcba2 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-script.https.sub.html @@ -0,0 +1,593 @@ + + + + + HTTP headers on request for HTML "script" element source + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-script.sub.html b/test/wpt/tests/fetch/metadata/generated/element-script.sub.html new file mode 100644 index 0000000..a252669 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-script.sub.html @@ -0,0 +1,488 @@ + + + + + HTTP headers on request for HTML "script" element source + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-video-poster.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-video-poster.https.sub.html new file mode 100644 index 0000000..5805b46 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-video-poster.https.sub.html @@ -0,0 +1,243 @@ + + + + + HTTP headers on request for HTML "video" element "poster" + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-video-poster.sub.html b/test/wpt/tests/fetch/metadata/generated/element-video-poster.sub.html new file mode 100644 index 0000000..e6cc5ee --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-video-poster.sub.html @@ -0,0 +1,198 @@ + + + + + HTTP headers on request for HTML "video" element "poster" + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-video.https.sub.html b/test/wpt/tests/fetch/metadata/generated/element-video.https.sub.html new file mode 100644 index 0000000..971360d --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-video.https.sub.html @@ -0,0 +1,325 @@ + + + + + HTTP headers on request for HTML "video" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/element-video.sub.html b/test/wpt/tests/fetch/metadata/generated/element-video.sub.html new file mode 100644 index 0000000..9707413 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/element-video.sub.html @@ -0,0 +1,229 @@ + + + + + HTTP headers on request for HTML "video" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/fetch-via-serviceworker.https.sub.html b/test/wpt/tests/fetch/metadata/generated/fetch-via-serviceworker.https.sub.html new file mode 100644 index 0000000..22f9309 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/fetch-via-serviceworker.https.sub.html @@ -0,0 +1,683 @@ + + + + + + HTTP headers on request using the "fetch" API and passing through a Serive Worker + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/fetch.https.sub.html b/test/wpt/tests/fetch/metadata/generated/fetch.https.sub.html new file mode 100644 index 0000000..dde1dae --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/fetch.https.sub.html @@ -0,0 +1,302 @@ + + + + + HTTP headers on request using the "fetch" API + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/fetch.sub.html b/test/wpt/tests/fetch/metadata/generated/fetch.sub.html new file mode 100644 index 0000000..d28ea9b --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/fetch.sub.html @@ -0,0 +1,220 @@ + + + + + HTTP headers on request using the "fetch" API + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/form-submission.https.sub.html b/test/wpt/tests/fetch/metadata/generated/form-submission.https.sub.html new file mode 100644 index 0000000..988b07c --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/form-submission.https.sub.html @@ -0,0 +1,522 @@ + + + + + + HTTP headers on request for HTML form navigation + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/form-submission.sub.html b/test/wpt/tests/fetch/metadata/generated/form-submission.sub.html new file mode 100644 index 0000000..f862062 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/form-submission.sub.html @@ -0,0 +1,400 @@ + + + + + + HTTP headers on request for HTML form navigation + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/header-link.https.sub.html b/test/wpt/tests/fetch/metadata/generated/header-link.https.sub.html new file mode 100644 index 0000000..09f0113 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/header-link.https.sub.html @@ -0,0 +1,529 @@ + + + + + HTTP headers on request for HTTP "Link" header + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/header-link.https.sub.tentative.html b/test/wpt/tests/fetch/metadata/generated/header-link.https.sub.tentative.html new file mode 100644 index 0000000..307c37f --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/header-link.https.sub.tentative.html @@ -0,0 +1,51 @@ + + + + + HTTP headers on request for HTTP "Link" header + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/header-link.sub.html b/test/wpt/tests/fetch/metadata/generated/header-link.sub.html new file mode 100644 index 0000000..8b6cdae --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/header-link.sub.html @@ -0,0 +1,460 @@ + + + + + HTTP headers on request for HTTP "Link" header + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/header-refresh.https.optional.sub.html b/test/wpt/tests/fetch/metadata/generated/header-refresh.https.optional.sub.html new file mode 100644 index 0000000..e63ee42 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/header-refresh.https.optional.sub.html @@ -0,0 +1,273 @@ + + + + + + HTTP headers on request for HTTP "Refresh" header + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/header-refresh.optional.sub.html b/test/wpt/tests/fetch/metadata/generated/header-refresh.optional.sub.html new file mode 100644 index 0000000..4674ada --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/header-refresh.optional.sub.html @@ -0,0 +1,222 @@ + + + + + + HTTP headers on request for HTTP "Refresh" header + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/script-module-import-dynamic.https.sub.html b/test/wpt/tests/fetch/metadata/generated/script-module-import-dynamic.https.sub.html new file mode 100644 index 0000000..72d60fc --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/script-module-import-dynamic.https.sub.html @@ -0,0 +1,254 @@ + + + + + HTTP headers on request for dynamic ECMAScript module import + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/script-module-import-dynamic.sub.html b/test/wpt/tests/fetch/metadata/generated/script-module-import-dynamic.sub.html new file mode 100644 index 0000000..088720c --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/script-module-import-dynamic.sub.html @@ -0,0 +1,214 @@ + + + + + HTTP headers on request for dynamic ECMAScript module import + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/script-module-import-static.https.sub.html b/test/wpt/tests/fetch/metadata/generated/script-module-import-static.https.sub.html new file mode 100644 index 0000000..cea3464 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/script-module-import-static.https.sub.html @@ -0,0 +1,288 @@ + + + + + HTTP headers on request for static ECMAScript module import + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/script-module-import-static.sub.html b/test/wpt/tests/fetch/metadata/generated/script-module-import-static.sub.html new file mode 100644 index 0000000..0f94f71 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/script-module-import-static.sub.html @@ -0,0 +1,246 @@ + + + + + HTTP headers on request for static ECMAScript module import + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/serviceworker.https.sub.html b/test/wpt/tests/fetch/metadata/generated/serviceworker.https.sub.html new file mode 100644 index 0000000..12e3736 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/serviceworker.https.sub.html @@ -0,0 +1,170 @@ + + + + + + HTTP headers on request for Service Workers + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/svg-image.https.sub.html b/test/wpt/tests/fetch/metadata/generated/svg-image.https.sub.html new file mode 100644 index 0000000..b059eb3 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/svg-image.https.sub.html @@ -0,0 +1,367 @@ + + + + + + HTTP headers on request for SVG "image" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/svg-image.sub.html b/test/wpt/tests/fetch/metadata/generated/svg-image.sub.html new file mode 100644 index 0000000..a28bbb1 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/svg-image.sub.html @@ -0,0 +1,265 @@ + + + + + + HTTP headers on request for SVG "image" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/window-history.https.sub.html b/test/wpt/tests/fetch/metadata/generated/window-history.https.sub.html new file mode 100644 index 0000000..c2b3079 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/window-history.https.sub.html @@ -0,0 +1,237 @@ + + + + + HTTP headers on request for navigation via the HTML History API + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/window-history.sub.html b/test/wpt/tests/fetch/metadata/generated/window-history.sub.html new file mode 100644 index 0000000..333d90c --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/window-history.sub.html @@ -0,0 +1,360 @@ + + + + + + HTTP headers on request for navigation via the HTML History API + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/window-location.https.sub.html b/test/wpt/tests/fetch/metadata/generated/window-location.https.sub.html new file mode 100644 index 0000000..4a0d2fd --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/window-location.https.sub.html @@ -0,0 +1,1184 @@ + + + + + + HTTP headers on request for navigation via the HTML Location API + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/window-location.sub.html b/test/wpt/tests/fetch/metadata/generated/window-location.sub.html new file mode 100644 index 0000000..bb3e680 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/window-location.sub.html @@ -0,0 +1,894 @@ + + + + + + HTTP headers on request for navigation via the HTML Location API + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/worker-dedicated-constructor.https.sub.html b/test/wpt/tests/fetch/metadata/generated/worker-dedicated-constructor.https.sub.html new file mode 100644 index 0000000..86f1760 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/worker-dedicated-constructor.https.sub.html @@ -0,0 +1,118 @@ + + + + + HTTP headers on request for dedicated worker via the "Worker" constructor + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/worker-dedicated-constructor.sub.html b/test/wpt/tests/fetch/metadata/generated/worker-dedicated-constructor.sub.html new file mode 100644 index 0000000..69ac768 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/worker-dedicated-constructor.sub.html @@ -0,0 +1,204 @@ + + + + + HTTP headers on request for dedicated worker via the "Worker" constructor + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/worker-dedicated-importscripts.https.sub.html b/test/wpt/tests/fetch/metadata/generated/worker-dedicated-importscripts.https.sub.html new file mode 100644 index 0000000..0cd9f35 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/worker-dedicated-importscripts.https.sub.html @@ -0,0 +1,268 @@ + + + + + HTTP headers on request for dedicated worker via the "importScripts" API + + + + + diff --git a/test/wpt/tests/fetch/metadata/generated/worker-dedicated-importscripts.sub.html b/test/wpt/tests/fetch/metadata/generated/worker-dedicated-importscripts.sub.html new file mode 100644 index 0000000..0555bba --- /dev/null +++ b/test/wpt/tests/fetch/metadata/generated/worker-dedicated-importscripts.sub.html @@ -0,0 +1,228 @@ + + + + + HTTP headers on request for dedicated worker via the "importScripts" API + + + + + diff --git a/test/wpt/tests/fetch/metadata/navigation.https.sub.html b/test/wpt/tests/fetch/metadata/navigation.https.sub.html new file mode 100644 index 0000000..32c9cf7 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/navigation.https.sub.html @@ -0,0 +1,23 @@ + + + + + + diff --git a/test/wpt/tests/fetch/metadata/object.https.sub.html b/test/wpt/tests/fetch/metadata/object.https.sub.html new file mode 100644 index 0000000..fae5b37 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/object.https.sub.html @@ -0,0 +1,62 @@ + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/paint-worklet.https.html b/test/wpt/tests/fetch/metadata/paint-worklet.https.html new file mode 100644 index 0000000..49fc776 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/paint-worklet.https.html @@ -0,0 +1,19 @@ + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/portal.https.sub.html b/test/wpt/tests/fetch/metadata/portal.https.sub.html new file mode 100644 index 0000000..55b555a --- /dev/null +++ b/test/wpt/tests/fetch/metadata/portal.https.sub.html @@ -0,0 +1,50 @@ + + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/preload.https.sub.html b/test/wpt/tests/fetch/metadata/preload.https.sub.html new file mode 100644 index 0000000..29042a8 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/preload.https.sub.html @@ -0,0 +1,50 @@ + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/redirect/multiple-redirect-https-downgrade-upgrade.sub.html b/test/wpt/tests/fetch/metadata/redirect/multiple-redirect-https-downgrade-upgrade.sub.html new file mode 100644 index 0000000..0f8f320 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/redirect/multiple-redirect-https-downgrade-upgrade.sub.html @@ -0,0 +1,18 @@ + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/redirect/redirect-http-upgrade.sub.html b/test/wpt/tests/fetch/metadata/redirect/redirect-http-upgrade.sub.html new file mode 100644 index 0000000..fa765b6 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/redirect/redirect-http-upgrade.sub.html @@ -0,0 +1,17 @@ + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/redirect/redirect-https-downgrade.sub.html b/test/wpt/tests/fetch/metadata/redirect/redirect-https-downgrade.sub.html new file mode 100644 index 0000000..4e5a48e --- /dev/null +++ b/test/wpt/tests/fetch/metadata/redirect/redirect-https-downgrade.sub.html @@ -0,0 +1,17 @@ + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/report.https.sub.html b/test/wpt/tests/fetch/metadata/report.https.sub.html new file mode 100644 index 0000000..b65f7c0 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/report.https.sub.html @@ -0,0 +1,33 @@ + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/report.https.sub.html.sub.headers b/test/wpt/tests/fetch/metadata/report.https.sub.html.sub.headers new file mode 100644 index 0000000..1ec5df7 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/report.https.sub.html.sub.headers @@ -0,0 +1,3 @@ +Content-Security-Policy: style-src 'self' 'unsafe-inline'; report-uri /fetch/metadata/resources/record-header.py?file=report-same-origin +Content-Security-Policy: style-src 'self' 'unsafe-inline'; report-uri https://{{hosts[][www]}}:{{ports[https][0]}}/fetch/metadata/resources/record-header.py?file=report-same-site +Content-Security-Policy: style-src 'self' 'unsafe-inline'; report-uri https://{{hosts[alt][www]}}:{{ports[https][0]}}/fetch/metadata/resources/record-header.py?file=report-cross-site diff --git a/test/wpt/tests/fetch/metadata/resources/appcache-iframe.sub.html b/test/wpt/tests/fetch/metadata/resources/appcache-iframe.sub.html new file mode 100644 index 0000000..cea9a4f --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/appcache-iframe.sub.html @@ -0,0 +1,15 @@ + + + + diff --git a/test/wpt/tests/fetch/metadata/resources/dedicatedWorker.js b/test/wpt/tests/fetch/metadata/resources/dedicatedWorker.js new file mode 100644 index 0000000..18626d3 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/dedicatedWorker.js @@ -0,0 +1 @@ +self.postMessage("Loaded"); diff --git a/test/wpt/tests/fetch/metadata/resources/echo-as-json.py b/test/wpt/tests/fetch/metadata/resources/echo-as-json.py new file mode 100644 index 0000000..44f68e8 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/echo-as-json.py @@ -0,0 +1,29 @@ +import json + +from wptserve.utils import isomorphic_decode + +def main(request, response): + headers = [(b"Content-Type", b"application/json"), + (b"Access-Control-Allow-Credentials", b"true")] + + if b"origin" in request.headers: + headers.append((b"Access-Control-Allow-Origin", request.headers[b"origin"])) + + body = u"" + + # If we're in a preflight, verify that `Sec-Fetch-Mode` is `cors`. + if request.method == u'OPTIONS': + if request.headers.get(b"sec-fetch-mode") != b"cors": + return (403, b"Failed"), [], body + + headers.append((b"Access-Control-Allow-Methods", b"*")) + headers.append((b"Access-Control-Allow-Headers", b"*")) + else: + body = json.dumps({ + u"dest": isomorphic_decode(request.headers.get(b"sec-fetch-dest", b"")), + u"mode": isomorphic_decode(request.headers.get(b"sec-fetch-mode", b"")), + u"site": isomorphic_decode(request.headers.get(b"sec-fetch-site", b"")), + u"user": isomorphic_decode(request.headers.get(b"sec-fetch-user", b"")), + }) + + return headers, body diff --git a/test/wpt/tests/fetch/metadata/resources/echo-as-script.py b/test/wpt/tests/fetch/metadata/resources/echo-as-script.py new file mode 100644 index 0000000..1e7bc91 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/echo-as-script.py @@ -0,0 +1,14 @@ +import json + +from wptserve.utils import isomorphic_decode + +def main(request, response): + headers = [(b"Content-Type", b"text/javascript")] + body = u"var header = %s;" % json.dumps({ + u"dest": isomorphic_decode(request.headers.get(b"sec-fetch-dest", b"")), + u"mode": isomorphic_decode(request.headers.get(b"sec-fetch-mode", b"")), + u"site": isomorphic_decode(request.headers.get(b"sec-fetch-site", b"")), + u"user": isomorphic_decode(request.headers.get(b"sec-fetch-user", b"")), + }) + + return headers, body diff --git a/test/wpt/tests/fetch/metadata/resources/es-module.sub.js b/test/wpt/tests/fetch/metadata/resources/es-module.sub.js new file mode 100644 index 0000000..f9668a3 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/es-module.sub.js @@ -0,0 +1 @@ +import '{{GET[moduleId]}}'; diff --git a/test/wpt/tests/fetch/metadata/resources/fetch-via-serviceworker--fallback--sw.js b/test/wpt/tests/fetch/metadata/resources/fetch-via-serviceworker--fallback--sw.js new file mode 100644 index 0000000..09858b2 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/fetch-via-serviceworker--fallback--sw.js @@ -0,0 +1,3 @@ +self.addEventListener('fetch', function(event) { + // Empty event handler - will fallback to the network. +}); diff --git a/test/wpt/tests/fetch/metadata/resources/fetch-via-serviceworker--respondWith--sw.js b/test/wpt/tests/fetch/metadata/resources/fetch-via-serviceworker--respondWith--sw.js new file mode 100644 index 0000000..8bf8d8f --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/fetch-via-serviceworker--respondWith--sw.js @@ -0,0 +1,3 @@ +self.addEventListener('fetch', function(event) { + event.respondWith(fetch(event.request)); +}); diff --git a/test/wpt/tests/fetch/metadata/resources/fetch-via-serviceworker-frame.html b/test/wpt/tests/fetch/metadata/resources/fetch-via-serviceworker-frame.html new file mode 100644 index 0000000..9879802 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/fetch-via-serviceworker-frame.html @@ -0,0 +1,3 @@ + + +Page Title diff --git a/test/wpt/tests/fetch/metadata/resources/header-link.py b/test/wpt/tests/fetch/metadata/resources/header-link.py new file mode 100644 index 0000000..de89116 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/header-link.py @@ -0,0 +1,15 @@ +def main(request, response): + """ + Respond with a blank HTML document and a `Link` header which describes + a link relation specified by the requests `location` and `rel` query string + parameters + """ + headers = [ + (b'Content-Type', b'text/html'), + ( + b'Link', + b'<' + request.GET.first(b'location') + b'>; rel=' + request.GET.first(b'rel') + ) + ] + return (200, headers, b'') + diff --git a/test/wpt/tests/fetch/metadata/resources/helper.js b/test/wpt/tests/fetch/metadata/resources/helper.js new file mode 100644 index 0000000..725f9a7 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/helper.js @@ -0,0 +1,42 @@ +function validate_expectations(key, expected, tag) { + return fetch("/fetch/metadata/resources/record-header.py?retrieve=true&file=" + key) + .then(response => response.text()) + .then(text => { + assert_not_equals(text, "No header has been recorded"); + let value = JSON.parse(text); + test(t => assert_equals(value.dest, expected.dest), `${tag}: sec-fetch-dest`); + test(t => assert_equals(value.mode, expected.mode), `${tag}: sec-fetch-mode`); + test(t => assert_equals(value.site, expected.site), `${tag}: sec-fetch-site`); + test(t => assert_equals(value.user, expected.user), `${tag}: sec-fetch-user`); + }); +} + +function validate_expectations_custom_url(url, header, expected, tag) { + return fetch(url, header) + .then(response => response.text()) + .then(text => { + assert_not_equals(text, "No header has been recorded"); + let value = JSON.parse(text); + test(t => assert_equals(value.dest, expected.dest), `${tag}: sec-fetch-dest`); + test(t => assert_equals(value.mode, expected.mode), `${tag}: sec-fetch-mode`); + test(t => assert_equals(value.site, expected.site), `${tag}: sec-fetch-site`); + test(t => assert_equals(value.user, expected.user), `${tag}: sec-fetch-user`); + }); +} + +/** + * @param {object} value + * @param {object} expected + * @param {string} tag + **/ +function assert_header_equals(value, expected, tag) { + if (typeof(value) === "string"){ + assert_not_equals(value, "No header has been recorded"); + value = JSON.parse(value); + } + + test(t => assert_equals(value.dest, expected.dest), `${tag}: sec-fetch-dest`); + test(t => assert_equals(value.mode, expected.mode), `${tag}: sec-fetch-mode`); + test(t => assert_equals(value.site, expected.site), `${tag}: sec-fetch-site`); + test(t => assert_equals(value.user, expected.user), `${tag}: sec-fetch-user`); +} diff --git a/test/wpt/tests/fetch/metadata/resources/helper.sub.js b/test/wpt/tests/fetch/metadata/resources/helper.sub.js new file mode 100644 index 0000000..fd179fe --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/helper.sub.js @@ -0,0 +1,67 @@ +'use strict'; + +/** + * Construct a URL which, when followed, will trigger redirection through zero + * or more specified origins and ultimately resolve in the Python handler + * `record-headers.py`. + * + * @param {string} key - the WPT server "stash" name where the request's + * headers should be stored + * @param {string[]} [origins] - zero or more origin names through which the + * request should pass; see the function + * implementation for a completel list of names + * and corresponding origins; If specified, the + * final origin will be used to access the + * `record-headers.py` hander. + * @param {object} [params] - a collection of key-value pairs to include as + * URL "search" parameters in the final request to + * `record-headers.py` + * + * @returns {string} an absolute URL + */ +function makeRequestURL(key, origins, params) { + const byName = { + httpOrigin: 'http://{{host}}:{{ports[http][0]}}', + httpSameSite: 'http://{{hosts[][www]}}:{{ports[http][0]}}', + httpCrossSite: 'http://{{hosts[alt][]}}:{{ports[http][0]}}', + httpsOrigin: 'https://{{host}}:{{ports[https][0]}}', + httpsSameSite: 'https://{{hosts[][www]}}:{{ports[https][0]}}', + httpsCrossSite: 'https://{{hosts[alt][]}}:{{ports[https][0]}}' + }; + const redirectPath = '/fetch/api/resources/redirect.py?location='; + const path = '/fetch/metadata/resources/record-headers.py?key=' + key; + + let requestUrl = path; + if (params) { + requestUrl += '&' + new URLSearchParams(params).toString(); + } + + if (origins && origins.length) { + requestUrl = byName[origins.pop()] + requestUrl; + + while (origins.length) { + requestUrl = byName[origins.pop()] + redirectPath + + encodeURIComponent(requestUrl); + } + } else { + requestUrl = byName.httpsOrigin + requestUrl; + } + + return requestUrl; +} + +function retrieve(key, options) { + return fetch('/fetch/metadata/resources/record-headers.py?retrieve&key=' + key) + .then((response) => { + if (response.status === 204 && options && options.poll) { + return new Promise((resolve) => setTimeout(resolve, 300)) + .then(() => retrieve(key, options)); + } + + if (response.status !== 200) { + throw new Error('Failed to query for recorded headers.'); + } + + return response.text().then((text) => JSON.parse(text)); + }); +} diff --git a/test/wpt/tests/fetch/metadata/resources/message-opener.html b/test/wpt/tests/fetch/metadata/resources/message-opener.html new file mode 100644 index 0000000..eb2af7b --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/message-opener.html @@ -0,0 +1,17 @@ + diff --git a/test/wpt/tests/fetch/metadata/resources/post-to-owner.py b/test/wpt/tests/fetch/metadata/resources/post-to-owner.py new file mode 100644 index 0000000..256dd6e --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/post-to-owner.py @@ -0,0 +1,36 @@ +import json + +from wptserve.utils import isomorphic_decode + +def main(request, response): + headers = [ + (b"Content-Type", b"text/html"), + (b"Cache-Control", b"no-cache, no-store, must-revalidate") + ] + key = request.GET.first(b"key", None) + + # We serialize the key into JSON, so have to decode it first. + if key is not None: + key = key.decode('utf-8') + + body = u""" + + + + """ % (json.dumps({ + u"dest": isomorphic_decode(request.headers.get(b"sec-fetch-dest", b"")), + u"mode": isomorphic_decode(request.headers.get(b"sec-fetch-mode", b"")), + u"site": isomorphic_decode(request.headers.get(b"sec-fetch-site", b"")), + u"user": isomorphic_decode(request.headers.get(b"sec-fetch-user", b"")), + }), json.dumps(key)) + return headers, body diff --git a/test/wpt/tests/fetch/metadata/resources/record-header.py b/test/wpt/tests/fetch/metadata/resources/record-header.py new file mode 100644 index 0000000..29ff2ed --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/record-header.py @@ -0,0 +1,145 @@ +import os +import hashlib +import json + +from wptserve.utils import isomorphic_decode + +def main(request, response): + ## Get the query parameter (key) from URL ## + ## Tests will record POST requests (CSP Report) and GET (rest) ## + if request.GET: + key = request.GET[b'file'] + elif request.POST: + key = request.POST[b'file'] + + ## Convert the key from String to UUID valid String ## + testId = hashlib.md5(key).hexdigest() + + ## Handle the header retrieval request ## + if b'retrieve' in request.GET: + response.writer.write_status(200) + response.writer.write_header(b"Connection", b"close") + response.writer.end_headers() + try: + header_value = request.server.stash.take(testId) + response.writer.write(header_value) + except (KeyError, ValueError) as e: + response.writer.write(u"No header has been recorded") + pass + + response.close_connection = True + + ## Record incoming fetch metadata header value + else: + try: + ## Return a serialized JSON object with one member per header. If the ## + ## header isn't present, the member will contain an empty string. ## + header = json.dumps({ + u"dest": isomorphic_decode(request.headers.get(b"sec-fetch-dest", b"")), + u"mode": isomorphic_decode(request.headers.get(b"sec-fetch-mode", b"")), + u"site": isomorphic_decode(request.headers.get(b"sec-fetch-site", b"")), + u"user": isomorphic_decode(request.headers.get(b"sec-fetch-user", b"")), + }) + request.server.stash.put(testId, header) + except KeyError: + ## The header is already recorded or it doesn't exist + pass + + ## Prevent the browser from caching returned responses and allow CORS ## + response.headers.set(b"Access-Control-Allow-Origin", b"*") + response.headers.set(b"Cache-Control", b"no-cache, no-store, must-revalidate") + response.headers.set(b"Pragma", b"no-cache") + response.headers.set(b"Expires", b"0") + + ## Add a valid ServiceWorker Content-Type ## + if key.startswith(b"serviceworker"): + response.headers.set(b"Content-Type", b"application/javascript") + + ## Add a valid image Content-Type ## + if key.startswith(b"image"): + response.headers.set(b"Content-Type", b"image/png") + file = open(os.path.join(request.doc_root, u"media", u"1x1-green.png"), u"rb") + image = file.read() + file.close() + return image + + ## Return a valid .vtt content for the tag ## + if key.startswith(b"track"): + return b"WEBVTT" + + ## Return a valid SharedWorker ## + if key.startswith(b"sharedworker"): + response.headers.set(b"Content-Type", b"application/javascript") + file = open(os.path.join(request.doc_root, u"fetch", u"metadata", + u"resources", u"sharedWorker.js"), u"rb") + shared_worker = file.read() + file.close() + return shared_worker + + ## Return a valid font content and Content-Type ## + if key.startswith(b"font"): + response.headers.set(b"Content-Type", b"application/x-font-ttf") + file = open(os.path.join(request.doc_root, u"fonts", u"Ahem.ttf"), u"rb") + font = file.read() + file.close() + return font + + ## Return a valid audio content and Content-Type ## + if key.startswith(b"audio"): + response.headers.set(b"Content-Type", b"audio/mpeg") + file = open(os.path.join(request.doc_root, u"media", u"sound_5.mp3"), u"rb") + audio = file.read() + file.close() + return audio + + ## Return a valid video content and Content-Type ## + if key.startswith(b"video"): + response.headers.set(b"Content-Type", b"video/mp4") + file = open(os.path.join(request.doc_root, u"media", u"A4.mp4"), u"rb") + video = file.read() + file.close() + return video + + ## Return valid style content and Content-Type ## + if key.startswith(b"style"): + response.headers.set(b"Content-Type", b"text/css") + return b"div { }" + + ## Return a valid embed/object content and Content-Type ## + if key.startswith(b"embed") or key.startswith(b"object"): + response.headers.set(b"Content-Type", b"text/html") + return b"EMBED!" + + ## Return a valid image content and Content-Type for redirect requests ## + if key.startswith(b"redirect"): + response.headers.set(b"Content-Type", b"image/jpeg") + file = open(os.path.join(request.doc_root, u"media", u"1x1-green.png"), u"rb") + image = file.read() + file.close() + return image + + ## Return a valid dedicated worker + if key.startswith(b"worker"): + response.headers.set(b"Content-Type", b"application/javascript") + return b"self.postMessage('loaded');" + + ## Return a valid worklet + if key.startswith(b"worklet"): + response.headers.set(b"Content-Type", b"application/javascript") + return b"" + + ## Return a valid XSLT + if key.startswith(b"xslt"): + response.headers.set(b"Content-Type", b"text/xsl") + return b""" + + + + + + +""" + + if key.startswith(b"script"): + response.headers.set(b"Content-Type", b"application/javascript") + return b"void 0;" diff --git a/test/wpt/tests/fetch/metadata/resources/record-headers.py b/test/wpt/tests/fetch/metadata/resources/record-headers.py new file mode 100644 index 0000000..0362fe2 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/record-headers.py @@ -0,0 +1,73 @@ +import os +import uuid +import hashlib +import time +import json + + +def bytes_to_strings(d): + # Recursively convert bytes to strings in `d`. + if not isinstance(d, dict): + if isinstance(d, (tuple,list,set)): + v = [bytes_to_strings(x) for x in d] + return v + else: + if isinstance(d, bytes): + d = d.decode() + return d + + result = {} + for k,v in d.items(): + if isinstance(k, bytes): + k = k.decode() + if isinstance(v, dict): + v = bytes_to_strings(v) + elif isinstance(v, (tuple,list,set)): + v = [bytes_to_strings(x) for x in v] + elif isinstance(v, bytes): + v = v.decode() + result[k] = v + return result + + +def main(request, response): + # This condition avoids false positives from CORS preflight checks, where the + # request under test may be followed immediately by a request to the same URL + # using a different HTTP method. + if b'requireOPTIONS' in request.GET and request.method != b'OPTIONS': + return + + if b'key' in request.GET: + key = request.GET[b'key'] + elif b'key' in request.POST: + key = request.POST[b'key'] + + ## Convert the key from String to UUID valid String ## + testId = hashlib.md5(key).hexdigest() + + ## Handle the header retrieval request ## + if b'retrieve' in request.GET: + recorded_headers = request.server.stash.take(testId) + + if recorded_headers is None: + return (204, [], b'') + + return (200, [], recorded_headers) + + ## Record incoming fetch metadata header value + else: + try: + request.server.stash.put(testId, json.dumps(bytes_to_strings(request.headers))) + except KeyError: + ## The header is already recorded or it doesn't exist + pass + + ## Prevent the browser from caching returned responses and allow CORS ## + response.headers.set(b"Access-Control-Allow-Origin", b"*") + response.headers.set(b"Cache-Control", b"no-cache, no-store, must-revalidate") + response.headers.set(b"Pragma", b"no-cache") + response.headers.set(b"Expires", b"0") + if b"mime" in request.GET: + response.headers.set(b"Content-Type", request.GET.first(b"mime")) + + return request.GET.first(b"body", request.POST.first(b"body", b"")) diff --git a/test/wpt/tests/fetch/metadata/resources/redirectTestHelper.sub.js b/test/wpt/tests/fetch/metadata/resources/redirectTestHelper.sub.js new file mode 100644 index 0000000..1bfbbae --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/redirectTestHelper.sub.js @@ -0,0 +1,167 @@ +function createVideoElement() { + let el = document.createElement('video'); + el.src = '/media/movie_5.mp4'; + el.setAttribute('controls', ''); + el.setAttribute('crossorigin', ''); + return el; +} + +function createTrack() { + let el = document.createElement('track'); + el.setAttribute('default', ''); + el.setAttribute('kind', 'captions'); + el.setAttribute('srclang', 'en'); + return el; +} + +let secureRedirectURL = 'https://{{host}}:{{ports[https][0]}}/fetch/api/resources/redirect.py?location='; +let insecureRedirectURL = 'http://{{host}}:{{ports[http][0]}}/fetch/api/resources/redirect.py?location='; +let secureTestURL = 'https://{{host}}:{{ports[https][0]}}/fetch/metadata/'; +let insecureTestURL = 'http://{{host}}:{{ports[http][0]}}/fetch/metadata/'; + +// Helper to craft an URL that will go from HTTPS => HTTP => HTTPS to +// simulate us downgrading then upgrading again during the same redirect chain. +function MultipleRedirectTo(partialPath) { + let finalURL = insecureRedirectURL + encodeURIComponent(secureTestURL + partialPath); + return secureRedirectURL + encodeURIComponent(finalURL); +} + +// Helper to craft an URL that will go from HTTP => HTTPS to simulate upgrading a +// given request. +function upgradeRedirectTo(partialPath) { + return insecureRedirectURL + encodeURIComponent(secureTestURL + partialPath); +} + +// Helper to craft an URL that will go from HTTPS => HTTP to simulate downgrading a +// given request. +function downgradeRedirectTo(partialPath) { + return secureRedirectURL + encodeURIComponent(insecureTestURL + partialPath); +} + +// Helper to run common redirect test cases that don't require special setup on +// the test page itself. +function RunCommonRedirectTests(testNamePrefix, urlHelperMethod, expectedResults) { + async_test(t => { + let testWindow = window.open(urlHelperMethod('resources/post-to-owner.py?top-level-navigation' + nonce)); + t.add_cleanup(_ => testWindow.close()); + window.addEventListener('message', t.step_func(e => { + if (e.source != testWindow) { + return; + } + + let expectation = { ...expectedResults }; + if (expectation['mode'] != '') + expectation['mode'] = 'navigate'; + if (expectation['dest'] == 'font') + expectation['dest'] = 'document'; + assert_header_equals(e.data, expectation, testNamePrefix + ' top level navigation'); + t.done(); + })); + }, testNamePrefix + ' top level navigation'); + + promise_test(t => { + return new Promise((resolve, reject) => { + let key = 'embed-https-redirect' + nonce; + let e = document.createElement('embed'); + e.src = urlHelperMethod('resources/record-header.py?file=' + key); + e.onload = e => { + let expectation = { ...expectedResults }; + if (expectation['mode'] != '') + expectation['mode'] = 'navigate'; + if (expectation['dest'] == 'font') + expectation['dest'] = 'embed'; + fetch('/fetch/metadata/resources/record-header.py?retrieve=true&file=' + key) + .then(response => response.text()) + .then(t.step_func(text => assert_header_equals(text, expectation, testNamePrefix + ' embed'))) + .then(resolve) + .catch(e => reject(e)); + }; + document.body.appendChild(e); + }); + }, testNamePrefix + ' embed'); + + promise_test(t => { + return new Promise((resolve, reject) => { + let key = 'object-https-redirect' + nonce; + let e = document.createElement('object'); + e.data = urlHelperMethod('resources/record-header.py?file=' + key); + e.onload = e => { + let expectation = { ...expectedResults }; + if (expectation['mode'] != '') + expectation['mode'] = 'navigate'; + if (expectation['dest'] == 'font') + expectation['dest'] = 'object'; + fetch('/fetch/metadata/resources/record-header.py?retrieve=true&file=' + key) + .then(response => response.text()) + .then(t.step_func(text => assert_header_equals(text, expectation, testNamePrefix + ' object'))) + .then(resolve) + .catch(e => reject(e)); + }; + document.body.appendChild(e); + }); + }, testNamePrefix + ' object'); + + if (document.createElement('link').relList.supports('preload')) { + async_test(t => { + let key = 'preload' + nonce; + let e = document.createElement('link'); + e.rel = 'preload'; + e.href = urlHelperMethod('resources/record-header.py?file=' + key); + e.setAttribute('as', 'track'); + e.onload = e.onerror = t.step_func_done(e => { + let expectation = { ...expectedResults }; + if (expectation['mode'] != '') + expectation['mode'] = 'cors'; + fetch('/fetch/metadata/resources/record-header.py?retrieve=true&file=' + key) + .then(t.step_func(response => response.text())) + .then(t.step_func_done(text => assert_header_equals(text, expectation, testNamePrefix + ' preload'))) + .catch(t.unreached_func()); + }); + document.head.appendChild(e); + }, testNamePrefix + ' preload'); + } + + promise_test(t => { + return new Promise((resolve, reject) => { + let key = 'style-https-redirect' + nonce; + let e = document.createElement('link'); + e.rel = 'stylesheet'; + e.href = urlHelperMethod('resources/record-header.py?file=' + key); + e.onload = e => { + let expectation = { ...expectedResults }; + if (expectation['mode'] != '') + expectation['mode'] = 'no-cors'; + if (expectation['dest'] == 'font') + expectation['dest'] = 'style'; + fetch('/fetch/metadata/resources/record-header.py?retrieve=true&file=' + key) + .then(response => response.text()) + .then(t.step_func(text => assert_header_equals(text, expectation, testNamePrefix + ' stylesheet'))) + .then(resolve) + .catch(e => reject(e)); + }; + document.body.appendChild(e); + }); + }, testNamePrefix + ' stylesheet'); + + promise_test(t => { + return new Promise((resolve, reject) => { + let key = 'track-https-redirect' + nonce; + let video = createVideoElement(); + let el = createTrack(); + el.src = urlHelperMethod('resources/record-header.py?file=' + key); + el.onload = t.step_func(_ => { + let expectation = { ...expectedResults }; + if (expectation['mode'] != '') + expectation['mode'] = 'cors'; + if (expectation['dest'] == 'font') + expectation['dest'] = 'track'; + fetch('/fetch/metadata/resources/record-header.py?retrieve=true&file=' + key) + .then(response => response.text()) + .then(t.step_func(text => assert_header_equals(text, expectation, testNamePrefix + ' track'))) + .then(resolve); + }); + video.appendChild(el); + document.body.appendChild(video); + }); + }, testNamePrefix + ' track'); +} diff --git a/test/wpt/tests/fetch/metadata/resources/serviceworker-accessors-frame.html b/test/wpt/tests/fetch/metadata/resources/serviceworker-accessors-frame.html new file mode 100644 index 0000000..9879802 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/serviceworker-accessors-frame.html @@ -0,0 +1,3 @@ + + +Page Title diff --git a/test/wpt/tests/fetch/metadata/resources/serviceworker-accessors.sw.js b/test/wpt/tests/fetch/metadata/resources/serviceworker-accessors.sw.js new file mode 100644 index 0000000..36c55a7 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/serviceworker-accessors.sw.js @@ -0,0 +1,14 @@ +addEventListener("fetch", event => { + event.waitUntil(async function () { + if (!event.clientId) return; + const client = await clients.get(event.clientId); + if (!client) return; + + client.postMessage({ + "dest": event.request.headers.get("sec-fetch-dest"), + "mode": event.request.headers.get("sec-fetch-mode"), + "site": event.request.headers.get("sec-fetch-site"), + "user": event.request.headers.get("sec-fetch-user") + }); + }()); +}); diff --git a/test/wpt/tests/fetch/metadata/resources/sharedWorker.js b/test/wpt/tests/fetch/metadata/resources/sharedWorker.js new file mode 100644 index 0000000..5eb89cb --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/sharedWorker.js @@ -0,0 +1,9 @@ +onconnect = function(e) { + var port = e.ports[0]; + + port.addEventListener('message', function(e) { + port.postMessage("Ready"); + }); + + port.start(); +} diff --git a/test/wpt/tests/fetch/metadata/resources/unload-with-beacon.html b/test/wpt/tests/fetch/metadata/resources/unload-with-beacon.html new file mode 100644 index 0000000..b00c9a5 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/unload-with-beacon.html @@ -0,0 +1,12 @@ + + diff --git a/test/wpt/tests/fetch/metadata/resources/xslt-test.sub.xml b/test/wpt/tests/fetch/metadata/resources/xslt-test.sub.xml new file mode 100644 index 0000000..acb478a --- /dev/null +++ b/test/wpt/tests/fetch/metadata/resources/xslt-test.sub.xml @@ -0,0 +1,12 @@ + + + + + + diff --git a/test/wpt/tests/fetch/metadata/serviceworker-accessors.https.sub.html b/test/wpt/tests/fetch/metadata/serviceworker-accessors.https.sub.html new file mode 100644 index 0000000..03a8321 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/serviceworker-accessors.https.sub.html @@ -0,0 +1,51 @@ + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/sharedworker.https.sub.html b/test/wpt/tests/fetch/metadata/sharedworker.https.sub.html new file mode 100644 index 0000000..4df8582 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/sharedworker.https.sub.html @@ -0,0 +1,40 @@ + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/style.https.sub.html b/test/wpt/tests/fetch/metadata/style.https.sub.html new file mode 100644 index 0000000..a30d81d --- /dev/null +++ b/test/wpt/tests/fetch/metadata/style.https.sub.html @@ -0,0 +1,86 @@ + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/README.md b/test/wpt/tests/fetch/metadata/tools/README.md new file mode 100644 index 0000000..1c3bac2 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/README.md @@ -0,0 +1,126 @@ +# Fetch Metadata test generation framework + +This directory defines a command-line tool for procedurally generating WPT +tests. + +## Motivation + +Many features of the web platform involve the browser making one or more HTTP +requests to remote servers. Only some aspects of these requests are specified +within the standard that defines the relevant feature. Other aspects are +specified by external standards which span the entire platform (e.g. [Fetch +Metadata Request Headers](https://w3c.github.io/webappsec-fetch-metadata/)). + +This state of affairs makes it difficult to maintain test coverage for two +reasons: + +- When a new feature introduces a new kind of web request, it must be verified + to integrate with every cross-cutting standard. +- When a new cross-cutting standard is introduced, it must be verified to + integrate with every kind of web request. + +The tool in this directory attempts to reduce this tension. It allows +maintainers to express instructions for making web requests in an abstract +sense. These generic instructions can be reused by to produce a different suite +of tests for each cross-cutting feature. + +When a new kind of request is proposed, a single generic template can be +defined here. This will provide the maintainers of all cross-cutting features +with clear instruction on how to extend their test suite with the new feature. + +Similarly, when a new cross-cutting feature is proposed, the authors can use +this tool to build a test suite which spans the entire platform. + +## Build script + +To generate the Fetch Metadata tests, run `./wpt update-built --include fetch` +in the root of the repository. + +## Configuration + +The test generation tool requires a YAML-formatted configuration file as its +input. The file should define a dictionary with the following keys: + +- `templates` - a string describing the filesystem path from which template + files should be loaded +- `output_directory` - a string describing the filesystem path where the + generated test files should be written +- `cases` - a list of dictionaries describing how the test templates should be + expanded with individual subtests; each dictionary should have the following + keys: + - `all_subtests` - properties which should be defined for every expansion + - `common_axis` - a list of dictionaries + - `template_axes` - a dictionary relating template names to properties that + should be used when expanding that particular template + +Internally, the tool creates a set of "subtests" for each template. This set is +the Cartesian product of the `common_axis` and the given template's entry in +the `template_axes` dictionary. It uses this set of subtests to expand the +template, creating an output file. Refer to the next section for a concrete +example of how the expansion is performed. + +In general, the tool will output a single file for each template. However, the +`filename_flags` attribute has special semantics. It is used to separate +subtests for the same template file. This is intended to accommodate [the +web-platform-test's filename-based +conventions](https://web-platform-tests.org/writing-tests/file-names.html). + +For instance, when `.https` is present in a test file's name, the WPT test +harness will load that test using the HTTPS protocol. Subtests which include +the value `https` in the `filename_flags` property will be expanded using the +appropriate template but written to a distinct file whose name includes +`.https`. + +The generation tool requires that the configuration file references every +template in the `templates` directory. Because templates and configuration +files may be contributed by different people, this requirement ensures that +configuration authors are aware of all available templates. Some templates may +not be relevant for some features; in those cases, the configuration file can +include an empty array for the template's entry in the `template_axes` +dictionary (as in `template3.html` in the example which follows). + +## Expansion example + +In the following example configuration file, `a`, `b`, `s`, `w`, `x`, `y`, and +`z` all represent associative arrays. + +```yaml +templates: path/to/templates +output_directory: path/to/output +cases: + - every_subtest: s + common_axis: [a, b] + template_axes: + template1.html: [w] + template2.html: [x, y, z] + template3.html: [] +``` + +When run with such a configuration file, the tool would generate two files, +expanded with data as described below (where `(a, b)` represents the union of +`a` and `b`): + + template1.html: [(a, w), (b, w)] + template2.html: [(a, x), (b, x), (a, y), (b, y), (a, z), (b, z)] + template3.html: (zero tests; not expanded) + +## Design Considerations + +**Efficiency of generated output** The tool is capable of generating a large +number of tests given a small amount of input. Naively structured, this could +result in test suites which take large amount of time and computational +resources to complete. The tool has been designed to help authors structure the +generated output to reduce these resource requirements. + +**Literalness of generated output** Because the generated output is how most +people will interact with the tests, it is important that it be approachable. +This tool avoids outputting abstractions which would frustrate attempts to read +the source code or step through its execution environment. + +**Simplicity** The test generation logic itself was written to be approachable. +This makes it easier to anticipate how the tool will behave with new input, and +it lowers the bar for others to contribute improvements. + +Non-goals include conciseness of template files (verbosity makes the potential +expansions more predictable) and conciseness of generated output (verbosity +aids in the interpretation of results). diff --git a/test/wpt/tests/fetch/metadata/tools/fetch-metadata.conf.yml b/test/wpt/tests/fetch/metadata/tools/fetch-metadata.conf.yml new file mode 100644 index 0000000..b277bcb --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/fetch-metadata.conf.yml @@ -0,0 +1,806 @@ +--- +templates: templates +output_directory: ../generated +cases: + - all_subtests: + expected: NULL + filename_flags: [] + common_axis: + - headerName: sec-fetch-site + origins: [httpOrigin] + description: Not sent to non-trustworthy same-origin destination + - headerName: sec-fetch-site + origins: [httpSameSite] + description: Not sent to non-trustworthy same-site destination + - headerName: sec-fetch-site + origins: [httpCrossSite] + description: Not sent to non-trustworthy cross-site destination + - headerName: sec-fetch-mode + origins: [httpOrigin] + description: Not sent to non-trustworthy same-origin destination + - headerName: sec-fetch-mode + origins: [httpSameSite] + description: Not sent to non-trustworthy same-site destination + - headerName: sec-fetch-mode + origins: [httpCrossSite] + description: Not sent to non-trustworthy cross-site destination + - headerName: sec-fetch-dest + origins: [httpOrigin] + description: Not sent to non-trustworthy same-origin destination + - headerName: sec-fetch-dest + origins: [httpSameSite] + description: Not sent to non-trustworthy same-site destination + - headerName: sec-fetch-dest + origins: [httpCrossSite] + description: Not sent to non-trustworthy cross-site destination + - headerName: sec-fetch-user + origins: [httpOrigin] + description: Not sent to non-trustworthy same-origin destination + - headerName: sec-fetch-user + origins: [httpSameSite] + description: Not sent to non-trustworthy same-site destination + - headerName: sec-fetch-user + origins: [httpCrossSite] + description: Not sent to non-trustworthy cross-site destination + template_axes: + # Unused + appcache-manifest.sub.https.html: [] + # The `audioWorklet` interface is only available in secure contexts + # https://webaudio.github.io/web-audio-api/#BaseAudioContext + audioworklet.https.sub.html: [] + # Service workers are only available in secure context + fetch-via-serviceworker.https.sub.html: [] + # Service workers are only available in secure context + serviceworker.https.sub.html: [] + + css-images.sub.html: + - filename_flags: [tentative] + css-font-face.sub.html: + - filename_flags: [tentative] + element-a.sub.html: [{}] + element-area.sub.html: [{}] + element-audio.sub.html: [{}] + element-embed.sub.html: [{}] + element-frame.sub.html: [{}] + element-iframe.sub.html: [{}] + element-img.sub.html: + - sourceAttr: src + - sourceAttr: srcset + element-img-environment-change.sub.html: [{}] + element-input-image.sub.html: [{}] + element-link-icon.sub.html: [{}] + element-link-prefetch.optional.sub.html: [{}] + element-meta-refresh.optional.sub.html: [{}] + element-picture.sub.html: [{}] + element-script.sub.html: + - {} + - elementAttrs: { type: module } + element-video.sub.html: [{}] + element-video-poster.sub.html: [{}] + fetch.sub.html: [{}] + form-submission.sub.html: + - method: GET + - method: POST + header-link.sub.html: + - rel: icon + - rel: stylesheet + header-refresh.optional.sub.html: [{}] + window-location.sub.html: [{}] + script-module-import-dynamic.sub.html: [{}] + script-module-import-static.sub.html: [{}] + svg-image.sub.html: [{}] + window-history.sub.html: [{}] + worker-dedicated-importscripts.sub.html: [{}] + worker-dedicated-constructor.sub.html: [{}] + + # Sec-Fetch-Site - direct requests + - all_subtests: + headerName: sec-fetch-site + filename_flags: [https] + common_axis: + - description: Same origin + origins: [httpsOrigin] + expected: same-origin + - description: Cross-site + origins: [httpsCrossSite] + expected: cross-site + - description: Same site + origins: [httpsSameSite] + expected: same-site + template_axes: + # Unused + # - the request mode of all "classic" worker scripts is set to + # "same-origin" + # https://html.spec.whatwg.org/#fetch-a-classic-worker-script + # - the request mode of all "top-level "module" worker scripts is set to + # "same-origin": + # https://html.spec.whatwg.org/#fetch-a-single-module-script + worker-dedicated-constructor.sub.html: [] + + appcache-manifest.sub.https.html: [{}] + audioworklet.https.sub.html: [{}] + css-images.sub.html: + - filename_flags: [tentative] + css-font-face.sub.html: + - filename_flags: [tentative] + element-a.sub.html: [{}] + element-area.sub.html: [{}] + element-audio.sub.html: [{}] + element-embed.sub.html: [{}] + element-frame.sub.html: [{}] + element-iframe.sub.html: [{}] + element-img.sub.html: + - sourceAttr: src + - sourceAttr: srcset + element-img-environment-change.sub.html: [{}] + element-input-image.sub.html: [{}] + element-link-icon.sub.html: [{}] + element-link-prefetch.optional.sub.html: [{}] + element-meta-refresh.optional.sub.html: [{}] + element-picture.sub.html: [{}] + element-script.sub.html: + - {} + - elementAttrs: { type: module } + element-video.sub.html: [{}] + element-video-poster.sub.html: [{}] + fetch.sub.html: [{ init: { mode: no-cors } }] + fetch-via-serviceworker.https.sub.html: [{ init: { mode: no-cors } }] + form-submission.sub.html: + - method: GET + - method: POST + header-link.sub.html: + - rel: icon + - rel: stylesheet + header-refresh.optional.sub.html: [{}] + window-location.sub.html: [{}] + script-module-import-dynamic.sub.html: [{}] + script-module-import-static.sub.html: [{}] + serviceworker.https.sub.html: [{}] + svg-image.sub.html: [{}] + window-history.sub.html: [{}] + worker-dedicated-importscripts.sub.html: [{}] + + # Sec-Fetch-Site - redirection from HTTP + - all_subtests: + headerName: sec-fetch-site + filename_flags: [] + common_axis: + - description: HTTPS downgrade (header not sent) + origins: [httpsOrigin, httpOrigin] + expected: NULL + - description: HTTPS upgrade + origins: [httpOrigin, httpsOrigin] + expected: cross-site + - description: HTTPS downgrade-upgrade + origins: [httpsOrigin, httpOrigin, httpsOrigin] + expected: cross-site + template_axes: + # Unused + # The `audioWorklet` interface is only available in secure contexts + # https://webaudio.github.io/web-audio-api/#BaseAudioContext + audioworklet.https.sub.html: [] + # Service workers are only available in secure context + fetch-via-serviceworker.https.sub.html: [] + # Service workers' redirect mode is "error" + serviceworker.https.sub.html: [] + # Interstitial locations in an HTTP redirect chain are not added to the + # session history, so these requests cannot be initiated using the + # History API. + window-history.sub.html: [] + # Unused + # - the request mode of all "classic" worker scripts is set to + # "same-origin" + # https://html.spec.whatwg.org/#fetch-a-classic-worker-script + # - the request mode of all "top-level "module" worker scripts is set to + # "same-origin": + # https://html.spec.whatwg.org/#fetch-a-single-module-script + worker-dedicated-constructor.sub.html: [] + + appcache-manifest.sub.https.html: [{}] + css-images.sub.html: + - filename_flags: [tentative] + css-font-face.sub.html: + - filename_flags: [tentative] + element-a.sub.html: [{}] + element-area.sub.html: [{}] + element-audio.sub.html: [{}] + element-embed.sub.html: [{}] + element-frame.sub.html: [{}] + element-iframe.sub.html: [{}] + element-img.sub.html: + - sourceAttr: src + - sourceAttr: srcset + element-img-environment-change.sub.html: [{}] + element-input-image.sub.html: [{}] + element-link-icon.sub.html: [{}] + element-link-prefetch.optional.sub.html: [{}] + element-meta-refresh.optional.sub.html: [{}] + element-picture.sub.html: [{}] + element-script.sub.html: + - {} + - elementAttrs: { type: module } + element-video.sub.html: [{}] + element-video-poster.sub.html: [{}] + fetch.sub.html: [{}] + form-submission.sub.html: + - method: GET + - method: POST + header-link.sub.html: + - rel: icon + - rel: stylesheet + header-refresh.optional.sub.html: [{}] + window-location.sub.html: [{}] + script-module-import-dynamic.sub.html: [{}] + script-module-import-static.sub.html: [{}] + svg-image.sub.html: [{}] + worker-dedicated-importscripts.sub.html: [{}] + + # Sec-Fetch-Site - redirection from HTTPS + - all_subtests: + headerName: sec-fetch-site + filename_flags: [https] + common_axis: + - description: Same-Origin -> Cross-Site -> Same-Origin redirect + origins: [httpsOrigin, httpsCrossSite, httpsOrigin] + expected: cross-site + - description: Same-Origin -> Same-Site -> Same-Origin redirect + origins: [httpsOrigin, httpsSameSite, httpsOrigin] + expected: same-site + - description: Cross-Site -> Same Origin + origins: [httpsCrossSite, httpsOrigin] + expected: cross-site + - description: Cross-Site -> Same-Site + origins: [httpsCrossSite, httpsSameSite] + expected: cross-site + - description: Cross-Site -> Cross-Site + origins: [httpsCrossSite, httpsCrossSite] + expected: cross-site + - description: Same-Origin -> Same Origin + origins: [httpsOrigin, httpsOrigin] + expected: same-origin + - description: Same-Origin -> Same-Site + origins: [httpsOrigin, httpsSameSite] + expected: same-site + - description: Same-Origin -> Cross-Site + origins: [httpsOrigin, httpsCrossSite] + expected: cross-site + - description: Same-Site -> Same Origin + origins: [httpsSameSite, httpsOrigin] + expected: same-site + - description: Same-Site -> Same-Site + origins: [httpsSameSite, httpsSameSite] + expected: same-site + - description: Same-Site -> Cross-Site + origins: [httpsSameSite, httpsCrossSite] + expected: cross-site + template_axes: + # Service Workers' redirect mode is "error" + serviceworker.https.sub.html: [] + # Interstitial locations in an HTTP redirect chain are not added to the + # session history, so these requests cannot be initiated using the + # History API. + window-history.sub.html: [] + # Unused + # - the request mode of all "classic" worker scripts is set to + # "same-origin" + # https://html.spec.whatwg.org/#fetch-a-classic-worker-script + # - the request mode of all "top-level "module" worker scripts is set to + # "same-origin": + # https://html.spec.whatwg.org/#fetch-a-single-module-script + worker-dedicated-constructor.sub.html: [] + + appcache-manifest.sub.https.html: [{}] + audioworklet.https.sub.html: [{}] + css-images.sub.html: + - filename_flags: [tentative] + css-font-face.sub.html: + - filename_flags: [tentative] + element-a.sub.html: [{}] + element-area.sub.html: [{}] + element-audio.sub.html: [{}] + element-embed.sub.html: [{}] + element-frame.sub.html: [{}] + element-iframe.sub.html: [{}] + element-img.sub.html: + - sourceAttr: src + - sourceAttr: srcset + element-img-environment-change.sub.html: [{}] + element-input-image.sub.html: [{}] + element-link-icon.sub.html: [{}] + element-link-prefetch.optional.sub.html: [{}] + element-meta-refresh.optional.sub.html: [{}] + element-picture.sub.html: [{}] + element-script.sub.html: + - {} + - elementAttrs: { type: module } + element-video.sub.html: [{}] + element-video-poster.sub.html: [{}] + fetch.sub.html: [{ init: { mode: no-cors } }] + fetch-via-serviceworker.https.sub.html: [{ init: { mode: no-cors } }] + form-submission.sub.html: + - method: GET + - method: POST + header-link.sub.html: + - rel: icon + - rel: stylesheet + header-refresh.optional.sub.html: [{}] + window-location.sub.html: [{}] + script-module-import-dynamic.sub.html: [{}] + script-module-import-static.sub.html: [{}] + svg-image.sub.html: [{}] + worker-dedicated-importscripts.sub.html: [{}] + + # Sec-Fetch-Site - redirection with mixed content + # These tests verify the effect that redirection has on the request's "site". + # The initial request must be made to a resource that is "same-site" with its + # origin. This avoids false positives because if the request were made to a + # cross-site resource, the value of "cross-site" would be assigned regardless + # of the subseqent redirection. + # + # Because these conditions necessarily warrant mixed content, only templates + # which can be configured to allow mixed content [1] can be used. + # + # [1] https://w3c.github.io/webappsec-mixed-content/#should-block-fetch + + - common_axis: + - description: HTTPS downgrade-upgrade + headerName: sec-fetch-site + origins: [httpsOrigin, httpOrigin, httpsOrigin] + expected: cross-site + filename_flags: [https] + template_axes: + # Mixed Content considers only a small subset of requests as + # "optionally-blockable." These are the only requests that can be tested + # for the "downgrade-upgrade" scenario, so all other templates must be + # explicitly ignored. + audioworklet.https.sub.html: [] + css-font-face.sub.html: [] + element-embed.sub.html: [] + element-frame.sub.html: [] + element-iframe.sub.html: [] + element-img-environment-change.sub.html: [] + element-link-icon.sub.html: [] + element-link-prefetch.optional.sub.html: [] + element-picture.sub.html: [] + element-script.sub.html: [] + fetch.sub.html: [] + fetch-via-serviceworker.https.sub.html: [] + header-link.sub.html: [] + script-module-import-static.sub.html: [] + script-module-import-dynamic.sub.html: [] + # Service Workers' redirect mode is "error" + serviceworker.https.sub.html: [] + # Interstitial locations in an HTTP redirect chain are not added to the + # session history, so these requests cannot be initiated using the + # History API. + window-history.sub.html: [] + worker-dedicated-constructor.sub.html: [] + worker-dedicated-importscripts.sub.html: [] + # Avoid duplicate subtest for 'sec-fetch-site - HTTPS downgrade-upgrade' + appcache-manifest.sub.https.html: [] + css-images.sub.html: + - filename_flags: [tentative] + element-a.sub.html: [{}] + element-area.sub.html: [{}] + element-audio.sub.html: [{}] + element-img.sub.html: + # srcset omitted because it is not "optionally-blockable" + # https://w3c.github.io/webappsec-mixed-content/#category-optionally-blockable + - sourceAttr: src + element-input-image.sub.html: [{}] + element-meta-refresh.optional.sub.html: [{}] + element-video.sub.html: [{}] + element-video-poster.sub.html: [{}] + form-submission.sub.html: + - method: GET + - method: POST + header-refresh.optional.sub.html: [{}] + svg-image.sub.html: [{}] + window-location.sub.html: [{}] + + # Sec-Fetch-Mode + # These tests are served over HTTPS so the induced requests will be both + # same-origin with the document [1] and a potentially-trustworthy URL [2]. + # + # [1] https://html.spec.whatwg.org/multipage/origin.html#same-origin + # [2] https://w3c.github.io/webappsec-secure-contexts/#potentially-trustworthy-url + - common_axis: + - headerName: sec-fetch-mode + filename_flags: [https] + origins: [] + template_axes: + appcache-manifest.sub.https.html: + - expected: no-cors + audioworklet.https.sub.html: + # https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script + - expected: cors + css-images.sub.html: + - expected: no-cors + filename_flags: [tentative] + css-font-face.sub.html: + - expected: cors + filename_flags: [tentative] + element-a.sub.html: + - expected: navigate + # https://html.spec.whatwg.org/multipage/links.html#downloading-hyperlinks + - elementAttrs: {download: ''} + expected: no-cors + element-area.sub.html: + - expected: navigate + # https://html.spec.whatwg.org/multipage/links.html#downloading-hyperlinks + - elementAttrs: {download: ''} + expected: no-cors + element-audio.sub.html: + - expected: no-cors + - expected: cors + elementAttrs: { crossorigin: '' } + - expected: cors + elementAttrs: { crossorigin: anonymous } + - expected: cors + elementAttrs: { crossorigin: use-credentials } + element-embed.sub.html: + - expected: no-cors + element-frame.sub.html: + - expected: navigate + element-iframe.sub.html: + - expected: navigate + element-img.sub.html: + - sourceAttr: src + expected: no-cors + - sourceAttr: src + expected: cors + elementAttrs: { crossorigin: '' } + - sourceAttr: src + expected: cors + elementAttrs: { crossorigin: anonymous } + - sourceAttr: src + expected: cors + elementAttrs: { crossorigin: use-credentials } + - sourceAttr: srcset + expected: no-cors + - sourceAttr: srcset + expected: cors + elementAttrs: { crossorigin: '' } + - sourceAttr: srcset + expected: cors + elementAttrs: { crossorigin: anonymous } + - sourceAttr: srcset + expected: cors + elementAttrs: { crossorigin: use-credentials } + element-img-environment-change.sub.html: + - expected: no-cors + - expected: cors + elementAttrs: { crossorigin: '' } + - expected: cors + elementAttrs: { crossorigin: anonymous } + - expected: cors + elementAttrs: { crossorigin: use-credentials } + element-input-image.sub.html: + - expected: no-cors + element-link-icon.sub.html: + - expected: no-cors + - expected: cors + elementAttrs: { crossorigin: '' } + - expected: cors + elementAttrs: { crossorigin: anonymous } + - expected: cors + elementAttrs: { crossorigin: use-credentials } + element-link-prefetch.optional.sub.html: + - expected: no-cors + - expected: cors + elementAttrs: { crossorigin: '' } + - expected: cors + elementAttrs: { crossorigin: anonymous } + - expected: cors + elementAttrs: { crossorigin: use-credentials } + element-meta-refresh.optional.sub.html: + - expected: navigate + element-picture.sub.html: + - expected: no-cors + - expected: cors + elementAttrs: { crossorigin: '' } + - expected: cors + elementAttrs: { crossorigin: anonymous } + - expected: cors + elementAttrs: { crossorigin: use-credentials } + element-script.sub.html: + - expected: no-cors + - expected: cors + elementAttrs: { type: module } + - expected: cors + elementAttrs: { crossorigin: '' } + - expected: cors + elementAttrs: { crossorigin: anonymous } + - expected: cors + elementAttrs: { crossorigin: use-credentials } + element-video.sub.html: + - expected: no-cors + - expected: cors + elementAttrs: { crossorigin: '' } + - expected: cors + elementAttrs: { crossorigin: anonymous } + - expected: cors + elementAttrs: { crossorigin: use-credentials } + element-video-poster.sub.html: + - expected: no-cors + fetch.sub.html: + - expected: cors + - expected: cors + init: { mode: cors } + - expected: no-cors + init: { mode: no-cors } + - expected: same-origin + init: { mode: same-origin } + fetch-via-serviceworker.https.sub.html: + - expected: cors + - expected: cors + init: { mode: cors } + - expected: no-cors + init: { mode: no-cors } + - expected: same-origin + init: { mode: same-origin } + form-submission.sub.html: + - method: GET + expected: navigate + - method: POST + expected: navigate + header-link.sub.html: + - rel: icon + expected: no-cors + - rel: stylesheet + expected: no-cors + header-refresh.optional.sub.html: + - expected: navigate + window-history.sub.html: + - expected: navigate + window-location.sub.html: + - expected: navigate + script-module-import-dynamic.sub.html: + - expected: cors + script-module-import-static.sub.html: + - expected: cors + # https://svgwg.org/svg2-draft/linking.html#processingURL-fetch + svg-image.sub.html: + - expected: no-cors + - expected: cors + elementAttrs: { crossorigin: '' } + - expected: cors + elementAttrs: { crossorigin: anonymous } + - expected: cors + elementAttrs: { crossorigin: use-credentials } + serviceworker.https.sub.html: + - expected: same-origin + options: { type: 'classic' } + # https://github.com/whatwg/html/pull/5875 + - expected: same-origin + worker-dedicated-constructor.sub.html: + - expected: same-origin + - options: { type: module } + expected: same-origin + worker-dedicated-importscripts.sub.html: + - expected: no-cors + + # Sec-Fetch-Dest + - common_axis: + - headerName: sec-fetch-dest + filename_flags: [https] + origins: [] + template_axes: + appcache-manifest.sub.https.html: + - expected: empty + audioworklet.https.sub.html: + # https://github.com/WebAudio/web-audio-api/issues/2203 + - expected: audioworklet + css-images.sub.html: + - expected: image + filename_flags: [tentative] + css-font-face.sub.html: + - expected: font + filename_flags: [tentative] + element-a.sub.html: + - expected: document + # https://html.spec.whatwg.org/multipage/links.html#downloading-hyperlinks + - elementAttrs: {download: ''} + expected: empty + element-area.sub.html: + - expected: document + # https://html.spec.whatwg.org/multipage/links.html#downloading-hyperlinks + - elementAttrs: {download: ''} + expected: empty + element-audio.sub.html: + - expected: audio + element-embed.sub.html: + - expected: embed + element-frame.sub.html: + # https://github.com/whatwg/html/pull/4976 + - expected: frame + element-iframe.sub.html: + # https://github.com/whatwg/html/pull/4976 + - expected: iframe + element-img.sub.html: + - sourceAttr: src + expected: image + - sourceAttr: srcset + expected: image + element-img-environment-change.sub.html: + - expected: image + element-input-image.sub.html: + - expected: image + element-link-icon.sub.html: + - expected: empty + element-link-prefetch.optional.sub.html: + - expected: empty + - elementAttrs: { as: audio } + expected: audio + - elementAttrs: { as: document } + expected: document + - elementAttrs: { as: embed } + expected: embed + - elementAttrs: { as: fetch } + expected: fetch + - elementAttrs: { as: font } + expected: font + - elementAttrs: { as: image } + expected: image + - elementAttrs: { as: object } + expected: object + - elementAttrs: { as: script } + expected: script + - elementAttrs: { as: style } + expected: style + - elementAttrs: { as: track } + expected: track + - elementAttrs: { as: video } + expected: video + - elementAttrs: { as: worker } + expected: worker + element-meta-refresh.optional.sub.html: + - expected: document + element-picture.sub.html: + - expected: image + element-script.sub.html: + - expected: script + element-video.sub.html: + - expected: video + element-video-poster.sub.html: + - expected: image + fetch.sub.html: + - expected: empty + fetch-via-serviceworker.https.sub.html: + - expected: empty + form-submission.sub.html: + - method: GET + expected: document + - method: POST + expected: document + header-link.sub.html: + - rel: icon + expected: empty + - rel: stylesheet + filename_flags: [tentative] + expected: style + header-refresh.optional.sub.html: + - expected: document + window-history.sub.html: + - expected: document + window-location.sub.html: + - expected: document + script-module-import-dynamic.sub.html: + - expected: script + script-module-import-static.sub.html: + - expected: script + serviceworker.https.sub.html: + - expected: serviceworker + # Implemented as "image" in Chromium and Firefox, but specified as + # "empty" + # https://github.com/w3c/svgwg/issues/782 + svg-image.sub.html: + - expected: empty + worker-dedicated-constructor.sub.html: + - expected: worker + - options: { type: module } + expected: worker + worker-dedicated-importscripts.sub.html: + - expected: script + + # Sec-Fetch-User + - common_axis: + - headerName: sec-fetch-user + filename_flags: [https] + origins: [] + template_axes: + appcache-manifest.sub.https.html: + - expected: NULL + audioworklet.https.sub.html: + - expected: NULL + css-images.sub.html: + - expected: NULL + filename_flags: [tentative] + css-font-face.sub.html: + - expected: NULL + filename_flags: [tentative] + element-a.sub.html: + - expected: NULL + - userActivated: TRUE + expected: ?1 + element-area.sub.html: + - expected: NULL + - userActivated: TRUE + expected: ?1 + element-audio.sub.html: + - expected: NULL + element-embed.sub.html: + - expected: NULL + element-frame.sub.html: + - expected: NULL + - userActivated: TRUE + expected: ?1 + element-iframe.sub.html: + - expected: NULL + - userActivated: TRUE + expected: ?1 + element-img.sub.html: + - sourceAttr: src + expected: NULL + - sourceAttr: srcset + expected: NULL + element-img-environment-change.sub.html: + - expected: NULL + element-input-image.sub.html: + - expected: NULL + element-link-icon.sub.html: + - expected: NULL + element-link-prefetch.optional.sub.html: + - expected: NULL + element-meta-refresh.optional.sub.html: + - expected: NULL + element-picture.sub.html: + - expected: NULL + element-script.sub.html: + - expected: NULL + element-video.sub.html: + - expected: NULL + element-video-poster.sub.html: + - expected: NULL + fetch.sub.html: + - expected: NULL + fetch-via-serviceworker.https.sub.html: + - expected: NULL + form-submission.sub.html: + - method: GET + expected: NULL + - method: GET + userActivated: TRUE + expected: ?1 + - method: POST + expected: NULL + - method: POST + userActivated: TRUE + expected: ?1 + header-link.sub.html: + - rel: icon + expected: NULL + - rel: stylesheet + expected: NULL + header-refresh.optional.sub.html: + - expected: NULL + window-history.sub.html: + - expected: NULL + window-location.sub.html: + - expected: NULL + - userActivated: TRUE + expected: ?1 + script-module-import-dynamic.sub.html: + - expected: NULL + script-module-import-static.sub.html: + - expected: NULL + serviceworker.https.sub.html: + - expected: NULL + svg-image.sub.html: + - expected: NULL + worker-dedicated-constructor.sub.html: + - expected: NULL + - options: { type: module } + expected: NULL + worker-dedicated-importscripts.sub.html: + - expected: NULL diff --git a/test/wpt/tests/fetch/metadata/tools/generate.py b/test/wpt/tests/fetch/metadata/tools/generate.py new file mode 100644 index 0000000..fa850c8 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/generate.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 + +import itertools +import os + +import jinja2 +import yaml + +HERE = os.path.abspath(os.path.dirname(__file__)) +PROJECT_ROOT = os.path.join(HERE, '..', '..', '..') + +def find_templates(starting_directory): + for directory, subdirectories, file_names in os.walk(starting_directory): + for file_name in file_names: + if file_name.startswith('.'): + continue + yield file_name, os.path.join(directory, file_name) + +def test_name(directory, template_name, subtest_flags): + ''' + Create a test name based on a template and the WPT file name flags [1] + required for a given subtest. This name is used to determine how subtests + may be grouped together. In order to promote grouping, the combination uses + a few aspects of how file name flags are interpreted: + + - repeated flags have no effect, so duplicates are removed + - flag sequence does not matter, so flags are consistently sorted + + directory | template_name | subtest_flags | result + ----------|------------------|-----------------|------- + cors | image.html | [] | cors/image.html + cors | image.https.html | [] | cors/image.https.html + cors | image.html | [https] | cors/image.https.html + cors | image.https.html | [https] | cors/image.https.html + cors | image.https.html | [https] | cors/image.https.html + cors | image.sub.html | [https] | cors/image.https.sub.html + cors | image.https.html | [sub] | cors/image.https.sub.html + + [1] docs/writing-tests/file-names.md + ''' + template_name_parts = template_name.split('.') + flags = set(subtest_flags) | set(template_name_parts[1:-1]) + test_name_parts = ( + [template_name_parts[0]] + + sorted(flags) + + [template_name_parts[-1]] + ) + return os.path.join(directory, '.'.join(test_name_parts)) + +def merge(a, b): + if type(a) != type(b): + raise Exception('Cannot merge disparate types') + if type(a) == list: + return a + b + if type(a) == dict: + merged = {} + + for key in a: + if key in b: + merged[key] = merge(a[key], b[key]) + else: + merged[key] = a[key] + + for key in b: + if not key in a: + merged[key] = b[key] + + return merged + + raise Exception('Cannot merge {} type'.format(type(a).__name__)) + +def product(a, b): + ''' + Given two lists of objects, compute their Cartesian product by merging the + elements together. For example, + + product( + [{'a': 1}, {'b': 2}], + [{'c': 3}, {'d': 4}, {'e': 5}] + ) + + returns the following list: + + [ + {'a': 1, 'c': 3}, + {'a': 1, 'd': 4}, + {'a': 1, 'e': 5}, + {'b': 2, 'c': 3}, + {'b': 2, 'd': 4}, + {'b': 2, 'e': 5} + ] + ''' + result = [] + + for a_object in a: + for b_object in b: + result.append(merge(a_object, b_object)) + + return result + +def make_provenance(project_root, cases, template): + return '\n'.join([ + 'This test was procedurally generated. Please do not modify it directly.', + 'Sources:', + '- {}'.format(os.path.relpath(cases, project_root)), + '- {}'.format(os.path.relpath(template, project_root)) + ]) + +def collection_filter(obj, title): + if not obj: + return 'no {}'.format(title) + + members = [] + for name, value in obj.items(): + if value == '': + members.append(name) + else: + members.append('{}={}'.format(name, value)) + + return '{}: {}'.format(title, ', '.join(members)) + +def pad_filter(value, side, padding): + if not value: + return '' + if side == 'start': + return padding + value + + return value + padding + +def main(config_file): + with open(config_file, 'r') as handle: + config = yaml.safe_load(handle.read()) + + templates_directory = os.path.normpath( + os.path.join(os.path.dirname(config_file), config['templates']) + ) + + environment = jinja2.Environment( + variable_start_string='[%', + variable_end_string='%]' + ) + environment.filters['collection'] = collection_filter + environment.filters['pad'] = pad_filter + templates = {} + subtests = {} + + for template_name, path in find_templates(templates_directory): + subtests[template_name] = [] + with open(path, 'r') as handle: + templates[template_name] = environment.from_string(handle.read()) + + for case in config['cases']: + unused_templates = set(templates) - set(case['template_axes']) + + # This warning is intended to help authors avoid mistakenly omitting + # templates. It can be silenced by extending the`template_axes` + # dictionary with an empty list for templates which are intentionally + # unused. + if unused_templates: + print( + 'Warning: case does not reference the following templates:' + ) + print('\n'.join('- {}'.format(name) for name in unused_templates)) + + common_axis = product( + case['common_axis'], [case.get('all_subtests', {})] + ) + + for template_name, template_axis in case['template_axes'].items(): + subtests[template_name].extend(product(common_axis, template_axis)) + + for template_name, template in templates.items(): + provenance = make_provenance( + PROJECT_ROOT, + config_file, + os.path.join(templates_directory, template_name) + ) + get_filename = lambda subtest: test_name( + config['output_directory'], + template_name, + subtest['filename_flags'] + ) + subtests_by_filename = itertools.groupby( + sorted(subtests[template_name], key=get_filename), + key=get_filename + ) + for filename, some_subtests in subtests_by_filename: + with open(filename, 'w') as handle: + handle.write(templates[template_name].render( + subtests=list(some_subtests), + provenance=provenance + ) + '\n') + +if __name__ == '__main__': + main('fetch-metadata.conf.yml') diff --git a/test/wpt/tests/fetch/metadata/tools/templates/appcache-manifest.sub.https.html b/test/wpt/tests/fetch/metadata/tools/templates/appcache-manifest.sub.https.html new file mode 100644 index 0000000..0dfc084 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/appcache-manifest.sub.https.html @@ -0,0 +1,63 @@ + + + + + HTTP headers on request for Appcache manifest + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/audioworklet.https.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/audioworklet.https.sub.html new file mode 100644 index 0000000..7be309c --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/audioworklet.https.sub.html @@ -0,0 +1,53 @@ + + + + + HTTP headers on request for AudioWorklet module + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/css-font-face.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/css-font-face.sub.html new file mode 100644 index 0000000..94b33f4 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/css-font-face.sub.html @@ -0,0 +1,60 @@ + + + + + HTTP headers on request for CSS font-face + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/css-images.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/css-images.sub.html new file mode 100644 index 0000000..e394f9f --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/css-images.sub.html @@ -0,0 +1,137 @@ + + + + + {%- if subtests|length > 10 %} + + {%- endif %} + HTTP headers on request for CSS image-accepting properties + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-a.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-a.sub.html new file mode 100644 index 0000000..2bd8e8a --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-a.sub.html @@ -0,0 +1,72 @@ + + + + + {%- if subtests|length > 10 %} + + {%- endif %} + HTTP headers on request for HTML "a" element navigation + + + {%- if subtests|selectattr('userActivated')|list %} + + + {%- endif %} + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-area.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-area.sub.html new file mode 100644 index 0000000..0cef5b2 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-area.sub.html @@ -0,0 +1,72 @@ + + + + + {%- if subtests|length > 10 %} + + {%- endif %} + HTTP headers on request for HTML "area" element navigation + + + {%- if subtests|selectattr('userActivated')|list %} + + + {%- endif %} + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-audio.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-audio.sub.html new file mode 100644 index 0000000..92bc221 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-audio.sub.html @@ -0,0 +1,51 @@ + + + + + HTTP headers on request for HTML "audio" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-embed.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-embed.sub.html new file mode 100644 index 0000000..18ce09e --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-embed.sub.html @@ -0,0 +1,54 @@ + + + + + HTTP headers on request for HTML "embed" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-frame.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-frame.sub.html new file mode 100644 index 0000000..ce90171 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-frame.sub.html @@ -0,0 +1,62 @@ + + + + + HTTP headers on request for HTML "frame" element source + + + {%- if subtests|selectattr('userActivated')|list %} + + + {%- endif %} + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-iframe.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-iframe.sub.html new file mode 100644 index 0000000..43a632a --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-iframe.sub.html @@ -0,0 +1,62 @@ + + + + + HTTP headers on request for HTML "frame" element source + + + {%- if subtests|selectattr('userActivated')|list %} + + + {%- endif %} + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-img-environment-change.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-img-environment-change.sub.html new file mode 100644 index 0000000..5a65114 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-img-environment-change.sub.html @@ -0,0 +1,78 @@ + + + + + HTTP headers on image request triggered by change to environment + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-img.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-img.sub.html new file mode 100644 index 0000000..1dac584 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-img.sub.html @@ -0,0 +1,52 @@ + + + + + HTTP headers on request for HTML "img" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-input-image.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-input-image.sub.html new file mode 100644 index 0000000..3c50008 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-input-image.sub.html @@ -0,0 +1,48 @@ + + + + + HTTP headers on request for HTML "input" element with type="button" + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-link-icon.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-link-icon.sub.html new file mode 100644 index 0000000..18ce12a --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-link-icon.sub.html @@ -0,0 +1,75 @@ + + + + + {%- if subtests|length > 10 %} + + {%- endif %} + HTTP headers on request for HTML "link" element with rel="icon" + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-link-prefetch.optional.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-link-prefetch.optional.sub.html new file mode 100644 index 0000000..59d677d --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-link-prefetch.optional.sub.html @@ -0,0 +1,71 @@ + + + + + {%- if subtests|length > 10 %} + + {%- endif %} + HTTP headers on request for HTML "link" element with rel="prefetch" + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-meta-refresh.optional.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-meta-refresh.optional.sub.html new file mode 100644 index 0000000..5a8d8f8 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-meta-refresh.optional.sub.html @@ -0,0 +1,60 @@ + + + + + HTTP headers on request for HTML "meta" element with http-equiv="refresh" + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-picture.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-picture.sub.html new file mode 100644 index 0000000..903aeed --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-picture.sub.html @@ -0,0 +1,101 @@ + + + + + HTTP headers on request for HTML "picture" element source + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-script.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-script.sub.html new file mode 100644 index 0000000..4a281ae --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-script.sub.html @@ -0,0 +1,54 @@ + + + + + HTTP headers on request for HTML "script" element source + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-video-poster.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-video-poster.sub.html new file mode 100644 index 0000000..9cdaf06 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-video-poster.sub.html @@ -0,0 +1,62 @@ + + + + + HTTP headers on request for HTML "video" element "poster" + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/element-video.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/element-video.sub.html new file mode 100644 index 0000000..1b7b976 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/element-video.sub.html @@ -0,0 +1,51 @@ + + + + + HTTP headers on request for HTML "video" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/fetch-via-serviceworker.https.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/fetch-via-serviceworker.https.sub.html new file mode 100644 index 0000000..eead710 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/fetch-via-serviceworker.https.sub.html @@ -0,0 +1,88 @@ + + + + + {%- if subtests|length > 10 %} + + {%- endif %} + HTTP headers on request using the "fetch" API and passing through a Serive Worker + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/fetch.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/fetch.sub.html new file mode 100644 index 0000000..a8dc536 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/fetch.sub.html @@ -0,0 +1,42 @@ + + + + + HTTP headers on request using the "fetch" API + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/form-submission.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/form-submission.sub.html new file mode 100644 index 0000000..4c9c8c5 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/form-submission.sub.html @@ -0,0 +1,87 @@ + + + + + + HTTP headers on request for HTML form navigation + + + {%- if subtests|selectattr('userActivated')|list %} + + + {%- endif %} + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/header-link.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/header-link.sub.html new file mode 100644 index 0000000..2831f22 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/header-link.sub.html @@ -0,0 +1,56 @@ + + + + + HTTP headers on request for HTTP "Link" header + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/header-refresh.optional.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/header-refresh.optional.sub.html new file mode 100644 index 0000000..ec963d5 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/header-refresh.optional.sub.html @@ -0,0 +1,59 @@ + + + + + {%- if subtests|length > 10 %} + + {%- endif %} + HTTP headers on request for HTTP "Refresh" header + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/script-module-import-dynamic.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/script-module-import-dynamic.sub.html new file mode 100644 index 0000000..653d3cd --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/script-module-import-dynamic.sub.html @@ -0,0 +1,35 @@ + + + + + HTTP headers on request for dynamic ECMAScript module import + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/script-module-import-static.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/script-module-import-static.sub.html new file mode 100644 index 0000000..c8d5f95 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/script-module-import-static.sub.html @@ -0,0 +1,53 @@ + + + + + HTTP headers on request for static ECMAScript module import + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/serviceworker.https.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/serviceworker.https.sub.html new file mode 100644 index 0000000..8284325 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/serviceworker.https.sub.html @@ -0,0 +1,72 @@ + + + + + + HTTP headers on request for Service Workers + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/svg-image.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/svg-image.sub.html new file mode 100644 index 0000000..52f7806 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/svg-image.sub.html @@ -0,0 +1,75 @@ + + + + + {%- if subtests|length > 10 %} + + {%- endif %} + HTTP headers on request for SVG "image" element source + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/window-history.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/window-history.sub.html new file mode 100644 index 0000000..286d019 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/window-history.sub.html @@ -0,0 +1,134 @@ + + + + + {%- if subtests|length > 10 %} + + {%- endif %} + HTTP headers on request for navigation via the HTML History API + + + {%- if subtests|selectattr('userActivated')|list %} + + + {%- endif %} + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/window-location.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/window-location.sub.html new file mode 100644 index 0000000..96f3912 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/window-location.sub.html @@ -0,0 +1,128 @@ + + + + + {%- if subtests|length > 10 %} + + {%- endif %} + HTTP headers on request for navigation via the HTML Location API + + + {%- if subtests|selectattr('userActivated')|list %} + + + {%- endif %} + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/worker-dedicated-constructor.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/worker-dedicated-constructor.sub.html new file mode 100644 index 0000000..fede596 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/worker-dedicated-constructor.sub.html @@ -0,0 +1,49 @@ + + + + + HTTP headers on request for dedicated worker via the "Worker" constructor + + + + + diff --git a/test/wpt/tests/fetch/metadata/tools/templates/worker-dedicated-importscripts.sub.html b/test/wpt/tests/fetch/metadata/tools/templates/worker-dedicated-importscripts.sub.html new file mode 100644 index 0000000..93e6374 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/tools/templates/worker-dedicated-importscripts.sub.html @@ -0,0 +1,54 @@ + + + + + HTTP headers on request for dedicated worker via the "importScripts" API + + + + + diff --git a/test/wpt/tests/fetch/metadata/track.https.sub.html b/test/wpt/tests/fetch/metadata/track.https.sub.html new file mode 100644 index 0000000..346798f --- /dev/null +++ b/test/wpt/tests/fetch/metadata/track.https.sub.html @@ -0,0 +1,119 @@ + + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/trailing-dot.https.sub.any.js b/test/wpt/tests/fetch/metadata/trailing-dot.https.sub.any.js new file mode 100644 index 0000000..5e32fc4 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/trailing-dot.https.sub.any.js @@ -0,0 +1,30 @@ +// META: global=window,worker +// META: script=/fetch/metadata/resources/helper.js + +// Site +promise_test(t => { + return validate_expectations_custom_url("https://{{host}}.:{{ports[https][0]}}/fetch/metadata/resources/echo-as-json.py", {}, { + "site": "cross-site", + "user": "", + "mode": "cors", + "dest": "empty" + }, "Fetching a resource from the same origin, but spelled with a trailing dot."); +}, "Fetching a resource from the same origin, but spelled with a trailing dot."); + +promise_test(t => { + return validate_expectations_custom_url("https://{{hosts[][www]}}.:{{ports[https][0]}}/fetch/metadata/resources/echo-as-json.py", {}, { + "site": "cross-site", + "user": "", + "mode": "cors", + "dest": "empty" + }, "Fetching a resource from the same site, but spelled with a trailing dot."); +}, "Fetching a resource from the same site, but spelled with a trailing dot."); + +promise_test(t => { + return validate_expectations_custom_url("https://{{hosts[alt][www]}}.:{{ports[https][0]}}/fetch/metadata/resources/echo-as-json.py", {}, { + "site": "cross-site", + "user": "", + "mode": "cors", + "dest": "empty" + }, "Fetching a resource from a cross-site host, spelled with a trailing dot."); +}, "Fetching a resource from a cross-site host, spelled with a trailing dot."); diff --git a/test/wpt/tests/fetch/metadata/unload.https.sub.html b/test/wpt/tests/fetch/metadata/unload.https.sub.html new file mode 100644 index 0000000..bc26048 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/unload.https.sub.html @@ -0,0 +1,64 @@ + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/window-open.https.sub.html b/test/wpt/tests/fetch/metadata/window-open.https.sub.html new file mode 100644 index 0000000..94ba76a --- /dev/null +++ b/test/wpt/tests/fetch/metadata/window-open.https.sub.html @@ -0,0 +1,199 @@ + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/worker.https.sub.html b/test/wpt/tests/fetch/metadata/worker.https.sub.html new file mode 100644 index 0000000..20a4fe5 --- /dev/null +++ b/test/wpt/tests/fetch/metadata/worker.https.sub.html @@ -0,0 +1,24 @@ + + + + + + + + + diff --git a/test/wpt/tests/fetch/metadata/xslt.https.sub.html b/test/wpt/tests/fetch/metadata/xslt.https.sub.html new file mode 100644 index 0000000..dc72d7b --- /dev/null +++ b/test/wpt/tests/fetch/metadata/xslt.https.sub.html @@ -0,0 +1,25 @@ + + + + + + + + diff --git a/test/wpt/tests/fetch/nosniff/image.html b/test/wpt/tests/fetch/nosniff/image.html new file mode 100644 index 0000000..9dfdb94 --- /dev/null +++ b/test/wpt/tests/fetch/nosniff/image.html @@ -0,0 +1,39 @@ + + +
+ diff --git a/test/wpt/tests/fetch/nosniff/importscripts.html b/test/wpt/tests/fetch/nosniff/importscripts.html new file mode 100644 index 0000000..920b6bd --- /dev/null +++ b/test/wpt/tests/fetch/nosniff/importscripts.html @@ -0,0 +1,14 @@ + + +
+ diff --git a/test/wpt/tests/fetch/nosniff/importscripts.js b/test/wpt/tests/fetch/nosniff/importscripts.js new file mode 100644 index 0000000..1895280 --- /dev/null +++ b/test/wpt/tests/fetch/nosniff/importscripts.js @@ -0,0 +1,28 @@ +// Testing importScripts() +function log(w) { this.postMessage(w) } +function f() { log("FAIL") } +function p() { log("PASS") } + +const get_url = (mime, outcome) => { + let url = "resources/js.py" + if (mime != null) { + url += "?type=" + encodeURIComponent(mime) + } + if (outcome) { + url += "&outcome=p" + } + return url +} + +[null, "", "x", "x/x", "text/html", "text/json"].forEach(function(mime) { + try { + importScripts(get_url(mime)) + } catch(e) { + (e.name == "NetworkError") ? p() : log("FAIL (no NetworkError exception): " + mime) + } + +}) +importScripts(get_url("text/javascript", true)) +importScripts(get_url("text/ecmascript", true)) +importScripts(get_url("text/ecmascript;blah", true)) +log("END") diff --git a/test/wpt/tests/fetch/nosniff/parsing-nosniff.window.js b/test/wpt/tests/fetch/nosniff/parsing-nosniff.window.js new file mode 100644 index 0000000..2a26486 --- /dev/null +++ b/test/wpt/tests/fetch/nosniff/parsing-nosniff.window.js @@ -0,0 +1,27 @@ +promise_test(() => fetch("resources/x-content-type-options.json").then(res => res.json()).then(runTests), "Loading JSON…"); + +function runTests(allTestData) { + for (let i = 0; i < allTestData.length; i++) { + const testData = allTestData[i], + input = encodeURIComponent(testData.input); + promise_test(t => { + let resolve; + const promise = new Promise(r => resolve = r); + const script = document.createElement("script"); + t.add_cleanup(() => script.remove()); + // A + +
+ diff --git a/test/wpt/tests/fetch/nosniff/stylesheet.html b/test/wpt/tests/fetch/nosniff/stylesheet.html new file mode 100644 index 0000000..8f2b547 --- /dev/null +++ b/test/wpt/tests/fetch/nosniff/stylesheet.html @@ -0,0 +1,60 @@ + + + +
+ diff --git a/test/wpt/tests/fetch/nosniff/worker.html b/test/wpt/tests/fetch/nosniff/worker.html new file mode 100644 index 0000000..c8c1076 --- /dev/null +++ b/test/wpt/tests/fetch/nosniff/worker.html @@ -0,0 +1,28 @@ + + +
+ diff --git a/test/wpt/tests/fetch/orb/resources/data.json b/test/wpt/tests/fetch/orb/resources/data.json new file mode 100644 index 0000000..f2a886f --- /dev/null +++ b/test/wpt/tests/fetch/orb/resources/data.json @@ -0,0 +1,3 @@ +{ + "hello": "world" +} diff --git a/test/wpt/tests/fetch/orb/resources/data_non_ascii.json b/test/wpt/tests/fetch/orb/resources/data_non_ascii.json new file mode 100644 index 0000000..64566c5 --- /dev/null +++ b/test/wpt/tests/fetch/orb/resources/data_non_ascii.json @@ -0,0 +1 @@ +["你好"] diff --git a/test/wpt/tests/fetch/orb/resources/empty.json b/test/wpt/tests/fetch/orb/resources/empty.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/test/wpt/tests/fetch/orb/resources/empty.json @@ -0,0 +1 @@ +{} diff --git a/test/wpt/tests/fetch/orb/resources/font.ttf b/test/wpt/tests/fetch/orb/resources/font.ttf new file mode 100644 index 0000000..9023592 Binary files /dev/null and b/test/wpt/tests/fetch/orb/resources/font.ttf differ diff --git a/test/wpt/tests/fetch/orb/resources/image.png b/test/wpt/tests/fetch/orb/resources/image.png new file mode 100644 index 0000000..820f8ca Binary files /dev/null and b/test/wpt/tests/fetch/orb/resources/image.png differ diff --git a/test/wpt/tests/fetch/orb/resources/js-unlabeled-utf16-without-bom.json b/test/wpt/tests/fetch/orb/resources/js-unlabeled-utf16-without-bom.json new file mode 100644 index 0000000..157a8f5 Binary files /dev/null and b/test/wpt/tests/fetch/orb/resources/js-unlabeled-utf16-without-bom.json differ diff --git a/test/wpt/tests/fetch/orb/resources/js-unlabeled.js b/test/wpt/tests/fetch/orb/resources/js-unlabeled.js new file mode 100644 index 0000000..a880a5b --- /dev/null +++ b/test/wpt/tests/fetch/orb/resources/js-unlabeled.js @@ -0,0 +1 @@ +window.has_executed_script = true; diff --git a/test/wpt/tests/fetch/orb/resources/png-mislabeled-as-html.png b/test/wpt/tests/fetch/orb/resources/png-mislabeled-as-html.png new file mode 100644 index 0000000..820f8ca Binary files /dev/null and b/test/wpt/tests/fetch/orb/resources/png-mislabeled-as-html.png differ diff --git a/test/wpt/tests/fetch/orb/resources/png-mislabeled-as-html.png.headers b/test/wpt/tests/fetch/orb/resources/png-mislabeled-as-html.png.headers new file mode 100644 index 0000000..156209f --- /dev/null +++ b/test/wpt/tests/fetch/orb/resources/png-mislabeled-as-html.png.headers @@ -0,0 +1 @@ +Content-Type: text/html diff --git a/test/wpt/tests/fetch/orb/resources/png-unlabeled.png b/test/wpt/tests/fetch/orb/resources/png-unlabeled.png new file mode 100644 index 0000000..820f8ca Binary files /dev/null and b/test/wpt/tests/fetch/orb/resources/png-unlabeled.png differ diff --git a/test/wpt/tests/fetch/orb/resources/script-asm-js-invalid.js b/test/wpt/tests/fetch/orb/resources/script-asm-js-invalid.js new file mode 100644 index 0000000..8d1bbd6 --- /dev/null +++ b/test/wpt/tests/fetch/orb/resources/script-asm-js-invalid.js @@ -0,0 +1,4 @@ +function f() { + "use asm"; + return; +} diff --git a/test/wpt/tests/fetch/orb/resources/script-asm-js-valid.js b/test/wpt/tests/fetch/orb/resources/script-asm-js-valid.js new file mode 100644 index 0000000..79b375f --- /dev/null +++ b/test/wpt/tests/fetch/orb/resources/script-asm-js-valid.js @@ -0,0 +1,4 @@ +function f() { + "use asm"; + return {}; +} diff --git a/test/wpt/tests/fetch/orb/resources/script-iso-8559-1.js b/test/wpt/tests/fetch/orb/resources/script-iso-8559-1.js new file mode 100644 index 0000000..3bccb6a --- /dev/null +++ b/test/wpt/tests/fetch/orb/resources/script-iso-8559-1.js @@ -0,0 +1,4 @@ +"use strict"; +function fn() { + return "§A¦n"; +} diff --git a/test/wpt/tests/fetch/orb/resources/script-utf16-bom.js b/test/wpt/tests/fetch/orb/resources/script-utf16-bom.js new file mode 100644 index 0000000..16b76e9 Binary files /dev/null and b/test/wpt/tests/fetch/orb/resources/script-utf16-bom.js differ diff --git a/test/wpt/tests/fetch/orb/resources/script-utf16-without-bom.js b/test/wpt/tests/fetch/orb/resources/script-utf16-without-bom.js new file mode 100644 index 0000000..d983086 Binary files /dev/null and b/test/wpt/tests/fetch/orb/resources/script-utf16-without-bom.js differ diff --git a/test/wpt/tests/fetch/orb/resources/script.js b/test/wpt/tests/fetch/orb/resources/script.js new file mode 100644 index 0000000..19675d2 --- /dev/null +++ b/test/wpt/tests/fetch/orb/resources/script.js @@ -0,0 +1,4 @@ +"use strict"; +function fn() { + return 42; +} diff --git a/test/wpt/tests/fetch/orb/resources/sound.mp3 b/test/wpt/tests/fetch/orb/resources/sound.mp3 new file mode 100644 index 0000000..a15d1de Binary files /dev/null and b/test/wpt/tests/fetch/orb/resources/sound.mp3 differ diff --git a/test/wpt/tests/fetch/orb/resources/text.txt b/test/wpt/tests/fetch/orb/resources/text.txt new file mode 100644 index 0000000..270c611 --- /dev/null +++ b/test/wpt/tests/fetch/orb/resources/text.txt @@ -0,0 +1 @@ +hello, world! diff --git a/test/wpt/tests/fetch/orb/resources/utils.js b/test/wpt/tests/fetch/orb/resources/utils.js new file mode 100644 index 0000000..94a2177 --- /dev/null +++ b/test/wpt/tests/fetch/orb/resources/utils.js @@ -0,0 +1,18 @@ +function header(name, value) { + return `header(${name},${value})`; +} + +function contentType(type) { + return header("Content-Type", type); +} + +function contentTypeOptions(type) { + return header("X-Content-Type-Options", type); +} + +function fetchORB(file, options, ...pipe) { + return fetch(`${file}${pipe.length ? `?pipe=${pipe.join("|")}` : ""}`, { + ...(options || {}), + mode: "no-cors", + }); +} diff --git a/test/wpt/tests/fetch/orb/tentative/compressed-image-sniffing.sub.html b/test/wpt/tests/fetch/orb/tentative/compressed-image-sniffing.sub.html new file mode 100644 index 0000000..38e70c6 --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/compressed-image-sniffing.sub.html @@ -0,0 +1,20 @@ + + + +
+ + diff --git a/test/wpt/tests/fetch/orb/tentative/content-range.sub.any.js b/test/wpt/tests/fetch/orb/tentative/content-range.sub.any.js new file mode 100644 index 0000000..ee97521 --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/content-range.sub.any.js @@ -0,0 +1,31 @@ +// META: script=/fetch/orb/resources/utils.js + +const url = + "http://{{domains[www1]}}:{{ports[http][0]}}/fetch/orb/resources/image.png"; + +promise_test(async () => { + let headers = new Headers([["Range", "bytes=0-99"]]); + await fetchORB( + url, + { headers }, + header("Content-Range", "bytes 0-99/1010"), + "slice(null,100)", + "status(206)" + ); +}, "ORB shouldn't block opaque range of image/png starting at zero"); + +promise_test( + t => + promise_rejects_js( + t, + TypeError, + fetchORB( + url, + { headers: new Headers([["Range", "bytes 10-99"]]) }, + header("Content-Range", "bytes 10-99/1010"), + "slice(10,100)", + "status(206)" + ) + ), + "ORB should block opaque range of image/png not starting at zero, that isn't subsequent" +); diff --git a/test/wpt/tests/fetch/orb/tentative/img-mime-types-coverage.tentative.sub.html b/test/wpt/tests/fetch/orb/tentative/img-mime-types-coverage.tentative.sub.html new file mode 100644 index 0000000..5dc6c5d --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/img-mime-types-coverage.tentative.sub.html @@ -0,0 +1,126 @@ + + + +
+ + diff --git a/test/wpt/tests/fetch/orb/tentative/img-png-mislabeled-as-html.sub-ref.html b/test/wpt/tests/fetch/orb/tentative/img-png-mislabeled-as-html.sub-ref.html new file mode 100644 index 0000000..66462fb --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/img-png-mislabeled-as-html.sub-ref.html @@ -0,0 +1,5 @@ + + + + + diff --git a/test/wpt/tests/fetch/orb/tentative/img-png-mislabeled-as-html.sub.html b/test/wpt/tests/fetch/orb/tentative/img-png-mislabeled-as-html.sub.html new file mode 100644 index 0000000..aa03f4d --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/img-png-mislabeled-as-html.sub.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/test/wpt/tests/fetch/orb/tentative/img-png-unlabeled.sub-ref.html b/test/wpt/tests/fetch/orb/tentative/img-png-unlabeled.sub-ref.html new file mode 100644 index 0000000..2d5e3bb --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/img-png-unlabeled.sub-ref.html @@ -0,0 +1,5 @@ + + + + + diff --git a/test/wpt/tests/fetch/orb/tentative/img-png-unlabeled.sub.html b/test/wpt/tests/fetch/orb/tentative/img-png-unlabeled.sub.html new file mode 100644 index 0000000..77415f6 --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/img-png-unlabeled.sub.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/test/wpt/tests/fetch/orb/tentative/known-mime-type.sub.any.js b/test/wpt/tests/fetch/orb/tentative/known-mime-type.sub.any.js new file mode 100644 index 0000000..b0521e8 --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/known-mime-type.sub.any.js @@ -0,0 +1,86 @@ +// META: script=/fetch/orb/resources/utils.js + +const path = "http://{{domains[www1]}}:{{ports[http][0]}}/fetch/orb/resources"; + +promise_test( + t => + promise_rejects_js( + t, + TypeError, + fetchORB(`${path}/font.ttf`, null, contentType("font/ttf")) + ), + "ORB should block opaque font/ttf" +); + +promise_test( + t => + promise_rejects_js( + t, + TypeError, + fetchORB(`${path}/text.txt`, null, contentType("text/plain")) + ), + "ORB should block opaque text/plain" +); + +promise_test( + t => + promise_rejects_js( + t, + TypeError, + fetchORB(`${path}/data.json`, null, contentType("application/json")) + ), + "ORB should block opaque application/json (non-empty)" +); + +promise_test( + t => + promise_rejects_js( + t, + TypeError, + fetchORB(`${path}/empty.json`, null, contentType("application/json")) + ), + "ORB should block opaque application/json (empty)" +); + +promise_test( + t => + promise_rejects_js( + t, + TypeError, + fetchORB(`${path}/data_non_ascii.json`, null, contentType("application/json")) + ), + "ORB should block opaque application/json which contains non ascii characters" +); + +promise_test(async () => { + fetchORB(`${path}/image.png`, null, contentType("image/png")); +}, "ORB shouldn't block opaque image/png"); + +promise_test(async () => { + await fetchORB(`${path}/script.js`, null, contentType("text/javascript")); +}, "ORB shouldn't block opaque text/javascript"); + +// Test javascript validation can correctly decode the content with BOM. +promise_test(async () => { + await fetchORB(`${path}/script-utf16-bom.js`, null, contentType("application/json")); +}, "ORB shouldn't block opaque text/javascript (utf16 encoded with BOM)"); + +// Test javascript validation can correctly decode the content with the http charset hint. +promise_test(async () => { + await fetchORB(`${path}/script-utf16-without-bom.js`, null, contentType("application/json; charset=utf-16")); +}, "ORB shouldn't block opaque text/javascript (utf16 encoded without BOM but charset is provided in content-type)"); + +// Test javascript validation can correctly decode the content for iso-8559-1 (fallback decoder in Firefox). +promise_test(async () => { + await fetchORB(`${path}/script-iso-8559-1.js`, null, contentType("application/json")); +}, "ORB shouldn't block opaque text/javascript (iso-8559-1 encoded)"); + +// Test javascript validation can correctly parse asm.js. +promise_test(async () => { + await fetchORB(`${path}/script-asm-js-valid.js`, null, contentType("application/json")); +}, "ORB shouldn't block text/javascript with valid asm.js"); + +// Test javascript validation can correctly parse invalid asm.js with valid JS syntax. +promise_test(async () => { + await fetchORB(`${path}/script-asm-js-invalid.js`, null, contentType("application/json")); +}, "ORB shouldn't block text/javascript with invalid asm.js"); diff --git a/test/wpt/tests/fetch/orb/tentative/nosniff.sub.any.js b/test/wpt/tests/fetch/orb/tentative/nosniff.sub.any.js new file mode 100644 index 0000000..3df9d22 --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/nosniff.sub.any.js @@ -0,0 +1,59 @@ +// META: script=/fetch/orb/resources/utils.js + +const path = "http://{{domains[www1]}}:{{ports[http][0]}}/fetch/orb/resources"; + +promise_test( + t => + promise_rejects_js( + t, + TypeError, + fetchORB( + `${path}/text.txt`, + null, + contentType("text/plain"), + contentTypeOptions("nosniff") + ) + ), + "ORB should block opaque text/plain with nosniff" +); + +promise_test( + t => + promise_rejects_js( + t, + TypeError, + fetchORB( + `${path}/data.json`, + null, + contentType("application/json"), + contentTypeOptions("nosniff") + ) + ), + "ORB should block opaque-response-blocklisted MIME type with nosniff" +); + +promise_test( + t => + promise_rejects_js( + t, + TypeError, + fetchORB( + `${path}/data.json`, + null, + contentType(""), + contentTypeOptions("nosniff") + ) + ), + "ORB should block opaque response with empty Content-Type and nosniff" +); + +promise_test( + () => + fetchORB( + `${path}/image.png`, + null, + contentType(""), + contentTypeOptions("nosniff") + ), + "ORB shouldn't block opaque image with empty Content-Type and nosniff" +); diff --git a/test/wpt/tests/fetch/orb/tentative/script-js-unlabeled-gziped.sub.html b/test/wpt/tests/fetch/orb/tentative/script-js-unlabeled-gziped.sub.html new file mode 100644 index 0000000..fe85440 --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/script-js-unlabeled-gziped.sub.html @@ -0,0 +1,24 @@ + + + + + +
+ + + + + + + + diff --git a/test/wpt/tests/fetch/orb/tentative/script-unlabeled.sub.html b/test/wpt/tests/fetch/orb/tentative/script-unlabeled.sub.html new file mode 100644 index 0000000..4987f13 --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/script-unlabeled.sub.html @@ -0,0 +1,24 @@ + + + + + +
+ + + + + + + + diff --git a/test/wpt/tests/fetch/orb/tentative/script-utf16-without-bom-hint-charset.sub.html b/test/wpt/tests/fetch/orb/tentative/script-utf16-without-bom-hint-charset.sub.html new file mode 100644 index 0000000..b15f976 --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/script-utf16-without-bom-hint-charset.sub.html @@ -0,0 +1,22 @@ + + + + +
+ + + + + + + diff --git a/test/wpt/tests/fetch/orb/tentative/status.sub.any.js b/test/wpt/tests/fetch/orb/tentative/status.sub.any.js new file mode 100644 index 0000000..b94d8b7 --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/status.sub.any.js @@ -0,0 +1,33 @@ +// META: script=/fetch/orb/resources/utils.js + +const path = "http://{{domains[www1]}}:{{ports[http][0]}}/fetch/orb/resources"; + +promise_test( + t => + promise_rejects_js( + t, + TypeError, + fetchORB( + `${path}/data.json`, + null, + contentType("application/json"), + "status(206)" + ) + ), + "ORB should block opaque-response-blocklisted MIME type with status 206" +); + +promise_test( + t => + promise_rejects_js( + t, + TypeError, + fetchORB( + `${path}/data.json`, + null, + contentType("application/json"), + "status(302)" + ) + ), + "ORB should block opaque response with non-ok status" +); diff --git a/test/wpt/tests/fetch/orb/tentative/status.sub.html b/test/wpt/tests/fetch/orb/tentative/status.sub.html new file mode 100644 index 0000000..a62bdeb --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/status.sub.html @@ -0,0 +1,17 @@ +'use strict'; + + + +
+ diff --git a/test/wpt/tests/fetch/orb/tentative/unknown-mime-type.sub.any.js b/test/wpt/tests/fetch/orb/tentative/unknown-mime-type.sub.any.js new file mode 100644 index 0000000..f72ff92 --- /dev/null +++ b/test/wpt/tests/fetch/orb/tentative/unknown-mime-type.sub.any.js @@ -0,0 +1,28 @@ +// META: script=/fetch/orb/resources/utils.js + +const path = "http://{{domains[www1]}}:{{ports[http][0]}}/fetch/orb/resources"; + +promise_test( + () => fetchORB(`${path}/font.ttf`, null, contentType("")), + "ORB shouldn't block opaque failed missing MIME type (font/ttf)" +); + +promise_test( + () => fetchORB(`${path}/text.txt`, null, contentType("")), + "ORB shouldn't block opaque failed missing MIME type (text/plain)" +); + +promise_test( + t => fetchORB(`${path}/data.json`, null, contentType("")), + "ORB shouldn't block opaque failed missing MIME type (application/json)" +); + +promise_test( + () => fetchORB(`${path}/image.png`, null, contentType("")), + "ORB shouldn't block opaque failed missing MIME type (image/png)" +); + +promise_test( + () => fetchORB(`${path}/script.js`, null, contentType("")), + "ORB shouldn't block opaque failed missing MIME type (text/javascript)" +); diff --git a/test/wpt/tests/fetch/origin/assorted.window.js b/test/wpt/tests/fetch/origin/assorted.window.js new file mode 100644 index 0000000..033d010 --- /dev/null +++ b/test/wpt/tests/fetch/origin/assorted.window.js @@ -0,0 +1,211 @@ +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js + +const origins = get_host_info(); + +promise_test(async function () { + const stash = token(), + redirectPath = "/fetch/origin/resources/redirect-and-stash.py"; + + // Cross-origin -> same-origin will result in setting the tainted origin flag for the second + // request. + let url = origins.HTTP_ORIGIN + redirectPath + "?stash=" + stash; + url = origins.HTTP_REMOTE_ORIGIN + redirectPath + "?stash=" + stash + "&location=" + encodeURIComponent(url) + "&dummyJS"; + + await fetch(url, { mode: "no-cors", method: "POST" }); + + const json = await (await fetch(redirectPath + "?dump&stash=" + stash)).json(); + + assert_equals(json[0], origins.HTTP_ORIGIN); + assert_equals(json[1], "null"); +}, "Origin header and 308 redirect"); + +promise_test(async function () { + const stash = token(), + redirectPath = "/fetch/origin/resources/redirect-and-stash.py"; + + let url = origins.HTTP_ORIGIN + redirectPath + "?stash=" + stash; + url = origins.HTTP_REMOTE_ORIGIN + redirectPath + "?stash=" + stash + "&location=" + encodeURIComponent(url); + + await new Promise(resolve => { + const frame = document.createElement("iframe"); + frame.src = url; + frame.onload = () => { + resolve(); + frame.remove(); + } + document.body.appendChild(frame); + }); + + const json = await (await fetch(redirectPath + "?dump&stash=" + stash)).json(); + + assert_equals(json[0], "no Origin header"); + assert_equals(json[1], "no Origin header"); +}, "Origin header and GET navigation"); + +promise_test(async function () { + const stash = token(), + redirectPath = "/fetch/origin/resources/redirect-and-stash.py"; + + let url = origins.HTTP_ORIGIN + redirectPath + "?stash=" + stash; + url = origins.HTTP_REMOTE_ORIGIN + redirectPath + "?stash=" + stash + "&location=" + encodeURIComponent(url); + + await new Promise(resolve => { + const frame = document.createElement("iframe"); + self.addEventListener("message", e => { + if (e.data === "loaded") { + resolve(); + frame.remove(); + } + }, { once: true }); + frame.onload = () => { + const doc = frame.contentDocument, + form = doc.body.appendChild(doc.createElement("form")), + submit = form.appendChild(doc.createElement("input")); + form.action = url; + form.method = "POST"; + submit.type = "submit"; + submit.click(); + } + document.body.appendChild(frame); + }); + + const json = await (await fetch(redirectPath + "?dump&stash=" + stash)).json(); + + assert_equals(json[0], origins.HTTP_ORIGIN); + assert_equals(json[1], "null"); +}, "Origin header and POST navigation"); + +function navigationReferrerPolicy(referrerPolicy, destination, expectedOrigin) { + return async function () { + const stash = token(); + const referrerPolicyPath = "/fetch/origin/resources/referrer-policy.py"; + const redirectPath = "/fetch/origin/resources/redirect-and-stash.py"; + + let postUrl = + (destination === "same-origin" ? origins.HTTP_ORIGIN + : origins.HTTP_REMOTE_ORIGIN) + + redirectPath + "?stash=" + stash; + + await new Promise(resolve => { + const frame = document.createElement("iframe"); + document.body.appendChild(frame); + frame.src = origins.HTTP_ORIGIN + referrerPolicyPath + + "?referrerPolicy=" + referrerPolicy; + self.addEventListener("message", function listener(e) { + if (e.data === "loaded") { + resolve(); + frame.remove(); + self.removeEventListener("message", listener); + } else if (e.data === "action") { + const doc = frame.contentDocument, + form = doc.body.appendChild(doc.createElement("form")), + submit = form.appendChild(doc.createElement("input")); + form.action = postUrl; + form.method = "POST"; + submit.type = "submit"; + submit.click(); + } + }); + }); + + const json = await (await fetch(redirectPath + "?dump&stash=" + stash)).json(); + + assert_equals(json[0], expectedOrigin); + }; +} + +function fetchReferrerPolicy(referrerPolicy, destination, fetchMode, expectedOrigin, httpMethod) { + return async function () { + const stash = token(); + const redirectPath = "/fetch/origin/resources/redirect-and-stash.py"; + + let fetchUrl = + (destination === "same-origin" ? origins.HTTP_ORIGIN + : origins.HTTP_REMOTE_ORIGIN) + + redirectPath + "?stash=" + stash + "&dummyJS"; + + await fetch(fetchUrl, { mode: fetchMode, method: httpMethod , "referrerPolicy": referrerPolicy}); + + const json = await (await fetch(redirectPath + "?dump&stash=" + stash)).json(); + + assert_equals(json[0], expectedOrigin); + }; +} + +function referrerPolicyTestString(referrerPolicy, method, destination) { + return "Origin header and " + method + " " + destination + " with Referrer-Policy " + + referrerPolicy; +} + +[ + { + "policy": "no-referrer", + "expectedOriginForSameOrigin": "null", + "expectedOriginForCrossOrigin": "null" + }, + { + "policy": "same-origin", + "expectedOriginForSameOrigin": origins.HTTP_ORIGIN, + "expectedOriginForCrossOrigin": "null" + }, + { + "policy": "origin-when-cross-origin", + "expectedOriginForSameOrigin": origins.HTTP_ORIGIN, + "expectedOriginForCrossOrigin": origins.HTTP_ORIGIN + }, + { + "policy": "no-referrer-when-downgrade", + "expectedOriginForSameOrigin": origins.HTTP_ORIGIN, + "expectedOriginForCrossOrigin": origins.HTTP_ORIGIN + }, + { + "policy": "unsafe-url", + "expectedOriginForSameOrigin": origins.HTTP_ORIGIN, + "expectedOriginForCrossOrigin": origins.HTTP_ORIGIN + }, +].forEach(testObj => { + [ + { + "name": "same-origin", + "expectedOrigin": testObj.expectedOriginForSameOrigin + }, + { + "name": "cross-origin", + "expectedOrigin": testObj.expectedOriginForCrossOrigin + } + ].forEach(destination => { + // Test form POST navigation + promise_test(navigationReferrerPolicy(testObj.policy, + destination.name, + destination.expectedOrigin), + referrerPolicyTestString(testObj.policy, "POST", + destination.name + " navigation")); + // Test fetch + promise_test(fetchReferrerPolicy(testObj.policy, + destination.name, + "no-cors", + destination.expectedOrigin, + "POST"), + referrerPolicyTestString(testObj.policy, "POST", + destination.name + " fetch no-cors mode")); + + // Test cors mode POST + promise_test(fetchReferrerPolicy(testObj.policy, + destination.name, + "cors", + origins.HTTP_ORIGIN, + "POST"), + referrerPolicyTestString(testObj.policy, "POST", + destination.name + " fetch cors mode")); + + // Test cors mode GET + promise_test(fetchReferrerPolicy(testObj.policy, + destination.name, + "cors", + (destination.name == "same-origin") ? "no Origin header" : origins.HTTP_ORIGIN, + "GET"), + referrerPolicyTestString(testObj.policy, "GET", + destination.name + " fetch cors mode")); + }); +}); diff --git a/test/wpt/tests/fetch/origin/resources/redirect-and-stash.py b/test/wpt/tests/fetch/origin/resources/redirect-and-stash.py new file mode 100644 index 0000000..36c584c --- /dev/null +++ b/test/wpt/tests/fetch/origin/resources/redirect-and-stash.py @@ -0,0 +1,38 @@ +import json + +from wptserve.utils import isomorphic_decode + +def main(request, response): + key = request.GET.first(b"stash") + origin = request.headers.get(b"origin") + if origin is None: + origin = b"no Origin header" + + origin_list = request.server.stash.take(key) + + if b"dump" in request.GET: + response.headers.set(b"Content-Type", b"application/json") + response.content = json.dumps(origin_list) + return + + if origin_list is None: + origin_list = [isomorphic_decode(origin)] + else: + origin_list.append(isomorphic_decode(origin)) + + request.server.stash.put(key, origin_list) + + if b"location" in request.GET: + location = request.GET.first(b"location") + if b"dummyJS" in request.GET: + location += b"&dummyJS" + response.status = 308 + response.headers.set(b"Location", location) + return + + response.headers.set(b"Content-Type", b"text/html") + response.headers.set(b"Access-Control-Allow-Origin", b"*") + if b"dummyJS" in request.GET: + response.content = b"console.log('dummy JS')" + else: + response.content = b"\n" diff --git a/test/wpt/tests/fetch/origin/resources/referrer-policy.py b/test/wpt/tests/fetch/origin/resources/referrer-policy.py new file mode 100644 index 0000000..15716e0 --- /dev/null +++ b/test/wpt/tests/fetch/origin/resources/referrer-policy.py @@ -0,0 +1,7 @@ +def main(request, response): + if b"referrerPolicy" in request.GET: + response.headers.set(b"Referrer-Policy", + request.GET.first(b"referrerPolicy")) + response.status = 200 + response.headers.set(b"Content-Type", b"text/html") + response.content = b"\n" diff --git a/test/wpt/tests/fetch/private-network-access/META.yml b/test/wpt/tests/fetch/private-network-access/META.yml new file mode 100644 index 0000000..944ce6f --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/META.yml @@ -0,0 +1,7 @@ +spec: https://wicg.github.io/private-network-access/ +suggested_reviewers: + - letitz + - lyf + - hemeryar + - camillelamy + - mikewest diff --git a/test/wpt/tests/fetch/private-network-access/README.md b/test/wpt/tests/fetch/private-network-access/README.md new file mode 100644 index 0000000..a69aab4 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/README.md @@ -0,0 +1,10 @@ +# Private Network Access tests + +This directory contains tests for Private Network Access' integration with +the Fetch specification. + +See also: + +* [The specification](https://wicg.github.io/private-network-access/) +* [The repository](https://github.com/WICG/private-network-access/) +* [Open issues](https://github.com/WICG/private-network-access/issues/) diff --git a/test/wpt/tests/fetch/private-network-access/fenced-frame-no-preflight-required.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/fenced-frame-no-preflight-required.tentative.https.window.js new file mode 100644 index 0000000..21233f6 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/fenced-frame-no-preflight-required.tentative.https.window.js @@ -0,0 +1,91 @@ +// META: script=/common/dispatcher/dispatcher.js +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// META: script=/fenced-frame/resources/utils.js +// META: timeout=long +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests verify that contexts can navigate fenced frames to more-public or +// same address spaces without private network access preflight request header. + +setup(() => { + assert_true(window.isSecureContext); +}); + +// Source: secure local context. +// +// All fetches unaffected by Private Network Access. + +promise_test_parallel( + t => fencedFrameTest(t, { + source: {server: Server.HTTPS_LOCAL}, + target: {server: Server.HTTPS_LOCAL}, + expected: FrameTestResult.SUCCESS, + }), + 'local to local: no preflight required.'); + +promise_test_parallel( + t => fencedFrameTest(t, { + source: {server: Server.HTTPS_LOCAL}, + target: {server: Server.HTTPS_PRIVATE}, + expected: FrameTestResult.SUCCESS, + }), + 'local to private: no preflight required.'); + +promise_test_parallel( + t => fencedFrameTest(t, { + source: {server: Server.HTTPS_LOCAL}, + target: {server: Server.HTTPS_PUBLIC}, + expected: FrameTestResult.SUCCESS, + }), + 'local to public: no preflight required.'); + +promise_test_parallel( + t => fencedFrameTest(t, { + source: {server: Server.HTTPS_PRIVATE}, + target: {server: Server.HTTPS_PRIVATE}, + expected: FrameTestResult.SUCCESS, + }), + 'private to private: no preflight required.'); + +promise_test_parallel( + t => fencedFrameTest(t, { + source: {server: Server.HTTPS_PRIVATE}, + target: {server: Server.HTTPS_PUBLIC}, + expected: FrameTestResult.SUCCESS, + }), + 'private to public: no preflight required.'); + +promise_test_parallel( + t => fencedFrameTest(t, { + source: {server: Server.HTTPS_PUBLIC}, + target: {server: Server.HTTPS_PUBLIC}, + expected: FrameTestResult.SUCCESS, + }), + 'public to public: no preflight required.'); + +promise_test_parallel( + t => fencedFrameTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: {server: Server.HTTPS_PUBLIC}, + expected: FrameTestResult.SUCCESS, + }), + 'treat-as-public-address to public: no preflight required.'); + +promise_test_parallel( + t => fencedFrameTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: {preflight: PreflightBehavior.optionalSuccess(token())} + }, + expected: FrameTestResult.SUCCESS, + }), + 'treat-as-public-address to local: optional preflight'); diff --git a/test/wpt/tests/fetch/private-network-access/fenced-frame-subresource-fetch.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/fenced-frame-subresource-fetch.tentative.https.window.js new file mode 100644 index 0000000..2dff325 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/fenced-frame-subresource-fetch.tentative.https.window.js @@ -0,0 +1,330 @@ +// META: script=/common/subset-tests-by-key.js +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// META: script=/fenced-frame/resources/utils.js +// META: variant=?include=baseline +// META: variant=?include=from-local +// META: variant=?include=from-private +// META: variant=?include=from-public +// META: timeout=long +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests verify that secure contexts can fetch subresources in fenced +// frames from all address spaces, provided that the target server, if more +// private than the initiator, respond affirmatively to preflight requests. +// + +setup(() => { + // Making sure we are in a secure context, as expected. + assert_true(window.isSecureContext); +}); + +// Source: secure local context. +// +// All fetches unaffected by Private Network Access. + +subsetTestByKey( + 'from-local', promise_test, t => fencedFrameFetchTest(t, { + source: {server: Server.HTTPS_LOCAL}, + target: {server: Server.HTTPS_LOCAL}, + fetchOptions: {method: 'GET', mode: 'cors'}, + expected: FetchTestResult.SUCCESS, + }), + 'local to local: no preflight required.'); + +subsetTestByKey( + 'from-local', promise_test, + t => fencedFrameFetchTest(t, { + source: {server: Server.HTTPS_LOCAL}, + target: { + server: Server.HTTPS_PRIVATE, + behavior: {response: ResponseBehavior.allowCrossOrigin()}, + }, + fetchOptions: {method: 'GET', mode: 'cors'}, + expected: FetchTestResult.SUCCESS, + }), + 'local to private: no preflight required.'); + + +subsetTestByKey( + 'from-local', promise_test, + t => fencedFrameFetchTest(t, { + source: {server: Server.HTTPS_LOCAL}, + target: { + server: Server.HTTPS_PUBLIC, + behavior: {response: ResponseBehavior.allowCrossOrigin()}, + }, + fetchOptions: {method: 'GET', mode: 'cors'}, + expected: FetchTestResult.SUCCESS, + }), + 'local to public: no preflight required.'); + +// Strictly speaking, the following two tests do not exercise PNA-specific +// logic, but they serve as a baseline for comparison, ensuring that non-PNA +// preflight requests are sent and handled as expected. + +subsetTestByKey( + 'baseline', promise_test, + t => fencedFrameFetchTest(t, { + source: {server: Server.HTTPS_LOCAL}, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { + preflight: PreflightBehavior.failure(), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: {method: 'PUT', mode: 'cors'}, + expected: FetchTestResult.FAILURE, + }), + 'local to public: PUT preflight failure.'); + +subsetTestByKey( + 'baseline', promise_test, + t => fencedFrameFetchTest(t, { + source: {server: Server.HTTPS_LOCAL}, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + } + }, + fetchOptions: {method: 'PUT', mode: 'cors'}, + expected: FetchTestResult.SUCCESS, + }), + 'local to public: PUT preflight success.'); + +// Generates tests of preflight behavior for a single (source, target) pair. +// +// Scenarios: +// +// - cors mode: +// - preflight response has non-2xx HTTP code +// - preflight response is missing CORS headers +// - preflight response is missing the PNA-specific `Access-Control` header +// - final response is missing CORS headers +// - success +// - success with PUT method (non-"simple" request) +// - no-cors mode: +// - preflight response has non-2xx HTTP code +// - preflight response is missing CORS headers +// - preflight response is missing the PNA-specific `Access-Control` header +// - success +// +function makePreflightTests({ + subsetKey, + source, + sourceDescription, + targetServer, + targetDescription, +}) { + const prefix = `${sourceDescription} to ${targetDescription}: `; + + subsetTestByKey( + subsetKey, promise_test, + t => fencedFrameFetchTest(t, { + source, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.failure(), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: {method: 'GET', mode: 'cors'}, + expected: FetchTestResult.FAILURE, + }), + prefix + 'failed preflight.'); + + subsetTestByKey( + subsetKey, promise_test, + t => fencedFrameFetchTest(t, { + source, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.noCorsHeader(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: {method: 'GET', mode: 'cors'}, + expected: FetchTestResult.FAILURE, + }), + prefix + 'missing CORS headers on preflight response.'); + + subsetTestByKey( + subsetKey, promise_test, + t => fencedFrameFetchTest(t, { + source, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.noPnaHeader(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: {method: 'GET', mode: 'cors'}, + expected: FetchTestResult.FAILURE, + }), + prefix + 'missing PNA header on preflight response.'); + + subsetTestByKey( + subsetKey, promise_test, + t => fencedFrameFetchTest(t, { + source, + target: { + server: targetServer, + behavior: {preflight: PreflightBehavior.success(token())}, + }, + fetchOptions: {method: 'GET', mode: 'cors'}, + expected: FetchTestResult.FAILURE, + }), + prefix + 'missing CORS headers on final response.'); + + subsetTestByKey( + subsetKey, promise_test, + t => fencedFrameFetchTest(t, { + source, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: {method: 'GET', mode: 'cors'}, + expected: FetchTestResult.SUCCESS, + }), + prefix + 'success.'); + + subsetTestByKey( + subsetKey, promise_test, + t => fencedFrameFetchTest(t, { + source, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: {method: 'PUT', mode: 'cors'}, + expected: FetchTestResult.SUCCESS, + }), + prefix + 'PUT success.'); + + subsetTestByKey( + subsetKey, promise_test, t => fencedFrameFetchTest(t, { + source, + target: {server: targetServer}, + fetchOptions: {method: 'GET', mode: 'no-cors'}, + expected: FetchTestResult.FAILURE, + }), + prefix + 'no-CORS mode failed preflight.'); + + subsetTestByKey( + subsetKey, promise_test, + t => fencedFrameFetchTest(t, { + source, + target: { + server: targetServer, + behavior: {preflight: PreflightBehavior.noCorsHeader(token())}, + }, + fetchOptions: {method: 'GET', mode: 'no-cors'}, + expected: FetchTestResult.FAILURE, + }), + prefix + 'no-CORS mode missing CORS headers on preflight response.'); + + subsetTestByKey( + subsetKey, promise_test, + t => fencedFrameFetchTest(t, { + source, + target: { + server: targetServer, + behavior: {preflight: PreflightBehavior.noPnaHeader(token())}, + }, + fetchOptions: {method: 'GET', mode: 'no-cors'}, + expected: FetchTestResult.FAILURE, + }), + prefix + 'no-CORS mode missing PNA header on preflight response.'); + + subsetTestByKey( + subsetKey, promise_test, + t => fencedFrameFetchTest(t, { + source, + target: { + server: targetServer, + behavior: {preflight: PreflightBehavior.success(token())}, + }, + fetchOptions: {method: 'GET', mode: 'no-cors'}, + expected: FetchTestResult.OPAQUE, + }), + prefix + 'no-CORS mode success.'); +} + +// Source: private secure context. +// +// Fetches to the local address space require a successful preflight response +// carrying a PNA-specific header. + +makePreflightTests({ + subsetKey: 'from-private', + source: {server: Server.HTTPS_PRIVATE}, + sourceDescription: 'private', + targetServer: Server.HTTPS_LOCAL, + targetDescription: 'local', +}); + +subsetTestByKey( + 'from-private', promise_test, t => fencedFrameFetchTest(t, { + source: {server: Server.HTTPS_PRIVATE}, + target: {server: Server.HTTPS_PRIVATE}, + fetchOptions: {method: 'GET', mode: 'cors'}, + expected: FetchTestResult.SUCCESS, + }), + 'private to private: no preflight required.'); + +subsetTestByKey( + 'from-private', promise_test, + t => fencedFrameFetchTest(t, { + source: {server: Server.HTTPS_PRIVATE}, + target: { + server: Server.HTTPS_PRIVATE, + behavior: {response: ResponseBehavior.allowCrossOrigin()}, + }, + fetchOptions: {method: 'GET', mode: 'cors'}, + expected: FetchTestResult.SUCCESS, + }), + 'private to public: no preflight required.'); + +// Source: public secure context. +// +// Fetches to the local and private address spaces require a successful +// preflight response carrying a PNA-specific header. + +makePreflightTests({ + subsetKey: 'from-public', + source: {server: Server.HTTPS_PUBLIC}, + sourceDescription: 'public', + targetServer: Server.HTTPS_LOCAL, + targetDescription: 'local', +}); + +makePreflightTests({ + subsetKey: 'from-public', + source: {server: Server.HTTPS_PUBLIC}, + sourceDescription: 'public', + targetServer: Server.HTTPS_PRIVATE, + targetDescription: 'private', +}); + +subsetTestByKey( + 'from-public', promise_test, t => fencedFrameFetchTest(t, { + source: {server: Server.HTTPS_PUBLIC}, + target: {server: Server.HTTPS_PUBLIC}, + fetchOptions: {method: 'GET', mode: 'cors'}, + expected: FetchTestResult.SUCCESS, + }), + 'public to public: no preflight required.'); diff --git a/test/wpt/tests/fetch/private-network-access/fenced-frame.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/fenced-frame.tentative.https.window.js new file mode 100644 index 0000000..370cc9f --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/fenced-frame.tentative.https.window.js @@ -0,0 +1,150 @@ +// META: script=/common/dispatcher/dispatcher.js +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// META: script=/fenced-frame/resources/utils.js +// META: timeout=long +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests verify that contexts can navigate fenced frames to less-public +// address spaces iff the target server responds affirmatively to preflight +// requests. + +setup(() => { + assert_true(window.isSecureContext); +}); + +// Generates tests of preflight behavior for a single (source, target) pair. +// +// Scenarios: +// +// - parent navigates child: +// - preflight response has non-2xx HTTP code +// - preflight response is missing CORS headers +// - preflight response is missing the PNA-specific `Access-Control` header +// - preflight response has the required PNA related headers, but still fails +// because of the limitation of fenced frame that subjects to PNA checks. +// +function makePreflightTests({ + sourceName, + sourceServer, + sourceTreatAsPublic, + targetName, + targetServer, +}) { + const prefix = `${sourceName} to ${targetName}: `; + + const source = { + server: sourceServer, + treatAsPublic: sourceTreatAsPublic, + }; + + promise_test_parallel( + t => fencedFrameTest(t, { + source, + target: { + server: targetServer, + behavior: {preflight: PreflightBehavior.failure()}, + }, + expected: FrameTestResult.FAILURE, + }), + prefix + 'failed preflight.'); + + promise_test_parallel( + t => fencedFrameTest(t, { + source, + target: { + server: targetServer, + behavior: {preflight: PreflightBehavior.noCorsHeader(token())}, + }, + expected: FrameTestResult.FAILURE, + }), + prefix + 'missing CORS headers.'); + + promise_test_parallel( + t => fencedFrameTest(t, { + source, + target: { + server: targetServer, + behavior: {preflight: PreflightBehavior.noPnaHeader(token())}, + }, + expected: FrameTestResult.FAILURE, + }), + prefix + 'missing PNA header.'); + + promise_test_parallel( + t => fencedFrameTest(t, { + source, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin() + }, + }, + expected: FrameTestResult.FAILURE, + }), + prefix + 'failed because fenced frames are incompatible with PNA.'); +} + +// Source: private secure context. +// +// Fetches to the local address space require a successful preflight response +// carrying a PNA-specific header. + +makePreflightTests({ + sourceServer: Server.HTTPS_PRIVATE, + sourceName: 'private', + targetServer: Server.HTTPS_LOCAL, + targetName: 'local', +}); + +// Source: public secure context. +// +// Fetches to the local and private address spaces require a successful +// preflight response carrying a PNA-specific header. + +makePreflightTests({ + sourceServer: Server.HTTPS_PUBLIC, + sourceName: 'public', + targetServer: Server.HTTPS_LOCAL, + targetName: 'local', +}); + +makePreflightTests({ + sourceServer: Server.HTTPS_PUBLIC, + sourceName: 'public', + targetServer: Server.HTTPS_PRIVATE, + targetName: 'private', +}); + +// The following tests verify that `CSP: treat-as-public-address` makes +// documents behave as if they had been served from a public IP address. + +makePreflightTests({ + sourceServer: Server.HTTPS_LOCAL, + sourceTreatAsPublic: true, + sourceName: 'treat-as-public-address', + targetServer: Server.OTHER_HTTPS_LOCAL, + targetName: 'local', +}); + +promise_test_parallel( + t => fencedFrameTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: {server: Server.HTTPS_LOCAL}, + expected: FrameTestResult.FAILURE, + }), + 'treat-as-public-address to local (same-origin): fenced frame embedder ' + + 'initiated navigation has opaque origin.'); + +makePreflightTests({ + sourceServer: Server.HTTPS_LOCAL, + sourceTreatAsPublic: true, + sourceName: 'treat-as-public-address', + targetServer: Server.HTTPS_PRIVATE, + targetName: 'private', +}); diff --git a/test/wpt/tests/fetch/private-network-access/fetch-from-treat-as-public.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/fetch-from-treat-as-public.tentative.https.window.js new file mode 100644 index 0000000..084e032 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/fetch-from-treat-as-public.tentative.https.window.js @@ -0,0 +1,80 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests verify that documents fetched from the `local` or `private` +// address space yet carrying the `treat-as-public-address` CSP directive are +// treated as if they had been fetched from the `public` address space. + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + preflight: PreflightBehavior.noPnaHeader(token()), + }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public-address to local: failed preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.SUCCESS, +}), "treat-as-public-address to local: success."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: FetchTestResult.SUCCESS, +}), "treat-as-public-address to local (same-origin): no preflight required."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_PRIVATE }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public-address to private: failed preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.SUCCESS, +}), "treat-as-public-address to private: success."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: FetchTestResult.SUCCESS, +}), "treat-as-public-address to public: no preflight required."); diff --git a/test/wpt/tests/fetch/private-network-access/fetch.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/fetch.tentative.https.window.js new file mode 100644 index 0000000..dbc4f23 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/fetch.tentative.https.window.js @@ -0,0 +1,271 @@ +// META: script=/common/subset-tests-by-key.js +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// META: variant=?include=baseline +// META: variant=?include=from-local +// META: variant=?include=from-private +// META: variant=?include=from-public +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests verify that secure contexts can fetch subresources from all +// address spaces, provided that the target server, if more private than the +// initiator, respond affirmatively to preflight requests. +// +// This file covers only those tests that must execute in a secure context. +// Other tests are defined in: fetch.window.js + +setup(() => { + // Making sure we are in a secure context, as expected. + assert_true(window.isSecureContext); +}); + +// Source: secure local context. +// +// All fetches unaffected by Private Network Access. + +subsetTestByKey("from-local", promise_test, t => fetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { server: Server.HTTPS_LOCAL }, + expected: FetchTestResult.SUCCESS, +}), "local to local: no preflight required."); + +subsetTestByKey("from-local", promise_test, t => fetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: FetchTestResult.SUCCESS, +}), "local to private: no preflight required."); + + +subsetTestByKey("from-local", promise_test, t => fetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: FetchTestResult.SUCCESS, +}), "local to public: no preflight required."); + +// Strictly speaking, the following two tests do not exercise PNA-specific +// logic, but they serve as a baseline for comparison, ensuring that non-PNA +// preflight requests are sent and handled as expected. + +subsetTestByKey("baseline", promise_test, t => fetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { + preflight: PreflightBehavior.failure(), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: { method: "PUT" }, + expected: FetchTestResult.FAILURE, +}), "local to public: PUT preflight failure."); + +subsetTestByKey("baseline", promise_test, t => fetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + } + }, + fetchOptions: { method: "PUT" }, + expected: FetchTestResult.SUCCESS, +}), "local to public: PUT preflight success."); + +// Generates tests of preflight behavior for a single (source, target) pair. +// +// Scenarios: +// +// - cors mode: +// - preflight response has non-2xx HTTP code +// - preflight response is missing CORS headers +// - preflight response is missing the PNA-specific `Access-Control` header +// - final response is missing CORS headers +// - success +// - success with PUT method (non-"simple" request) +// - no-cors mode: +// - preflight response has non-2xx HTTP code +// - preflight response is missing CORS headers +// - preflight response is missing the PNA-specific `Access-Control` header +// - success +// +function makePreflightTests({ + subsetKey, + source, + sourceDescription, + targetServer, + targetDescription, +}) { + const prefix = + `${sourceDescription} to ${targetDescription}: `; + + subsetTestByKey(subsetKey, promise_test, t => fetchTest(t, { + source, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.failure(), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.FAILURE, + }), prefix + "failed preflight."); + + subsetTestByKey(subsetKey, promise_test, t => fetchTest(t, { + source, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.noCorsHeader(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.FAILURE, + }), prefix + "missing CORS headers on preflight response."); + + subsetTestByKey(subsetKey, promise_test, t => fetchTest(t, { + source, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.noPnaHeader(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.FAILURE, + }), prefix + "missing PNA header on preflight response."); + + subsetTestByKey(subsetKey, promise_test, t => fetchTest(t, { + source, + target: { + server: targetServer, + behavior: { preflight: PreflightBehavior.success(token()) }, + }, + expected: FetchTestResult.FAILURE, + }), prefix + "missing CORS headers on final response."); + + subsetTestByKey(subsetKey, promise_test, t => fetchTest(t, { + source, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.SUCCESS, + }), prefix + "success."); + + subsetTestByKey(subsetKey, promise_test, t => fetchTest(t, { + source, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: { method: "PUT" }, + expected: FetchTestResult.SUCCESS, + }), prefix + "PUT success."); + + subsetTestByKey(subsetKey, promise_test, t => fetchTest(t, { + source, + target: { server: targetServer }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.FAILURE, + }), prefix + "no-CORS mode failed preflight."); + + subsetTestByKey(subsetKey, promise_test, t => fetchTest(t, { + source, + target: { + server: targetServer, + behavior: { preflight: PreflightBehavior.noCorsHeader(token()) }, + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.FAILURE, + }), prefix + "no-CORS mode missing CORS headers on preflight response."); + + subsetTestByKey(subsetKey, promise_test, t => fetchTest(t, { + source, + target: { + server: targetServer, + behavior: { preflight: PreflightBehavior.noPnaHeader(token()) }, + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.FAILURE, + }), prefix + "no-CORS mode missing PNA header on preflight response."); + + subsetTestByKey(subsetKey, promise_test, t => fetchTest(t, { + source, + target: { + server: targetServer, + behavior: { preflight: PreflightBehavior.success(token()) }, + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.OPAQUE, + }), prefix + "no-CORS mode success."); +} + +// Source: private secure context. +// +// Fetches to the local address space require a successful preflight response +// carrying a PNA-specific header. + +makePreflightTests({ + subsetKey: "from-private", + source: { server: Server.HTTPS_PRIVATE }, + sourceDescription: "private", + targetServer: Server.HTTPS_LOCAL, + targetDescription: "local", +}); + +subsetTestByKey("from-private", promise_test, t => fetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { server: Server.HTTPS_PRIVATE }, + expected: FetchTestResult.SUCCESS, +}), "private to private: no preflight required."); + +subsetTestByKey("from-private", promise_test, t => fetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: FetchTestResult.SUCCESS, +}), "private to public: no preflight required."); + +// Source: public secure context. +// +// Fetches to the local and private address spaces require a successful +// preflight response carrying a PNA-specific header. + +makePreflightTests({ + subsetKey: "from-public", + source: { server: Server.HTTPS_PUBLIC }, + sourceDescription: "public", + targetServer: Server.HTTPS_LOCAL, + targetDescription: "local", +}); + +makePreflightTests({ + subsetKey: "from-public", + source: { server: Server.HTTPS_PUBLIC }, + sourceDescription: "public", + targetServer: Server.HTTPS_PRIVATE, + targetDescription: "private", +}); + +subsetTestByKey("from-public", promise_test, t => fetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.HTTPS_PUBLIC }, + expected: FetchTestResult.SUCCESS, +}), "public to public: no preflight required."); + diff --git a/test/wpt/tests/fetch/private-network-access/fetch.tentative.window.js b/test/wpt/tests/fetch/private-network-access/fetch.tentative.window.js new file mode 100644 index 0000000..8ee54c9 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/fetch.tentative.window.js @@ -0,0 +1,183 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests verify that non-secure contexts cannot fetch subresources from +// less-public address spaces, and can fetch them otherwise. +// +// This file covers only those tests that must execute in a non secure context. +// Other tests are defined in: fetch.https.window.js + +setup(() => { + // Making sure we are in a non secure context, as expected. + assert_false(window.isSecureContext); +}); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { server: Server.HTTP_LOCAL }, + expected: FetchTestResult.SUCCESS, +}), "local to local: no preflight required."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: FetchTestResult.SUCCESS, +}), "local to private: no preflight required."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { + server: Server.HTTP_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: FetchTestResult.SUCCESS, +}), "local to public: no preflight required."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.FAILURE, +}), "private to local: failure."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { server: Server.HTTP_PRIVATE }, + expected: FetchTestResult.SUCCESS, +}), "private to private: no preflight required."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { + server: Server.HTTP_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: FetchTestResult.SUCCESS, +}), "private to public: no preflight required."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.FAILURE, +}), "public to local: failure."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.FAILURE, +}), "public to private: failure."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.HTTP_PUBLIC }, + expected: FetchTestResult.SUCCESS, +}), "public to public: no preflight required."); + +// These tests verify that documents fetched from the `local` address space yet +// carrying the `treat-as-public-address` CSP directive are treated as if they +// had been fetched from the `public` address space. + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public-address to local: failure."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public-address to private: failure."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: FetchTestResult.SUCCESS, +}), "treat-as-public-address to public: no preflight required."); + +// These tests verify that HTTPS iframes embedded in an HTTP top-level document +// cannot fetch subresources from less-public address spaces. Indeed, even +// though the iframes have HTTPS origins, they are non-secure contexts because +// their parent is a non-secure context. + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.FAILURE, +}), "private https to local: failure."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.FAILURE, +}), "public https to local: failure."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.FAILURE, +}), "public https to private: failure."); diff --git a/test/wpt/tests/fetch/private-network-access/iframe.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/iframe.tentative.https.window.js new file mode 100644 index 0000000..0c12970 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/iframe.tentative.https.window.js @@ -0,0 +1,266 @@ +// META: script=/common/subset-tests-by-key.js +// META: script=/common/dispatcher/dispatcher.js +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// META: timeout=long +// META: variant=?include=from-local +// META: variant=?include=from-private +// META: variant=?include=from-public +// META: variant=?include=from-treat-as-public +// META: variant=?include=grandparent +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests verify that contexts can navigate iframes to less-public address +// spaces iff the target server responds affirmatively to preflight requests. +// +// This file covers only those tests that must execute in a secure context. +// Other tests are defined in: iframe.tentative.window.js + +setup(() => { + assert_true(window.isSecureContext); +}); + +// Source: secure local context. +// +// All fetches unaffected by Private Network Access. + +subsetTestByKey("from-local", promise_test_parallel, t => iframeTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { server: Server.HTTPS_LOCAL }, + expected: FrameTestResult.SUCCESS, +}), "local to local: no preflight required."); + +subsetTestByKey("from-local", promise_test_parallel, t => iframeTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { server: Server.HTTPS_PRIVATE }, + expected: FrameTestResult.SUCCESS, +}), "local to private: no preflight required."); + +subsetTestByKey("from-local", promise_test_parallel, t => iframeTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { server: Server.HTTPS_PUBLIC }, + expected: FrameTestResult.SUCCESS, +}), "local to public: no preflight required."); + +// Generates tests of preflight behavior for a single (source, target) pair. +// +// Scenarios: +// +// - parent navigates child: +// - preflight response has non-2xx HTTP code +// - preflight response is missing CORS headers +// - preflight response is missing the PNA-specific `Access-Control` header +// - success +// +function makePreflightTests({ + key, + sourceName, + sourceServer, + sourceTreatAsPublic, + targetName, + targetServer, +}) { + const prefix = + `${sourceName} to ${targetName}: `; + + const source = { + server: sourceServer, + treatAsPublic: sourceTreatAsPublic, + }; + + promise_test_parallel(t => iframeTest(t, { + source, + target: { + server: targetServer, + behavior: { preflight: PreflightBehavior.failure() }, + }, + expected: FrameTestResult.FAILURE, + }), prefix + "failed preflight."); + + promise_test_parallel(t => iframeTest(t, { + source, + target: { + server: targetServer, + behavior: { preflight: PreflightBehavior.noCorsHeader(token()) }, + }, + expected: FrameTestResult.FAILURE, + }), prefix + "missing CORS headers."); + + promise_test_parallel(t => iframeTest(t, { + source, + target: { + server: targetServer, + behavior: { preflight: PreflightBehavior.noPnaHeader(token()) }, + }, + expected: FrameTestResult.FAILURE, + }), prefix + "missing PNA header."); + + promise_test_parallel(t => iframeTest(t, { + source, + target: { + server: targetServer, + behavior: { preflight: PreflightBehavior.success(token()) }, + }, + expected: FrameTestResult.SUCCESS, + }), prefix + "success."); +} + +// Source: private secure context. +// +// Fetches to the local address space require a successful preflight response +// carrying a PNA-specific header. + +subsetTestByKey('from-private', makePreflightTests, { + sourceServer: Server.HTTPS_PRIVATE, + sourceName: 'private', + targetServer: Server.HTTPS_LOCAL, + targetName: 'local', +}); + +subsetTestByKey("from-private", promise_test_parallel, t => iframeTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { server: Server.HTTPS_PRIVATE }, + expected: FrameTestResult.SUCCESS, +}), "private to private: no preflight required."); + +subsetTestByKey("from-private", promise_test_parallel, t => iframeTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { server: Server.HTTPS_PUBLIC }, + expected: FrameTestResult.SUCCESS, +}), "private to public: no preflight required."); + +// Source: public secure context. +// +// Fetches to the local and private address spaces require a successful +// preflight response carrying a PNA-specific header. + +subsetTestByKey('from-public', makePreflightTests, { + sourceServer: Server.HTTPS_PUBLIC, + sourceName: "public", + targetServer: Server.HTTPS_LOCAL, + targetName: "local", +}); + +subsetTestByKey('from-public', makePreflightTests, { + sourceServer: Server.HTTPS_PUBLIC, + sourceName: "public", + targetServer: Server.HTTPS_PRIVATE, + targetName: "private", +}); + +subsetTestByKey("from-public", promise_test_parallel, t => iframeTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.HTTPS_PUBLIC }, + expected: FrameTestResult.SUCCESS, +}), "public to public: no preflight required."); + +// The following tests verify that `CSP: treat-as-public-address` makes +// documents behave as if they had been served from a public IP address. + +subsetTestByKey('from-treat-as-public', makePreflightTests, { + sourceServer: Server.HTTPS_LOCAL, + sourceTreatAsPublic: true, + sourceName: "treat-as-public-address", + targetServer: Server.OTHER_HTTPS_LOCAL, + targetName: "local", +}); + +subsetTestByKey( + 'from-treat-as-public', promise_test_parallel, + t => iframeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: {server: Server.HTTPS_LOCAL}, + expected: FrameTestResult.SUCCESS, + }), + 'treat-as-public-address to local (same-origin): no preflight required.' +); + +subsetTestByKey('from-treat-as-public', makePreflightTests, { + sourceServer: Server.HTTPS_LOCAL, + sourceTreatAsPublic: true, + sourceName: "treat-as-public-address", + targetServer: Server.HTTPS_PRIVATE, + targetName: "private", +}); + +subsetTestByKey( + 'from-treat-as-public', promise_test_parallel, + t => iframeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: {server: Server.HTTPS_PUBLIC}, + expected: FrameTestResult.SUCCESS, + }), + 'treat-as-public-address to public: no preflight required.' +); + +subsetTestByKey( + 'from-treat-as-public', promise_test_parallel, + t => iframeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: {preflight: PreflightBehavior.optionalSuccess(token())} + }, + expected: FrameTestResult.SUCCESS, + }), + 'treat-as-public-address to local: optional preflight' +); + +// The following tests verify that when a grandparent frame navigates its +// grandchild, the IP address space of the grandparent is compared against the +// IP address space of the response. Indeed, the navigation initiator in this +// case is the grandparent, not the parent. + +subsetTestByKey('grandparent', iframeGrandparentTest, { + name: 'local to local, grandparent navigates: no preflight required.', + grandparentServer: Server.HTTPS_LOCAL, + child: {server: Server.HTTPS_PUBLIC}, + grandchild: {server: Server.OTHER_HTTPS_LOCAL}, + expected: FrameTestResult.SUCCESS, +}); + +subsetTestByKey('grandparent', iframeGrandparentTest, { + name: "local to local (same-origin), grandparent navigates: no preflight required.", + grandparentServer: Server.HTTPS_LOCAL, + child: { server: Server.HTTPS_PUBLIC }, + grandchild: { server: Server.HTTPS_LOCAL }, + expected: FrameTestResult.SUCCESS, +}); + +subsetTestByKey('grandparent', iframeGrandparentTest, { + name: "public to local, grandparent navigates: failure.", + grandparentServer: Server.HTTPS_PUBLIC, + child: { + server: Server.HTTPS_LOCAL, + behavior: { preflight: PreflightBehavior.success(token()) }, + }, + grandchild: { + server: Server.HTTPS_LOCAL, + behavior: { preflight: PreflightBehavior.failure() }, + }, + expected: FrameTestResult.FAILURE, +}); + +subsetTestByKey('grandparent', iframeGrandparentTest, { + name: "public to local, grandparent navigates: success.", + grandparentServer: Server.HTTPS_PUBLIC, + child: { + server: Server.HTTPS_LOCAL, + behavior: { preflight: PreflightBehavior.success(token()) }, + }, + grandchild: { + server: Server.HTTPS_LOCAL, + behavior: { preflight: PreflightBehavior.success(token()) }, + }, + expected: FrameTestResult.SUCCESS, +}); diff --git a/test/wpt/tests/fetch/private-network-access/iframe.tentative.window.js b/test/wpt/tests/fetch/private-network-access/iframe.tentative.window.js new file mode 100644 index 0000000..c0770df --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/iframe.tentative.window.js @@ -0,0 +1,110 @@ +// META: script=/common/dispatcher/dispatcher.js +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests verify that non-secure contexts cannot navigate iframes to +// less-public address spaces, and can navigate them otherwise. +// +// This file covers only those tests that must execute in a non secure context. +// Other tests are defined in: iframe.https.window.js + +setup(() => { + // Making sure we are in a non secure context, as expected. + assert_false(window.isSecureContext); +}); + +promise_test_parallel(t => iframeTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { server: Server.HTTP_LOCAL }, + expected: FrameTestResult.SUCCESS, +}), "local to local: no preflight required."); + +promise_test_parallel(t => iframeTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { server: Server.HTTP_PRIVATE }, + expected: FrameTestResult.SUCCESS, +}), "local to private: no preflight required."); + +promise_test_parallel(t => iframeTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { server: Server.HTTP_PUBLIC }, + expected: FrameTestResult.SUCCESS, +}), "local to public: no preflight required."); + +promise_test_parallel(t => iframeTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { server: Server.HTTP_LOCAL }, + expected: FrameTestResult.FAILURE, +}), "private to local: failure."); + +promise_test_parallel(t => iframeTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { server: Server.HTTP_PRIVATE }, + expected: FrameTestResult.SUCCESS, +}), "private to private: no preflight required."); + +promise_test_parallel(t => iframeTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { server: Server.HTTP_PUBLIC }, + expected: FrameTestResult.SUCCESS, +}), "private to public: no preflight required."); + +promise_test_parallel(t => iframeTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.HTTP_LOCAL }, + expected: FrameTestResult.FAILURE, +}), "public to local: failure."); + +promise_test_parallel(t => iframeTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.HTTP_PRIVATE }, + expected: FrameTestResult.FAILURE, +}), "public to private: failure."); + +promise_test_parallel(t => iframeTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.HTTP_PUBLIC }, + expected: FrameTestResult.SUCCESS, +}), "public to public: no preflight required."); + +promise_test_parallel(t => iframeTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTP_LOCAL }, + expected: FrameTestResult.FAILURE, +}), "treat-as-public-address to local: failure."); + +promise_test_parallel(t => iframeTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTP_PRIVATE }, + expected: FrameTestResult.FAILURE, +}), "treat-as-public-address to private: failure."); + +promise_test_parallel(t => iframeTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTP_PUBLIC }, + expected: FrameTestResult.SUCCESS, +}), "treat-as-public-address to public: no preflight required."); + +// The following test verifies that when a grandparent frame navigates its +// grandchild, the IP address space of the grandparent is compared against the +// IP address space of the response. Indeed, the navigation initiator in this +// case is the grandparent, not the parent. + +iframeGrandparentTest({ + name: "local to local, grandparent navigates: success.", + grandparentServer: Server.HTTP_LOCAL, + child: { server: Server.HTTP_PUBLIC }, + grandchild: { server: Server.HTTP_LOCAL }, + expected: FrameTestResult.SUCCESS, +}); diff --git a/test/wpt/tests/fetch/private-network-access/mixed-content-fetch.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/mixed-content-fetch.tentative.https.window.js new file mode 100644 index 0000000..54485dc --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/mixed-content-fetch.tentative.https.window.js @@ -0,0 +1,277 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access +// +// These tests verify that secure contexts can fetch non-secure subresources +// from more private address spaces, avoiding mixed context checks, as long as +// they specify a valid `targetAddressSpace` fetch option that matches the +// target server's address space. + +setup(() => { + // Making sure we are in a secure context, as expected. + assert_true(window.isSecureContext); +}); + +// Given `addressSpace`, returns the other three possible IP address spaces. +function otherAddressSpaces(addressSpace) { + switch (addressSpace) { + case "local": return ["unknown", "private", "public"]; + case "private": return ["unknown", "local", "public"]; + case "public": return ["unknown", "local", "private"]; + } +} + +// Generates tests of `targetAddressSpace` for the given (source, target) +// address space pair, expecting fetches to succeed iff `targetAddressSpace` is +// correct. +// +// Scenarios exercised: +// +// - cors mode: +// - missing targetAddressSpace option +// - incorrect targetAddressSpace option (x3, see `otherAddressSpaces()`) +// - failed preflight +// - success +// - success with PUT method (non-"simple" request) +// - no-cors mode: +// - success +// +function makeTests({ source, target }) { + const sourceServer = Server.get("https", source); + const targetServer = Server.get("http", target); + + const makeTest = ({ + fetchOptions, + targetBehavior, + name, + expected + }) => { + promise_test_parallel(t => fetchTest(t, { + source: { server: sourceServer }, + target: { + server: targetServer, + behavior: targetBehavior, + }, + fetchOptions, + expected, + }), `${sourceServer.name} to ${targetServer.name}: ${name}.`); + }; + + makeTest({ + name: "missing targetAddressSpace", + targetBehavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + expected: FetchTestResult.FAILURE, + }); + + const correctAddressSpace = targetServer.addressSpace; + + for (const targetAddressSpace of otherAddressSpaces(correctAddressSpace)) { + makeTest({ + name: `wrong targetAddressSpace "${targetAddressSpace}"`, + targetBehavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + fetchOptions: { targetAddressSpace }, + expected: FetchTestResult.FAILURE, + }); + } + + makeTest({ + name: "failed preflight", + targetBehavior: { + preflight: PreflightBehavior.failure(), + response: ResponseBehavior.allowCrossOrigin(), + }, + fetchOptions: { targetAddressSpace: correctAddressSpace }, + expected: FetchTestResult.FAILURE, + }); + + makeTest({ + name: "success", + targetBehavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + fetchOptions: { targetAddressSpace: correctAddressSpace }, + expected: FetchTestResult.SUCCESS, + }); + + makeTest({ + name: "PUT success", + targetBehavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + fetchOptions: { + targetAddressSpace: correctAddressSpace, + method: "PUT", + }, + expected: FetchTestResult.SUCCESS, + }); + + makeTest({ + name: "no-cors success", + targetBehavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + fetchOptions: { + targetAddressSpace: correctAddressSpace, + mode: "no-cors", + }, + expected: FetchTestResult.OPAQUE, + }); +} + +// Generates tests for the given (source, target) address space pair expecting +// that `targetAddressSpace` cannot be used to bypass mixed content. +// +// Scenarios exercised: +// +// - wrong `targetAddressSpace` (x3, see `otherAddressSpaces()`) +// - correct `targetAddressSpace` +// +function makeNoBypassTests({ source, target }) { + const sourceServer = Server.get("https", source); + const targetServer = Server.get("http", target); + + const prefix = `${sourceServer.name} to ${targetServer.name}: `; + + const correctAddressSpace = targetServer.addressSpace; + for (const targetAddressSpace of otherAddressSpaces(correctAddressSpace)) { + promise_test_parallel(t => fetchTest(t, { + source: { server: sourceServer }, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: { targetAddressSpace }, + expected: FetchTestResult.FAILURE, + }), prefix + `wrong targetAddressSpace "${targetAddressSpace}".`); + } + + promise_test_parallel(t => fetchTest(t, { + source: { server: sourceServer }, + target: { + server: targetServer, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: { targetAddressSpace: correctAddressSpace }, + expected: FetchTestResult.FAILURE, + }), prefix + 'not a private network request.'); +} + +// Source: local secure context. +// +// Fetches to the local and private address spaces cannot use +// `targetAddressSpace` to bypass mixed content, as they are not otherwise +// blocked by Private Network Access. + +makeNoBypassTests({ source: "local", target: "local" }); +makeNoBypassTests({ source: "local", target: "private" }); +makeNoBypassTests({ source: "local", target: "public" }); + +// Source: private secure context. +// +// Fetches to the local address space requires the right `targetAddressSpace` +// option, as well as a successful preflight response carrying a PNA-specific +// header. +// +// Fetches to the private address space cannot use `targetAddressSpace` to +// bypass mixed content, as they are not otherwise blocked by Private Network +// Access. + +makeTests({ source: "private", target: "local" }); + +makeNoBypassTests({ source: "private", target: "private" }); +makeNoBypassTests({ source: "private", target: "public" }); + +// Source: public secure context. +// +// Fetches to the local and private address spaces require the right +// `targetAddressSpace` option, as well as a successful preflight response +// carrying a PNA-specific header. + +makeTests({ source: "public", target: "local" }); +makeTests({ source: "public", target: "private" }); + +makeNoBypassTests({ source: "public", target: "public" }); + +// These tests verify that documents fetched from the `local` address space yet +// carrying the `treat-as-public-address` CSP directive are treated as if they +// had been fetched from the `public` address space. + +promise_test_parallel(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: { targetAddressSpace: "private" }, + expected: FetchTestResult.FAILURE, +}), 'https-treat-as-public to http-local: wrong targetAddressSpace "private".'); + +promise_test_parallel(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: { targetAddressSpace: "local" }, + expected: FetchTestResult.SUCCESS, +}), "https-treat-as-public to http-local: success."); + +promise_test_parallel(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: { targetAddressSpace: "local" }, + expected: FetchTestResult.FAILURE, +}), 'https-treat-as-public to http-private: wrong targetAddressSpace "local".'); + +promise_test_parallel(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + fetchOptions: { targetAddressSpace: "private" }, + expected: FetchTestResult.SUCCESS, +}), "https-treat-as-public to http-private: success."); diff --git a/test/wpt/tests/fetch/private-network-access/nested-worker.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/nested-worker.tentative.https.window.js new file mode 100644 index 0000000..3eeb435 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/nested-worker.tentative.https.window.js @@ -0,0 +1,36 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that initial `Worker` script fetches from within worker +// scopes are subject to Private Network Access checks, just like a worker +// script fetches from within document scopes (for non-nested workers). The +// latter are tested in: worker.https.window.js +// +// This file covers only those tests that must execute in a secure context. +// Other tests are defined in: nested-worker.window.js + +promise_test(t => nestedWorkerScriptTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: WorkerScriptTestResult.FAILURE, +}), "treat-as-public to local: failure."); + +promise_test(t => nestedWorkerScriptTest(t, { + source: { + server: Server.HTTPS_PRIVATE, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_PRIVATE }, + expected: WorkerScriptTestResult.FAILURE, +}), "treat-as-public to private: failure."); + +promise_test(t => nestedWorkerScriptTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.HTTPS_PUBLIC }, + expected: WorkerScriptTestResult.SUCCESS, +}), "public to public: success."); diff --git a/test/wpt/tests/fetch/private-network-access/nested-worker.tentative.window.js b/test/wpt/tests/fetch/private-network-access/nested-worker.tentative.window.js new file mode 100644 index 0000000..6d246e1 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/nested-worker.tentative.window.js @@ -0,0 +1,36 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that initial `Worker` script fetches from within worker +// scopes are subject to Private Network Access checks, just like a worker +// script fetches from within document scopes (for non-nested workers). The +// latter are tested in: worker.window.js +// +// This file covers only those tests that must execute in a non secure context. +// Other tests are defined in: nested-worker.https.window.js + +promise_test(t => nestedWorkerScriptTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTP_LOCAL }, + expected: WorkerScriptTestResult.FAILURE, +}), "treat-as-public to local: failure."); + +promise_test(t => nestedWorkerScriptTest(t, { + source: { + server: Server.HTTP_PRIVATE, + treatAsPublic: true, + }, + target: { server: Server.HTTP_PRIVATE }, + expected: WorkerScriptTestResult.FAILURE, +}), "treat-as-public to private: failure."); + +promise_test(t => nestedWorkerScriptTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.HTTP_PUBLIC }, + expected: WorkerScriptTestResult.SUCCESS, +}), "public to public: success."); diff --git a/test/wpt/tests/fetch/private-network-access/preflight-cache.https.tentative.window.js b/test/wpt/tests/fetch/private-network-access/preflight-cache.https.tentative.window.js new file mode 100644 index 0000000..87dbf50 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/preflight-cache.https.tentative.window.js @@ -0,0 +1,88 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#cors-preflight +// +// These tests verify that PNA preflight responses are cached. +// +// TODO(https://crbug.com/1268312): We cannot currently test that cache +// entries are keyed by target IP address space because that requires +// loading the same URL from different IP address spaces, and the WPT +// framework does not allow that. +promise_test(async t => { + let uuid = token(); + await fetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.singlePreflight(uuid), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.SUCCESS, + }); + await fetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.singlePreflight(uuid), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.SUCCESS, + }); +}, "private to local: success."); + +promise_test(async t => { + let uuid = token(); + await fetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.singlePreflight(uuid), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.SUCCESS, + }); + await fetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.singlePreflight(uuid), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.SUCCESS, + }); +}, "public to local: success."); + +promise_test(async t => { + let uuid = token(); + await fetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.singlePreflight(uuid), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.SUCCESS, + }); + await fetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.singlePreflight(uuid), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: FetchTestResult.SUCCESS, + }); +}, "public to private: success."); \ No newline at end of file diff --git a/test/wpt/tests/fetch/private-network-access/redirect.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/redirect.tentative.https.window.js new file mode 100644 index 0000000..efbd8f3 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/redirect.tentative.https.window.js @@ -0,0 +1,640 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// This test verifies that Private Network Access checks are applied to all +// the endpoints in a redirect chain, relative to the same client context. + +// local -> private -> public +// +// Request 1 (local -> private): no preflight. +// Request 2 (local -> public): no preflight. + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.HTTPS_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }), + } + }, + expected: FetchTestResult.SUCCESS, +}), "local to private to public: success."); + +// local -> private -> local +// +// Request 1 (local -> private): no preflight. +// Request 2 (local -> local): no preflight. +// +// This checks that the client for the second request is still the initial +// context, not the redirector. + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }), + } + }, + expected: FetchTestResult.SUCCESS, +}), "local to private to local: success."); + +// private -> private -> local +// +// Request 1 (private -> private): no preflight. +// Request 2 (private -> local): preflight required. +// +// This verifies that PNA checks are applied after redirects. + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + redirect: preflightUrl({ + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }), + } + }, + expected: FetchTestResult.FAILURE, +}), "private to private to local: failed preflight."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + redirect: preflightUrl({ + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + } + }, + expected: FetchTestResult.SUCCESS, +}), "private to private to local: success."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + redirect: preflightUrl({ + server: Server.HTTPS_LOCAL, + behavior: { preflight: PreflightBehavior.success(token()) }, + }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.OPAQUE, +}), "private to private to local: no-cors success."); + +// private -> local -> private +// +// Request 1 (private -> local): preflight required. +// Request 2 (private -> private): no preflight. +// +// This verifies that PNA checks are applied independently to every step in a +// redirect chain. + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + }), + } + }, + expected: FetchTestResult.FAILURE, +}), "private to local to private: failed preflight."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }), + } + }, + expected: FetchTestResult.SUCCESS, +}), "private to local to private: success."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + redirect: preflightUrl({ server: Server.HTTPS_PRIVATE }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.OPAQUE, +}), "private to local to private: no-cors success."); + +// public -> private -> local +// +// Request 1 (public -> private): preflight required. +// Request 2 (public -> local): preflight required. +// +// This verifies that PNA checks are applied to every step in a redirect chain. + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + } + }, + expected: FetchTestResult.FAILURE, +}), "public to private to local: failed first preflight."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.HTTPS_LOCAL, + behavior: { + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + } + }, + expected: FetchTestResult.FAILURE, +}), "public to private to local: failed second preflight."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + } + }, + expected: FetchTestResult.SUCCESS, +}), "public to private to local: success."); + +promise_test(t => fetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + redirect: preflightUrl({ + server: Server.HTTPS_LOCAL, + behavior: { preflight: PreflightBehavior.success(token()) }, + }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.OPAQUE, +}), "public to private to local: no-cors success."); + +// treat-as-public -> local -> private + +// Request 1 (treat-as-public -> local): preflight required. +// Request 2 (treat-as-public -> private): preflight required. + +// This verifies that PNA checks are applied to every step in a redirect chain. + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + response: ResponseBehavior.allowCrossOrigin(), + } + }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to local to private: failed first preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.noPnaHeader(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + response: ResponseBehavior.allowCrossOrigin(), + } + }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to local to private: failed second preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + response: ResponseBehavior.allowCrossOrigin(), + } + }, + expected: FetchTestResult.SUCCESS, +}), "treat-as-public to local to private: success."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + behavior: { preflight: PreflightBehavior.success(token()) }, + }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to local to private: no-cors failed first preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + redirect: preflightUrl({ server: Server.HTTPS_PRIVATE }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to local to private: no-cors failed second preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + behavior: { preflight: PreflightBehavior.success(token()) }, + }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.OPAQUE, +}), "treat-as-public to local to private: no-cors success."); + +// treat-as-public -> local (same-origin) -> private + +// Request 1 (treat-as-public -> local (same-origin)): no preflight required. +// Request 2 (treat-as-public -> private): preflight required. + +// This verifies that PNA checks are applied only to the second step in a +// redirect chain if the first step is same-origin and the origin is potentially +// trustworthy. + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.noPnaHeader(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + } + }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to local (same-origin) to private: failed second preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + } + }, + expected: FetchTestResult.SUCCESS, +}), "treat-as-public to local (same-origin) to private: success."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + redirect: preflightUrl({ server: Server.HTTPS_PRIVATE }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to local (same-origin) to private: no-cors failed second preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + behavior: { preflight: PreflightBehavior.success(token()) }, + }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.OPAQUE, +}), "treat-as-public to local (same-origin) to private: no-cors success."); + +// treat-as-public -> private -> local + +// Request 1 (treat-as-public -> private): preflight required. +// Request 2 (treat-as-public -> local): preflight required. + +// This verifies that PNA checks are applied to every step in a redirect chain. + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.noPnaHeader(token()), + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + } + }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to private to local: failed first preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.OTHER_HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }), + } + }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to private to local: failed second preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + } + }, + expected: FetchTestResult.SUCCESS, +}), "treat-as-public to private to local: success."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + redirect: preflightUrl({ + server: Server.OTHER_HTTPS_LOCAL, + behavior: { preflight: PreflightBehavior.success(token()) }, + }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to private to local: no-cors failed first preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + redirect: preflightUrl({ server: Server.OTHER_HTTPS_LOCAL }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to private to local: no-cors failed second preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + redirect: preflightUrl({ + server: Server.OTHER_HTTPS_LOCAL, + behavior: { preflight: PreflightBehavior.success(token()) }, + }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.OPAQUE, +}), "treat-as-public to private to local: no-cors success."); + +// treat-as-public -> private -> local (same-origin) + +// Request 1 (treat-as-public -> private): preflight required. +// Request 2 (treat-as-public -> local (same-origin)): no preflight required. + +// This verifies that PNA checks are only applied to the first step in a +// redirect chain if the second step is same-origin and the origin is +// potentially trustworthy. + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.noPnaHeader(token()), + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }), + } + }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to private to local (same-origin): failed first preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }), + } + }, + expected: FetchTestResult.SUCCESS, +}), "treat-as-public to private to local (same-origin): success."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + redirect: preflightUrl({ server: Server.HTTPS_LOCAL }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to private to local (same-origin): no-cors failed first preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + redirect: preflightUrl({ server: Server.HTTPS_LOCAL }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.OPAQUE, +}), "treat-as-public to private to local (same-origin): no-cors success."); diff --git a/test/wpt/tests/fetch/private-network-access/resources/executor.html b/test/wpt/tests/fetch/private-network-access/resources/executor.html new file mode 100644 index 0000000..d712129 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/executor.html @@ -0,0 +1,9 @@ + + +Executor + + + diff --git a/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-fetcher.https.html b/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-fetcher.https.html new file mode 100644 index 0000000..b14601d --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-fetcher.https.html @@ -0,0 +1,25 @@ + + + +Fetcher + \ No newline at end of file diff --git a/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-fetcher.https.html.headers b/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-fetcher.https.html.headers new file mode 100644 index 0000000..6247f6d --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-fetcher.https.html.headers @@ -0,0 +1 @@ +Supports-Loading-Mode: fenced-frame \ No newline at end of file diff --git a/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-local-network-access-target.https.html b/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-local-network-access-target.https.html new file mode 100644 index 0000000..2b55e05 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-local-network-access-target.https.html @@ -0,0 +1,8 @@ + + + +Fenced frame target + diff --git a/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-local-network-access.https.html b/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-local-network-access.https.html new file mode 100644 index 0000000..98f1184 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-local-network-access.https.html @@ -0,0 +1,14 @@ + + + + + +Fenced frame + + diff --git a/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-local-network-access.https.html.headers b/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-local-network-access.https.html.headers new file mode 100644 index 0000000..6247f6d --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/fenced-frame-local-network-access.https.html.headers @@ -0,0 +1 @@ +Supports-Loading-Mode: fenced-frame \ No newline at end of file diff --git a/test/wpt/tests/fetch/private-network-access/resources/fetcher.html b/test/wpt/tests/fetch/private-network-access/resources/fetcher.html new file mode 100644 index 0000000..000a5cc --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/fetcher.html @@ -0,0 +1,21 @@ + + +Fetcher + diff --git a/test/wpt/tests/fetch/private-network-access/resources/fetcher.js b/test/wpt/tests/fetch/private-network-access/resources/fetcher.js new file mode 100644 index 0000000..3a18598 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/fetcher.js @@ -0,0 +1,20 @@ +async function doFetch(url) { + const response = await fetch(url); + const body = await response.text(); + return { + status: response.status, + body, + }; +} + +async function fetchAndPost(url) { + try { + const message = await doFetch(url); + self.postMessage(message); + } catch(e) { + self.postMessage({ error: e.name }); + } +} + +const url = new URL(self.location.href).searchParams.get("url"); +fetchAndPost(url); diff --git a/test/wpt/tests/fetch/private-network-access/resources/iframed.html b/test/wpt/tests/fetch/private-network-access/resources/iframed.html new file mode 100644 index 0000000..c889c28 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/iframed.html @@ -0,0 +1,7 @@ + + +Iframed + diff --git a/test/wpt/tests/fetch/private-network-access/resources/iframer.html b/test/wpt/tests/fetch/private-network-access/resources/iframer.html new file mode 100644 index 0000000..304cc54 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/iframer.html @@ -0,0 +1,9 @@ + + +Iframer + + diff --git a/test/wpt/tests/fetch/private-network-access/resources/preflight.py b/test/wpt/tests/fetch/private-network-access/resources/preflight.py new file mode 100644 index 0000000..be3abdb --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/preflight.py @@ -0,0 +1,175 @@ +# This endpoint responds to both preflight requests and the subsequent requests. +# +# Its behavior can be configured with various search/GET parameters, all of +# which are optional: +# +# - treat-as-public-once: Must be a valid UUID if set. +# If set, then this endpoint expects to receive a non-preflight request first, +# for which it sets the `Content-Security-Policy: treat-as-public-address` +# response header. This allows testing "DNS rebinding", where a URL first +# resolves to the public IP address space, then a non-public IP address space. +# - preflight-uuid: Must be a valid UUID if set, distinct from the value of the +# `treat-as-public-once` parameter if both are set. +# If set, then this endpoint expects to receive a preflight request first +# followed by a regular request, as in the regular CORS protocol. If the +# `treat-as-public-once` header is also set, it takes precedence: this +# endpoint expects to receive a non-preflight request first, then a preflight +# request, then finally a regular request. +# If unset, then this endpoint expects to receive no preflight request, only +# a regular (non-OPTIONS) request. +# - preflight-headers: Valid values are: +# - cors: this endpoint responds with valid CORS headers to preflights. These +# should be sufficient for non-PNA preflight requests to succeed, but not +# for PNA-specific preflight requests. +# - cors+pna: this endpoint responds with valid CORS and PNA headers to +# preflights. These should be sufficient for both non-PNA preflight +# requests and PNA-specific preflight requests to succeed. +# - cors+pna+sw: this endpoint responds with valid CORS and PNA headers and +# "Access-Control-Allow-Headers: Service-Worker" to preflights. These should +# be sufficient for both non-PNA preflight requests and PNA-specific +# preflight requests to succeed. This allows the main request to fetch a +# service worker script. +# - unspecified, or any other value: this endpoint responds with no CORS or +# PNA headers. Preflight requests should fail. +# - final-headers: Valid values are: +# - cors: this endpoint responds with valid CORS headers to CORS-enabled +# non-preflight requests. These should be sufficient for non-preflighted +# CORS-enabled requests to succeed. +# - unspecified: this endpoint responds with no CORS headers to non-preflight +# requests. This should fail CORS-enabled requests, but be sufficient for +# no-CORS requests. +# +# The following parameters only affect non-preflight responses: +# +# - redirect: If set, the response code is set to 301 and the `Location` +# response header is set to this value. +# - mime-type: If set, the `Content-Type` response header is set to this value. +# - file: Specifies a path (relative to this file's directory) to a file. If +# set, the response body is copied from this file. +# - random-js-prefix: If set to any value, the response body is prefixed with +# a Javascript comment line containing a random value. This is useful in +# service worker tests, since service workers are only updated if the new +# script is not byte-for-byte identical with the old script. +# - body: If set and `file` is not, the response body is set to this value. +# + +import os +import random + +from wptserve.utils import isomorphic_encode + +_ACAO = ("Access-Control-Allow-Origin", "*") +_ACAPN = ("Access-Control-Allow-Private-Network", "true") +_ACAH = ("Access-Control-Allow-Headers", "Service-Worker") + +def _get_response_headers(method, mode): + acam = ("Access-Control-Allow-Methods", method) + + if mode == b"cors": + return [acam, _ACAO] + + if mode == b"cors+pna": + return [acam, _ACAO, _ACAPN] + + if mode == b"cors+pna+sw": + return [acam, _ACAO, _ACAPN, _ACAH] + + return [] + +def _get_expect_single_preflight(request): + return request.GET.get(b"expect-single-preflight") + +def _is_preflight_optional(request): + return request.GET.get(b"is-preflight-optional") + +def _get_preflight_uuid(request): + return request.GET.get(b"preflight-uuid") + +def _is_loaded_in_fenced_frame(request): + return request.GET.get(b"is-loaded-in-fenced-frame") + +def _should_treat_as_public_once(request): + uuid = request.GET.get(b"treat-as-public-once") + if uuid is None: + # If the search parameter is not given, never treat as public. + return False + + # If the parameter is given, we treat the request as public only if the UUID + # has never been seen and stashed. + result = request.server.stash.take(uuid) is None + request.server.stash.put(uuid, "") + return result + +def _handle_preflight_request(request, response): + if _should_treat_as_public_once(request): + return (400, [], "received preflight for first treat-as-public request") + + uuid = _get_preflight_uuid(request) + if uuid is None: + return (400, [], "missing `preflight-uuid` param from preflight URL") + + value = request.server.stash.take(uuid) + request.server.stash.put(uuid, "preflight") + if _get_expect_single_preflight(request) and value is not None: + return (400, [], "received duplicated preflight") + + method = request.headers.get("Access-Control-Request-Method") + mode = request.GET.get(b"preflight-headers") + headers = _get_response_headers(method, mode) + + return (headers, "preflight") + +def _final_response_body(request): + file_name = request.GET.get(b"file") + if file_name is None: + return request.GET.get(b"body") or "success" + + prefix = b"" + if request.GET.get(b"random-js-prefix"): + value = random.randint(0, 1000000000) + prefix = isomorphic_encode("// Random value: {}\n\n".format(value)) + + path = os.path.join(os.path.dirname(isomorphic_encode(__file__)), file_name) + with open(path, 'rb') as f: + contents = f.read() + + return prefix + contents + +def _handle_final_request(request, response): + if _should_treat_as_public_once(request): + headers = [("Content-Security-Policy", "treat-as-public-address"),] + else: + uuid = _get_preflight_uuid(request) + if uuid is not None: + if (request.server.stash.take(uuid) is None and + not _is_preflight_optional(request)): + return (405, [], "no preflight received") + request.server.stash.put(uuid, "final") + + mode = request.GET.get(b"final-headers") + headers = _get_response_headers(request.method, mode) + + redirect = request.GET.get(b"redirect") + if redirect is not None: + headers.append(("Location", redirect)) + return (301, headers, b"") + + mime_type = request.GET.get(b"mime-type") + if mime_type is not None: + headers.append(("Content-Type", mime_type),) + + if _is_loaded_in_fenced_frame(request): + headers.append(("Supports-Loading-Mode", "fenced-frame")) + + body = _final_response_body(request) + return (headers, body) + +def main(request, response): + try: + if request.method == "OPTIONS": + return _handle_preflight_request(request, response) + else: + return _handle_final_request(request, response) + except BaseException as e: + # Surface exceptions to the client, where they show up as assertion errors. + return (500, [("X-exception", str(e))], "exception: {}".format(e)) diff --git a/test/wpt/tests/fetch/private-network-access/resources/service-worker-bridge.html b/test/wpt/tests/fetch/private-network-access/resources/service-worker-bridge.html new file mode 100644 index 0000000..816de53 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/service-worker-bridge.html @@ -0,0 +1,155 @@ + + +ServiceWorker Bridge + + + diff --git a/test/wpt/tests/fetch/private-network-access/resources/service-worker.js b/test/wpt/tests/fetch/private-network-access/resources/service-worker.js new file mode 100644 index 0000000..bca71ad --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/service-worker.js @@ -0,0 +1,18 @@ +self.addEventListener("install", () => { + // Skip waiting before replacing the previously-active service worker, if any. + // This allows the bridge script to notice the controller change and query + // the install time via fetch. + self.skipWaiting(); +}); + +self.addEventListener("activate", (event) => { + // Claim all clients so that the bridge script notices the activation. + event.waitUntil(self.clients.claim()); +}); + +self.addEventListener("fetch", (event) => { + const url = new URL(event.request.url).searchParams.get("proxied-url"); + if (url) { + event.respondWith(fetch(url)); + } +}); diff --git a/test/wpt/tests/fetch/private-network-access/resources/shared-fetcher.js b/test/wpt/tests/fetch/private-network-access/resources/shared-fetcher.js new file mode 100644 index 0000000..30bde1e --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/shared-fetcher.js @@ -0,0 +1,23 @@ +async function doFetch(url) { + const response = await fetch(url); + const body = await response.text(); + return { + status: response.status, + body, + }; +} + +async function fetchAndPost(url, port) { + try { + const message = await doFetch(url); + port.postMessage(message); + } catch(e) { + port.postMessage({ error: e.name }); + } +} + +const url = new URL(self.location.href).searchParams.get("url"); + +self.addEventListener("connect", async (evt) => { + await fetchAndPost(url, evt.ports[0]); +}); diff --git a/test/wpt/tests/fetch/private-network-access/resources/shared-worker-blob-fetcher.html b/test/wpt/tests/fetch/private-network-access/resources/shared-worker-blob-fetcher.html new file mode 100644 index 0000000..a79869b --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/shared-worker-blob-fetcher.html @@ -0,0 +1,50 @@ + + +SharedWorker Blob Fetcher + diff --git a/test/wpt/tests/fetch/private-network-access/resources/shared-worker-fetcher.html b/test/wpt/tests/fetch/private-network-access/resources/shared-worker-fetcher.html new file mode 100644 index 0000000..4af4b1f --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/shared-worker-fetcher.html @@ -0,0 +1,19 @@ + + +SharedWorker Fetcher + diff --git a/test/wpt/tests/fetch/private-network-access/resources/socket-opener.html b/test/wpt/tests/fetch/private-network-access/resources/socket-opener.html new file mode 100644 index 0000000..48d2721 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/socket-opener.html @@ -0,0 +1,15 @@ + + +WebSocket Opener + diff --git a/test/wpt/tests/fetch/private-network-access/resources/support.sub.js b/test/wpt/tests/fetch/private-network-access/resources/support.sub.js new file mode 100644 index 0000000..27d733d --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/support.sub.js @@ -0,0 +1,759 @@ +// Creates a new iframe in `doc`, calls `func` on it and appends it as a child +// of `doc`. +// Returns a promise that resolves to the iframe once loaded (successfully or +// not). +// The iframe is removed from `doc` once test `t` is done running. +// +// NOTE: There exists no interoperable way to check whether an iframe failed to +// load, so this should only be used when the iframe is expected to load. It +// also means we cannot wire the iframe's `error` event to a promise +// rejection. See: https://github.com/whatwg/html/issues/125 +function appendIframeWith(t, doc, func) { + return new Promise(resolve => { + const child = doc.createElement("iframe"); + t.add_cleanup(() => child.remove()); + + child.addEventListener("load", () => resolve(child), { once: true }); + func(child); + doc.body.appendChild(child); + }); +} + +// Appends a child iframe to `doc` sourced from `src`. +// +// See `appendIframeWith()` for more details. +function appendIframe(t, doc, src) { + return appendIframeWith(t, doc, child => { child.src = src; }); +} + +// Registers an event listener that will resolve this promise when this +// window receives a message posted to it. +// +// `options` has the following shape: +// +// { +// source: If specified, this function waits for the first message from the +// given source only, ignoring other messages. +// +// filter: If specified, this function calls `filter` on each incoming +// message, and resolves iff it returns true. +// } +// +function futureMessage(options) { + return new Promise(resolve => { + window.addEventListener("message", (e) => { + if (options?.source && options.source !== e.source) { + return; + } + + if (options?.filter && !options.filter(e.data)) { + return; + } + + resolve(e.data); + }); + }); +}; + +// Like `promise_test()`, but executes tests in parallel like `async_test()`. +// +// Cribbed from COEP tests. +function promise_test_parallel(promise, description) { + async_test(test => { + promise(test) + .then(() => test.done()) + .catch(test.step_func(error => { throw error; })); + }, description); +}; + +async function postMessageAndAwaitReply(target, message) { + const reply = futureMessage({ source: target }); + target.postMessage(message, "*"); + return await reply; +} + +// Maps protocol (without the trailing colon) and address space to port. +const SERVER_PORTS = { + "http": { + "local": {{ports[http][0]}}, + "private": {{ports[http-private][0]}}, + "public": {{ports[http-public][0]}}, + }, + "https": { + "local": {{ports[https][0]}}, + "other-local": {{ports[https][1]}}, + "private": {{ports[https-private][0]}}, + "public": {{ports[https-public][0]}}, + }, + "ws": { + "local": {{ports[ws][0]}}, + }, + "wss": { + "local": {{ports[wss][0]}}, + }, +}; + +// A `Server` is a web server accessible by tests. It has the following shape: +// +// { +// addressSpace: the IP address space of the server ("local", "private" or +// "public"), +// name: a human-readable name for the server, +// port: the port on which the server listens for connections, +// protocol: the protocol (including trailing colon) spoken by the server, +// } +// +// Constants below define the available servers, which can also be accessed +// programmatically with `get()`. +class Server { + // Maps the given `protocol` (without a trailing colon) and `addressSpace` to + // a server. Returns null if no such server exists. + static get(protocol, addressSpace) { + const ports = SERVER_PORTS[protocol]; + if (ports === undefined) { + return null; + } + + const port = ports[addressSpace]; + if (port === undefined) { + return null; + } + + return { + addressSpace, + name: `${protocol}-${addressSpace}`, + port, + protocol: protocol + ':', + }; + } + + static HTTP_LOCAL = Server.get("http", "local"); + static HTTP_PRIVATE = Server.get("http", "private"); + static HTTP_PUBLIC = Server.get("http", "public"); + static HTTPS_LOCAL = Server.get("https", "local"); + static OTHER_HTTPS_LOCAL = Server.get("https", "other-local"); + static HTTPS_PRIVATE = Server.get("https", "private"); + static HTTPS_PUBLIC = Server.get("https", "public"); + static WS_LOCAL = Server.get("ws", "local"); + static WSS_LOCAL = Server.get("wss", "local"); +}; + +// Resolves a URL relative to the current location, returning an absolute URL. +// +// `url` specifies the relative URL, e.g. "foo.html" or "http://foo.example". +// `options`, if defined, should have the following shape: +// +// { +// // Optional. Overrides the protocol of the returned URL. +// protocol, +// +// // Optional. Overrides the port of the returned URL. +// port, +// +// // Extra headers. +// headers, +// +// // Extra search params. +// searchParams, +// } +// +function resolveUrl(url, options) { + const result = new URL(url, window.location); + if (options === undefined) { + return result; + } + + const { port, protocol, headers, searchParams } = options; + if (port !== undefined) { + result.port = port; + } + if (protocol !== undefined) { + result.protocol = protocol; + } + if (headers !== undefined) { + const pipes = []; + for (key in headers) { + pipes.push(`header(${key},${headers[key]})`); + } + result.searchParams.append("pipe", pipes.join("|")); + } + if (searchParams !== undefined) { + for (key in searchParams) { + result.searchParams.append(key, searchParams[key]); + } + } + + return result; +} + +// Computes options to pass to `resolveUrl()` for a source document's URL. +// +// `server` identifies the server from which to load the document. +// `treatAsPublic`, if set to true, specifies that the source document should +// be artificially placed in the `public` address space using CSP. +function sourceResolveOptions({ server, treatAsPublic }) { + const options = {...server}; + if (treatAsPublic) { + options.headers = { "Content-Security-Policy": "treat-as-public-address" }; + } + return options; +} + +// Computes the URL of a preflight handler configured with the given options. +// +// `server` identifies the server from which to load the resource. +// `behavior` specifies the behavior of the target server. It may contain: +// - `preflight`: The result of calling one of `PreflightBehavior`'s methods. +// - `response`: The result of calling one of `ResponseBehavior`'s methods. +// - `redirect`: A URL to which the target should redirect GET requests. +function preflightUrl({ server, behavior }) { + assert_not_equals(server, undefined, 'server'); + const options = {...server}; + if (behavior) { + const { preflight, response, redirect } = behavior; + options.searchParams = { + ...preflight, + ...response, + }; + if (redirect !== undefined) { + options.searchParams.redirect = redirect; + } + } + + return resolveUrl("resources/preflight.py", options); +} + +// Methods generate behavior specifications for how `resources/preflight.py` +// should behave upon receiving a preflight request. +const PreflightBehavior = { + // The preflight response should fail with a non-2xx code. + failure: () => ({}), + + // The preflight response should be missing CORS headers. + // `uuid` should be a UUID that uniquely identifies the preflight request. + noCorsHeader: (uuid) => ({ + "preflight-uuid": uuid, + }), + + // The preflight response should be missing PNA headers. + // `uuid` should be a UUID that uniquely identifies the preflight request. + noPnaHeader: (uuid) => ({ + "preflight-uuid": uuid, + "preflight-headers": "cors", + }), + + // The preflight response should succeed. + // `uuid` should be a UUID that uniquely identifies the preflight request. + success: (uuid) => ({ + "preflight-uuid": uuid, + "preflight-headers": "cors+pna", + }), + + optionalSuccess: (uuid) => ({ + "preflight-uuid": uuid, + "preflight-headers": "cors+pna", + "is-preflight-optional": true, + }), + + // The preflight response should succeed and allow service-worker header. + // `uuid` should be a UUID that uniquely identifies the preflight request. + serviceWorkerSuccess: (uuid) => ({ + "preflight-uuid": uuid, + "preflight-headers": "cors+pna+sw", + }), + + // The preflight response should succeed only if it is the first preflight. + // `uuid` should be a UUID that uniquely identifies the preflight request. + singlePreflight: (uuid) => ({ + "preflight-uuid": uuid, + "preflight-headers": "cors+pna", + "expect-single-preflight": true, + }), +}; + +// Methods generate behavior specifications for how `resources/preflight.py` +// should behave upon receiving a regular (non-preflight) request. +const ResponseBehavior = { + // The response should succeed without CORS headers. + default: () => ({}), + + // The response should succeed with CORS headers. + allowCrossOrigin: () => ({ "final-headers": "cors" }), +}; + +const FetchTestResult = { + SUCCESS: { + ok: true, + body: "success", + }, + OPAQUE: { + ok: false, + type: "opaque", + body: "", + }, + FAILURE: { + error: "TypeError: Failed to fetch", + }, +}; + +// Runs a fetch test. Tries to fetch a given subresource from a given document. +// +// Main argument shape: +// +// { +// // Optional. Passed to `sourceResolveOptions()`. +// source, +// +// // Optional. Passed to `preflightUrl()`. +// target, +// +// // Optional. Passed to `fetch()`. +// fetchOptions, +// +// // Required. One of the values in `FetchTestResult`. +// expected, +// } +// +async function fetchTest(t, { source, target, fetchOptions, expected }) { + const sourceUrl = + resolveUrl("resources/fetcher.html", sourceResolveOptions(source)); + + const targetUrl = preflightUrl(target); + + const iframe = await appendIframe(t, document, sourceUrl); + const reply = futureMessage({ source: iframe.contentWindow }); + + const message = { + url: targetUrl.href, + options: fetchOptions, + }; + iframe.contentWindow.postMessage(message, "*"); + + const { error, ok, type, body } = await reply; + + assert_equals(error, expected.error, "error"); + + assert_equals(ok, expected.ok, "response ok"); + assert_equals(body, expected.body, "response body"); + + if (expected.type !== undefined) { + assert_equals(type, expected.type, "response type"); + } +} + +// Similar to `fetchTest`, but replaced iframes with fenced frames. +async function fencedFrameFetchTest(t, { source, target, fetchOptions, expected }) { + const fetcher_url = + resolveUrl("resources/fenced-frame-fetcher.https.html", sourceResolveOptions(source)); + + const target_url = preflightUrl(target); + target_url.searchParams.set("is-loaded-in-fenced-frame", true); + + fetcher_url.searchParams.set("mode", fetchOptions.mode); + fetcher_url.searchParams.set("method", fetchOptions.method); + fetcher_url.searchParams.set("url", target_url); + + const error_token = token(); + const ok_token = token(); + const body_token = token(); + const type_token = token(); + const source_url = generateURL(fetcher_url, [error_token, ok_token, body_token, type_token]); + + const urn = await generateURNFromFledge(source_url, []); + attachFencedFrame(urn); + + const error = await nextValueFromServer(error_token); + const ok = await nextValueFromServer(ok_token); + const body = await nextValueFromServer(body_token); + const type = await nextValueFromServer(type_token); + + assert_equals(error, expected.error || "" , "error"); + assert_equals(body, expected.body || "", "response body"); + assert_equals(ok, expected.ok !== undefined ? expected.ok.toString() : "", "response ok"); + if (expected.type !== undefined) { + assert_equals(type, expected.type, "response type"); + } +} + +const XhrTestResult = { + SUCCESS: { + loaded: true, + status: 200, + body: "success", + }, + FAILURE: { + loaded: false, + status: 0, + }, +}; + +// Runs an XHR test. Tries to fetch a given subresource from a given document. +// +// Main argument shape: +// +// { +// // Optional. Passed to `sourceResolveOptions()`. +// source, +// +// // Optional. Passed to `preflightUrl()`. +// target, +// +// // Optional. Method to use when sending the request. Defaults to "GET". +// method, +// +// // Required. One of the values in `XhrTestResult`. +// expected, +// } +// +async function xhrTest(t, { source, target, method, expected }) { + const sourceUrl = + resolveUrl("resources/xhr-sender.html", sourceResolveOptions(source)); + + const targetUrl = preflightUrl(target); + + const iframe = await appendIframe(t, document, sourceUrl); + const reply = futureMessage(); + + const message = { + url: targetUrl.href, + method: method, + }; + iframe.contentWindow.postMessage(message, "*"); + + const { loaded, status, body } = await reply; + + assert_equals(loaded, expected.loaded, "response loaded"); + assert_equals(status, expected.status, "response status"); + assert_equals(body, expected.body, "response body"); +} + +const FrameTestResult = { + SUCCESS: "loaded", + FAILURE: "timeout", +}; + +async function iframeTest(t, { source, target, expected }) { + // Allows running tests in parallel. + const uuid = token(); + + const targetUrl = preflightUrl(target); + targetUrl.searchParams.set("file", "iframed.html"); + targetUrl.searchParams.set("iframe-uuid", uuid); + + const sourceUrl = + resolveUrl("resources/iframer.html", sourceResolveOptions(source)); + sourceUrl.searchParams.set("url", targetUrl); + + const messagePromise = futureMessage({ + filter: (data) => data.uuid === uuid, + }); + const iframe = await appendIframe(t, document, sourceUrl); + + // The grandchild frame posts a message iff it loads successfully. + // There exists no interoperable way to check whether an iframe failed to + // load, so we use a timeout. + // See: https://github.com/whatwg/html/issues/125 + const result = await Promise.race([ + messagePromise.then((data) => data.message), + new Promise((resolve) => { + t.step_timeout(() => resolve("timeout"), 500 /* ms */); + }), + ]); + + assert_equals(result, expected); +} + +// Similar to `iframeTest`, but replaced iframes with fenced frames. +async function fencedFrameTest(t, { source, target, expected }) { + // Allows running tests in parallel. + const target_url = preflightUrl(target); + target_url.searchParams.set("file", "fenced-frame-local-network-access-target.https.html"); + target_url.searchParams.set("is-loaded-in-fenced-frame", true); + + const frame_loaded_key = token(); + const child_frame_target = generateURL(target_url, [frame_loaded_key]); + + const source_url = + resolveUrl("resources/fenced-frame-local-network-access.https.html", sourceResolveOptions(source)); + source_url.searchParams.set("fenced_frame_url", child_frame_target); + + const urn = await generateURNFromFledge(source_url, []); + attachFencedFrame(urn); + + // The grandchild fenced frame writes a value to the server iff it loads + // successfully. + const result = (expected == FrameTestResult.SUCCESS) ? + await nextValueFromServer(frame_loaded_key) : + await Promise.race([ + nextValueFromServer(frame_loaded_key), + new Promise((resolve) => { + t.step_timeout(() => resolve("timeout"), 10000 /* ms */); + }), + ]); + + assert_equals(result, expected); +} + +const iframeGrandparentTest = ({ + name, + grandparentServer, + child, + grandchild, + expected, +}) => promise_test_parallel(async (t) => { + // Allows running tests in parallel. + const grandparentUuid = token(); + const childUuid = token(); + const grandchildUuid = token(); + + const grandparentUrl = + resolveUrl("resources/executor.html", grandparentServer); + grandparentUrl.searchParams.set("executor-uuid", grandparentUuid); + + const childUrl = preflightUrl(child); + childUrl.searchParams.set("file", "executor.html"); + childUrl.searchParams.set("executor-uuid", childUuid); + + const grandchildUrl = preflightUrl(grandchild); + grandchildUrl.searchParams.set("file", "iframed.html"); + grandchildUrl.searchParams.set("iframe-uuid", grandchildUuid); + + const iframe = await appendIframe(t, document, grandparentUrl); + + const addChild = (url) => new Promise((resolve) => { + const child = document.createElement("iframe"); + child.src = url; + child.addEventListener("load", () => resolve(), { once: true }); + document.body.appendChild(child); + }); + + const grandparentCtx = new RemoteContext(grandparentUuid); + await grandparentCtx.execute_script(addChild, [childUrl]); + + // Add a blank grandchild frame inside the child. + // Apply a timeout to this step so that failures at this step do not block the + // execution of other tests. + const childCtx = new RemoteContext(childUuid); + await Promise.race([ + childCtx.execute_script(addChild, ["about:blank"]), + new Promise((resolve, reject) => t.step_timeout( + () => reject("timeout adding grandchild"), + 2000 /* ms */ + )), + ]); + + const messagePromise = futureMessage({ + filter: (data) => data.uuid === grandchildUuid, + }); + await grandparentCtx.execute_script((url) => { + const child = window.frames[0]; + const grandchild = child.frames[0]; + grandchild.location = url; + }, [grandchildUrl]); + + // The great-grandchild frame posts a message iff it loads successfully. + // There exists no interoperable way to check whether an iframe failed to + // load, so we use a timeout. + // See: https://github.com/whatwg/html/issues/125 + const result = await Promise.race([ + messagePromise.then((data) => data.message), + new Promise((resolve) => { + t.step_timeout(() => resolve("timeout"), 2000 /* ms */); + }), + ]); + + assert_equals(result, expected); +}, name); + +const WebsocketTestResult = { + SUCCESS: "open", + + // The code is a best guess. It is not yet entirely specified, so it may need + // to be changed in the future based on implementation experience. + FAILURE: "close: code 1006", +}; + +// Runs a websocket test. Attempts to open a websocket from `source` (in an +// iframe) to `target`, then checks that the result is as `expected`. +// +// Argument shape: +// +// { +// // Required. Passed to `sourceResolveOptions()`. +// source, +// +// // Required. +// target: { +// // Required. Target server. +// server, +// } +// +// // Required. Should be one of the values in `WebsocketTestResult`. +// expected, +// } +// +async function websocketTest(t, { source, target, expected }) { + const sourceUrl = + resolveUrl("resources/socket-opener.html", sourceResolveOptions(source)); + + const targetUrl = resolveUrl("/echo", target.server); + + const iframe = await appendIframe(t, document, sourceUrl); + + const reply = futureMessage(); + iframe.contentWindow.postMessage(targetUrl.href, "*"); + + assert_equals(await reply, expected); +} + +const WorkerScriptTestResult = { + SUCCESS: { loaded: true }, + FAILURE: { error: "unknown error" }, +}; + +function workerScriptUrl(target) { + const url = preflightUrl(target); + + url.searchParams.append("body", "postMessage({ loaded: true })") + url.searchParams.append("mime-type", "application/javascript") + + return url; +} + +async function workerScriptTest(t, { source, target, expected }) { + const sourceUrl = + resolveUrl("resources/worker-fetcher.html", sourceResolveOptions(source)); + + const targetUrl = workerScriptUrl(target); + + const iframe = await appendIframe(t, document, sourceUrl); + const reply = futureMessage(); + + iframe.contentWindow.postMessage({ url: targetUrl.href }, "*"); + + const { error, loaded } = await reply; + + assert_equals(error, expected.error, "worker error"); + assert_equals(loaded, expected.loaded, "response loaded"); +} + +async function nestedWorkerScriptTest(t, { source, target, expected }) { + const targetUrl = workerScriptUrl(target); + + const sourceUrl = resolveUrl( + "resources/worker-fetcher.js", sourceResolveOptions(source)); + sourceUrl.searchParams.append("url", targetUrl); + + // Iframe must be same-origin with the parent worker. + const iframeUrl = new URL("worker-fetcher.html", sourceUrl); + + const iframe = await appendIframe(t, document, iframeUrl); + const reply = futureMessage(); + + iframe.contentWindow.postMessage({ url: sourceUrl.href }, "*"); + + const { error, loaded } = await reply; + + assert_equals(error, expected.error, "worker error"); + assert_equals(loaded, expected.loaded, "response loaded"); +} + +async function sharedWorkerScriptTest(t, { source, target, expected }) { + const sourceUrl = resolveUrl("resources/shared-worker-fetcher.html", + sourceResolveOptions(source)); + const targetUrl = preflightUrl(target); + targetUrl.searchParams.append( + "body", "onconnect = (e) => e.ports[0].postMessage({ loaded: true })") + targetUrl.searchParams.append("mime-type", "application/javascript") + + const iframe = await appendIframe(t, document, sourceUrl); + const reply = futureMessage(); + + iframe.contentWindow.postMessage({ url: targetUrl.href }, "*"); + + const { error, loaded } = await reply; + + assert_equals(error, expected.error, "worker error"); + assert_equals(loaded, expected.loaded, "response loaded"); +} + +// Results that may be expected in tests. +const WorkerFetchTestResult = { + SUCCESS: { status: 200, body: "success" }, + FAILURE: { error: "TypeError" }, +}; + +async function workerFetchTest(t, { source, target, expected }) { + const targetUrl = preflightUrl(target); + + const sourceUrl = + resolveUrl("resources/fetcher.js", sourceResolveOptions(source)); + sourceUrl.searchParams.append("url", targetUrl.href); + + const fetcherUrl = new URL("worker-fetcher.html", sourceUrl); + + const reply = futureMessage(); + const iframe = await appendIframe(t, document, fetcherUrl); + + iframe.contentWindow.postMessage({ url: sourceUrl.href }, "*"); + + const { error, status, body } = await reply; + assert_equals(error, expected.error, "fetch error"); + assert_equals(status, expected.status, "response status"); + assert_equals(body, expected.body, "response body"); +} + +async function workerBlobFetchTest(t, { source, target, expected }) { + const targetUrl = preflightUrl(target); + + const fetcherUrl = resolveUrl( + 'resources/worker-blob-fetcher.html', sourceResolveOptions(source)); + + const reply = futureMessage(); + const iframe = await appendIframe(t, document, fetcherUrl); + + iframe.contentWindow.postMessage({ url: targetUrl.href }, "*"); + + const { error, status, body } = await reply; + assert_equals(error, expected.error, "fetch error"); + assert_equals(status, expected.status, "response status"); + assert_equals(body, expected.body, "response body"); +} + +async function sharedWorkerFetchTest(t, { source, target, expected }) { + const targetUrl = preflightUrl(target); + + const sourceUrl = + resolveUrl("resources/shared-fetcher.js", sourceResolveOptions(source)); + sourceUrl.searchParams.append("url", targetUrl.href); + + const fetcherUrl = new URL("shared-worker-fetcher.html", sourceUrl); + + const reply = futureMessage(); + const iframe = await appendIframe(t, document, fetcherUrl); + + iframe.contentWindow.postMessage({ url: sourceUrl.href }, "*"); + + const { error, status, body } = await reply; + assert_equals(error, expected.error, "fetch error"); + assert_equals(status, expected.status, "response status"); + assert_equals(body, expected.body, "response body"); +} + +async function sharedWorkerBlobFetchTest(t, { source, target, expected }) { + const targetUrl = preflightUrl(target); + + const fetcherUrl = resolveUrl( + 'resources/shared-worker-blob-fetcher.html', + sourceResolveOptions(source)); + + const reply = futureMessage(); + const iframe = await appendIframe(t, document, fetcherUrl); + + iframe.contentWindow.postMessage({ url: targetUrl.href }, "*"); + + const { error, status, body } = await reply; + assert_equals(error, expected.error, "fetch error"); + assert_equals(status, expected.status, "response status"); + assert_equals(body, expected.body, "response body"); +} diff --git a/test/wpt/tests/fetch/private-network-access/resources/worker-blob-fetcher.html b/test/wpt/tests/fetch/private-network-access/resources/worker-blob-fetcher.html new file mode 100644 index 0000000..5a50271 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/worker-blob-fetcher.html @@ -0,0 +1,45 @@ + + +Worker Blob Fetcher + diff --git a/test/wpt/tests/fetch/private-network-access/resources/worker-fetcher.html b/test/wpt/tests/fetch/private-network-access/resources/worker-fetcher.html new file mode 100644 index 0000000..bd155a5 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/worker-fetcher.html @@ -0,0 +1,18 @@ + + +Worker Fetcher + diff --git a/test/wpt/tests/fetch/private-network-access/resources/worker-fetcher.js b/test/wpt/tests/fetch/private-network-access/resources/worker-fetcher.js new file mode 100644 index 0000000..aab49af --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/worker-fetcher.js @@ -0,0 +1,11 @@ +const url = new URL(self.location).searchParams.get("url"); +const worker = new Worker(url); + +// Relay messages from the worker to the parent frame. +worker.addEventListener("message", (evt) => { + self.postMessage(evt.data); +}); + +worker.addEventListener("error", (evt) => { + self.postMessage({ error: evt.message || "unknown error" }); +}); diff --git a/test/wpt/tests/fetch/private-network-access/resources/xhr-sender.html b/test/wpt/tests/fetch/private-network-access/resources/xhr-sender.html new file mode 100644 index 0000000..b131fa4 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/resources/xhr-sender.html @@ -0,0 +1,33 @@ + + +XHR Sender + diff --git a/test/wpt/tests/fetch/private-network-access/service-worker-background-fetch.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/service-worker-background-fetch.tentative.https.window.js new file mode 100644 index 0000000..6369b16 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/service-worker-background-fetch.tentative.https.window.js @@ -0,0 +1,142 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// Spec: https://wicg.github.io/background-fetch/ +// +// These tests check that background fetches from within `ServiceWorker` scripts +// are not subject to Private Network Access checks. + +// Results that may be expected in tests. +const TestResult = { + SUCCESS: { ok: true, body: "success", result: "success", failureReason: "" }, +}; + +async function makeTest(t, { source, target, expected }) { + const scriptUrl = + resolveUrl("resources/service-worker.js", sourceResolveOptions(source)); + + const bridgeUrl = new URL("service-worker-bridge.html", scriptUrl); + + const targetUrl = preflightUrl(target); + + const iframe = await appendIframe(t, document, bridgeUrl); + + const request = (message) => { + const reply = futureMessage(); + iframe.contentWindow.postMessage(message, "*"); + return reply; + }; + + { + const { error, loaded } = await request({ + action: "register", + url: scriptUrl.href, + }); + + assert_equals(error, undefined, "register error"); + assert_true(loaded, "response loaded"); + } + + { + const { error, state } = await request({ + action: "set-permission", + name: "background-fetch", + state: "granted", + }); + + assert_equals(error, undefined, "set permission error"); + assert_equals(state, "granted", "permission state"); + } + + { + const { error, result, failureReason, ok, body } = await request({ + action: "background-fetch", + url: targetUrl.href, + }); + + assert_equals(error, expected.error, "error"); + assert_equals(failureReason, expected.failureReason, "fetch failure reason"); + assert_equals(result, expected.result, "fetch result"); + assert_equals(ok, expected.ok, "response ok"); + assert_equals(body, expected.body, "response body"); + } +} + +promise_test(t => makeTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { server: Server.HTTPS_LOCAL }, + expected: TestResult.SUCCESS, +}), "local to local: success."); + +promise_test(t => makeTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: TestResult.SUCCESS, +}), "private to local: success."); + +promise_test(t => makeTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { server: Server.HTTPS_PRIVATE }, + expected: TestResult.SUCCESS, +}), "private to private: success."); + +promise_test(t => makeTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: TestResult.SUCCESS, +}), "public to local: success."); + +promise_test(t => makeTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: TestResult.SUCCESS, +}), "public to private: success."); + +promise_test(t => makeTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.HTTPS_PUBLIC }, + expected: TestResult.SUCCESS, +}), "public to public: success."); + +promise_test(t => makeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: TestResult.SUCCESS, +}), "treat-as-public to local: success."); + +promise_test(t => makeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: TestResult.SUCCESS, +}), "treat-as-public to private: success."); + +promise_test(t => makeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: TestResult.SUCCESS, +}), "treat-as-public to public: success."); diff --git a/test/wpt/tests/fetch/private-network-access/service-worker-fetch.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/service-worker-fetch.tentative.https.window.js new file mode 100644 index 0000000..cb6d1f7 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/service-worker-fetch.tentative.https.window.js @@ -0,0 +1,235 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// META: script=/common/subset-tests.js +// META: variant=?1-8 +// META: variant=?9-last +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that fetches from within `ServiceWorker` scripts are +// subject to Private Network Access checks, just like fetches from within +// documents. + +// Results that may be expected in tests. +const TestResult = { + SUCCESS: { ok: true, body: "success" }, + FAILURE: { error: "TypeError" }, +}; + +async function makeTest(t, { source, target, expected }) { + const bridgeUrl = resolveUrl( + "resources/service-worker-bridge.html", + sourceResolveOptions({ server: source.server })); + + const scriptUrl = + resolveUrl("resources/service-worker.js", sourceResolveOptions(source)); + + const realTargetUrl = preflightUrl(target); + + // Fetch a URL within the service worker's scope, but tell it which URL to + // really fetch. + const targetUrl = new URL("service-worker-proxy", scriptUrl); + targetUrl.searchParams.append("proxied-url", realTargetUrl.href); + + const iframe = await appendIframe(t, document, bridgeUrl); + + const request = (message) => { + const reply = futureMessage(); + iframe.contentWindow.postMessage(message, "*"); + return reply; + }; + + { + const { error, loaded } = await request({ + action: "register", + url: scriptUrl.href, + }); + + assert_equals(error, undefined, "register error"); + assert_true(loaded, "response loaded"); + } + + try { + const { controlled, numControllerChanges } = await request({ + action: "wait", + numControllerChanges: 1, + }); + + assert_equals(numControllerChanges, 1, "controller change"); + assert_true(controlled, "bridge script is controlled"); + + const { error, ok, body } = await request({ + action: "fetch", + url: targetUrl.href, + }); + + assert_equals(error, expected.error, "fetch error"); + assert_equals(ok, expected.ok, "response ok"); + assert_equals(body, expected.body, "response body"); + } finally { + // Always unregister the service worker. + const { error, unregistered } = await request({ + action: "unregister", + scope: new URL("./", scriptUrl).href, + }); + + assert_equals(error, undefined, "unregister error"); + assert_true(unregistered, "unregistered"); + } +} + +subsetTest(promise_test, t => makeTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { server: Server.HTTPS_LOCAL }, + expected: TestResult.SUCCESS, +}), "local to local: success."); + +subsetTest(promise_test, t => makeTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: TestResult.FAILURE, +}), "private to local: failed preflight."); + +subsetTest(promise_test, t => makeTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: TestResult.SUCCESS, +}), "private to local: success."); + +subsetTest(promise_test, t => makeTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { server: Server.HTTPS_PRIVATE }, + expected: TestResult.SUCCESS, +}), "private to private: success."); + +subsetTest(promise_test, t => makeTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: TestResult.FAILURE, +}), "public to local: failed preflight."); + +subsetTest(promise_test, t => makeTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: TestResult.SUCCESS, +}), "public to local: success."); + +subsetTest(promise_test, t => makeTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: TestResult.FAILURE, +}), "public to private: failed preflight."); + +subsetTest(promise_test, t => makeTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: TestResult.SUCCESS, +}), "public to private: success."); + +subsetTest(promise_test, t => makeTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.HTTPS_PUBLIC }, + expected: TestResult.SUCCESS, +}), "public to public: success."); + +subsetTest(promise_test, t => makeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: TestResult.FAILURE, +}), "treat-as-public to local: failed preflight."); + +subsetTest(promise_test, t => makeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: TestResult.SUCCESS, +}), "treat-as-public to local: success."); + +subsetTest(promise_test, t => makeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: TestResult.SUCCESS, +}), "treat-as-public to local (same-origin): no preflight required."); + +subsetTest(promise_test, t => makeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: TestResult.FAILURE, +}), "treat-as-public to private: failed preflight."); + +subsetTest(promise_test, t => makeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: TestResult.SUCCESS, +}), "treat-as-public to private: success."); + +subsetTest(promise_test, t => makeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: TestResult.SUCCESS, +}), "treat-as-public to public: success."); diff --git a/test/wpt/tests/fetch/private-network-access/service-worker-update.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/service-worker-update.tentative.https.window.js new file mode 100644 index 0000000..4882d23 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/service-worker-update.tentative.https.window.js @@ -0,0 +1,106 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that `ServiceWorker` script update fetches are exempt from +// Private Network Access checks because they are always same-origin and the +// origin is potentially trustworthy. The client of the fetch, for PNA purposes, +// is taken to be the previous script. +// +// The tests is carried out by instantiating a service worker from a resource +// that carries the `Content-Security-Policy: treat-as-public-address` header, +// such that the registration is placed in the public IP address space. When +// the script is fetched for an update, the client is thus considered public, +// yet the same-origin fetch observes that the server's IP endpoint is not +// necessarily in the public IP address space. +// +// See also: worker.https.window.js + +// Results that may be expected in tests. +const TestResult = { + SUCCESS: { updated: true }, + FAILURE: { error: "TypeError" }, +}; + +async function makeTest(t, { target, expected }) { + // The bridge must be same-origin with the service worker script. + const bridgeUrl = resolveUrl( + "resources/service-worker-bridge.html", + sourceResolveOptions({ server: target.server })); + + const scriptUrl = preflightUrl(target); + scriptUrl.searchParams.append("treat-as-public-once", token()); + scriptUrl.searchParams.append("mime-type", "application/javascript"); + scriptUrl.searchParams.append("file", "service-worker.js"); + scriptUrl.searchParams.append("random-js-prefix", true); + + const iframe = await appendIframe(t, document, bridgeUrl); + + const request = (message) => { + const reply = futureMessage(); + iframe.contentWindow.postMessage(message, "*"); + return reply; + }; + + { + const { error, loaded } = await request({ + action: "register", + url: scriptUrl.href, + }); + + assert_equals(error, undefined, "register error"); + assert_true(loaded, "response loaded"); + } + + try { + let { controlled, numControllerChanges } = await request({ + action: "wait", + numControllerChanges: 1, + }); + + assert_equals(numControllerChanges, 1, "controller change"); + assert_true(controlled, "bridge script is controlled"); + + const { error, updated } = await request({ action: "update" }); + + assert_equals(error, expected.error, "update error"); + assert_equals(updated, expected.updated, "registration updated"); + + // Stop here if we do not expect the update to succeed. + if (!expected.updated) { + return; + } + + ({ controlled, numControllerChanges } = await request({ + action: "wait", + numControllerChanges: 2, + })); + + assert_equals(numControllerChanges, 2, "controller change"); + assert_true(controlled, "bridge script still controlled"); + } finally { + const { error, unregistered } = await request({ + action: "unregister", + scope: new URL("./", scriptUrl).href, + }); + + assert_equals(error, undefined, "unregister error"); + assert_true(unregistered, "unregistered"); + } +} + +promise_test(t => makeTest(t, { + target: { server: Server.HTTPS_LOCAL }, + expected: TestResult.SUCCESS, +}), "update public to local: success."); + +promise_test(t => makeTest(t, { + target: { server: Server.HTTPS_PRIVATE }, + expected: TestResult.SUCCESS, +}), "update public to private: success."); + +promise_test(t => makeTest(t, { + target: { server: Server.HTTPS_PUBLIC }, + expected: TestResult.SUCCESS, +}), "update public to public: success."); diff --git a/test/wpt/tests/fetch/private-network-access/service-worker.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/service-worker.tentative.https.window.js new file mode 100644 index 0000000..046f662 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/service-worker.tentative.https.window.js @@ -0,0 +1,84 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that initial `ServiceWorker` script fetches are exempt from +// Private Network Access checks because they are always same-origin and the +// origin is potentially trustworthy. +// +// See also: worker.https.window.js + +// Results that may be expected in tests. +const TestResult = { + SUCCESS: { + register: { loaded: true }, + unregister: { unregistered: true }, + }, + FAILURE: { + register: { error: "TypeError" }, + unregister: { unregistered: false, error: "no registration" }, + }, +}; + +async function makeTest(t, { source, target, expected }) { + const sourceUrl = resolveUrl("resources/service-worker-bridge.html", + sourceResolveOptions(source)); + + const targetUrl = preflightUrl(target); + targetUrl.searchParams.append("body", "undefined"); + targetUrl.searchParams.append("mime-type", "application/javascript"); + + const scope = resolveUrl(`resources/${token()}`, {...target.server}).href; + + const iframe = await appendIframe(t, document, sourceUrl); + + { + const reply = futureMessage(); + const message = { + action: "register", + url: targetUrl.href, + options: { scope }, + }; + iframe.contentWindow.postMessage(message, "*"); + + const { error, loaded } = await reply; + + assert_equals(error, expected.register.error, "register error"); + assert_equals(loaded, expected.register.loaded, "response loaded"); + } + + { + const reply = futureMessage(); + iframe.contentWindow.postMessage({ action: "unregister", scope }, "*"); + + const { error, unregistered } = await reply; + assert_equals(error, expected.unregister.error, "unregister error"); + assert_equals( + unregistered, expected.unregister.unregistered, "worker unregistered"); + } +} + +promise_test(t => makeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: TestResult.SUCCESS, +}), "treat-as-public to local: success."); + +promise_test(t => makeTest(t, { + source: { + server: Server.HTTPS_PRIVATE, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_PRIVATE }, + expected: TestResult.SUCCESS, +}), "treat-as-public to private: success."); + +promise_test(t => makeTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.HTTPS_PUBLIC }, + expected: TestResult.SUCCESS, +}), "public to public: success."); diff --git a/test/wpt/tests/fetch/private-network-access/shared-worker-blob-fetch.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/shared-worker-blob-fetch.tentative.https.window.js new file mode 100644 index 0000000..269abb7 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/shared-worker-blob-fetch.tentative.https.window.js @@ -0,0 +1,168 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that fetches from within `SharedWorker` scripts that are +// loaded from blob URLs are subject to Private Network Access checks, just like +// fetches from within documents. +// +// This file covers only those tests that must execute in a secure context. +// Other tests are defined in: shared-worker-blob-fetch.window.js + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { server: Server.HTTPS_LOCAL }, + expected: WorkerFetchTestResult.SUCCESS, +}), "local to local: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "private to local: failed preflight."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "private to local: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { server: Server.HTTPS_PRIVATE }, + expected: WorkerFetchTestResult.SUCCESS, +}), "private to private: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to local: failed preflight."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to local: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to private: failed preflight."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to private: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.HTTPS_PUBLIC }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to public: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to local: failed preflight."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to local: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to local (same-origin): no preflight required."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to private: failed preflight."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to private: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to public: success."); + diff --git a/test/wpt/tests/fetch/private-network-access/shared-worker-blob-fetch.tentative.window.js b/test/wpt/tests/fetch/private-network-access/shared-worker-blob-fetch.tentative.window.js new file mode 100644 index 0000000..d430ea7 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/shared-worker-blob-fetch.tentative.window.js @@ -0,0 +1,173 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that fetches from within `SharedWorker` scripts that are +// loaded from blob URLs are subject to Private Network Access checks, just like +// fetches from within documents. +// +// This file covers only those tests that must execute in a non-secure context. +// Other tests are defined in: shared-worker-blob-fetch.https.window.js + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { server: Server.HTTP_LOCAL }, + expected: WorkerFetchTestResult.SUCCESS, +}), "local to local: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "private to local: failure."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { server: Server.HTTP_PRIVATE }, + expected: WorkerFetchTestResult.SUCCESS, +}), "private to private: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to local: failure."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to private: failure."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.HTTP_PUBLIC }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to public: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_LOCAL, + behavior: { preflight: PreflightBehavior.optionalSuccess(token()) }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to local: failure."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to private: failure."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to public: success."); + +// The following tests verify that workers served over HTTPS are not allowed to +// make private network requests because they are not secure contexts. + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTP_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "local https to local: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "private https to local: failure."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public https to local: failure."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "local https to local https: success."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "private https to local https: failure."); + +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public https to local https: failure."); diff --git a/test/wpt/tests/fetch/private-network-access/shared-worker-fetch.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/shared-worker-fetch.tentative.https.window.js new file mode 100644 index 0000000..e5f2b94 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/shared-worker-fetch.tentative.https.window.js @@ -0,0 +1,167 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that fetches from within `SharedWorker` scripts are subject +// to Private Network Access checks, just like fetches from within documents. +// +// This file covers only those tests that must execute in a secure context. +// Other tests are defined in: shared-worker-fetch.window.js + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { server: Server.HTTPS_LOCAL }, + expected: WorkerFetchTestResult.SUCCESS, +}), "local to local: success."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "private to local: failure."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "private to local: success."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { server: Server.HTTPS_PRIVATE }, + expected: WorkerFetchTestResult.SUCCESS, +}), "private to private: success."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to local: failed preflight."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to local: success."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to private: failed preflight."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to private: success."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.HTTPS_PUBLIC }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to public: success."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to local: failed preflight."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to local: success."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to local (same-origin): no preflight required."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to private: failed preflight."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to private: success."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to public: success."); + diff --git a/test/wpt/tests/fetch/private-network-access/shared-worker-fetch.tentative.window.js b/test/wpt/tests/fetch/private-network-access/shared-worker-fetch.tentative.window.js new file mode 100644 index 0000000..9bc1a89 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/shared-worker-fetch.tentative.window.js @@ -0,0 +1,154 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that fetches from within `SharedWorker` scripts are subject +// to Private Network Access checks, just like fetches from within documents. +// +// This file covers only those tests that must execute in a non-secure context. +// Other tests are defined in: shared-worker-fetch.https.window.js + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { server: Server.HTTP_LOCAL }, + expected: WorkerFetchTestResult.SUCCESS, +}), "local to local: success."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "private to local: failure."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { server: Server.HTTP_PRIVATE }, + expected: WorkerFetchTestResult.SUCCESS, +}), "private to private: success."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to local: failure."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to private: failure."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.HTTP_PUBLIC }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to public: success."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_LOCAL, + behavior: { preflight: PreflightBehavior.optionalSuccess(token()) }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to local: failure."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to private: failure."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to public: success."); + +// The following tests verify that workers served over HTTPS are not allowed to +// make private network requests because they are not secure contexts. + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "local https to local: success."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "private https to local: failure."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public https to local: failure."); + +promise_test(t => sharedWorkerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public https to private: failure."); diff --git a/test/wpt/tests/fetch/private-network-access/shared-worker.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/shared-worker.tentative.https.window.js new file mode 100644 index 0000000..24ae108 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/shared-worker.tentative.https.window.js @@ -0,0 +1,34 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests mirror `Worker` tests, except using `SharedWorker`. +// See also: worker.https.window.js +// +// This file covers only those tests that must execute in a secure context. +// Other tests are defined in: shared-worker.window.js + +promise_test(t => sharedWorkerScriptTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: WorkerScriptTestResult.SUCCESS, +}), "treat-as-public to local: success."); + +promise_test(t => sharedWorkerScriptTest(t, { + source: { + server: Server.HTTPS_PRIVATE, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_PRIVATE }, + expected: WorkerScriptTestResult.SUCCESS, +}), "treat-as-public to private: success."); + +promise_test(t => sharedWorkerScriptTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.HTTPS_PUBLIC }, + expected: WorkerScriptTestResult.SUCCESS, +}), "public to public: success."); diff --git a/test/wpt/tests/fetch/private-network-access/shared-worker.tentative.window.js b/test/wpt/tests/fetch/private-network-access/shared-worker.tentative.window.js new file mode 100644 index 0000000..ffa8a36 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/shared-worker.tentative.window.js @@ -0,0 +1,34 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests mirror `Worker` tests, except using `SharedWorker`. +// See also: shared-worker.window.js +// +// This file covers only those tests that must execute in a non secure context. +// Other tests are defined in: shared-worker.https.window.js + +promise_test(t => sharedWorkerScriptTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTP_LOCAL }, + expected: WorkerScriptTestResult.FAILURE, +}), "treat-as-public to local: failure."); + +promise_test(t => sharedWorkerScriptTest(t, { + source: { + server: Server.HTTP_PRIVATE, + treatAsPublic: true, + }, + target: { server: Server.HTTP_PRIVATE }, + expected: WorkerScriptTestResult.FAILURE, +}), "treat-as-public to private: failure."); + +promise_test(t => sharedWorkerScriptTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.HTTP_PUBLIC }, + expected: WorkerScriptTestResult.SUCCESS, +}), "public to public: success."); diff --git a/test/wpt/tests/fetch/private-network-access/websocket.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/websocket.tentative.https.window.js new file mode 100644 index 0000000..0731896 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/websocket.tentative.https.window.js @@ -0,0 +1,40 @@ +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests verify that websocket connections behave similarly to fetches. +// +// This file covers only those tests that must execute in a secure context. +// Other tests are defined in: websocket.https.window.js + +setup(() => { + // Making sure we are in a secure context, as expected. + assert_true(window.isSecureContext); +}); + +promise_test(t => websocketTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { server: Server.WSS_LOCAL }, + expected: WebsocketTestResult.SUCCESS, +}), "local to local: websocket success."); + +promise_test(t => websocketTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { server: Server.WSS_LOCAL }, + expected: WebsocketTestResult.SUCCESS, +}), "private to local: websocket success."); + +promise_test(t => websocketTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.WSS_LOCAL }, + expected: WebsocketTestResult.SUCCESS, +}), "public to local: websocket success."); + +promise_test(t => websocketTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.WSS_LOCAL }, + expected: WebsocketTestResult.SUCCESS, +}), "treat-as-public to local: websocket success."); diff --git a/test/wpt/tests/fetch/private-network-access/websocket.tentative.window.js b/test/wpt/tests/fetch/private-network-access/websocket.tentative.window.js new file mode 100644 index 0000000..a44cfae --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/websocket.tentative.window.js @@ -0,0 +1,40 @@ +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch + +// These tests verify that websocket connections behave similarly to fetches. +// +// This file covers only those tests that must execute in a non secure context. +// Other tests are defined in: websocket.https.window.js + +setup(() => { + // Making sure we are in a non secure context, as expected. + assert_false(window.isSecureContext); +}); + +promise_test(t => websocketTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { server: Server.WS_LOCAL }, + expected: WebsocketTestResult.SUCCESS, +}), "local to local: websocket success."); + +promise_test(t => websocketTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { server: Server.WS_LOCAL }, + expected: WebsocketTestResult.FAILURE, +}), "private to local: websocket failure."); + +promise_test(t => websocketTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.WS_LOCAL }, + expected: WebsocketTestResult.FAILURE, +}), "public to local: websocket failure."); + +promise_test(t => websocketTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.WS_LOCAL }, + expected: WebsocketTestResult.FAILURE, +}), "treat-as-public to local: websocket failure."); diff --git a/test/wpt/tests/fetch/private-network-access/worker-blob-fetch.tentative.window.js b/test/wpt/tests/fetch/private-network-access/worker-blob-fetch.tentative.window.js new file mode 100644 index 0000000..e119746 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/worker-blob-fetch.tentative.window.js @@ -0,0 +1,155 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that fetches from within `Worker` scripts loaded from blob +// URLs are subject to Private Network Access checks, just like fetches from +// within documents. +// +// This file covers only those tests that must execute in a non-secure context. +// Other tests are defined in: worker-blob-fetch.https.window.js + +promise_test(t => workerBlobFetchTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { server: Server.HTTP_LOCAL }, + expected: WorkerFetchTestResult.SUCCESS, +}), "local to local: success."); + +promise_test(t => workerBlobFetchTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "private to local: failure."); + +promise_test(t => workerBlobFetchTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { server: Server.HTTP_PRIVATE }, + expected: WorkerFetchTestResult.SUCCESS, +}), "private to private: success."); + +promise_test(t => workerBlobFetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to local: failure."); + +promise_test(t => workerBlobFetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to private: failure."); + +promise_test(t => workerBlobFetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.HTTP_PUBLIC }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to public: success."); + +promise_test(t => workerBlobFetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_LOCAL, + behavior: { preflight: PreflightBehavior.optionalSuccess(token()) }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to local: failure."); + +promise_test(t => workerBlobFetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to private: failure."); + +promise_test(t => workerBlobFetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to public: success."); + +// The following tests verify that workers served over HTTPS are not allowed to +// make private network requests because they are not secure contexts. + +promise_test(t => workerBlobFetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "local https to local https: success."); + +promise_test(t => workerBlobFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "private https to local https: failure."); + +promise_test(t => workerBlobFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public https to private https: failure."); + +promise_test(t => workerBlobFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public https to local https: failure."); diff --git a/test/wpt/tests/fetch/private-network-access/worker-fetch.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/worker-fetch.tentative.https.window.js new file mode 100644 index 0000000..89e0c3c --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/worker-fetch.tentative.https.window.js @@ -0,0 +1,151 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that fetches from within `Worker` scripts are subject to +// Private Network Access checks, just like fetches from within documents. +// +// This file covers only those tests that must execute in a secure context. +// Other tests are defined in: worker-fetch.window.js + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { server: Server.HTTPS_LOCAL }, + expected: WorkerFetchTestResult.SUCCESS, +}), "local to local: success."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "private to local: failed preflight."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "private to local: success."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { server: Server.HTTPS_PRIVATE }, + expected: WorkerFetchTestResult.SUCCESS, +}), "private to private: success."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to local: failed preflight."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to local: success."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to private: failed preflight."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to private: success."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.HTTPS_PUBLIC }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to public: success."); + +promise_test(t => workerFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to local: failed preflight."); + +promise_test(t => workerFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { preflight: PreflightBehavior.optionalSuccess(token()) }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to local: success."); + +promise_test(t => workerFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to private: failed preflight."); + +promise_test(t => workerFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to private: success."); + +promise_test(t => workerFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to public: success."); diff --git a/test/wpt/tests/fetch/private-network-access/worker-fetch.tentative.window.js b/test/wpt/tests/fetch/private-network-access/worker-fetch.tentative.window.js new file mode 100644 index 0000000..4d6b12f --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/worker-fetch.tentative.window.js @@ -0,0 +1,154 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that fetches from within `Worker` scripts are subject to +// Private Network Access checks, just like fetches from within documents. +// +// This file covers only those tests that must execute in a non-secure context. +// Other tests are defined in: worker-fetch.https.window.js + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { server: Server.HTTP_LOCAL }, + expected: WorkerFetchTestResult.SUCCESS, +}), "local to local: success."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "private to local: failure."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { server: Server.HTTP_PRIVATE }, + expected: WorkerFetchTestResult.SUCCESS, +}), "private to private: success."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to local: failure."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public to private: failure."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.HTTP_PUBLIC }, + expected: WorkerFetchTestResult.SUCCESS, +}), "public to public: success."); + +promise_test(t => workerFetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_LOCAL, + behavior: { preflight: PreflightBehavior.optionalSuccess(token()) }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to local: failure."); + +promise_test(t => workerFetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "treat-as-public to private: failure."); + +promise_test(t => workerFetchTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to public: success."); + +// The following tests verify that workers served over HTTPS are not allowed to +// make private network requests because they are not secure contexts. + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.SUCCESS, +}), "local https to local https: success."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "private https to local https: failure."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public https to private https: failure."); + +promise_test(t => workerFetchTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: WorkerFetchTestResult.FAILURE, +}), "public https to local https: failure."); diff --git a/test/wpt/tests/fetch/private-network-access/worker.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/worker.tentative.https.window.js new file mode 100644 index 0000000..a0f1931 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/worker.tentative.https.window.js @@ -0,0 +1,37 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that initial `Worker` script fetches in secure contexts are +// exempt from Private Network Access checks because workers can only be fetched +// same-origin and the origin is potentially trustworthy. The only way to test +// this is using the `treat-as-public` CSP directive to artificially place the +// parent document in the `public` IP address space. +// +// This file covers only those tests that must execute in a secure context. +// Other tests are defined in: worker.window.js + +promise_test(t => workerScriptTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: WorkerScriptTestResult.SUCCESS, +}), "treat-as-public to local: success."); + +promise_test(t => workerScriptTest(t, { + source: { + server: Server.HTTPS_PRIVATE, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_PRIVATE }, + expected: WorkerScriptTestResult.SUCCESS, +}), "treat-as-public to private: success."); + +promise_test(t => workerScriptTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.HTTPS_PUBLIC }, + expected: WorkerScriptTestResult.SUCCESS, +}), "public to public: success."); diff --git a/test/wpt/tests/fetch/private-network-access/worker.tentative.window.js b/test/wpt/tests/fetch/private-network-access/worker.tentative.window.js new file mode 100644 index 0000000..118c099 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/worker.tentative.window.js @@ -0,0 +1,37 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests check that initial `Worker` script fetches are subject to Private +// Network Access checks, just like a regular `fetch()`. The main difference is +// that workers can only be fetched same-origin, so the only way to test this +// is using the `treat-as-public` CSP directive to artificially place the parent +// document in the `public` IP address space. +// +// This file covers only those tests that must execute in a non secure context. +// Other tests are defined in: worker.https.window.js + +promise_test(t => workerScriptTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTP_LOCAL }, + expected: WorkerScriptTestResult.FAILURE, +}), "treat-as-public to local: failure."); + +promise_test(t => workerScriptTest(t, { + source: { + server: Server.HTTP_PRIVATE, + treatAsPublic: true, + }, + target: { server: Server.HTTP_PRIVATE }, + expected: WorkerScriptTestResult.FAILURE, +}), "treat-as-public to private: failure."); + +promise_test(t => workerScriptTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.HTTP_PUBLIC }, + expected: WorkerScriptTestResult.SUCCESS, +}), "public to public: success."); diff --git a/test/wpt/tests/fetch/private-network-access/xhr-from-treat-as-public.tentative.https.window.js b/test/wpt/tests/fetch/private-network-access/xhr-from-treat-as-public.tentative.https.window.js new file mode 100644 index 0000000..3aae305 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/xhr-from-treat-as-public.tentative.https.window.js @@ -0,0 +1,83 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests verify that documents fetched from the `local` address space yet +// carrying the `treat-as-public-address` CSP directive are treated as if they +// had been fetched from the `public` address space. + +promise_test(t => xhrTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.FAILURE, +}), "treat-as-public to local: failed preflight."); + +promise_test(t => xhrTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.SUCCESS, +}), "treat-as-public to local: success."); + +promise_test(t => xhrTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: XhrTestResult.SUCCESS, +}), "treat-as-public to local (same-origin): no preflight required."); + +promise_test(t => xhrTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.FAILURE, +}), "treat-as-public to private: failed preflight."); + +promise_test(t => xhrTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.SUCCESS, +}), "treat-as-public to private: success."); + +promise_test(t => xhrTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.SUCCESS, +}), "treat-as-public to public: no preflight required."); diff --git a/test/wpt/tests/fetch/private-network-access/xhr.https.tentative.window.js b/test/wpt/tests/fetch/private-network-access/xhr.https.tentative.window.js new file mode 100644 index 0000000..4dc5da9 --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/xhr.https.tentative.window.js @@ -0,0 +1,142 @@ +// META: script=/common/subset-tests-by-key.js +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// META: variant=?include=from-local +// META: variant=?include=from-private +// META: variant=?include=from-public +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests mirror fetch.https.window.js, but use `XmlHttpRequest` instead of +// `fetch()` to perform subresource fetches. Preflights are tested less +// extensively due to coverage being already provided by `fetch()`. +// +// This file covers only those tests that must execute in a secure context. +// Other tests are defined in: xhr.window.js + +setup(() => { + // Making sure we are in a secure context, as expected. + assert_true(window.isSecureContext); +}); + +// Source: secure local context. +// +// All fetches unaffected by Private Network Access. + +subsetTestByKey("from-local", promise_test, t => xhrTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { server: Server.HTTPS_LOCAL }, + expected: XhrTestResult.SUCCESS, +}), "local to local: no preflight required."); + +subsetTestByKey("from-local", promise_test, t => xhrTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.SUCCESS, +}), "local to private: no preflight required."); + +subsetTestByKey("from-local", promise_test, t => xhrTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.SUCCESS, +}), "local to public: no preflight required."); + +// Source: private secure context. +// +// Fetches to the local address space require a successful preflight response +// carrying a PNA-specific header. + +subsetTestByKey("from-private", promise_test, t => xhrTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.FAILURE, +}), "private to local: failed preflight."); + +subsetTestByKey("from-private", promise_test, t => xhrTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.SUCCESS, +}), "private to local: success."); + +subsetTestByKey("from-private", promise_test, t => xhrTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { server: Server.HTTPS_PRIVATE }, + expected: XhrTestResult.SUCCESS, +}), "private to private: no preflight required."); + +subsetTestByKey("from-private", promise_test, t => xhrTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.SUCCESS, +}), "private to public: no preflight required."); + +// Source: public secure context. +// +// Fetches to the local and private address spaces require a successful +// preflight response carrying a PNA-specific header. + +subsetTestByKey("from-public", promise_test, t => xhrTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.FAILURE, +}), "public to local: failed preflight."); + +subsetTestByKey("from-public", promise_test, t => xhrTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.SUCCESS, +}), "public to local: success."); + +subsetTestByKey("from-public", promise_test, t => xhrTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.FAILURE, +}), "public to private: failed preflight."); + +subsetTestByKey("from-public", promise_test, t => xhrTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.SUCCESS, +}), "public to private: success."); + +subsetTestByKey("from-public", promise_test, t => xhrTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { server: Server.HTTPS_PUBLIC }, + expected: XhrTestResult.SUCCESS, +}), "public to public: no preflight required."); diff --git a/test/wpt/tests/fetch/private-network-access/xhr.tentative.window.js b/test/wpt/tests/fetch/private-network-access/xhr.tentative.window.js new file mode 100644 index 0000000..fa307dc --- /dev/null +++ b/test/wpt/tests/fetch/private-network-access/xhr.tentative.window.js @@ -0,0 +1,195 @@ +// META: script=/common/utils.js +// META: script=resources/support.sub.js +// +// Spec: https://wicg.github.io/private-network-access/#integration-fetch +// +// These tests mirror fetch.window.js, but use `XmlHttpRequest` instead of +// `fetch()` to perform subresource fetches. +// +// This file covers only those tests that must execute in a non secure context. +// Other tests are defined in: xhr.https.window.js + +setup(() => { + // Making sure we are in a non secure context, as expected. + assert_false(window.isSecureContext); +}); + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { server: Server.HTTP_LOCAL }, + expected: XhrTestResult.SUCCESS, +}), "local to local: no preflight required."); + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.SUCCESS, +}), "local to private: no preflight required."); + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTP_LOCAL }, + target: { + server: Server.HTTP_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.SUCCESS, +}), "local to public: no preflight required."); + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.FAILURE, +}), "private to local: failure."); + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { server: Server.HTTP_PRIVATE }, + expected: XhrTestResult.SUCCESS, +}), "private to private: no preflight required."); + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTP_PRIVATE }, + target: { + server: Server.HTTP_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.SUCCESS, +}), "private to public: no preflight required."); + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.FAILURE, +}), "public to local: failure."); + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.FAILURE, +}), "public to private: failure."); + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTP_PUBLIC }, + target: { server: Server.HTTP_PUBLIC }, + expected: XhrTestResult.SUCCESS, +}), "public to public: no preflight required."); + +// These tests verify that documents fetched from the `local` address space yet +// carrying the `treat-as-public-address` CSP directive are treated as if they +// had been fetched from the `public` address space. + +promise_test(t => xhrTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.FAILURE, +}), "treat-as-public-address to local: failure."); + +promise_test(t => xhrTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.FAILURE, +}), "treat-as-public-address to private: failure."); + +promise_test(t => xhrTest(t, { + source: { + server: Server.HTTP_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTP_PUBLIC, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, + expected: XhrTestResult.SUCCESS, +}), "treat-as-public-address to public: no preflight required."); + +// These tests verify that HTTPS iframes embedded in an HTTP top-level document +// cannot fetch subresources from less-public address spaces. Indeed, even +// though the iframes have HTTPS origins, they are non-secure contexts because +// their parent is a non-secure context. + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.SUCCESS, +}), "local https to local: success."); + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTPS_PRIVATE }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.FAILURE, +}), "private https to local: failure."); + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.FAILURE, +}), "public https to local: failure."); + +promise_test(t => xhrTest(t, { + source: { server: Server.HTTPS_PUBLIC }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.optionalSuccess(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }, + expected: XhrTestResult.FAILURE, +}), "public https to private: failure."); diff --git a/test/wpt/tests/fetch/range/blob.any.js b/test/wpt/tests/fetch/range/blob.any.js new file mode 100644 index 0000000..7bcd4b9 --- /dev/null +++ b/test/wpt/tests/fetch/range/blob.any.js @@ -0,0 +1,233 @@ +// META: script=/common/utils.js + +const supportedBlobRange = [ + { + name: "A simple blob range request.", + data: ["A simple Hello, World! example"], + type: "text/plain", + range: "bytes=9-21", + content_length: 13, + content_range: "bytes 9-21/30", + result: "Hello, World!", + }, + { + name: "A blob range request with no type.", + data: ["A simple Hello, World! example"], + type: undefined, + range: "bytes=9-21", + content_length: 13, + content_range: "bytes 9-21/30", + result: "Hello, World!", + }, + { + name: "A blob range request with no end.", + data: ["Range with no end"], + type: "text/plain", + range: "bytes=11-", + content_length: 6, + content_range: "bytes 11-16/17", + result: "no end", + }, + { + name: "A blob range request with no start.", + data: ["Range with no start"], + type: "text/plain", + range: "bytes=-8", + content_length: 8, + content_range: "bytes 11-18/19", + result: "no start", + }, + { + name: "A simple blob range request with whitespace.", + data: ["A simple Hello, World! example"], + type: "text/plain", + range: "bytes= \t9-21", + content_length: 13, + content_range: "bytes 9-21/30", + result: "Hello, World!", + }, + { + name: "Blob content with short content and a large range end", + data: ["Not much here"], + type: "text/plain", + range: "bytes=4-100000000000", + content_length: 9, + content_range: "bytes 4-12/13", + result: "much here", + }, + { + name: "Blob content with short content and a range end matching content length", + data: ["Not much here"], + type: "text/plain", + range: "bytes=4-13", + content_length: 9, + content_range: "bytes 4-12/13", + result: "much here", + }, + { + name: "Blob range with whitespace before and after hyphen", + data: ["Valid whitespace #1"], + type: "text/plain", + range: "bytes=5 - 10", + content_length: 6, + content_range: "bytes 5-10/19", + result: " white", + }, + { + name: "Blob range with whitespace after hyphen", + data: ["Valid whitespace #2"], + type: "text/plain", + range: "bytes=-\t 5", + content_length: 5, + content_range: "bytes 14-18/19", + result: "ce #2", + }, + { + name: "Blob range with whitespace around equals sign", + data: ["Valid whitespace #3"], + type: "text/plain", + range: "bytes \t =\t 6-", + content_length: 13, + content_range: "bytes 6-18/19", + result: "whitespace #3", + }, +]; + +const unsupportedBlobRange = [ + { + name: "Blob range with no value", + data: ["Blob range should have a value"], + type: "text/plain", + range: "", + }, + { + name: "Blob range with incorrect range header", + data: ["A"], + type: "text/plain", + range: "byte=0-" + }, + { + name: "Blob range with incorrect range header #2", + data: ["A"], + type: "text/plain", + range: "bytes" + }, + { + name: "Blob range with incorrect range header #3", + data: ["A"], + type: "text/plain", + range: "bytes\t \t" + }, + { + name: "Blob range request with multiple range values", + data: ["Multiple ranges are not currently supported"], + type: "text/plain", + range: "bytes=0-5,15-", + }, + { + name: "Blob range request with multiple range values and whitespace", + data: ["Multiple ranges are not currently supported"], + type: "text/plain", + range: "bytes=0-5, 15-", + }, + { + name: "Blob range request with trailing comma", + data: ["Range with invalid trailing comma"], + type: "text/plain", + range: "bytes=0-5,", + }, + { + name: "Blob range with no start or end", + data: ["Range with no start or end"], + type: "text/plain", + range: "bytes=-", + }, + { + name: "Blob range request with short range end", + data: ["Range end should be greater than range start"], + type: "text/plain", + range: "bytes=10-5", + }, + { + name: "Blob range start should be an ASCII digit", + data: ["Range start must be an ASCII digit"], + type: "text/plain", + range: "bytes=x-5", + }, + { + name: "Blob range should have a dash", + data: ["Blob range should have a dash"], + type: "text/plain", + range: "bytes=5", + }, + { + name: "Blob range end should be an ASCII digit", + data: ["Range end must be an ASCII digit"], + type: "text/plain", + range: "bytes=5-x", + }, + { + name: "Blob range should include '-'", + data: ["Range end must include '-'"], + type: "text/plain", + range: "bytes=x", + }, + { + name: "Blob range should include '='", + data: ["Range end must include '='"], + type: "text/plain", + range: "bytes 5-", + }, + { + name: "Blob range should include 'bytes='", + data: ["Range end must include 'bytes='"], + type: "text/plain", + range: "5-", + }, + { + name: "Blob content with short content and a large range start", + data: ["Not much here"], + type: "text/plain", + range: "bytes=100000-", + }, + { + name: "Blob content with short content and a range start matching the content length", + data: ["Not much here"], + type: "text/plain", + range: "bytes=13-", + }, +]; + +supportedBlobRange.forEach(({ name, data, type, range, content_length, content_range, result }) => { + promise_test(async t => { + const blob = new Blob(data, { "type" : type }); + const blobURL = URL.createObjectURL(blob); + t.add_cleanup(() => URL.revokeObjectURL(blobURL)); + const resp = await fetch(blobURL, { + "headers": { + "Range": range + } + }); + assert_equals(resp.status, 206, "HTTP status is 206"); + assert_equals(resp.type, "basic", "response type is basic"); + assert_equals(resp.headers.get("Content-Type"), type || "", "Content-Type is " + resp.headers.get("Content-Type")); + assert_equals(resp.headers.get("Content-Length"), content_length.toString(), "Content-Length is " + resp.headers.get("Content-Length")); + assert_equals(resp.headers.get("Content-Range"), content_range, "Content-Range is " + resp.headers.get("Content-Range")); + const text = await resp.text(); + assert_equals(text, result, "Response's body is correct"); + }, name); +}); + +unsupportedBlobRange.forEach(({ name, data, type, range }) => { + promise_test(t => { + const blob = new Blob(data, { "type" : type }); + const blobURL = URL.createObjectURL(blob); + t.add_cleanup(() => URL.revokeObjectURL(blobURL)); + const promise = fetch(blobURL, { + "headers": { + "Range": range + } + }); + return promise_rejects_js(t, TypeError, promise); + }, name); +}); diff --git a/test/wpt/tests/fetch/range/data.any.js b/test/wpt/tests/fetch/range/data.any.js new file mode 100644 index 0000000..22ef11e --- /dev/null +++ b/test/wpt/tests/fetch/range/data.any.js @@ -0,0 +1,29 @@ +// META: script=/common/utils.js + +promise_test(async () => { + return fetch("data:text/plain;charset=US-ASCII,paddingHello%2C%20World%21padding", { + "method": "GET", + "Range": "bytes=13-26" + }).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type, "basic", "response type is basic"); + assert_equals(resp.headers.get("Content-Type"), "text/plain;charset=US-ASCII", "Content-Type is " + resp.headers.get("Content-Type")); + return resp.text(); + }).then(function(text) { + assert_equals(text, 'paddingHello, World!padding', "Response's body ignores range"); + }); +}, "data: URL and Range header"); + +promise_test(async () => { + return fetch("data:text/plain;charset=US-ASCII,paddingHello%2C%20paddingWorld%21padding", { + "method": "GET", + "Range": "bytes=7-14,21-27" + }).then(function(resp) { + assert_equals(resp.status, 200, "HTTP status is 200"); + assert_equals(resp.type, "basic", "response type is basic"); + assert_equals(resp.headers.get("Content-Type"), "text/plain;charset=US-ASCII", "Content-Type is " + resp.headers.get("Content-Type")); + return resp.text(); + }).then(function(text) { + assert_equals(text, 'paddingHello, paddingWorld!padding', "Response's body ignores range"); + }); +}, "data: URL and Range header with multiple ranges"); diff --git a/test/wpt/tests/fetch/range/general.any.js b/test/wpt/tests/fetch/range/general.any.js new file mode 100644 index 0000000..64b225a --- /dev/null +++ b/test/wpt/tests/fetch/range/general.any.js @@ -0,0 +1,140 @@ +// META: timeout=long +// META: global=window,worker +// META: script=/common/get-host-info.sub.js +// META: script=/common/utils.js + +// Helpers that return headers objects with a particular guard +function headersGuardNone(fill) { + if (fill) return new Headers(fill); + return new Headers(); +} + +function headersGuardResponse(fill) { + const opts = {}; + if (fill) opts.headers = fill; + return new Response('', opts).headers; +} + +function headersGuardRequest(fill) { + const opts = {}; + if (fill) opts.headers = fill; + return new Request('./', opts).headers; +} + +function headersGuardRequestNoCors(fill) { + const opts = { mode: 'no-cors' }; + if (fill) opts.headers = fill; + return new Request('./', opts).headers; +} + +const headerGuardTypes = [ + ['none', headersGuardNone], + ['response', headersGuardResponse], + ['request', headersGuardRequest] +]; + +for (const [guardType, createHeaders] of headerGuardTypes) { + test(() => { + // There are three ways to set headers. + // Filling, appending, and setting. Test each: + let headers = createHeaders({ Range: 'foo' }); + assert_equals(headers.get('Range'), 'foo'); + + headers = createHeaders(); + headers.append('Range', 'foo'); + assert_equals(headers.get('Range'), 'foo'); + + headers = createHeaders(); + headers.set('Range', 'foo'); + assert_equals(headers.get('Range'), 'foo'); + }, `Range header setting allowed for guard type: ${guardType}`); +} + +test(() => { + let headers = headersGuardRequestNoCors({ Range: 'foo' }); + assert_false(headers.has('Range')); + + headers = headersGuardRequestNoCors(); + headers.append('Range', 'foo'); + assert_false(headers.has('Range')); + + headers = headersGuardRequestNoCors(); + headers.set('Range', 'foo'); + assert_false(headers.has('Range')); +}, `Privileged header not allowed for guard type: request-no-cors`); + +promise_test(async () => { + const wavURL = new URL('resources/long-wav.py', location); + const stashTakeURL = new URL('resources/stash-take.py', location); + + function changeToken() { + const stashToken = token(); + wavURL.searchParams.set('accept-encoding-key', stashToken); + stashTakeURL.searchParams.set('key', stashToken); + } + + const rangeHeaders = [ + 'bytes=0-10', + 'foo=0-10', + 'foo', + '' + ]; + + for (const rangeHeader of rangeHeaders) { + changeToken(); + + await fetch(wavURL, { + headers: { Range: rangeHeader } + }); + + const response = await fetch(stashTakeURL); + + assert_regexp_match(await response.json(), + /.*\bidentity\b.*/, + `Expect identity accept-encoding if range header is ${JSON.stringify(rangeHeader)}`); + } +}, `Fetch with range header will be sent with Accept-Encoding: identity`); + +promise_test(async () => { + const wavURL = new URL(get_host_info().HTTP_REMOTE_ORIGIN + '/fetch/range/resources/long-wav.py'); + const stashTakeURL = new URL('resources/stash-take.py', location); + + function changeToken() { + const stashToken = token(); + wavURL.searchParams.set('accept-encoding-key', stashToken); + stashTakeURL.searchParams.set('key', stashToken); + } + + const rangeHeaders = [ + 'bytes=10-9', + 'bytes=-0', + 'bytes=0000000000000000000000000000000000000000000000000000000000011-0000000000000000000000000000000000000000000000000000000000111', + ]; + + for (const rangeHeader of rangeHeaders) { + changeToken(); + await fetch(wavURL, { headers: { Range : rangeHeader} }).then(() => { throw "loaded with range header " + rangeHeader }, () => { }); + } +}, `Cross Origin Fetch with non safe range header`); + +promise_test(async () => { + const wavURL = new URL(get_host_info().HTTP_REMOTE_ORIGIN + '/fetch/range/resources/long-wav.py'); + const stashTakeURL = new URL('resources/stash-take.py', location); + + function changeToken() { + const stashToken = token(); + wavURL.searchParams.set('accept-encoding-key', stashToken); + stashTakeURL.searchParams.set('key', stashToken); + } + + const rangeHeaders = [ + 'bytes=0-10', + 'bytes=0-', + 'bytes=00000000000000000000000000000000000000000000000000000000011-00000000000000000000000000000000000000000000000000000000000111', + ]; + + for (const rangeHeader of rangeHeaders) { + changeToken(); + await fetch(wavURL, { headers: { Range: rangeHeader } }).then(() => { }, () => { throw "failed load with range header " + rangeHeader }); + } +}, `Cross Origin Fetch with safe range header`); diff --git a/test/wpt/tests/fetch/range/general.window.js b/test/wpt/tests/fetch/range/general.window.js new file mode 100644 index 0000000..afe80d6 --- /dev/null +++ b/test/wpt/tests/fetch/range/general.window.js @@ -0,0 +1,29 @@ +// META: script=resources/utils.js +// META: script=/common/utils.js + +const onload = new Promise(r => window.addEventListener('load', r)); + +// It's weird that browsers do this, but it should continue to work. +promise_test(async t => { + await loadScript('resources/partial-script.py?pretend-offset=90000'); + assert_true(self.scriptExecuted); +}, `Script executed from partial response`); + +promise_test(async () => { + const wavURL = new URL('resources/long-wav.py', location); + const stashTakeURL = new URL('resources/stash-take.py', location); + const stashToken = token(); + wavURL.searchParams.set('accept-encoding-key', stashToken); + stashTakeURL.searchParams.set('key', stashToken); + + // The testing framework waits for window onload. If the audio element + // is appended before onload, it extends it, and the test times out. + await onload; + + const audio = appendAudio(document, wavURL); + await new Promise(r => audio.addEventListener('progress', r)); + audio.remove(); + + const response = await fetch(stashTakeURL); + assert_equals(await response.json(), 'identity', `Expect identity accept-encoding on media request`); +}, `Fetch with range header will be sent with Accept-Encoding: identity`); diff --git a/test/wpt/tests/fetch/range/non-matching-range-response.html b/test/wpt/tests/fetch/range/non-matching-range-response.html new file mode 100644 index 0000000..ba76c36 --- /dev/null +++ b/test/wpt/tests/fetch/range/non-matching-range-response.html @@ -0,0 +1,34 @@ + + + + + + + diff --git a/test/wpt/tests/fetch/range/resources/basic.html b/test/wpt/tests/fetch/range/resources/basic.html new file mode 100644 index 0000000..0e76edd --- /dev/null +++ b/test/wpt/tests/fetch/range/resources/basic.html @@ -0,0 +1 @@ + diff --git a/test/wpt/tests/fetch/range/resources/long-wav.py b/test/wpt/tests/fetch/range/resources/long-wav.py new file mode 100644 index 0000000..acfc81a --- /dev/null +++ b/test/wpt/tests/fetch/range/resources/long-wav.py @@ -0,0 +1,134 @@ +""" +This generates a 30 minute silent wav, and is capable of +responding to Range requests. +""" +import time +import re +import struct + +from wptserve.utils import isomorphic_decode + +def create_wav_header(sample_rate, bit_depth, channels, duration): + bytes_per_sample = int(bit_depth / 8) + block_align = bytes_per_sample * channels + byte_rate = sample_rate * block_align + sub_chunk_2_size = duration * byte_rate + + data = b'' + # ChunkID + data += b'RIFF' + # ChunkSize + data += struct.pack(' 0: + to_send = b'\x00' * min(bytes_remaining_to_send, sample_rate) + bytes_remaining_to_send -= len(to_send) + + if not response.writer.write(to_send): + break + + # Throttle the stream + time.sleep(0.5) diff --git a/test/wpt/tests/fetch/range/resources/partial-script.py b/test/wpt/tests/fetch/range/resources/partial-script.py new file mode 100644 index 0000000..a9570ec --- /dev/null +++ b/test/wpt/tests/fetch/range/resources/partial-script.py @@ -0,0 +1,29 @@ +""" +This generates a partial response containing valid JavaScript. +""" + +def main(request, response): + require_range = request.GET.first(b'require-range', b'') + pretend_offset = int(request.GET.first(b'pretend-offset', b'0')) + range_header = request.headers.get(b'Range', b'') + + if require_range and not range_header: + response.set_error(412, u"Range header required") + response.write() + return + + response.headers.set(b"Content-Type", b"text/plain") + response.headers.set(b"Accept-Ranges", b"bytes") + response.headers.set(b"Cache-Control", b"no-cache") + response.status = 206 + + to_send = b'self.scriptExecuted = true;' + length = len(to_send) + + content_range = b"bytes %d-%d/%d" % ( + pretend_offset, pretend_offset + length - 1, pretend_offset + length) + + response.headers.set(b"Content-Range", content_range) + response.headers.set(b"Content-Length", length) + + response.content = to_send diff --git a/test/wpt/tests/fetch/range/resources/partial-text.py b/test/wpt/tests/fetch/range/resources/partial-text.py new file mode 100644 index 0000000..fa3d117 --- /dev/null +++ b/test/wpt/tests/fetch/range/resources/partial-text.py @@ -0,0 +1,53 @@ +""" +This generates a partial response for a 100-byte text file. +""" +import re + +from wptserve.utils import isomorphic_decode + +def main(request, response): + total_length = int(request.GET.first(b'length', b'100')) + partial_code = int(request.GET.first(b'partial', b'206')) + content_type = request.GET.first(b'type', b'text/plain') + range_header = request.headers.get(b'Range', b'') + + # Send a 200 if there is no range request + if not range_header: + to_send = ''.zfill(total_length) + response.headers.set(b"Content-Type", content_type) + response.headers.set(b"Cache-Control", b"no-cache") + response.headers.set(b"Content-Length", total_length) + response.content = to_send + return + + # Simple range parsing, requires specifically "bytes=xxx-xxxx" + range_header_match = re.search(r'^bytes=(\d*)-(\d*)$', isomorphic_decode(range_header)) + start, end = range_header_match.groups() + start = int(start) + end = int(end) if end else total_length + length = end - start + + # Error the request if the range goes beyond the length + if length <= 0 or end > total_length: + response.set_error(416, u"Range Not Satisfiable") + # set_error sets the MIME type to application/json, which - for a + # no-cors media request - will be blocked by ORB. We'll just force + # the expected MIME type here, whichfixes the test, but doesn't make + # sense in general. + response.headers = [(b"Content-Type", content_type)] + response.write() + return + + # Generate a partial response of the requested length + to_send = ''.zfill(length) + response.headers.set(b"Content-Type", content_type) + response.headers.set(b"Accept-Ranges", b"bytes") + response.headers.set(b"Cache-Control", b"no-cache") + response.status = partial_code + + content_range = b"bytes %d-%d/%d" % (start, end, total_length) + + response.headers.set(b"Content-Range", content_range) + response.headers.set(b"Content-Length", length) + + response.content = to_send diff --git a/test/wpt/tests/fetch/range/resources/range-sw.js b/test/wpt/tests/fetch/range/resources/range-sw.js new file mode 100644 index 0000000..b47823f --- /dev/null +++ b/test/wpt/tests/fetch/range/resources/range-sw.js @@ -0,0 +1,218 @@ +importScripts('/resources/testharness.js'); + +setup({ explicit_done: true }); + +function assert_range_request(request, expectedRangeHeader, name) { + assert_equals(request.headers.get('Range'), expectedRangeHeader, name); +} + +async function broadcast(msg) { + for (const client of await clients.matchAll()) { + client.postMessage(msg); + } +} + +addEventListener('fetch', async event => { + /** @type Request */ + const request = event.request; + const url = new URL(request.url); + const action = url.searchParams.get('action'); + + switch (action) { + case 'range-header-filter-test': + rangeHeaderFilterTest(request); + return; + case 'range-header-passthrough-test': + rangeHeaderPassthroughTest(event); + return; + case 'store-ranged-response': + storeRangedResponse(event); + return; + case 'use-stored-ranged-response': + useStoredRangeResponse(event); + return; + case 'broadcast-accept-encoding': + broadcastAcceptEncoding(event); + return; + case 'record-media-range-request': + return recordMediaRangeRequest(event); + case 'use-media-range-request': + useMediaRangeRequest(event); + return; + } +}); + +/** + * @param {Request} request + */ +function rangeHeaderFilterTest(request) { + const rangeValue = request.headers.get('Range'); + + test(() => { + assert_range_request(new Request(request), rangeValue, `Untampered`); + assert_range_request(new Request(request, {}), rangeValue, `Untampered (no init props set)`); + assert_range_request(new Request(request, { __foo: 'bar' }), rangeValue, `Untampered (only invalid props set)`); + assert_range_request(new Request(request, { mode: 'cors' }), rangeValue, `More permissive mode`); + assert_range_request(request.clone(), rangeValue, `Clone`); + }, "Range headers correctly preserved"); + + test(() => { + assert_range_request(new Request(request, { headers: { Range: 'foo' } }), null, `Tampered - range header set`); + assert_range_request(new Request(request, { headers: {} }), null, `Tampered - empty headers set`); + assert_range_request(new Request(request, { mode: 'no-cors' }), null, `Tampered – mode set`); + assert_range_request(new Request(request, { cache: 'no-cache' }), null, `Tampered – cache mode set`); + }, "Range headers correctly removed"); + + test(() => { + let headers; + + headers = new Request(request).headers; + headers.delete('does-not-exist'); + assert_equals(headers.get('Range'), rangeValue, `Preserved if no header actually removed`); + + headers = new Request(request).headers; + headers.append('foo', 'bar'); + assert_equals(headers.get('Range'), rangeValue, `Preserved if silent-failure on append (due to request-no-cors guard)`); + + headers = new Request(request).headers; + headers.set('foo', 'bar'); + assert_equals(headers.get('Range'), rangeValue, `Preserved if silent-failure on set (due to request-no-cors guard)`); + + headers = new Request(request).headers; + headers.append('Range', 'foo'); + assert_equals(headers.get('Range'), rangeValue, `Preserved if silent-failure on append (due to request-no-cors guard)`); + + headers = new Request(request).headers; + headers.set('Range', 'foo'); + assert_equals(headers.get('Range'), rangeValue, `Preserved if silent-failure on set (due to request-no-cors guard)`); + + headers = new Request(request).headers; + headers.append('Accept', 'whatever'); + assert_equals(headers.get('Range'), null, `Stripped if header successfully appended`); + + headers = new Request(request).headers; + headers.set('Accept', 'whatever'); + assert_equals(headers.get('Range'), null, `Stripped if header successfully set`); + + headers = new Request(request).headers; + headers.delete('Accept'); + assert_equals(headers.get('Range'), null, `Stripped if header successfully deleted`); + + headers = new Request(request).headers; + headers.delete('Range'); + assert_equals(headers.get('Range'), null, `Stripped if range header successfully deleted`); + }, "Headers correctly filtered"); + + done(); +} + +function rangeHeaderPassthroughTest(event) { + /** @type Request */ + const request = event.request; + const url = new URL(request.url); + const key = url.searchParams.get('range-received-key'); + + event.waitUntil(new Promise(resolve => { + promise_test(async () => { + await fetch(event.request); + const response = await fetch('stash-take.py?key=' + key); + assert_equals(await response.json(), 'range-header-received'); + resolve(); + }, `Include range header in network request`); + + done(); + })); + + // Just send back any response, it isn't important for the test. + event.respondWith(new Response('')); +} + +let storedRangeResponseP; + +function storeRangedResponse(event) { + /** @type Request */ + const request = event.request; + const id = new URL(request.url).searchParams.get('id'); + + storedRangeResponseP = fetch(event.request); + broadcast({ id }); + + // Just send back any response, it isn't important for the test. + event.respondWith(new Response('')); +} + +function useStoredRangeResponse(event) { + event.respondWith(async function() { + const response = await storedRangeResponseP; + if (!response) throw Error("Expected stored range response"); + return response.clone(); + }()); +} + +function broadcastAcceptEncoding(event) { + /** @type Request */ + const request = event.request; + const id = new URL(request.url).searchParams.get('id'); + + broadcast({ + id, + acceptEncoding: request.headers.get('Accept-Encoding') + }); + + // Just send back any response, it isn't important for the test. + event.respondWith(new Response('')); +} + +let rangeResponse = {}; + +async function recordMediaRangeRequest(event) { + /** @type Request */ + const request = event.request; + const url = new URL(request.url); + const urlParams = new URLSearchParams(url.search); + const size = urlParams.get("size"); + const id = urlParams.get('id'); + const key = 'size' + size; + + if (key in rangeResponse) { + // Don't re-fetch ranges we already have. + const clonedResponse = rangeResponse[key].clone(); + event.respondWith(clonedResponse); + } else if (event.request.headers.get("range") === "bytes=0-") { + // Generate a bogus 206 response to trigger subsequent range requests + // of the desired size. + const length = urlParams.get("length") + 100; + const body = "A".repeat(Number(size)); + event.respondWith(new Response(body, {status: 206, headers: { + "Content-Type": "audio/mp4", + "Content-Range": `bytes 0-1/${length}` + }})); + } else if (event.request.headers.get("range") === `bytes=${Number(size)}-`) { + // Pass through actual range requests which will attempt to fetch up to the + // length in the original response which is bigger than the actual resource + // to make sure 206 and 416 responses are treated the same. + rangeResponse[key] = await fetch(event.request); + + // Let the client know we have the range response for the given ID + broadcast({id}); + } else { + event.respondWith(Promise.reject(Error("Invalid Request"))); + } +} + +function useMediaRangeRequest(event) { + /** @type Request */ + const request = event.request; + const url = new URL(request.url); + const urlParams = new URLSearchParams(url.search); + const size = urlParams.get("size"); + const key = 'size' + size; + + // Send a clone of the range response to preload. + if (key in rangeResponse) { + const clonedResponse = rangeResponse[key].clone(); + event.respondWith(clonedResponse); + } else { + event.respondWith(Promise.reject(Error("Invalid Request"))); + } +} diff --git a/test/wpt/tests/fetch/range/resources/stash-take.py b/test/wpt/tests/fetch/range/resources/stash-take.py new file mode 100644 index 0000000..6cf6ff5 --- /dev/null +++ b/test/wpt/tests/fetch/range/resources/stash-take.py @@ -0,0 +1,7 @@ +from wptserve.handlers import json_handler + + +@json_handler +def main(request, response): + key = request.GET.first(b"key") + return request.server.stash.take(key, b'/fetch/range/') diff --git a/test/wpt/tests/fetch/range/resources/utils.js b/test/wpt/tests/fetch/range/resources/utils.js new file mode 100644 index 0000000..ad2853b --- /dev/null +++ b/test/wpt/tests/fetch/range/resources/utils.js @@ -0,0 +1,36 @@ +function loadScript(url, { doc = document }={}) { + return new Promise((resolve, reject) => { + const script = doc.createElement('script'); + script.onload = () => resolve(); + script.onerror = () => reject(Error("Script load failed")); + script.src = url; + doc.body.appendChild(script); + }) +} + +function preloadImage(url, { doc = document }={}) { + return new Promise((resolve, reject) => { + const preload = doc.createElement('link'); + preload.rel = 'preload'; + preload.as = 'image'; + preload.onload = () => resolve(); + preload.onerror = () => resolve(); + preload.href = url; + doc.body.appendChild(preload); + }) +} + +/** + * + * @param {Document} document + * @param {string|URL} url + * @returns {HTMLAudioElement} + */ +function appendAudio(document, url) { + const audio = document.createElement('audio'); + audio.muted = true; + audio.src = url; + audio.preload = true; + document.body.appendChild(audio); + return audio; +} diff --git a/test/wpt/tests/fetch/range/resources/video-with-range.py b/test/wpt/tests/fetch/range/resources/video-with-range.py new file mode 100644 index 0000000..2d15ccf --- /dev/null +++ b/test/wpt/tests/fetch/range/resources/video-with-range.py @@ -0,0 +1,43 @@ +import re +import os +import json +from wptserve.utils import isomorphic_decode + +def main(request, response): + path = os.path.join(request.doc_root, u"media", "sine440.mp3") + total_size = os.path.getsize(path) + rewrites = json.loads(request.GET.first(b'rewrites', '[]')) + range_header = request.headers.get(b'Range') + range_header_match = range_header and re.search(r'^bytes=(\d*)-(\d*)$', isomorphic_decode(range_header)) + start = None + end = None + if range_header_match: + response.status = 206 + start, end = range_header_match.groups() + if range_header: + status = 206 + else: + status = 200 + for rewrite in rewrites: + req_start, req_end = rewrite['request'] + if start == req_start or req_start == '*': + if end == req_end or req_end == '*': + if 'response' in rewrite: + start, end = rewrite['response'] + if 'status' in rewrite: + status = rewrite['status'] + + start = int(start or 0) + end = int(end or total_size) + headers = [] + if status == 206: + headers.append((b"Content-Range", b"bytes %d-%d/%d" % (start, end - 1, total_size))) + headers.append((b"Accept-Ranges", b"bytes")) + + headers.append((b"Content-Type", b"audio/mp3")) + headers.append((b"Content-Length", str(end - start))) + headers.append((b"Cache-Control", b"no-cache")) + video_file = open(path, "rb") + video_file.seek(start) + content = video_file.read(end) + return status, headers, content diff --git a/test/wpt/tests/fetch/range/sw.https.window.js b/test/wpt/tests/fetch/range/sw.https.window.js new file mode 100644 index 0000000..62ad894 --- /dev/null +++ b/test/wpt/tests/fetch/range/sw.https.window.js @@ -0,0 +1,228 @@ +// META: script=../../../service-workers/service-worker/resources/test-helpers.sub.js +// META: script=/common/utils.js +// META: script=/common/get-host-info.sub.js +// META: script=resources/utils.js + +const { REMOTE_HOST } = get_host_info(); +const BASE_SCOPE = 'resources/basic.html?'; + +async function cleanup() { + for (const iframe of document.querySelectorAll('.test-iframe')) { + iframe.parentNode.removeChild(iframe); + } + + for (const reg of await navigator.serviceWorker.getRegistrations()) { + await reg.unregister(); + } +} + +async function setupRegistration(t, scope) { + await cleanup(); + const reg = await navigator.serviceWorker.register('resources/range-sw.js', { scope }); + await wait_for_state(t, reg.installing, 'activated'); + return reg; +} + +function awaitMessage(obj, id) { + return new Promise(resolve => { + obj.addEventListener('message', function listener(event) { + if (event.data.id !== id) return; + obj.removeEventListener('message', listener); + resolve(event.data); + }); + }); +} + +promise_test(async t => { + const scope = BASE_SCOPE + Math.random(); + const reg = await setupRegistration(t, scope); + const iframe = await with_iframe(scope); + const w = iframe.contentWindow; + + // Trigger a cross-origin range request using media + const url = new URL('long-wav.py?action=range-header-filter-test', w.location); + url.hostname = REMOTE_HOST; + appendAudio(w.document, url); + + // See rangeHeaderFilterTest in resources/range-sw.js + await fetch_tests_from_worker(reg.active); +}, `Defer range header filter tests to service worker`); + +promise_test(async t => { + const scope = BASE_SCOPE + Math.random(); + const reg = await setupRegistration(t, scope); + const iframe = await with_iframe(scope); + const w = iframe.contentWindow; + + // Trigger a cross-origin range request using media + const url = new URL('long-wav.py', w.location); + url.searchParams.set('action', 'range-header-passthrough-test'); + url.searchParams.set('range-received-key', token()); + url.hostname = REMOTE_HOST; + appendAudio(w.document, url); + + // See rangeHeaderPassthroughTest in resources/range-sw.js + await fetch_tests_from_worker(reg.active); +}, `Defer range header passthrough tests to service worker`); + +promise_test(async t => { + const scope = BASE_SCOPE + Math.random(); + await setupRegistration(t, scope); + const iframe = await with_iframe(scope); + const w = iframe.contentWindow; + const id = Math.random() + ''; + const storedRangeResponse = awaitMessage(w.navigator.serviceWorker, id); + + // Trigger a cross-origin range request using media + const url = new URL('partial-script.py', w.location); + url.searchParams.set('require-range', '1'); + url.searchParams.set('action', 'store-ranged-response'); + url.searchParams.set('id', id); + url.hostname = REMOTE_HOST; + + appendAudio(w.document, url); + + await storedRangeResponse; + + // Fetching should reject + const fetchPromise = w.fetch('?action=use-stored-ranged-response', { mode: 'no-cors' }); + await promise_rejects_js(t, w.TypeError, fetchPromise); + + // Script loading should error too + const loadScriptPromise = loadScript('?action=use-stored-ranged-response', { doc: w.document }); + await promise_rejects_js(t, Error, loadScriptPromise); + + await loadScriptPromise.catch(() => {}); + + assert_false(!!w.scriptExecuted, `Partial response shouldn't be executed`); +}, `Ranged response not allowed following no-cors ranged request`); + +promise_test(async t => { + const scope = BASE_SCOPE + Math.random(); + await setupRegistration(t, scope); + const iframe = await with_iframe(scope); + const w = iframe.contentWindow; + const id = Math.random() + ''; + const storedRangeResponse = awaitMessage(w.navigator.serviceWorker, id); + + // Trigger a range request using media + const url = new URL('partial-script.py', w.location); + url.searchParams.set('require-range', '1'); + url.searchParams.set('action', 'store-ranged-response'); + url.searchParams.set('id', id); + + appendAudio(w.document, url); + + await storedRangeResponse; + + // This should not throw + await w.fetch('?action=use-stored-ranged-response'); + + // This shouldn't throw either + await loadScript('?action=use-stored-ranged-response', { doc: w.document }); + + assert_true(w.scriptExecuted, `Partial response should be executed`); +}, `Non-opaque ranged response executed`); + +promise_test(async t => { + const scope = BASE_SCOPE + Math.random(); + await setupRegistration(t, scope); + const iframe = await with_iframe(scope); + const w = iframe.contentWindow; + const fetchId = Math.random() + ''; + const fetchBroadcast = awaitMessage(w.navigator.serviceWorker, fetchId); + const audioId = Math.random() + ''; + const audioBroadcast = awaitMessage(w.navigator.serviceWorker, audioId); + + const url = new URL('long-wav.py', w.location); + url.searchParams.set('action', 'broadcast-accept-encoding'); + url.searchParams.set('id', fetchId); + + await w.fetch(url, { + headers: { Range: 'bytes=0-10' } + }); + + assert_equals((await fetchBroadcast).acceptEncoding, null, "Accept-Encoding should not be set for fetch"); + + url.searchParams.set('id', audioId); + appendAudio(w.document, url); + + assert_equals((await audioBroadcast).acceptEncoding, null, "Accept-Encoding should not be set for media"); +}, `Accept-Encoding should not appear in a service worker`); + +promise_test(async t => { + const scope = BASE_SCOPE + Math.random(); + await setupRegistration(t, scope); + const iframe = await with_iframe(scope); + const w = iframe.contentWindow; + const length = 100; + const count = 3; + const counts = {}; + + // test a single range request size + async function testSizedRange(size, partialResponseCode) { + const rangeId = Math.random() + ''; + const rangeBroadcast = awaitMessage(w.navigator.serviceWorker, rangeId); + + // Create a bogus audio element to trick the browser into sending + // cross-origin range requests that can be manipulated by the service worker. + const sound_url = new URL('partial-text.py', w.location); + sound_url.hostname = REMOTE_HOST; + sound_url.searchParams.set('action', 'record-media-range-request'); + sound_url.searchParams.set('length', length); + sound_url.searchParams.set('size', size); + sound_url.searchParams.set('partial', partialResponseCode); + sound_url.searchParams.set('id', rangeId); + sound_url.searchParams.set('type', 'audio/mp4'); + appendAudio(w.document, sound_url); + + // wait for the range requests to happen + await rangeBroadcast; + + // Create multiple preload requests and count the number of resource timing + // entries that get created to make sure 206 and 416 range responses are treated + // the same. + const url = new URL('partial-text.py', w.location); + url.searchParams.set('action', 'use-media-range-request'); + url.searchParams.set('size', size); + url.searchParams.set('type', 'audio/mp4'); + counts['size' + size] = 0; + for (let i = 0; i < count; i++) { + await preloadImage(url, { doc: w.document }); + } + } + + // Test range requests from 1 smaller than the correct size to 1 larger than + // the correct size to exercise the various permutations using the default 206 + // response code for successful range requests. + for (let size = length - 1; size <= length + 1; size++) { + await testSizedRange(size, '206'); + } + + // Test a successful range request using a 200 response. + await testSizedRange(length - 2, '200'); + + // Check the resource timing entries and count the reported number of fetches of each type + const resources = w.performance.getEntriesByType("resource"); + for (const entry of resources) { + const url = new URL(entry.name); + if (url.searchParams.has('action') && + url.searchParams.get('action') == 'use-media-range-request' && + url.searchParams.has('size')) { + counts['size' + url.searchParams.get('size')]++; + } + } + + // Make sure there are a non-zero number of preload requests and they are all the same + let counts_valid = true; + const first = 'size' + (length - 2); + for (let size = length - 2; size <= length + 1; size++) { + let key = 'size' + size; + if (!(key in counts) || counts[key] <= 0 || counts[key] != counts[first]) { + counts_valid = false; + break; + } + } + + assert_true(counts_valid, `Opaque range request preloads were different for error and success`); +}, `Opaque range preload successes and failures should be indistinguishable`); diff --git a/test/wpt/tests/fetch/redirect-navigate/302-found-post-handler.py b/test/wpt/tests/fetch/redirect-navigate/302-found-post-handler.py new file mode 100644 index 0000000..40a224f --- /dev/null +++ b/test/wpt/tests/fetch/redirect-navigate/302-found-post-handler.py @@ -0,0 +1,15 @@ +from wptserve.utils import isomorphic_encode + +def main(request, response): + if request.method == u"POST": + response.add_required_headers = False + response.writer.write_status(302) + response.writer.write_header(b"Location", isomorphic_encode(request.url)) + response.writer.end_headers() + response.writer.write(b"") + elif request.method == u"GET": + return ([(b"Content-Type", b"text/plain")], + b"OK") + else: + return ([(b"Content-Type", b"text/plain")], + b"FAIL") \ No newline at end of file diff --git a/test/wpt/tests/fetch/redirect-navigate/302-found-post.html b/test/wpt/tests/fetch/redirect-navigate/302-found-post.html new file mode 100644 index 0000000..854cd32 --- /dev/null +++ b/test/wpt/tests/fetch/redirect-navigate/302-found-post.html @@ -0,0 +1,20 @@ + + +HTTP 302 Found POST Navigation Test + + + + + diff --git a/test/wpt/tests/fetch/redirect-navigate/preserve-fragment.html b/test/wpt/tests/fetch/redirect-navigate/preserve-fragment.html new file mode 100644 index 0000000..682539a --- /dev/null +++ b/test/wpt/tests/fetch/redirect-navigate/preserve-fragment.html @@ -0,0 +1,202 @@ + + + + + Ensure fragment is kept across redirects + + + + + + + + + + + + + + diff --git a/test/wpt/tests/fetch/redirect-navigate/resources/destination.html b/test/wpt/tests/fetch/redirect-navigate/resources/destination.html new file mode 100644 index 0000000..f98c5a8 --- /dev/null +++ b/test/wpt/tests/fetch/redirect-navigate/resources/destination.html @@ -0,0 +1,28 @@ + + + + + + + + +

Target

+

Target

+ + diff --git a/test/wpt/tests/fetch/redirects/data.window.js b/test/wpt/tests/fetch/redirects/data.window.js new file mode 100644 index 0000000..eeb4196 --- /dev/null +++ b/test/wpt/tests/fetch/redirects/data.window.js @@ -0,0 +1,25 @@ +// See ../api/redirect/redirect-to-dataurl.any.js for fetch() tests + +async_test(t => { + const img = document.createElement("img"); + img.onload = t.unreached_func(); + img.onerror = t.step_func_done(); + img.src = "../api/resources/redirect.py?location=data:image/png%3Bbase64,iVBORw0KGgoAAAANSUhEUgAAAIUAAABqCAIAAAAdqgU8AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAF6SURBVHhe7dNBDQAADIPA%2Bje92eBxSQUQSLedlQzo0TLQonFWPVoGWjT%2BoUfLQIvGP/RoGWjR%2BIceLQMtGv/Qo2WgReMferQMtGj8Q4%2BWgRaNf%2BjRMtCi8Q89WgZaNP6hR8tAi8Y/9GgZaNH4hx4tAy0a/9CjZaBF4x96tAy0aPxDj5aBFo1/6NEy0KLxDz1aBlo0/qFHy0CLxj/0aBlo0fiHHi0DLRr/0KNloEXjH3q0DLRo/EOPloEWjX/o0TLQovEPPVoGWjT%2BoUfLQIvGP/RoGWjR%2BIceLQMtGv/Qo2WgReMferQMtGj8Q4%2BWgRaNf%2BjRMtCi8Q89WgZaNP6hR8tAi8Y/9GgZaNH4hx4tAy0a/9CjZaBF4x96tAy0aPxDj5aBFo1/6NEy0KLxDz1aBlo0/qFHy0CLxj/0aBlo0fiHHi0DLRr/0KNloEXjH3q0DLRo/EOPloEWjX/o0TLQovEPPVoGWjT%2BoUfLQIvGP/RoGWjR%2BIceJQMPIOzeGc0PIDEAAAAASUVORK5CYII"; +}, " fetch that redirects to data: URL"); + +globalThis.globalTest = null; +async_test(t => { + globalThis.globalTest = t; + const script = document.createElement("script"); + script.src = "../api/resources/redirect.py?location=data:text/javascript,(globalThis.globalTest.unreached_func())()"; + script.onerror = t.step_func_done(); + document.body.append(script); +}, " + + +
+ + + + + + + diff --git a/test/wpt/tests/fetch/security/1xx-response.any.js b/test/wpt/tests/fetch/security/1xx-response.any.js new file mode 100644 index 0000000..df4dafc --- /dev/null +++ b/test/wpt/tests/fetch/security/1xx-response.any.js @@ -0,0 +1,28 @@ +promise_test(async (t) => { + // The 100 response should be ignored, then the transaction ends, which + // should lead to an error. + await promise_rejects_js( + t, TypeError, fetch('/common/text-plain.txt?pipe=status(100)')); +}, 'Status(100) should be ignored.'); + +// This behavior is being discussed at https://github.com/whatwg/fetch/issues/1397. +promise_test(async (t) => { + const res = await fetch('/common/text-plain.txt?pipe=status(101)'); + assert_equals(res.status, 101); + const body = await res.text(); + assert_equals(body, ''); +}, 'Status(101) should be accepted, with removing body.'); + +promise_test(async (t) => { + // The 103 response should be ignored, then the transaction ends, which + // should lead to an error. + await promise_rejects_js( + t, TypeError, fetch('/common/text-plain.txt?pipe=status(103)')); +}, 'Status(103) should be ignored.'); + +promise_test(async (t) => { + // The 199 response should be ignored, then the transaction ends, which + // should lead to an error. + await promise_rejects_js( + t, TypeError, fetch('/common/text-plain.txt?pipe=status(199)')); +}, 'Status(199) should be ignored.'); diff --git a/test/wpt/tests/fetch/security/dangling-markup-mitigation-data-url.tentative.sub.html b/test/wpt/tests/fetch/security/dangling-markup-mitigation-data-url.tentative.sub.html new file mode 100644 index 0000000..f27735d --- /dev/null +++ b/test/wpt/tests/fetch/security/dangling-markup-mitigation-data-url.tentative.sub.html @@ -0,0 +1,229 @@ + + + + + diff --git a/test/wpt/tests/fetch/security/dangling-markup-mitigation.tentative.html b/test/wpt/tests/fetch/security/dangling-markup-mitigation.tentative.html new file mode 100644 index 0000000..61a9316 --- /dev/null +++ b/test/wpt/tests/fetch/security/dangling-markup-mitigation.tentative.html @@ -0,0 +1,147 @@ + + + + + diff --git a/test/wpt/tests/fetch/security/embedded-credentials.tentative.sub.html b/test/wpt/tests/fetch/security/embedded-credentials.tentative.sub.html new file mode 100644 index 0000000..ca5ee1c --- /dev/null +++ b/test/wpt/tests/fetch/security/embedded-credentials.tentative.sub.html @@ -0,0 +1,89 @@ + + + + + diff --git a/test/wpt/tests/fetch/security/redirect-to-url-with-credentials.https.html b/test/wpt/tests/fetch/security/redirect-to-url-with-credentials.https.html new file mode 100644 index 0000000..b064648 --- /dev/null +++ b/test/wpt/tests/fetch/security/redirect-to-url-with-credentials.https.html @@ -0,0 +1,68 @@ + +
+ + + +
+ + + + diff --git a/test/wpt/tests/fetch/security/support/embedded-credential-window.sub.html b/test/wpt/tests/fetch/security/support/embedded-credential-window.sub.html new file mode 100644 index 0000000..20d307e --- /dev/null +++ b/test/wpt/tests/fetch/security/support/embedded-credential-window.sub.html @@ -0,0 +1,19 @@ + + diff --git a/test/wpt/tests/fetch/stale-while-revalidate/fetch-sw.https.html b/test/wpt/tests/fetch/stale-while-revalidate/fetch-sw.https.html new file mode 100644 index 0000000..efcebc2 --- /dev/null +++ b/test/wpt/tests/fetch/stale-while-revalidate/fetch-sw.https.html @@ -0,0 +1,65 @@ + + + + + Stale Revalidation Requests don't get sent to service worker + + + + + + + + + diff --git a/test/wpt/tests/fetch/stale-while-revalidate/fetch.any.js b/test/wpt/tests/fetch/stale-while-revalidate/fetch.any.js new file mode 100644 index 0000000..3682b9d --- /dev/null +++ b/test/wpt/tests/fetch/stale-while-revalidate/fetch.any.js @@ -0,0 +1,32 @@ +// META: global=window,worker +// META: title=Tests Stale While Revalidate is executed for fetch API +// META: script=/common/utils.js + +function wait25ms(test) { + return new Promise(resolve => { + test.step_timeout(() => { + resolve(); + }, 25); + }); +} + +promise_test(async (test) => { + var request_token = token(); + + const response = await fetch(`resources/stale-script.py?token=` + request_token); + // Wait until resource is completely fetched to allow caching before next fetch. + const body = await response.text(); + const response2 = await fetch(`resources/stale-script.py?token=` + request_token); + + assert_equals(response.headers.get('Unique-Id'), response2.headers.get('Unique-Id')); + const body2 = await response2.text(); + assert_equals(body, body2); + + while(true) { + const revalidation_check = await fetch(`resources/stale-script.py?query&token=` + request_token); + if (revalidation_check.headers.get('Count') == '2') { + break; + } + await wait25ms(test); + } +}, 'Second fetch returns same response'); diff --git a/test/wpt/tests/fetch/stale-while-revalidate/resources/stale-css.py b/test/wpt/tests/fetch/stale-while-revalidate/resources/stale-css.py new file mode 100644 index 0000000..b876683 --- /dev/null +++ b/test/wpt/tests/fetch/stale-while-revalidate/resources/stale-css.py @@ -0,0 +1,28 @@ +def main(request, response): + + token = request.GET.first(b"token", None) + is_query = request.GET.first(b"query", None) != None + with request.server.stash.lock: + value = request.server.stash.take(token) + count = 0 + if value != None: + count = int(value) + if is_query: + if count < 2: + request.server.stash.put(token, count) + else: + count = count + 1 + request.server.stash.put(token, count) + if is_query: + headers = [(b"Count", count)] + content = b"" + return 200, headers, content + else: + content = b"body { background: rgb(0, 128, 0); }" + if count > 1: + content = b"body { background: rgb(255, 0, 0); }" + + headers = [(b"Content-Type", b"text/css"), + (b"Cache-Control", b"private, max-age=0, stale-while-revalidate=60")] + + return 200, headers, content diff --git a/test/wpt/tests/fetch/stale-while-revalidate/resources/stale-image.py b/test/wpt/tests/fetch/stale-while-revalidate/resources/stale-image.py new file mode 100644 index 0000000..36e6fc0 --- /dev/null +++ b/test/wpt/tests/fetch/stale-while-revalidate/resources/stale-image.py @@ -0,0 +1,40 @@ +import os.path + +from wptserve.utils import isomorphic_decode + +def main(request, response): + + token = request.GET.first(b"token", None) + is_query = request.GET.first(b"query", None) != None + with request.server.stash.lock: + value = request.server.stash.take(token) + count = 0 + if value != None: + count = int(value) + if is_query: + if count < 2: + request.server.stash.put(token, count) + else: + count = count + 1 + request.server.stash.put(token, count) + + if is_query: + headers = [(b"Count", count)] + content = b"" + return 200, headers, content + else: + filename = u"green-16x16.png" + if count > 1: + filename = u"green-256x256.png" + + path = os.path.join(os.path.dirname(isomorphic_decode(__file__)), u"../../../images", filename) + body = open(path, "rb").read() + + response.add_required_headers = False + response.writer.write_status(200) + response.writer.write_header(b"content-length", len(body)) + response.writer.write_header(b"Cache-Control", b"private, max-age=0, stale-while-revalidate=60") + response.writer.write_header(b"content-type", b"image/png") + response.writer.end_headers() + + response.writer.write(body) diff --git a/test/wpt/tests/fetch/stale-while-revalidate/resources/stale-script.py b/test/wpt/tests/fetch/stale-while-revalidate/resources/stale-script.py new file mode 100644 index 0000000..731cd80 --- /dev/null +++ b/test/wpt/tests/fetch/stale-while-revalidate/resources/stale-script.py @@ -0,0 +1,32 @@ +import random, string + +def id_token(): + letters = string.ascii_lowercase + return b''.join(random.choice(letters).encode("utf-8") for i in range(20)) + +def main(request, response): + token = request.GET.first(b"token", None) + is_query = request.GET.first(b"query", None) != None + with request.server.stash.lock: + value = request.server.stash.take(token) + count = 0 + if value != None: + count = int(value) + if is_query: + if count < 2: + request.server.stash.put(token, count) + else: + count = count + 1 + request.server.stash.put(token, count) + + if is_query: + headers = [(b"Count", count)] + content = u"" + return 200, headers, content + else: + unique_id = id_token() + headers = [(b"Content-Type", b"text/javascript"), + (b"Cache-Control", b"private, max-age=0, stale-while-revalidate=60"), + (b"Unique-Id", unique_id)] + content = b"report('%s')" % unique_id + return 200, headers, content diff --git a/test/wpt/tests/fetch/stale-while-revalidate/revalidate-not-blocked-by-csp.html b/test/wpt/tests/fetch/stale-while-revalidate/revalidate-not-blocked-by-csp.html new file mode 100644 index 0000000..ea70b9a --- /dev/null +++ b/test/wpt/tests/fetch/stale-while-revalidate/revalidate-not-blocked-by-csp.html @@ -0,0 +1,69 @@ + + +Test revalidations requests aren't blocked by CSP. + + + + + + diff --git a/test/wpt/tests/fetch/stale-while-revalidate/stale-css.html b/test/wpt/tests/fetch/stale-while-revalidate/stale-css.html new file mode 100644 index 0000000..603a60c --- /dev/null +++ b/test/wpt/tests/fetch/stale-while-revalidate/stale-css.html @@ -0,0 +1,51 @@ + + +Tests Stale While Revalidate works for css + + + + + + diff --git a/test/wpt/tests/fetch/stale-while-revalidate/stale-image.html b/test/wpt/tests/fetch/stale-while-revalidate/stale-image.html new file mode 100644 index 0000000..d86bdfb --- /dev/null +++ b/test/wpt/tests/fetch/stale-while-revalidate/stale-image.html @@ -0,0 +1,55 @@ + + +Tests Stale While Revalidate works for images + + + + + + + + + diff --git a/test/wpt/tests/fetch/stale-while-revalidate/stale-script.html b/test/wpt/tests/fetch/stale-while-revalidate/stale-script.html new file mode 100644 index 0000000..f531748 --- /dev/null +++ b/test/wpt/tests/fetch/stale-while-revalidate/stale-script.html @@ -0,0 +1,59 @@ + + +Tests Stale While Revalidate works for scripts + + + + + + diff --git a/test/wpt/tests/fetch/stale-while-revalidate/sw-intercept.js b/test/wpt/tests/fetch/stale-while-revalidate/sw-intercept.js new file mode 100644 index 0000000..dca7de5 --- /dev/null +++ b/test/wpt/tests/fetch/stale-while-revalidate/sw-intercept.js @@ -0,0 +1,14 @@ +async function broadcast(msg) { + for (const client of await clients.matchAll()) { + client.postMessage(msg); + } +} + +self.addEventListener('fetch', event => { + event.waitUntil(broadcast(event.request.url)); + event.respondWith(fetch(event.request)); +}); + +self.addEventListener('activate', event => { + self.clients.claim(); +}); diff --git a/test/wpt/tests/interfaces/ANGLE_instanced_arrays.idl b/test/wpt/tests/interfaces/ANGLE_instanced_arrays.idl new file mode 100644 index 0000000..557a416 --- /dev/null +++ b/test/wpt/tests/interfaces/ANGLE_instanced_arrays.idl @@ -0,0 +1,12 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL ANGLE_instanced_arrays Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/ANGLE_instanced_arrays/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface ANGLE_instanced_arrays { + const GLenum VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 0x88FE; + undefined drawArraysInstancedANGLE(GLenum mode, GLint first, GLsizei count, GLsizei primcount); + undefined drawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, GLintptr offset, GLsizei primcount); + undefined vertexAttribDivisorANGLE(GLuint index, GLuint divisor); +}; diff --git a/test/wpt/tests/interfaces/CSP.idl b/test/wpt/tests/interfaces/CSP.idl new file mode 100644 index 0000000..ac0a6ff --- /dev/null +++ b/test/wpt/tests/interfaces/CSP.idl @@ -0,0 +1,56 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Content Security Policy Level 3 (https://w3c.github.io/webappsec-csp/) + +[Exposed=Window] +interface CSPViolationReportBody : ReportBody { + [Default] object toJSON(); + readonly attribute USVString documentURL; + readonly attribute USVString? referrer; + readonly attribute USVString? blockedURL; + readonly attribute DOMString effectiveDirective; + readonly attribute DOMString originalPolicy; + readonly attribute USVString? sourceFile; + readonly attribute DOMString? sample; + readonly attribute SecurityPolicyViolationEventDisposition disposition; + readonly attribute unsigned short statusCode; + readonly attribute unsigned long? lineNumber; + readonly attribute unsigned long? columnNumber; +}; + +enum SecurityPolicyViolationEventDisposition { + "enforce", "report" +}; + +[Exposed=(Window,Worker)] +interface SecurityPolicyViolationEvent : Event { + constructor(DOMString type, optional SecurityPolicyViolationEventInit eventInitDict = {}); + readonly attribute USVString documentURI; + readonly attribute USVString referrer; + readonly attribute USVString blockedURI; + readonly attribute DOMString effectiveDirective; + readonly attribute DOMString violatedDirective; // historical alias of effectiveDirective + readonly attribute DOMString originalPolicy; + readonly attribute USVString sourceFile; + readonly attribute DOMString sample; + readonly attribute SecurityPolicyViolationEventDisposition disposition; + readonly attribute unsigned short statusCode; + readonly attribute unsigned long lineNumber; + readonly attribute unsigned long columnNumber; +}; + +dictionary SecurityPolicyViolationEventInit : EventInit { + required USVString documentURI; + USVString referrer = ""; + USVString blockedURI = ""; + required DOMString violatedDirective; + required DOMString effectiveDirective; + required DOMString originalPolicy; + USVString sourceFile = ""; + DOMString sample = ""; + required SecurityPolicyViolationEventDisposition disposition; + required unsigned short statusCode; + unsigned long lineNumber = 0; + unsigned long columnNumber = 0; +}; diff --git a/test/wpt/tests/interfaces/DOM-Parsing.idl b/test/wpt/tests/interfaces/DOM-Parsing.idl new file mode 100644 index 0000000..d0d84ab --- /dev/null +++ b/test/wpt/tests/interfaces/DOM-Parsing.idl @@ -0,0 +1,26 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: DOM Parsing and Serialization (https://w3c.github.io/DOM-Parsing/) + +[Exposed=Window] +interface XMLSerializer { + constructor(); + DOMString serializeToString(Node root); +}; + +interface mixin InnerHTML { + [CEReactions] attribute [LegacyNullToEmptyString] DOMString innerHTML; +}; + +Element includes InnerHTML; +ShadowRoot includes InnerHTML; + +partial interface Element { + [CEReactions] attribute [LegacyNullToEmptyString] DOMString outerHTML; + [CEReactions] undefined insertAdjacentHTML(DOMString position, DOMString text); +}; + +partial interface Range { + [CEReactions, NewObject] DocumentFragment createContextualFragment(DOMString fragment); +}; diff --git a/test/wpt/tests/interfaces/EXT_blend_minmax.idl b/test/wpt/tests/interfaces/EXT_blend_minmax.idl new file mode 100644 index 0000000..fd7d26e --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_blend_minmax.idl @@ -0,0 +1,10 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_blend_minmax Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_blend_minmax/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_blend_minmax { + const GLenum MIN_EXT = 0x8007; + const GLenum MAX_EXT = 0x8008; +}; diff --git a/test/wpt/tests/interfaces/EXT_color_buffer_float.idl b/test/wpt/tests/interfaces/EXT_color_buffer_float.idl new file mode 100644 index 0000000..09bd397 --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_color_buffer_float.idl @@ -0,0 +1,8 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_color_buffer_float Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_color_buffer_float/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_color_buffer_float { +}; // interface EXT_color_buffer_float diff --git a/test/wpt/tests/interfaces/EXT_color_buffer_half_float.idl b/test/wpt/tests/interfaces/EXT_color_buffer_half_float.idl new file mode 100644 index 0000000..7197e44 --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_color_buffer_half_float.idl @@ -0,0 +1,12 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_color_buffer_half_float Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_color_buffer_half_float/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_color_buffer_half_float { + const GLenum RGBA16F_EXT = 0x881A; + const GLenum RGB16F_EXT = 0x881B; + const GLenum FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT = 0x8211; + const GLenum UNSIGNED_NORMALIZED_EXT = 0x8C17; +}; // interface EXT_color_buffer_half_float diff --git a/test/wpt/tests/interfaces/EXT_disjoint_timer_query.idl b/test/wpt/tests/interfaces/EXT_disjoint_timer_query.idl new file mode 100644 index 0000000..cf0c8d9 --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_disjoint_timer_query.idl @@ -0,0 +1,30 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_disjoint_timer_query Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_disjoint_timer_query/) + +typedef unsigned long long GLuint64EXT; + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WebGLTimerQueryEXT : WebGLObject { +}; + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_disjoint_timer_query { + const GLenum QUERY_COUNTER_BITS_EXT = 0x8864; + const GLenum CURRENT_QUERY_EXT = 0x8865; + const GLenum QUERY_RESULT_EXT = 0x8866; + const GLenum QUERY_RESULT_AVAILABLE_EXT = 0x8867; + const GLenum TIME_ELAPSED_EXT = 0x88BF; + const GLenum TIMESTAMP_EXT = 0x8E28; + const GLenum GPU_DISJOINT_EXT = 0x8FBB; + + WebGLTimerQueryEXT? createQueryEXT(); + undefined deleteQueryEXT(WebGLTimerQueryEXT? query); + [WebGLHandlesContextLoss] boolean isQueryEXT(WebGLTimerQueryEXT? query); + undefined beginQueryEXT(GLenum target, WebGLTimerQueryEXT query); + undefined endQueryEXT(GLenum target); + undefined queryCounterEXT(WebGLTimerQueryEXT query, GLenum target); + any getQueryEXT(GLenum target, GLenum pname); + any getQueryObjectEXT(WebGLTimerQueryEXT query, GLenum pname); +}; diff --git a/test/wpt/tests/interfaces/EXT_disjoint_timer_query_webgl2.idl b/test/wpt/tests/interfaces/EXT_disjoint_timer_query_webgl2.idl new file mode 100644 index 0000000..689203c --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_disjoint_timer_query_webgl2.idl @@ -0,0 +1,14 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_disjoint_timer_query_webgl2 Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_disjoint_timer_query_webgl2/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_disjoint_timer_query_webgl2 { + const GLenum QUERY_COUNTER_BITS_EXT = 0x8864; + const GLenum TIME_ELAPSED_EXT = 0x88BF; + const GLenum TIMESTAMP_EXT = 0x8E28; + const GLenum GPU_DISJOINT_EXT = 0x8FBB; + + undefined queryCounterEXT(WebGLQuery query, GLenum target); +}; diff --git a/test/wpt/tests/interfaces/EXT_float_blend.idl b/test/wpt/tests/interfaces/EXT_float_blend.idl new file mode 100644 index 0000000..58ec47e --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_float_blend.idl @@ -0,0 +1,8 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_float_blend Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_float_blend/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_float_blend { +}; // interface EXT_float_blend diff --git a/test/wpt/tests/interfaces/EXT_frag_depth.idl b/test/wpt/tests/interfaces/EXT_frag_depth.idl new file mode 100644 index 0000000..1ae6896 --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_frag_depth.idl @@ -0,0 +1,8 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_frag_depth Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_frag_depth/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_frag_depth { +}; diff --git a/test/wpt/tests/interfaces/EXT_sRGB.idl b/test/wpt/tests/interfaces/EXT_sRGB.idl new file mode 100644 index 0000000..3c03c33 --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_sRGB.idl @@ -0,0 +1,12 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_sRGB Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_sRGB/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_sRGB { + const GLenum SRGB_EXT = 0x8C40; + const GLenum SRGB_ALPHA_EXT = 0x8C42; + const GLenum SRGB8_ALPHA8_EXT = 0x8C43; + const GLenum FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT = 0x8210; +}; diff --git a/test/wpt/tests/interfaces/EXT_shader_texture_lod.idl b/test/wpt/tests/interfaces/EXT_shader_texture_lod.idl new file mode 100644 index 0000000..13df26c --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_shader_texture_lod.idl @@ -0,0 +1,8 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_shader_texture_lod Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_shader_texture_lod/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_shader_texture_lod { +}; diff --git a/test/wpt/tests/interfaces/EXT_texture_compression_bptc.idl b/test/wpt/tests/interfaces/EXT_texture_compression_bptc.idl new file mode 100644 index 0000000..2772980 --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_texture_compression_bptc.idl @@ -0,0 +1,12 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_texture_compression_bptc Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_texture_compression_bptc { + const GLenum COMPRESSED_RGBA_BPTC_UNORM_EXT = 0x8E8C; + const GLenum COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = 0x8E8D; + const GLenum COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT = 0x8E8E; + const GLenum COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT = 0x8E8F; +}; diff --git a/test/wpt/tests/interfaces/EXT_texture_compression_rgtc.idl b/test/wpt/tests/interfaces/EXT_texture_compression_rgtc.idl new file mode 100644 index 0000000..f12b962 --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_texture_compression_rgtc.idl @@ -0,0 +1,12 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_texture_compression_rgtc Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_texture_compression_rgtc { + const GLenum COMPRESSED_RED_RGTC1_EXT = 0x8DBB; + const GLenum COMPRESSED_SIGNED_RED_RGTC1_EXT = 0x8DBC; + const GLenum COMPRESSED_RED_GREEN_RGTC2_EXT = 0x8DBD; + const GLenum COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT = 0x8DBE; +}; diff --git a/test/wpt/tests/interfaces/EXT_texture_filter_anisotropic.idl b/test/wpt/tests/interfaces/EXT_texture_filter_anisotropic.idl new file mode 100644 index 0000000..5c78bfa --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_texture_filter_anisotropic.idl @@ -0,0 +1,10 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_texture_filter_anisotropic Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_texture_filter_anisotropic/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_texture_filter_anisotropic { + const GLenum TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE; + const GLenum MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FF; +}; diff --git a/test/wpt/tests/interfaces/EXT_texture_norm16.idl b/test/wpt/tests/interfaces/EXT_texture_norm16.idl new file mode 100644 index 0000000..1fe5ed8 --- /dev/null +++ b/test/wpt/tests/interfaces/EXT_texture_norm16.idl @@ -0,0 +1,16 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL EXT_texture_norm16 Extension Specification (https://registry.khronos.org/webgl/extensions/EXT_texture_norm16/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface EXT_texture_norm16 { + const GLenum R16_EXT = 0x822A; + const GLenum RG16_EXT = 0x822C; + const GLenum RGB16_EXT = 0x8054; + const GLenum RGBA16_EXT = 0x805B; + const GLenum R16_SNORM_EXT = 0x8F98; + const GLenum RG16_SNORM_EXT = 0x8F99; + const GLenum RGB16_SNORM_EXT = 0x8F9A; + const GLenum RGBA16_SNORM_EXT = 0x8F9B; +}; diff --git a/test/wpt/tests/interfaces/FedCM.idl b/test/wpt/tests/interfaces/FedCM.idl new file mode 100644 index 0000000..8de87e8 --- /dev/null +++ b/test/wpt/tests/interfaces/FedCM.idl @@ -0,0 +1,67 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Federated Credential Management API (https://fedidcg.github.io/FedCM/) + +[Exposed=Window, SecureContext] +interface IdentityCredential : Credential { + readonly attribute USVString? token; +}; + +partial dictionary CredentialRequestOptions { + IdentityCredentialRequestOptions identity; +}; + +dictionary IdentityCredentialRequestOptions { + sequence providers; +}; + +dictionary IdentityProviderConfig { + required USVString configURL; + required USVString clientId; + USVString nonce; +}; + +dictionary IdentityProviderWellKnown { + required sequence provider_urls; +}; + +dictionary IdentityProviderIcon { + required USVString url; + unsigned long size; +}; + +dictionary IdentityProviderBranding { + USVString background_color; + USVString color; + sequence icons; + USVString name; +}; + +dictionary IdentityProviderAPIConfig { + required USVString accounts_endpoint; + required USVString client_metadata_endpoint; + required USVString id_assertion_endpoint; + IdentityProviderBranding branding; +}; + +dictionary IdentityProviderAccount { + required USVString id; + required USVString name; + required USVString email; + USVString given_name; + USVString picture; + sequence approved_clients; +}; +dictionary IdentityProviderAccountList { + sequence accounts; +}; + +dictionary IdentityProviderToken { + required USVString token; +}; + +dictionary IdentityProviderClientMetadata { + USVString privacy_policy_url; + USVString terms_of_service_url; +}; diff --git a/test/wpt/tests/interfaces/FileAPI.idl b/test/wpt/tests/interfaces/FileAPI.idl new file mode 100644 index 0000000..aee0e65 --- /dev/null +++ b/test/wpt/tests/interfaces/FileAPI.idl @@ -0,0 +1,100 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: File API (https://w3c.github.io/FileAPI/) + +[Exposed=(Window,Worker), Serializable] +interface Blob { + constructor(optional sequence blobParts, + optional BlobPropertyBag options = {}); + + readonly attribute unsigned long long size; + readonly attribute DOMString type; + + // slice Blob into byte-ranged chunks + Blob slice(optional [Clamp] long long start, + optional [Clamp] long long end, + optional DOMString contentType); + + // read from the Blob. + [NewObject] ReadableStream stream(); + [NewObject] Promise text(); + [NewObject] Promise arrayBuffer(); +}; + +enum EndingType { "transparent", "native" }; + +dictionary BlobPropertyBag { + DOMString type = ""; + EndingType endings = "transparent"; +}; + +typedef (BufferSource or Blob or USVString) BlobPart; + +[Exposed=(Window,Worker), Serializable] +interface File : Blob { + constructor(sequence fileBits, + USVString fileName, + optional FilePropertyBag options = {}); + readonly attribute DOMString name; + readonly attribute long long lastModified; +}; + +dictionary FilePropertyBag : BlobPropertyBag { + long long lastModified; +}; + +[Exposed=(Window,Worker), Serializable] +interface FileList { + getter File? item(unsigned long index); + readonly attribute unsigned long length; +}; + +[Exposed=(Window,Worker)] +interface FileReader: EventTarget { + constructor(); + // async read methods + undefined readAsArrayBuffer(Blob blob); + undefined readAsBinaryString(Blob blob); + undefined readAsText(Blob blob, optional DOMString encoding); + undefined readAsDataURL(Blob blob); + + undefined abort(); + + // states + const unsigned short EMPTY = 0; + const unsigned short LOADING = 1; + const unsigned short DONE = 2; + + readonly attribute unsigned short readyState; + + // File or Blob data + readonly attribute (DOMString or ArrayBuffer)? result; + + readonly attribute DOMException? error; + + // event handler content attributes + attribute EventHandler onloadstart; + attribute EventHandler onprogress; + attribute EventHandler onload; + attribute EventHandler onabort; + attribute EventHandler onerror; + attribute EventHandler onloadend; +}; + +[Exposed=(DedicatedWorker,SharedWorker)] +interface FileReaderSync { + constructor(); + // Synchronously return strings + + ArrayBuffer readAsArrayBuffer(Blob blob); + DOMString readAsBinaryString(Blob blob); + DOMString readAsText(Blob blob, optional DOMString encoding); + DOMString readAsDataURL(Blob blob); +}; + +[Exposed=(Window,DedicatedWorker,SharedWorker)] +partial interface URL { + static DOMString createObjectURL((Blob or MediaSource) obj); + static undefined revokeObjectURL(DOMString url); +}; diff --git a/test/wpt/tests/interfaces/IndexedDB.idl b/test/wpt/tests/interfaces/IndexedDB.idl new file mode 100644 index 0000000..d82391d --- /dev/null +++ b/test/wpt/tests/interfaces/IndexedDB.idl @@ -0,0 +1,226 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Indexed Database API 3.0 (https://w3c.github.io/IndexedDB/) + +[Exposed=(Window,Worker)] +interface IDBRequest : EventTarget { + readonly attribute any result; + readonly attribute DOMException? error; + readonly attribute (IDBObjectStore or IDBIndex or IDBCursor)? source; + readonly attribute IDBTransaction? transaction; + readonly attribute IDBRequestReadyState readyState; + + // Event handlers: + attribute EventHandler onsuccess; + attribute EventHandler onerror; +}; + +enum IDBRequestReadyState { + "pending", + "done" +}; + +[Exposed=(Window,Worker)] +interface IDBOpenDBRequest : IDBRequest { + // Event handlers: + attribute EventHandler onblocked; + attribute EventHandler onupgradeneeded; +}; + +[Exposed=(Window,Worker)] +interface IDBVersionChangeEvent : Event { + constructor(DOMString type, optional IDBVersionChangeEventInit eventInitDict = {}); + readonly attribute unsigned long long oldVersion; + readonly attribute unsigned long long? newVersion; +}; + +dictionary IDBVersionChangeEventInit : EventInit { + unsigned long long oldVersion = 0; + unsigned long long? newVersion = null; +}; + +partial interface mixin WindowOrWorkerGlobalScope { + [SameObject] readonly attribute IDBFactory indexedDB; +}; + +[Exposed=(Window,Worker)] +interface IDBFactory { + [NewObject] IDBOpenDBRequest open(DOMString name, + optional [EnforceRange] unsigned long long version); + [NewObject] IDBOpenDBRequest deleteDatabase(DOMString name); + + Promise> databases(); + + short cmp(any first, any second); +}; + +dictionary IDBDatabaseInfo { + DOMString name; + unsigned long long version; +}; + +[Exposed=(Window,Worker)] +interface IDBDatabase : EventTarget { + readonly attribute DOMString name; + readonly attribute unsigned long long version; + readonly attribute DOMStringList objectStoreNames; + + [NewObject] IDBTransaction transaction((DOMString or sequence) storeNames, + optional IDBTransactionMode mode = "readonly", + optional IDBTransactionOptions options = {}); + undefined close(); + + [NewObject] IDBObjectStore createObjectStore( + DOMString name, + optional IDBObjectStoreParameters options = {}); + undefined deleteObjectStore(DOMString name); + + // Event handlers: + attribute EventHandler onabort; + attribute EventHandler onclose; + attribute EventHandler onerror; + attribute EventHandler onversionchange; +}; + +enum IDBTransactionDurability { "default", "strict", "relaxed" }; + +dictionary IDBTransactionOptions { + IDBTransactionDurability durability = "default"; +}; + +dictionary IDBObjectStoreParameters { + (DOMString or sequence)? keyPath = null; + boolean autoIncrement = false; +}; + +[Exposed=(Window,Worker)] +interface IDBObjectStore { + attribute DOMString name; + readonly attribute any keyPath; + readonly attribute DOMStringList indexNames; + [SameObject] readonly attribute IDBTransaction transaction; + readonly attribute boolean autoIncrement; + + [NewObject] IDBRequest put(any value, optional any key); + [NewObject] IDBRequest add(any value, optional any key); + [NewObject] IDBRequest delete(any query); + [NewObject] IDBRequest clear(); + [NewObject] IDBRequest get(any query); + [NewObject] IDBRequest getKey(any query); + [NewObject] IDBRequest getAll(optional any query, + optional [EnforceRange] unsigned long count); + [NewObject] IDBRequest getAllKeys(optional any query, + optional [EnforceRange] unsigned long count); + [NewObject] IDBRequest count(optional any query); + + [NewObject] IDBRequest openCursor(optional any query, + optional IDBCursorDirection direction = "next"); + [NewObject] IDBRequest openKeyCursor(optional any query, + optional IDBCursorDirection direction = "next"); + + IDBIndex index(DOMString name); + + [NewObject] IDBIndex createIndex(DOMString name, + (DOMString or sequence) keyPath, + optional IDBIndexParameters options = {}); + undefined deleteIndex(DOMString name); +}; + +dictionary IDBIndexParameters { + boolean unique = false; + boolean multiEntry = false; +}; + +[Exposed=(Window,Worker)] +interface IDBIndex { + attribute DOMString name; + [SameObject] readonly attribute IDBObjectStore objectStore; + readonly attribute any keyPath; + readonly attribute boolean multiEntry; + readonly attribute boolean unique; + + [NewObject] IDBRequest get(any query); + [NewObject] IDBRequest getKey(any query); + [NewObject] IDBRequest getAll(optional any query, + optional [EnforceRange] unsigned long count); + [NewObject] IDBRequest getAllKeys(optional any query, + optional [EnforceRange] unsigned long count); + [NewObject] IDBRequest count(optional any query); + + [NewObject] IDBRequest openCursor(optional any query, + optional IDBCursorDirection direction = "next"); + [NewObject] IDBRequest openKeyCursor(optional any query, + optional IDBCursorDirection direction = "next"); +}; + +[Exposed=(Window,Worker)] +interface IDBKeyRange { + readonly attribute any lower; + readonly attribute any upper; + readonly attribute boolean lowerOpen; + readonly attribute boolean upperOpen; + + // Static construction methods: + [NewObject] static IDBKeyRange only(any value); + [NewObject] static IDBKeyRange lowerBound(any lower, optional boolean open = false); + [NewObject] static IDBKeyRange upperBound(any upper, optional boolean open = false); + [NewObject] static IDBKeyRange bound(any lower, + any upper, + optional boolean lowerOpen = false, + optional boolean upperOpen = false); + + boolean includes(any key); +}; + +[Exposed=(Window,Worker)] +interface IDBCursor { + readonly attribute (IDBObjectStore or IDBIndex) source; + readonly attribute IDBCursorDirection direction; + readonly attribute any key; + readonly attribute any primaryKey; + [SameObject] readonly attribute IDBRequest request; + + undefined advance([EnforceRange] unsigned long count); + undefined continue(optional any key); + undefined continuePrimaryKey(any key, any primaryKey); + + [NewObject] IDBRequest update(any value); + [NewObject] IDBRequest delete(); +}; + +enum IDBCursorDirection { + "next", + "nextunique", + "prev", + "prevunique" +}; + +[Exposed=(Window,Worker)] +interface IDBCursorWithValue : IDBCursor { + readonly attribute any value; +}; + +[Exposed=(Window,Worker)] +interface IDBTransaction : EventTarget { + readonly attribute DOMStringList objectStoreNames; + readonly attribute IDBTransactionMode mode; + readonly attribute IDBTransactionDurability durability; + [SameObject] readonly attribute IDBDatabase db; + readonly attribute DOMException? error; + + IDBObjectStore objectStore(DOMString name); + undefined commit(); + undefined abort(); + + // Event handlers: + attribute EventHandler onabort; + attribute EventHandler oncomplete; + attribute EventHandler onerror; +}; + +enum IDBTransactionMode { + "readonly", + "readwrite", + "versionchange" +}; diff --git a/test/wpt/tests/interfaces/KHR_parallel_shader_compile.idl b/test/wpt/tests/interfaces/KHR_parallel_shader_compile.idl new file mode 100644 index 0000000..1470965 --- /dev/null +++ b/test/wpt/tests/interfaces/KHR_parallel_shader_compile.idl @@ -0,0 +1,9 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL KHR_parallel_shader_compile Extension Specification (https://registry.khronos.org/webgl/extensions/KHR_parallel_shader_compile/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface KHR_parallel_shader_compile { + const GLenum COMPLETION_STATUS_KHR = 0x91B1; +}; diff --git a/test/wpt/tests/interfaces/META.yml b/test/wpt/tests/interfaces/META.yml new file mode 100644 index 0000000..c1dd8dd --- /dev/null +++ b/test/wpt/tests/interfaces/META.yml @@ -0,0 +1,2 @@ +suggested_reviewers: + - foolip diff --git a/test/wpt/tests/interfaces/OES_draw_buffers_indexed.idl b/test/wpt/tests/interfaces/OES_draw_buffers_indexed.idl new file mode 100644 index 0000000..ea1e217 --- /dev/null +++ b/test/wpt/tests/interfaces/OES_draw_buffers_indexed.idl @@ -0,0 +1,26 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL OES_draw_buffers_indexed Extension Specification (https://registry.khronos.org/webgl/extensions/OES_draw_buffers_indexed/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface OES_draw_buffers_indexed { + undefined enableiOES(GLenum target, GLuint index); + + undefined disableiOES(GLenum target, GLuint index); + + undefined blendEquationiOES(GLuint buf, GLenum mode); + + undefined blendEquationSeparateiOES(GLuint buf, + GLenum modeRGB, GLenum modeAlpha); + + undefined blendFunciOES(GLuint buf, + GLenum src, GLenum dst); + + undefined blendFuncSeparateiOES(GLuint buf, + GLenum srcRGB, GLenum dstRGB, + GLenum srcAlpha, GLenum dstAlpha); + + undefined colorMaskiOES(GLuint buf, + GLboolean r, GLboolean g, GLboolean b, GLboolean a); +}; diff --git a/test/wpt/tests/interfaces/OES_element_index_uint.idl b/test/wpt/tests/interfaces/OES_element_index_uint.idl new file mode 100644 index 0000000..df43a57 --- /dev/null +++ b/test/wpt/tests/interfaces/OES_element_index_uint.idl @@ -0,0 +1,8 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL OES_element_index_uint Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/OES_element_index_uint/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface OES_element_index_uint { +}; diff --git a/test/wpt/tests/interfaces/OES_fbo_render_mipmap.idl b/test/wpt/tests/interfaces/OES_fbo_render_mipmap.idl new file mode 100644 index 0000000..608c392 --- /dev/null +++ b/test/wpt/tests/interfaces/OES_fbo_render_mipmap.idl @@ -0,0 +1,8 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL OES_fbo_render_mipmap Extension Specification (https://registry.khronos.org/webgl/extensions/OES_fbo_render_mipmap/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface OES_fbo_render_mipmap { +}; diff --git a/test/wpt/tests/interfaces/OES_standard_derivatives.idl b/test/wpt/tests/interfaces/OES_standard_derivatives.idl new file mode 100644 index 0000000..7bf073a --- /dev/null +++ b/test/wpt/tests/interfaces/OES_standard_derivatives.idl @@ -0,0 +1,9 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL OES_standard_derivatives Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/OES_standard_derivatives/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface OES_standard_derivatives { + const GLenum FRAGMENT_SHADER_DERIVATIVE_HINT_OES = 0x8B8B; +}; diff --git a/test/wpt/tests/interfaces/OES_texture_float.idl b/test/wpt/tests/interfaces/OES_texture_float.idl new file mode 100644 index 0000000..a1bb79c --- /dev/null +++ b/test/wpt/tests/interfaces/OES_texture_float.idl @@ -0,0 +1,7 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL OES_texture_float Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/OES_texture_float/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface OES_texture_float { }; diff --git a/test/wpt/tests/interfaces/OES_texture_float_linear.idl b/test/wpt/tests/interfaces/OES_texture_float_linear.idl new file mode 100644 index 0000000..4626297 --- /dev/null +++ b/test/wpt/tests/interfaces/OES_texture_float_linear.idl @@ -0,0 +1,7 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL OES_texture_float_linear Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/OES_texture_float_linear/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface OES_texture_float_linear { }; diff --git a/test/wpt/tests/interfaces/OES_texture_half_float.idl b/test/wpt/tests/interfaces/OES_texture_half_float.idl new file mode 100644 index 0000000..be41454 --- /dev/null +++ b/test/wpt/tests/interfaces/OES_texture_half_float.idl @@ -0,0 +1,9 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL OES_texture_half_float Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/OES_texture_half_float/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface OES_texture_half_float { + const GLenum HALF_FLOAT_OES = 0x8D61; +}; diff --git a/test/wpt/tests/interfaces/OES_texture_half_float_linear.idl b/test/wpt/tests/interfaces/OES_texture_half_float_linear.idl new file mode 100644 index 0000000..2f1a999 --- /dev/null +++ b/test/wpt/tests/interfaces/OES_texture_half_float_linear.idl @@ -0,0 +1,7 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL OES_texture_half_float_linear Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/OES_texture_half_float_linear/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface OES_texture_half_float_linear { }; diff --git a/test/wpt/tests/interfaces/OES_vertex_array_object.idl b/test/wpt/tests/interfaces/OES_vertex_array_object.idl new file mode 100644 index 0000000..8aeb745 --- /dev/null +++ b/test/wpt/tests/interfaces/OES_vertex_array_object.idl @@ -0,0 +1,18 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL OES_vertex_array_object Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/OES_vertex_array_object/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WebGLVertexArrayObjectOES : WebGLObject { +}; + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface OES_vertex_array_object { + const GLenum VERTEX_ARRAY_BINDING_OES = 0x85B5; + + WebGLVertexArrayObjectOES? createVertexArrayOES(); + undefined deleteVertexArrayOES(WebGLVertexArrayObjectOES? arrayObject); + [WebGLHandlesContextLoss] GLboolean isVertexArrayOES(WebGLVertexArrayObjectOES? arrayObject); + undefined bindVertexArrayOES(WebGLVertexArrayObjectOES? arrayObject); +}; diff --git a/test/wpt/tests/interfaces/OVR_multiview2.idl b/test/wpt/tests/interfaces/OVR_multiview2.idl new file mode 100644 index 0000000..9c1ecc4 --- /dev/null +++ b/test/wpt/tests/interfaces/OVR_multiview2.idl @@ -0,0 +1,14 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL OVR_multiview2 Extension Specification (https://registry.khronos.org/webgl/extensions/OVR_multiview2/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface OVR_multiview2 { + const GLenum FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR = 0x9630; + const GLenum FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR = 0x9632; + const GLenum MAX_VIEWS_OVR = 0x9631; + const GLenum FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR = 0x9633; + + undefined framebufferTextureMultiviewOVR(GLenum target, GLenum attachment, WebGLTexture? texture, GLint level, GLint baseViewIndex, GLsizei numViews); +}; diff --git a/test/wpt/tests/interfaces/README.md b/test/wpt/tests/interfaces/README.md new file mode 100644 index 0000000..5e948ad --- /dev/null +++ b/test/wpt/tests/interfaces/README.md @@ -0,0 +1,3 @@ +This directory contains [Web IDL](https://webidl.spec.whatwg.org/) interface definitions for use in idlharness.js tests. + +The `.idl` files (except `*.tentative.idl`) are copied from [@webref/idl](https://www.npmjs.com/package/@webref/idl) by a [workflow](https://github.com/web-platform-tests/wpt/blob/master/.github/workflows/interfaces.yml) that tries to sync the files daily. The resulting pull requests require manual review but can be approved/merged by anyone with write access. diff --git a/test/wpt/tests/interfaces/SVG.idl b/test/wpt/tests/interfaces/SVG.idl new file mode 100644 index 0000000..3a0b861 --- /dev/null +++ b/test/wpt/tests/interfaces/SVG.idl @@ -0,0 +1,693 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Scalable Vector Graphics (SVG) 2 (https://svgwg.org/svg2-draft/) + +[Exposed=Window] +interface SVGElement : Element { + + [SameObject] readonly attribute SVGAnimatedString className; + + readonly attribute SVGSVGElement? ownerSVGElement; + readonly attribute SVGElement? viewportElement; +}; + +SVGElement includes GlobalEventHandlers; +SVGElement includes SVGElementInstance; +SVGElement includes HTMLOrSVGElement; + +dictionary SVGBoundingBoxOptions { + boolean fill = true; + boolean stroke = false; + boolean markers = false; + boolean clipped = false; +}; + +[Exposed=Window] +interface SVGGraphicsElement : SVGElement { + [SameObject] readonly attribute SVGAnimatedTransformList transform; + + DOMRect getBBox(optional SVGBoundingBoxOptions options = {}); + DOMMatrix? getCTM(); + DOMMatrix? getScreenCTM(); +}; + +SVGGraphicsElement includes SVGTests; + +[Exposed=Window] +interface SVGGeometryElement : SVGGraphicsElement { + [SameObject] readonly attribute SVGAnimatedNumber pathLength; + + boolean isPointInFill(optional DOMPointInit point = {}); + boolean isPointInStroke(optional DOMPointInit point = {}); + float getTotalLength(); + DOMPoint getPointAtLength(float distance); +}; + +[Exposed=Window] +interface SVGNumber { + attribute float value; +}; + +[Exposed=Window] +interface SVGLength { + + // Length Unit Types + const unsigned short SVG_LENGTHTYPE_UNKNOWN = 0; + const unsigned short SVG_LENGTHTYPE_NUMBER = 1; + const unsigned short SVG_LENGTHTYPE_PERCENTAGE = 2; + const unsigned short SVG_LENGTHTYPE_EMS = 3; + const unsigned short SVG_LENGTHTYPE_EXS = 4; + const unsigned short SVG_LENGTHTYPE_PX = 5; + const unsigned short SVG_LENGTHTYPE_CM = 6; + const unsigned short SVG_LENGTHTYPE_MM = 7; + const unsigned short SVG_LENGTHTYPE_IN = 8; + const unsigned short SVG_LENGTHTYPE_PT = 9; + const unsigned short SVG_LENGTHTYPE_PC = 10; + + readonly attribute unsigned short unitType; + attribute float value; + attribute float valueInSpecifiedUnits; + attribute DOMString valueAsString; + + undefined newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits); + undefined convertToSpecifiedUnits(unsigned short unitType); +}; + +[Exposed=Window] +interface SVGAngle { + + // Angle Unit Types + const unsigned short SVG_ANGLETYPE_UNKNOWN = 0; + const unsigned short SVG_ANGLETYPE_UNSPECIFIED = 1; + const unsigned short SVG_ANGLETYPE_DEG = 2; + const unsigned short SVG_ANGLETYPE_RAD = 3; + const unsigned short SVG_ANGLETYPE_GRAD = 4; + + readonly attribute unsigned short unitType; + attribute float value; + attribute float valueInSpecifiedUnits; + attribute DOMString valueAsString; + + undefined newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits); + undefined convertToSpecifiedUnits(unsigned short unitType); +}; + +[Exposed=Window] +interface SVGNumberList { + + readonly attribute unsigned long length; + readonly attribute unsigned long numberOfItems; + + undefined clear(); + SVGNumber initialize(SVGNumber newItem); + getter SVGNumber getItem(unsigned long index); + SVGNumber insertItemBefore(SVGNumber newItem, unsigned long index); + SVGNumber replaceItem(SVGNumber newItem, unsigned long index); + SVGNumber removeItem(unsigned long index); + SVGNumber appendItem(SVGNumber newItem); + setter undefined (unsigned long index, SVGNumber newItem); +}; + +[Exposed=Window] +interface SVGLengthList { + + readonly attribute unsigned long length; + readonly attribute unsigned long numberOfItems; + + undefined clear(); + SVGLength initialize(SVGLength newItem); + getter SVGLength getItem(unsigned long index); + SVGLength insertItemBefore(SVGLength newItem, unsigned long index); + SVGLength replaceItem(SVGLength newItem, unsigned long index); + SVGLength removeItem(unsigned long index); + SVGLength appendItem(SVGLength newItem); + setter undefined (unsigned long index, SVGLength newItem); +}; + +[Exposed=Window] +interface SVGStringList { + + readonly attribute unsigned long length; + readonly attribute unsigned long numberOfItems; + + undefined clear(); + DOMString initialize(DOMString newItem); + getter DOMString getItem(unsigned long index); + DOMString insertItemBefore(DOMString newItem, unsigned long index); + DOMString replaceItem(DOMString newItem, unsigned long index); + DOMString removeItem(unsigned long index); + DOMString appendItem(DOMString newItem); + setter undefined (unsigned long index, DOMString newItem); +}; + +[Exposed=Window] +interface SVGAnimatedBoolean { + attribute boolean baseVal; + readonly attribute boolean animVal; +}; + +[Exposed=Window] +interface SVGAnimatedEnumeration { + attribute unsigned short baseVal; + readonly attribute unsigned short animVal; +}; + +[Exposed=Window] +interface SVGAnimatedInteger { + attribute long baseVal; + readonly attribute long animVal; +}; + +[Exposed=Window] +interface SVGAnimatedNumber { + attribute float baseVal; + readonly attribute float animVal; +}; + +[Exposed=Window] +interface SVGAnimatedLength { + [SameObject] readonly attribute SVGLength baseVal; + [SameObject] readonly attribute SVGLength animVal; +}; + +[Exposed=Window] +interface SVGAnimatedAngle { + [SameObject] readonly attribute SVGAngle baseVal; + [SameObject] readonly attribute SVGAngle animVal; +}; + +[Exposed=Window] +interface SVGAnimatedString { + attribute DOMString baseVal; + readonly attribute DOMString animVal; +}; + +[Exposed=Window] +interface SVGAnimatedRect { + [SameObject] readonly attribute DOMRect baseVal; + [SameObject] readonly attribute DOMRectReadOnly animVal; +}; + +[Exposed=Window] +interface SVGAnimatedNumberList { + [SameObject] readonly attribute SVGNumberList baseVal; + [SameObject] readonly attribute SVGNumberList animVal; +}; + +[Exposed=Window] +interface SVGAnimatedLengthList { + [SameObject] readonly attribute SVGLengthList baseVal; + [SameObject] readonly attribute SVGLengthList animVal; +}; + +[Exposed=Window] +interface SVGUnitTypes { + // Unit Types + const unsigned short SVG_UNIT_TYPE_UNKNOWN = 0; + const unsigned short SVG_UNIT_TYPE_USERSPACEONUSE = 1; + const unsigned short SVG_UNIT_TYPE_OBJECTBOUNDINGBOX = 2; +}; + +interface mixin SVGTests { + [SameObject] readonly attribute SVGStringList requiredExtensions; + [SameObject] readonly attribute SVGStringList systemLanguage; +}; + +interface mixin SVGFitToViewBox { + [SameObject] readonly attribute SVGAnimatedRect viewBox; + [SameObject] readonly attribute SVGAnimatedPreserveAspectRatio preserveAspectRatio; +}; + +interface mixin SVGURIReference { + [SameObject] readonly attribute SVGAnimatedString href; +}; + +partial interface Document { + readonly attribute SVGSVGElement? rootElement; +}; + +[Exposed=Window] +interface SVGSVGElement : SVGGraphicsElement { + + [SameObject] readonly attribute SVGAnimatedLength x; + [SameObject] readonly attribute SVGAnimatedLength y; + [SameObject] readonly attribute SVGAnimatedLength width; + [SameObject] readonly attribute SVGAnimatedLength height; + + attribute float currentScale; + [SameObject] readonly attribute DOMPointReadOnly currentTranslate; + + NodeList getIntersectionList(DOMRectReadOnly rect, SVGElement? referenceElement); + NodeList getEnclosureList(DOMRectReadOnly rect, SVGElement? referenceElement); + boolean checkIntersection(SVGElement element, DOMRectReadOnly rect); + boolean checkEnclosure(SVGElement element, DOMRectReadOnly rect); + + undefined deselectAll(); + + SVGNumber createSVGNumber(); + SVGLength createSVGLength(); + SVGAngle createSVGAngle(); + DOMPoint createSVGPoint(); + DOMMatrix createSVGMatrix(); + DOMRect createSVGRect(); + SVGTransform createSVGTransform(); + SVGTransform createSVGTransformFromMatrix(optional DOMMatrix2DInit matrix = {}); + + Element getElementById(DOMString elementId); + + // Deprecated methods that have no effect when called, + // but which are kept for compatibility reasons. + unsigned long suspendRedraw(unsigned long maxWaitMilliseconds); + undefined unsuspendRedraw(unsigned long suspendHandleID); + undefined unsuspendRedrawAll(); + undefined forceRedraw(); +}; + +SVGSVGElement includes SVGFitToViewBox; +SVGSVGElement includes WindowEventHandlers; + +[Exposed=Window] +interface SVGGElement : SVGGraphicsElement { +}; + +[Exposed=Window] +interface SVGDefsElement : SVGGraphicsElement { +}; + +[Exposed=Window] +interface SVGDescElement : SVGElement { +}; + +[Exposed=Window] +interface SVGMetadataElement : SVGElement { +}; + +[Exposed=Window] +interface SVGTitleElement : SVGElement { +}; + +[Exposed=Window] +interface SVGSymbolElement : SVGGraphicsElement { +}; + +SVGSymbolElement includes SVGFitToViewBox; + +[Exposed=Window] +interface SVGUseElement : SVGGraphicsElement { + [SameObject] readonly attribute SVGAnimatedLength x; + [SameObject] readonly attribute SVGAnimatedLength y; + [SameObject] readonly attribute SVGAnimatedLength width; + [SameObject] readonly attribute SVGAnimatedLength height; + [SameObject] readonly attribute SVGElement? instanceRoot; + [SameObject] readonly attribute SVGElement? animatedInstanceRoot; +}; + +SVGUseElement includes SVGURIReference; + +[Exposed=Window] +interface SVGUseElementShadowRoot : ShadowRoot { +}; + +interface mixin SVGElementInstance { + [SameObject] readonly attribute SVGElement? correspondingElement; + [SameObject] readonly attribute SVGUseElement? correspondingUseElement; +}; + +[Exposed=Window] +interface ShadowAnimation : Animation { + constructor(Animation source, (Element or CSSPseudoElement) newTarget); + [SameObject] readonly attribute Animation sourceAnimation; +}; + +[Exposed=Window] +interface SVGSwitchElement : SVGGraphicsElement { +}; + +interface mixin GetSVGDocument { + Document getSVGDocument(); +}; + +[Exposed=Window] +interface SVGStyleElement : SVGElement { + attribute DOMString type; + attribute DOMString media; + attribute DOMString title; +}; + +SVGStyleElement includes LinkStyle; + +[Exposed=Window] +interface SVGTransform { + + // Transform Types + const unsigned short SVG_TRANSFORM_UNKNOWN = 0; + const unsigned short SVG_TRANSFORM_MATRIX = 1; + const unsigned short SVG_TRANSFORM_TRANSLATE = 2; + const unsigned short SVG_TRANSFORM_SCALE = 3; + const unsigned short SVG_TRANSFORM_ROTATE = 4; + const unsigned short SVG_TRANSFORM_SKEWX = 5; + const unsigned short SVG_TRANSFORM_SKEWY = 6; + + readonly attribute unsigned short type; + [SameObject] readonly attribute DOMMatrix matrix; + readonly attribute float angle; + + undefined setMatrix(optional DOMMatrix2DInit matrix = {}); + undefined setTranslate(float tx, float ty); + undefined setScale(float sx, float sy); + undefined setRotate(float angle, float cx, float cy); + undefined setSkewX(float angle); + undefined setSkewY(float angle); +}; + +[Exposed=Window] +interface SVGTransformList { + + readonly attribute unsigned long length; + readonly attribute unsigned long numberOfItems; + + undefined clear(); + SVGTransform initialize(SVGTransform newItem); + getter SVGTransform getItem(unsigned long index); + SVGTransform insertItemBefore(SVGTransform newItem, unsigned long index); + SVGTransform replaceItem(SVGTransform newItem, unsigned long index); + SVGTransform removeItem(unsigned long index); + SVGTransform appendItem(SVGTransform newItem); + setter undefined (unsigned long index, SVGTransform newItem); + + // Additional methods not common to other list interfaces. + SVGTransform createSVGTransformFromMatrix(optional DOMMatrix2DInit matrix = {}); + SVGTransform? consolidate(); +}; + +[Exposed=Window] +interface SVGAnimatedTransformList { + [SameObject] readonly attribute SVGTransformList baseVal; + [SameObject] readonly attribute SVGTransformList animVal; +}; + +[Exposed=Window] +interface SVGPreserveAspectRatio { + + // Alignment Types + const unsigned short SVG_PRESERVEASPECTRATIO_UNKNOWN = 0; + const unsigned short SVG_PRESERVEASPECTRATIO_NONE = 1; + const unsigned short SVG_PRESERVEASPECTRATIO_XMINYMIN = 2; + const unsigned short SVG_PRESERVEASPECTRATIO_XMIDYMIN = 3; + const unsigned short SVG_PRESERVEASPECTRATIO_XMAXYMIN = 4; + const unsigned short SVG_PRESERVEASPECTRATIO_XMINYMID = 5; + const unsigned short SVG_PRESERVEASPECTRATIO_XMIDYMID = 6; + const unsigned short SVG_PRESERVEASPECTRATIO_XMAXYMID = 7; + const unsigned short SVG_PRESERVEASPECTRATIO_XMINYMAX = 8; + const unsigned short SVG_PRESERVEASPECTRATIO_XMIDYMAX = 9; + const unsigned short SVG_PRESERVEASPECTRATIO_XMAXYMAX = 10; + + // Meet-or-slice Types + const unsigned short SVG_MEETORSLICE_UNKNOWN = 0; + const unsigned short SVG_MEETORSLICE_MEET = 1; + const unsigned short SVG_MEETORSLICE_SLICE = 2; + + attribute unsigned short align; + attribute unsigned short meetOrSlice; +}; + +[Exposed=Window] +interface SVGAnimatedPreserveAspectRatio { + [SameObject] readonly attribute SVGPreserveAspectRatio baseVal; + [SameObject] readonly attribute SVGPreserveAspectRatio animVal; +}; + +[Exposed=Window] +interface SVGPathElement : SVGGeometryElement { +}; + +[Exposed=Window] +interface SVGRectElement : SVGGeometryElement { + [SameObject] readonly attribute SVGAnimatedLength x; + [SameObject] readonly attribute SVGAnimatedLength y; + [SameObject] readonly attribute SVGAnimatedLength width; + [SameObject] readonly attribute SVGAnimatedLength height; + [SameObject] readonly attribute SVGAnimatedLength rx; + [SameObject] readonly attribute SVGAnimatedLength ry; +}; + +[Exposed=Window] +interface SVGCircleElement : SVGGeometryElement { + [SameObject] readonly attribute SVGAnimatedLength cx; + [SameObject] readonly attribute SVGAnimatedLength cy; + [SameObject] readonly attribute SVGAnimatedLength r; +}; + +[Exposed=Window] +interface SVGEllipseElement : SVGGeometryElement { + [SameObject] readonly attribute SVGAnimatedLength cx; + [SameObject] readonly attribute SVGAnimatedLength cy; + [SameObject] readonly attribute SVGAnimatedLength rx; + [SameObject] readonly attribute SVGAnimatedLength ry; +}; + +[Exposed=Window] +interface SVGLineElement : SVGGeometryElement { + [SameObject] readonly attribute SVGAnimatedLength x1; + [SameObject] readonly attribute SVGAnimatedLength y1; + [SameObject] readonly attribute SVGAnimatedLength x2; + [SameObject] readonly attribute SVGAnimatedLength y2; +}; + +interface mixin SVGAnimatedPoints { + [SameObject] readonly attribute SVGPointList points; + [SameObject] readonly attribute SVGPointList animatedPoints; +}; + +[Exposed=Window] +interface SVGPointList { + + readonly attribute unsigned long length; + readonly attribute unsigned long numberOfItems; + + undefined clear(); + DOMPoint initialize(DOMPoint newItem); + getter DOMPoint getItem(unsigned long index); + DOMPoint insertItemBefore(DOMPoint newItem, unsigned long index); + DOMPoint replaceItem(DOMPoint newItem, unsigned long index); + DOMPoint removeItem(unsigned long index); + DOMPoint appendItem(DOMPoint newItem); + setter undefined (unsigned long index, DOMPoint newItem); +}; + +[Exposed=Window] +interface SVGPolylineElement : SVGGeometryElement { +}; + +SVGPolylineElement includes SVGAnimatedPoints; + +[Exposed=Window] +interface SVGPolygonElement : SVGGeometryElement { +}; + +SVGPolygonElement includes SVGAnimatedPoints; + +[Exposed=Window] +interface SVGTextContentElement : SVGGraphicsElement { + + // lengthAdjust Types + const unsigned short LENGTHADJUST_UNKNOWN = 0; + const unsigned short LENGTHADJUST_SPACING = 1; + const unsigned short LENGTHADJUST_SPACINGANDGLYPHS = 2; + + [SameObject] readonly attribute SVGAnimatedLength textLength; + [SameObject] readonly attribute SVGAnimatedEnumeration lengthAdjust; + + long getNumberOfChars(); + float getComputedTextLength(); + float getSubStringLength(unsigned long charnum, unsigned long nchars); + DOMPoint getStartPositionOfChar(unsigned long charnum); + DOMPoint getEndPositionOfChar(unsigned long charnum); + DOMRect getExtentOfChar(unsigned long charnum); + float getRotationOfChar(unsigned long charnum); + long getCharNumAtPosition(optional DOMPointInit point = {}); + undefined selectSubString(unsigned long charnum, unsigned long nchars); +}; + +[Exposed=Window] +interface SVGTextPositioningElement : SVGTextContentElement { + [SameObject] readonly attribute SVGAnimatedLengthList x; + [SameObject] readonly attribute SVGAnimatedLengthList y; + [SameObject] readonly attribute SVGAnimatedLengthList dx; + [SameObject] readonly attribute SVGAnimatedLengthList dy; + [SameObject] readonly attribute SVGAnimatedNumberList rotate; +}; + +[Exposed=Window] +interface SVGTextElement : SVGTextPositioningElement { +}; + +[Exposed=Window] +interface SVGTSpanElement : SVGTextPositioningElement { +}; + +[Exposed=Window] +interface SVGTextPathElement : SVGTextContentElement { + + // textPath Method Types + const unsigned short TEXTPATH_METHODTYPE_UNKNOWN = 0; + const unsigned short TEXTPATH_METHODTYPE_ALIGN = 1; + const unsigned short TEXTPATH_METHODTYPE_STRETCH = 2; + + // textPath Spacing Types + const unsigned short TEXTPATH_SPACINGTYPE_UNKNOWN = 0; + const unsigned short TEXTPATH_SPACINGTYPE_AUTO = 1; + const unsigned short TEXTPATH_SPACINGTYPE_EXACT = 2; + + [SameObject] readonly attribute SVGAnimatedLength startOffset; + [SameObject] readonly attribute SVGAnimatedEnumeration method; + [SameObject] readonly attribute SVGAnimatedEnumeration spacing; +}; + +SVGTextPathElement includes SVGURIReference; + +[Exposed=Window] +interface SVGImageElement : SVGGraphicsElement { + [SameObject] readonly attribute SVGAnimatedLength x; + [SameObject] readonly attribute SVGAnimatedLength y; + [SameObject] readonly attribute SVGAnimatedLength width; + [SameObject] readonly attribute SVGAnimatedLength height; + [SameObject] readonly attribute SVGAnimatedPreserveAspectRatio preserveAspectRatio; + attribute DOMString? crossOrigin; +}; + +SVGImageElement includes SVGURIReference; + +[Exposed=Window] +interface SVGForeignObjectElement : SVGGraphicsElement { + [SameObject] readonly attribute SVGAnimatedLength x; + [SameObject] readonly attribute SVGAnimatedLength y; + [SameObject] readonly attribute SVGAnimatedLength width; + [SameObject] readonly attribute SVGAnimatedLength height; +}; + +[Exposed=Window] +interface SVGMarkerElement : SVGElement { + + // Marker Unit Types + const unsigned short SVG_MARKERUNITS_UNKNOWN = 0; + const unsigned short SVG_MARKERUNITS_USERSPACEONUSE = 1; + const unsigned short SVG_MARKERUNITS_STROKEWIDTH = 2; + + // Marker Orientation Types + const unsigned short SVG_MARKER_ORIENT_UNKNOWN = 0; + const unsigned short SVG_MARKER_ORIENT_AUTO = 1; + const unsigned short SVG_MARKER_ORIENT_ANGLE = 2; + + [SameObject] readonly attribute SVGAnimatedLength refX; + [SameObject] readonly attribute SVGAnimatedLength refY; + [SameObject] readonly attribute SVGAnimatedEnumeration markerUnits; + [SameObject] readonly attribute SVGAnimatedLength markerWidth; + [SameObject] readonly attribute SVGAnimatedLength markerHeight; + [SameObject] readonly attribute SVGAnimatedEnumeration orientType; + [SameObject] readonly attribute SVGAnimatedAngle orientAngle; + attribute DOMString orient; + + undefined setOrientToAuto(); + undefined setOrientToAngle(SVGAngle angle); +}; + +SVGMarkerElement includes SVGFitToViewBox; + +[Exposed=Window] +interface SVGGradientElement : SVGElement { + + // Spread Method Types + const unsigned short SVG_SPREADMETHOD_UNKNOWN = 0; + const unsigned short SVG_SPREADMETHOD_PAD = 1; + const unsigned short SVG_SPREADMETHOD_REFLECT = 2; + const unsigned short SVG_SPREADMETHOD_REPEAT = 3; + + [SameObject] readonly attribute SVGAnimatedEnumeration gradientUnits; + [SameObject] readonly attribute SVGAnimatedTransformList gradientTransform; + [SameObject] readonly attribute SVGAnimatedEnumeration spreadMethod; +}; + +SVGGradientElement includes SVGURIReference; + +[Exposed=Window] +interface SVGLinearGradientElement : SVGGradientElement { + [SameObject] readonly attribute SVGAnimatedLength x1; + [SameObject] readonly attribute SVGAnimatedLength y1; + [SameObject] readonly attribute SVGAnimatedLength x2; + [SameObject] readonly attribute SVGAnimatedLength y2; +}; + +[Exposed=Window] +interface SVGRadialGradientElement : SVGGradientElement { + [SameObject] readonly attribute SVGAnimatedLength cx; + [SameObject] readonly attribute SVGAnimatedLength cy; + [SameObject] readonly attribute SVGAnimatedLength r; + [SameObject] readonly attribute SVGAnimatedLength fx; + [SameObject] readonly attribute SVGAnimatedLength fy; + [SameObject] readonly attribute SVGAnimatedLength fr; +}; + +[Exposed=Window] +interface SVGStopElement : SVGElement { + [SameObject] readonly attribute SVGAnimatedNumber offset; +}; + +[Exposed=Window] +interface SVGPatternElement : SVGElement { + [SameObject] readonly attribute SVGAnimatedEnumeration patternUnits; + [SameObject] readonly attribute SVGAnimatedEnumeration patternContentUnits; + [SameObject] readonly attribute SVGAnimatedTransformList patternTransform; + [SameObject] readonly attribute SVGAnimatedLength x; + [SameObject] readonly attribute SVGAnimatedLength y; + [SameObject] readonly attribute SVGAnimatedLength width; + [SameObject] readonly attribute SVGAnimatedLength height; +}; + +SVGPatternElement includes SVGFitToViewBox; +SVGPatternElement includes SVGURIReference; + +[Exposed=Window] +interface SVGScriptElement : SVGElement { + attribute DOMString type; + attribute DOMString? crossOrigin; +}; + +SVGScriptElement includes SVGURIReference; + +[Exposed=Window] +interface SVGAElement : SVGGraphicsElement { + [SameObject] readonly attribute SVGAnimatedString target; + attribute DOMString download; + attribute USVString ping; + attribute DOMString rel; + [SameObject, PutForwards=value] readonly attribute DOMTokenList relList; + attribute DOMString hreflang; + attribute DOMString type; + + attribute DOMString text; + + attribute DOMString referrerPolicy; +}; + +SVGAElement includes SVGURIReference; + +// Inline HTMLHyperlinkElementUtils except href, which conflicts. +partial interface SVGAElement { + readonly attribute USVString origin; + [CEReactions] attribute USVString protocol; + [CEReactions] attribute USVString username; + [CEReactions] attribute USVString password; + [CEReactions] attribute USVString host; + [CEReactions] attribute USVString hostname; + [CEReactions] attribute USVString port; + [CEReactions] attribute USVString pathname; + [CEReactions] attribute USVString search; + [CEReactions] attribute USVString hash; +}; + +[Exposed=Window] +interface SVGViewElement : SVGElement {}; + +SVGViewElement includes SVGFitToViewBox; diff --git a/test/wpt/tests/interfaces/WEBGL_blend_equation_advanced_coherent.idl b/test/wpt/tests/interfaces/WEBGL_blend_equation_advanced_coherent.idl new file mode 100644 index 0000000..2208329 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_blend_equation_advanced_coherent.idl @@ -0,0 +1,23 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_blend_equation_advanced_coherent Extension Draft Specification (https://registry.khronos.org/webgl/extensions/WEBGL_blend_equation_advanced_coherent/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_blend_equation_advanced_coherent { + const GLenum MULTIPLY = 0x9294; + const GLenum SCREEN = 0x9295; + const GLenum OVERLAY = 0x9296; + const GLenum DARKEN = 0x9297; + const GLenum LIGHTEN = 0x9298; + const GLenum COLORDODGE = 0x9299; + const GLenum COLORBURN = 0x929A; + const GLenum HARDLIGHT = 0x929B; + const GLenum SOFTLIGHT = 0x929C; + const GLenum DIFFERENCE = 0x929E; + const GLenum EXCLUSION = 0x92A0; + const GLenum HSL_HUE = 0x92AD; + const GLenum HSL_SATURATION = 0x92AE; + const GLenum HSL_COLOR = 0x92AF; + const GLenum HSL_LUMINOSITY = 0x92B0; +}; diff --git a/test/wpt/tests/interfaces/WEBGL_clip_cull_distance.idl b/test/wpt/tests/interfaces/WEBGL_clip_cull_distance.idl new file mode 100644 index 0000000..46fa921 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_clip_cull_distance.idl @@ -0,0 +1,20 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_clip_cull_distance Extension Draft Specification (https://registry.khronos.org/webgl/extensions/WEBGL_clip_cull_distance/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_clip_cull_distance { + const GLenum MAX_CLIP_DISTANCES_WEBGL = 0x0D32; + const GLenum MAX_CULL_DISTANCES_WEBGL = 0x82F9; + const GLenum MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL = 0x82FA; + + const GLenum CLIP_DISTANCE0_WEBGL = 0x3000; + const GLenum CLIP_DISTANCE1_WEBGL = 0x3001; + const GLenum CLIP_DISTANCE2_WEBGL = 0x3002; + const GLenum CLIP_DISTANCE3_WEBGL = 0x3003; + const GLenum CLIP_DISTANCE4_WEBGL = 0x3004; + const GLenum CLIP_DISTANCE5_WEBGL = 0x3005; + const GLenum CLIP_DISTANCE6_WEBGL = 0x3006; + const GLenum CLIP_DISTANCE7_WEBGL = 0x3007; +}; diff --git a/test/wpt/tests/interfaces/WEBGL_color_buffer_float.idl b/test/wpt/tests/interfaces/WEBGL_color_buffer_float.idl new file mode 100644 index 0000000..b73f631 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_color_buffer_float.idl @@ -0,0 +1,11 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_color_buffer_float Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_color_buffer_float/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_color_buffer_float { + const GLenum RGBA32F_EXT = 0x8814; + const GLenum FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT = 0x8211; + const GLenum UNSIGNED_NORMALIZED_EXT = 0x8C17; +}; // interface WEBGL_color_buffer_float diff --git a/test/wpt/tests/interfaces/WEBGL_compressed_texture_astc.idl b/test/wpt/tests/interfaces/WEBGL_compressed_texture_astc.idl new file mode 100644 index 0000000..9e4632f --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_compressed_texture_astc.idl @@ -0,0 +1,41 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_compressed_texture_astc Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_compressed_texture_astc { + /* Compressed Texture Format */ + const GLenum COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93B0; + const GLenum COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93B1; + const GLenum COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93B2; + const GLenum COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93B3; + const GLenum COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93B4; + const GLenum COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93B5; + const GLenum COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93B6; + const GLenum COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93B7; + const GLenum COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93B8; + const GLenum COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93B9; + const GLenum COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93BA; + const GLenum COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93BB; + const GLenum COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93BC; + const GLenum COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93BD; + + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93D0; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93D1; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93D2; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93D3; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93D4; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93D5; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93D6; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93D7; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93D8; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93D9; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93DA; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93DB; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93DC; + const GLenum COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93DD; + + // Profile query support. + sequence getSupportedProfiles(); +}; diff --git a/test/wpt/tests/interfaces/WEBGL_compressed_texture_etc.idl b/test/wpt/tests/interfaces/WEBGL_compressed_texture_etc.idl new file mode 100644 index 0000000..5174a08 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_compressed_texture_etc.idl @@ -0,0 +1,19 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_compressed_texture_etc Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_compressed_texture_etc { + /* Compressed Texture Formats */ + const GLenum COMPRESSED_R11_EAC = 0x9270; + const GLenum COMPRESSED_SIGNED_R11_EAC = 0x9271; + const GLenum COMPRESSED_RG11_EAC = 0x9272; + const GLenum COMPRESSED_SIGNED_RG11_EAC = 0x9273; + const GLenum COMPRESSED_RGB8_ETC2 = 0x9274; + const GLenum COMPRESSED_SRGB8_ETC2 = 0x9275; + const GLenum COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276; + const GLenum COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277; + const GLenum COMPRESSED_RGBA8_ETC2_EAC = 0x9278; + const GLenum COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279; +}; diff --git a/test/wpt/tests/interfaces/WEBGL_compressed_texture_etc1.idl b/test/wpt/tests/interfaces/WEBGL_compressed_texture_etc1.idl new file mode 100644 index 0000000..773697e --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_compressed_texture_etc1.idl @@ -0,0 +1,10 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_compressed_texture_etc1 Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc1/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_compressed_texture_etc1 { + /* Compressed Texture Format */ + const GLenum COMPRESSED_RGB_ETC1_WEBGL = 0x8D64; +}; diff --git a/test/wpt/tests/interfaces/WEBGL_compressed_texture_pvrtc.idl b/test/wpt/tests/interfaces/WEBGL_compressed_texture_pvrtc.idl new file mode 100644 index 0000000..5aa004a --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_compressed_texture_pvrtc.idl @@ -0,0 +1,13 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_compressed_texture_pvrtc Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_compressed_texture_pvrtc { + /* Compressed Texture Formats */ + const GLenum COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00; + const GLenum COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8C01; + const GLenum COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8C02; + const GLenum COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03; +}; diff --git a/test/wpt/tests/interfaces/WEBGL_compressed_texture_s3tc.idl b/test/wpt/tests/interfaces/WEBGL_compressed_texture_s3tc.idl new file mode 100644 index 0000000..6e7c4bd --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_compressed_texture_s3tc.idl @@ -0,0 +1,13 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_compressed_texture_s3tc Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_compressed_texture_s3tc { + /* Compressed Texture Formats */ + const GLenum COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0; + const GLenum COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1; + const GLenum COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2; + const GLenum COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3; +}; diff --git a/test/wpt/tests/interfaces/WEBGL_compressed_texture_s3tc_srgb.idl b/test/wpt/tests/interfaces/WEBGL_compressed_texture_s3tc_srgb.idl new file mode 100644 index 0000000..809265e --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_compressed_texture_s3tc_srgb.idl @@ -0,0 +1,13 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_compressed_texture_s3tc_srgb Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_compressed_texture_s3tc_srgb { + /* Compressed Texture Formats */ + const GLenum COMPRESSED_SRGB_S3TC_DXT1_EXT = 0x8C4C; + const GLenum COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 0x8C4D; + const GLenum COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 0x8C4E; + const GLenum COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 0x8C4F; +}; diff --git a/test/wpt/tests/interfaces/WEBGL_debug_renderer_info.idl b/test/wpt/tests/interfaces/WEBGL_debug_renderer_info.idl new file mode 100644 index 0000000..7694061 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_debug_renderer_info.idl @@ -0,0 +1,12 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_debug_renderer_info Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_debug_renderer_info/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_debug_renderer_info { + + const GLenum UNMASKED_VENDOR_WEBGL = 0x9245; + const GLenum UNMASKED_RENDERER_WEBGL = 0x9246; + +}; diff --git a/test/wpt/tests/interfaces/WEBGL_debug_shaders.idl b/test/wpt/tests/interfaces/WEBGL_debug_shaders.idl new file mode 100644 index 0000000..ecb48d0 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_debug_shaders.idl @@ -0,0 +1,11 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_debug_shaders Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_debug_shaders/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_debug_shaders { + + DOMString getTranslatedShaderSource(WebGLShader shader); + +}; diff --git a/test/wpt/tests/interfaces/WEBGL_depth_texture.idl b/test/wpt/tests/interfaces/WEBGL_depth_texture.idl new file mode 100644 index 0000000..a9ec791 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_depth_texture.idl @@ -0,0 +1,9 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_depth_texture Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_depth_texture/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_depth_texture { + const GLenum UNSIGNED_INT_24_8_WEBGL = 0x84FA; +}; diff --git a/test/wpt/tests/interfaces/WEBGL_draw_buffers.idl b/test/wpt/tests/interfaces/WEBGL_draw_buffers.idl new file mode 100644 index 0000000..3310388 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_draw_buffers.idl @@ -0,0 +1,46 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_draw_buffers Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_draw_buffers/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_draw_buffers { + const GLenum COLOR_ATTACHMENT0_WEBGL = 0x8CE0; + const GLenum COLOR_ATTACHMENT1_WEBGL = 0x8CE1; + const GLenum COLOR_ATTACHMENT2_WEBGL = 0x8CE2; + const GLenum COLOR_ATTACHMENT3_WEBGL = 0x8CE3; + const GLenum COLOR_ATTACHMENT4_WEBGL = 0x8CE4; + const GLenum COLOR_ATTACHMENT5_WEBGL = 0x8CE5; + const GLenum COLOR_ATTACHMENT6_WEBGL = 0x8CE6; + const GLenum COLOR_ATTACHMENT7_WEBGL = 0x8CE7; + const GLenum COLOR_ATTACHMENT8_WEBGL = 0x8CE8; + const GLenum COLOR_ATTACHMENT9_WEBGL = 0x8CE9; + const GLenum COLOR_ATTACHMENT10_WEBGL = 0x8CEA; + const GLenum COLOR_ATTACHMENT11_WEBGL = 0x8CEB; + const GLenum COLOR_ATTACHMENT12_WEBGL = 0x8CEC; + const GLenum COLOR_ATTACHMENT13_WEBGL = 0x8CED; + const GLenum COLOR_ATTACHMENT14_WEBGL = 0x8CEE; + const GLenum COLOR_ATTACHMENT15_WEBGL = 0x8CEF; + + const GLenum DRAW_BUFFER0_WEBGL = 0x8825; + const GLenum DRAW_BUFFER1_WEBGL = 0x8826; + const GLenum DRAW_BUFFER2_WEBGL = 0x8827; + const GLenum DRAW_BUFFER3_WEBGL = 0x8828; + const GLenum DRAW_BUFFER4_WEBGL = 0x8829; + const GLenum DRAW_BUFFER5_WEBGL = 0x882A; + const GLenum DRAW_BUFFER6_WEBGL = 0x882B; + const GLenum DRAW_BUFFER7_WEBGL = 0x882C; + const GLenum DRAW_BUFFER8_WEBGL = 0x882D; + const GLenum DRAW_BUFFER9_WEBGL = 0x882E; + const GLenum DRAW_BUFFER10_WEBGL = 0x882F; + const GLenum DRAW_BUFFER11_WEBGL = 0x8830; + const GLenum DRAW_BUFFER12_WEBGL = 0x8831; + const GLenum DRAW_BUFFER13_WEBGL = 0x8832; + const GLenum DRAW_BUFFER14_WEBGL = 0x8833; + const GLenum DRAW_BUFFER15_WEBGL = 0x8834; + + const GLenum MAX_COLOR_ATTACHMENTS_WEBGL = 0x8CDF; + const GLenum MAX_DRAW_BUFFERS_WEBGL = 0x8824; + + undefined drawBuffersWEBGL(sequence buffers); +}; diff --git a/test/wpt/tests/interfaces/WEBGL_draw_instanced_base_vertex_base_instance.idl b/test/wpt/tests/interfaces/WEBGL_draw_instanced_base_vertex_base_instance.idl new file mode 100644 index 0000000..38f7a42 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_draw_instanced_base_vertex_base_instance.idl @@ -0,0 +1,14 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_draw_instanced_base_vertex_base_instance Extension Draft Specification (https://registry.khronos.org/webgl/extensions/WEBGL_draw_instanced_base_vertex_base_instance/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_draw_instanced_base_vertex_base_instance { + undefined drawArraysInstancedBaseInstanceWEBGL( + GLenum mode, GLint first, GLsizei count, + GLsizei instanceCount, GLuint baseInstance); + undefined drawElementsInstancedBaseVertexBaseInstanceWEBGL( + GLenum mode, GLsizei count, GLenum type, GLintptr offset, + GLsizei instanceCount, GLint baseVertex, GLuint baseInstance); +}; diff --git a/test/wpt/tests/interfaces/WEBGL_lose_context.idl b/test/wpt/tests/interfaces/WEBGL_lose_context.idl new file mode 100644 index 0000000..ee68fb5 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_lose_context.idl @@ -0,0 +1,10 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_lose_context Khronos Ratified Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_lose_context/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_lose_context { + undefined loseContext(); + undefined restoreContext(); +}; diff --git a/test/wpt/tests/interfaces/WEBGL_multi_draw.idl b/test/wpt/tests/interfaces/WEBGL_multi_draw.idl new file mode 100644 index 0000000..ee8c044 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_multi_draw.idl @@ -0,0 +1,32 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_multi_draw Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_multi_draw/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_multi_draw { + undefined multiDrawArraysWEBGL( + GLenum mode, + ([AllowShared] Int32Array or sequence) firstsList, GLuint firstsOffset, + ([AllowShared] Int32Array or sequence) countsList, GLuint countsOffset, + GLsizei drawcount); + undefined multiDrawElementsWEBGL( + GLenum mode, + ([AllowShared] Int32Array or sequence) countsList, GLuint countsOffset, + GLenum type, + ([AllowShared] Int32Array or sequence) offsetsList, GLuint offsetsOffset, + GLsizei drawcount); + undefined multiDrawArraysInstancedWEBGL( + GLenum mode, + ([AllowShared] Int32Array or sequence) firstsList, GLuint firstsOffset, + ([AllowShared] Int32Array or sequence) countsList, GLuint countsOffset, + ([AllowShared] Int32Array or sequence) instanceCountsList, GLuint instanceCountsOffset, + GLsizei drawcount); + undefined multiDrawElementsInstancedWEBGL( + GLenum mode, + ([AllowShared] Int32Array or sequence) countsList, GLuint countsOffset, + GLenum type, + ([AllowShared] Int32Array or sequence) offsetsList, GLuint offsetsOffset, + ([AllowShared] Int32Array or sequence) instanceCountsList, GLuint instanceCountsOffset, + GLsizei drawcount); +}; diff --git a/test/wpt/tests/interfaces/WEBGL_multi_draw_instanced_base_vertex_base_instance.idl b/test/wpt/tests/interfaces/WEBGL_multi_draw_instanced_base_vertex_base_instance.idl new file mode 100644 index 0000000..2258fa9 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_multi_draw_instanced_base_vertex_base_instance.idl @@ -0,0 +1,26 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_multi_draw_instanced_base_vertex_base_instance Extension Draft Specification (https://registry.khronos.org/webgl/extensions/WEBGL_multi_draw_instanced_base_vertex_base_instance/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_multi_draw_instanced_base_vertex_base_instance { + undefined multiDrawArraysInstancedBaseInstanceWEBGL( + GLenum mode, + ([AllowShared] Int32Array or sequence) firstsList, GLuint firstsOffset, + ([AllowShared] Int32Array or sequence) countsList, GLuint countsOffset, + ([AllowShared] Int32Array or sequence) instanceCountsList, GLuint instanceCountsOffset, + ([AllowShared] Uint32Array or sequence) baseInstancesList, GLuint baseInstancesOffset, + GLsizei drawcount + ); + undefined multiDrawElementsInstancedBaseVertexBaseInstanceWEBGL( + GLenum mode, + ([AllowShared] Int32Array or sequence) countsList, GLuint countsOffset, + GLenum type, + ([AllowShared] Int32Array or sequence) offsetsList, GLuint offsetsOffset, + ([AllowShared] Int32Array or sequence) instanceCountsList, GLuint instanceCountsOffset, + ([AllowShared] Int32Array or sequence) baseVerticesList, GLuint baseVerticesOffset, + ([AllowShared] Uint32Array or sequence) baseInstancesList, GLuint baseInstancesOffset, + GLsizei drawcount + ); +}; diff --git a/test/wpt/tests/interfaces/WEBGL_provoking_vertex.idl b/test/wpt/tests/interfaces/WEBGL_provoking_vertex.idl new file mode 100644 index 0000000..035e1d2 --- /dev/null +++ b/test/wpt/tests/interfaces/WEBGL_provoking_vertex.idl @@ -0,0 +1,13 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebGL WEBGL_provoking_vertex Extension Specification (https://registry.khronos.org/webgl/extensions/WEBGL_provoking_vertex/) + +[Exposed=(Window,Worker), LegacyNoInterfaceObject] +interface WEBGL_provoking_vertex { + const GLenum FIRST_VERTEX_CONVENTION_WEBGL = 0x8E4D; + const GLenum LAST_VERTEX_CONVENTION_WEBGL = 0x8E4E; // default + const GLenum PROVOKING_VERTEX_WEBGL = 0x8E4F; + + undefined provokingVertexWEBGL(GLenum provokeMode); +}; diff --git a/test/wpt/tests/interfaces/WebCryptoAPI.idl b/test/wpt/tests/interfaces/WebCryptoAPI.idl new file mode 100644 index 0000000..0e68ea8 --- /dev/null +++ b/test/wpt/tests/interfaces/WebCryptoAPI.idl @@ -0,0 +1,237 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Web Cryptography API (https://w3c.github.io/webcrypto/) + +partial interface mixin WindowOrWorkerGlobalScope { + [SameObject] readonly attribute Crypto crypto; +}; + +[Exposed=(Window,Worker)] +interface Crypto { + [SecureContext] readonly attribute SubtleCrypto subtle; + ArrayBufferView getRandomValues(ArrayBufferView array); + [SecureContext] DOMString randomUUID(); +}; + +typedef (object or DOMString) AlgorithmIdentifier; + +typedef AlgorithmIdentifier HashAlgorithmIdentifier; + +dictionary Algorithm { + required DOMString name; +}; + +dictionary KeyAlgorithm { + required DOMString name; +}; + +enum KeyType { "public", "private", "secret" }; + +enum KeyUsage { "encrypt", "decrypt", "sign", "verify", "deriveKey", "deriveBits", "wrapKey", "unwrapKey" }; + +[SecureContext,Exposed=(Window,Worker),Serializable] +interface CryptoKey { + readonly attribute KeyType type; + readonly attribute boolean extractable; + readonly attribute object algorithm; + readonly attribute object usages; +}; + +enum KeyFormat { "raw", "spki", "pkcs8", "jwk" }; + +[SecureContext,Exposed=(Window,Worker)] +interface SubtleCrypto { + Promise encrypt(AlgorithmIdentifier algorithm, + CryptoKey key, + BufferSource data); + Promise decrypt(AlgorithmIdentifier algorithm, + CryptoKey key, + BufferSource data); + Promise sign(AlgorithmIdentifier algorithm, + CryptoKey key, + BufferSource data); + Promise verify(AlgorithmIdentifier algorithm, + CryptoKey key, + BufferSource signature, + BufferSource data); + Promise digest(AlgorithmIdentifier algorithm, + BufferSource data); + + Promise generateKey(AlgorithmIdentifier algorithm, + boolean extractable, + sequence keyUsages ); + Promise deriveKey(AlgorithmIdentifier algorithm, + CryptoKey baseKey, + AlgorithmIdentifier derivedKeyType, + boolean extractable, + sequence keyUsages ); + Promise deriveBits(AlgorithmIdentifier algorithm, + CryptoKey baseKey, + unsigned long length); + + Promise importKey(KeyFormat format, + (BufferSource or JsonWebKey) keyData, + AlgorithmIdentifier algorithm, + boolean extractable, + sequence keyUsages ); + Promise exportKey(KeyFormat format, CryptoKey key); + + Promise wrapKey(KeyFormat format, + CryptoKey key, + CryptoKey wrappingKey, + AlgorithmIdentifier wrapAlgorithm); + Promise unwrapKey(KeyFormat format, + BufferSource wrappedKey, + CryptoKey unwrappingKey, + AlgorithmIdentifier unwrapAlgorithm, + AlgorithmIdentifier unwrappedKeyAlgorithm, + boolean extractable, + sequence keyUsages ); +}; + +dictionary RsaOtherPrimesInfo { + // The following fields are defined in Section 6.3.2.7 of JSON Web Algorithms + DOMString r; + DOMString d; + DOMString t; +}; + +dictionary JsonWebKey { + // The following fields are defined in Section 3.1 of JSON Web Key + DOMString kty; + DOMString use; + sequence key_ops; + DOMString alg; + + // The following fields are defined in JSON Web Key Parameters Registration + boolean ext; + + // The following fields are defined in Section 6 of JSON Web Algorithms + DOMString crv; + DOMString x; + DOMString y; + DOMString d; + DOMString n; + DOMString e; + DOMString p; + DOMString q; + DOMString dp; + DOMString dq; + DOMString qi; + sequence oth; + DOMString k; +}; + +typedef Uint8Array BigInteger; + +dictionary CryptoKeyPair { + CryptoKey publicKey; + CryptoKey privateKey; +}; + +dictionary RsaKeyGenParams : Algorithm { + required [EnforceRange] unsigned long modulusLength; + required BigInteger publicExponent; +}; + +dictionary RsaHashedKeyGenParams : RsaKeyGenParams { + required HashAlgorithmIdentifier hash; +}; + +dictionary RsaKeyAlgorithm : KeyAlgorithm { + required unsigned long modulusLength; + required BigInteger publicExponent; +}; + +dictionary RsaHashedKeyAlgorithm : RsaKeyAlgorithm { + required KeyAlgorithm hash; +}; + +dictionary RsaHashedImportParams : Algorithm { + required HashAlgorithmIdentifier hash; +}; + +dictionary RsaPssParams : Algorithm { + required [EnforceRange] unsigned long saltLength; +}; + +dictionary RsaOaepParams : Algorithm { + BufferSource label; +}; + +dictionary EcdsaParams : Algorithm { + required HashAlgorithmIdentifier hash; +}; + +typedef DOMString NamedCurve; + +dictionary EcKeyGenParams : Algorithm { + required NamedCurve namedCurve; +}; + +dictionary EcKeyAlgorithm : KeyAlgorithm { + required NamedCurve namedCurve; +}; + +dictionary EcKeyImportParams : Algorithm { + required NamedCurve namedCurve; +}; + +dictionary EcdhKeyDeriveParams : Algorithm { + required CryptoKey public; +}; + +dictionary AesCtrParams : Algorithm { + required BufferSource counter; + required [EnforceRange] octet length; +}; + +dictionary AesKeyAlgorithm : KeyAlgorithm { + required unsigned short length; +}; + +dictionary AesKeyGenParams : Algorithm { + required [EnforceRange] unsigned short length; +}; + +dictionary AesDerivedKeyParams : Algorithm { + required [EnforceRange] unsigned short length; +}; + +dictionary AesCbcParams : Algorithm { + required BufferSource iv; +}; + +dictionary AesGcmParams : Algorithm { + required BufferSource iv; + BufferSource additionalData; + [EnforceRange] octet tagLength; +}; + +dictionary HmacImportParams : Algorithm { + required HashAlgorithmIdentifier hash; + [EnforceRange] unsigned long length; +}; + +dictionary HmacKeyAlgorithm : KeyAlgorithm { + required KeyAlgorithm hash; + required unsigned long length; +}; + +dictionary HmacKeyGenParams : Algorithm { + required HashAlgorithmIdentifier hash; + [EnforceRange] unsigned long length; +}; + +dictionary HkdfParams : Algorithm { + required HashAlgorithmIdentifier hash; + required BufferSource salt; + required BufferSource info; +}; + +dictionary Pbkdf2Params : Algorithm { + required BufferSource salt; + required [EnforceRange] unsigned long iterations; + required HashAlgorithmIdentifier hash; +}; diff --git a/test/wpt/tests/interfaces/accelerometer.idl b/test/wpt/tests/interfaces/accelerometer.idl new file mode 100644 index 0000000..fc8fc07 --- /dev/null +++ b/test/wpt/tests/interfaces/accelerometer.idl @@ -0,0 +1,40 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Accelerometer (https://w3c.github.io/accelerometer/) + +[SecureContext, Exposed=Window] +interface Accelerometer : Sensor { + constructor(optional AccelerometerSensorOptions options = {}); + readonly attribute double? x; + readonly attribute double? y; + readonly attribute double? z; +}; + +enum AccelerometerLocalCoordinateSystem { "device", "screen" }; + +dictionary AccelerometerSensorOptions : SensorOptions { + AccelerometerLocalCoordinateSystem referenceFrame = "device"; +}; + +[SecureContext, Exposed=Window] +interface LinearAccelerationSensor : Accelerometer { + constructor(optional AccelerometerSensorOptions options = {}); +}; + +[SecureContext, Exposed=Window] +interface GravitySensor : Accelerometer { + constructor(optional AccelerometerSensorOptions options = {}); +}; + +dictionary AccelerometerReadingValues { + required double? x; + required double? y; + required double? z; +}; + +dictionary LinearAccelerationReadingValues : AccelerometerReadingValues { +}; + +dictionary GravityReadingValues : AccelerometerReadingValues { +}; diff --git a/test/wpt/tests/interfaces/ambient-light.idl b/test/wpt/tests/interfaces/ambient-light.idl new file mode 100644 index 0000000..6d9c8e0 --- /dev/null +++ b/test/wpt/tests/interfaces/ambient-light.idl @@ -0,0 +1,14 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Ambient Light Sensor (https://w3c.github.io/ambient-light/) + +[SecureContext, Exposed=Window] +interface AmbientLightSensor : Sensor { + constructor(optional SensorOptions sensorOptions = {}); + readonly attribute double? illuminance; +}; + +dictionary AmbientLightReadingValues { + required double? illuminance; +}; diff --git a/test/wpt/tests/interfaces/anchors.idl b/test/wpt/tests/interfaces/anchors.idl new file mode 100644 index 0000000..d8c5aa6 --- /dev/null +++ b/test/wpt/tests/interfaces/anchors.idl @@ -0,0 +1,37 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: WebXR Anchors Module (https://immersive-web.github.io/anchors/) + +[SecureContext, Exposed=Window] +interface XRAnchor { + readonly attribute XRSpace anchorSpace; + + Promise requestPersistentHandle(); + + undefined delete(); +}; + +partial interface XRFrame { + Promise createAnchor(XRRigidTransform pose, XRSpace space); +}; + +partial interface XRSession { + readonly attribute FrozenArray persistentAnchors; + + Promise restorePersistentAnchor(DOMString uuid); + Promise deletePersistentAnchor(DOMString uuid); +}; + +partial interface XRHitTestResult { + Promise createAnchor(); +}; + +[Exposed=Window] +interface XRAnchorSet { + readonly setlike; +}; + +partial interface XRFrame { + [SameObject] readonly attribute XRAnchorSet trackedAnchors; +}; diff --git a/test/wpt/tests/interfaces/attribution-reporting-api.idl b/test/wpt/tests/interfaces/attribution-reporting-api.idl new file mode 100644 index 0000000..ed4497b --- /dev/null +++ b/test/wpt/tests/interfaces/attribution-reporting-api.idl @@ -0,0 +1,26 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Attribution Reporting (https://wicg.github.io/attribution-reporting-api/) + +interface mixin HTMLAttributionSrcElementUtils { + [CEReactions, SecureContext] attribute USVString attributionSrc; +}; + +HTMLAnchorElement includes HTMLAttributionSrcElementUtils; +HTMLImageElement includes HTMLAttributionSrcElementUtils; +HTMLScriptElement includes HTMLAttributionSrcElementUtils; + +dictionary AttributionReportingRequestOptions { + required boolean eventSourceEligible; + required boolean triggerEligible; +}; + +partial dictionary RequestInit { + AttributionReportingRequestOptions attributionReporting; +}; + +partial interface XMLHttpRequest { + [SecureContext] + undefined setAttributionReporting(AttributionReportingRequestOptions options); +}; diff --git a/test/wpt/tests/interfaces/audio-output.idl b/test/wpt/tests/interfaces/audio-output.idl new file mode 100644 index 0000000..80ceb22 --- /dev/null +++ b/test/wpt/tests/interfaces/audio-output.idl @@ -0,0 +1,17 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Audio Output Devices API (https://w3c.github.io/mediacapture-output/) + +partial interface HTMLMediaElement { + [SecureContext] readonly attribute DOMString sinkId; + [SecureContext] Promise setSinkId (DOMString sinkId); +}; + +partial interface MediaDevices { + Promise selectAudioOutput(optional AudioOutputOptions options = {}); +}; + +dictionary AudioOutputOptions { + DOMString deviceId = ""; +}; diff --git a/test/wpt/tests/interfaces/autoplay-detection.idl b/test/wpt/tests/interfaces/autoplay-detection.idl new file mode 100644 index 0000000..cd0884f --- /dev/null +++ b/test/wpt/tests/interfaces/autoplay-detection.idl @@ -0,0 +1,19 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Autoplay Policy Detection (https://w3c.github.io/autoplay/) + +enum AutoplayPolicy { + "allowed", + "allowed-muted", + "disallowed" +}; + +enum AutoplayPolicyMediaType { "mediaelement", "audiocontext" }; + +[Exposed=Window] +partial interface Navigator { + AutoplayPolicy getAutoplayPolicy(AutoplayPolicyMediaType type); + AutoplayPolicy getAutoplayPolicy(HTMLMediaElement element); + AutoplayPolicy getAutoplayPolicy(AudioContext context); +}; diff --git a/test/wpt/tests/interfaces/background-fetch.idl b/test/wpt/tests/interfaces/background-fetch.idl new file mode 100644 index 0000000..993bd8b --- /dev/null +++ b/test/wpt/tests/interfaces/background-fetch.idl @@ -0,0 +1,89 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Background Fetch (https://wicg.github.io/background-fetch/) + +partial interface ServiceWorkerGlobalScope { + attribute EventHandler onbackgroundfetchsuccess; + attribute EventHandler onbackgroundfetchfail; + attribute EventHandler onbackgroundfetchabort; + attribute EventHandler onbackgroundfetchclick; +}; + +partial interface ServiceWorkerRegistration { + readonly attribute BackgroundFetchManager backgroundFetch; +}; + +[Exposed=(Window,Worker)] +interface BackgroundFetchManager { + Promise fetch(DOMString id, (RequestInfo or sequence) requests, optional BackgroundFetchOptions options = {}); + Promise get(DOMString id); + Promise> getIds(); +}; + +dictionary BackgroundFetchUIOptions { + sequence icons; + DOMString title; +}; + +dictionary BackgroundFetchOptions : BackgroundFetchUIOptions { + unsigned long long downloadTotal = 0; +}; + +[Exposed=(Window,Worker)] +interface BackgroundFetchRegistration : EventTarget { + readonly attribute DOMString id; + readonly attribute unsigned long long uploadTotal; + readonly attribute unsigned long long uploaded; + readonly attribute unsigned long long downloadTotal; + readonly attribute unsigned long long downloaded; + readonly attribute BackgroundFetchResult result; + readonly attribute BackgroundFetchFailureReason failureReason; + readonly attribute boolean recordsAvailable; + + attribute EventHandler onprogress; + + Promise abort(); + Promise match(RequestInfo request, optional CacheQueryOptions options = {}); + Promise> matchAll(optional RequestInfo request, optional CacheQueryOptions options = {}); +}; + +enum BackgroundFetchResult { "", "success", "failure" }; + +enum BackgroundFetchFailureReason { + // The background fetch has not completed yet, or was successful. + "", + // The operation was aborted by the user, or abort() was called. + "aborted", + // A response had a not-ok-status. + "bad-status", + // A fetch failed for other reasons, e.g. CORS, MIX, an invalid partial response, + // or a general network failure for a fetch that cannot be retried. + "fetch-error", + // Storage quota was reached during the operation. + "quota-exceeded", + // The provided downloadTotal was exceeded. + "download-total-exceeded" +}; + +[Exposed=(Window,Worker)] +interface BackgroundFetchRecord { + readonly attribute Request request; + readonly attribute Promise responseReady; +}; + +[Exposed=ServiceWorker] +interface BackgroundFetchEvent : ExtendableEvent { + constructor(DOMString type, BackgroundFetchEventInit init); + readonly attribute BackgroundFetchRegistration registration; +}; + +dictionary BackgroundFetchEventInit : ExtendableEventInit { + required BackgroundFetchRegistration registration; +}; + +[Exposed=ServiceWorker] +interface BackgroundFetchUpdateUIEvent : BackgroundFetchEvent { + constructor(DOMString type, BackgroundFetchEventInit init); + Promise updateUI(optional BackgroundFetchUIOptions options = {}); +}; diff --git a/test/wpt/tests/interfaces/background-sync.idl b/test/wpt/tests/interfaces/background-sync.idl new file mode 100644 index 0000000..79a13a6 --- /dev/null +++ b/test/wpt/tests/interfaces/background-sync.idl @@ -0,0 +1,30 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Web Background Synchronization (https://wicg.github.io/background-sync/spec/) + +partial interface ServiceWorkerRegistration { + readonly attribute SyncManager sync; +}; + +[Exposed=(Window,Worker)] +interface SyncManager { + Promise register(DOMString tag); + Promise> getTags(); +}; + +partial interface ServiceWorkerGlobalScope { + attribute EventHandler onsync; +}; + +[Exposed=ServiceWorker] +interface SyncEvent : ExtendableEvent { + constructor(DOMString type, SyncEventInit init); + readonly attribute DOMString tag; + readonly attribute boolean lastChance; +}; + +dictionary SyncEventInit : ExtendableEventInit { + required DOMString tag; + boolean lastChance = false; +}; diff --git a/test/wpt/tests/interfaces/badging.idl b/test/wpt/tests/interfaces/badging.idl new file mode 100644 index 0000000..8b401e0 --- /dev/null +++ b/test/wpt/tests/interfaces/badging.idl @@ -0,0 +1,15 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Badging API (https://w3c.github.io/badging/) + +[SecureContext] +interface mixin NavigatorBadge { + Promise setAppBadge( + optional [EnforceRange] unsigned long long contents + ); + Promise clearAppBadge(); +}; + +Navigator includes NavigatorBadge; +WorkerNavigator includes NavigatorBadge; diff --git a/test/wpt/tests/interfaces/battery-status.idl b/test/wpt/tests/interfaces/battery-status.idl new file mode 100644 index 0000000..2d042db --- /dev/null +++ b/test/wpt/tests/interfaces/battery-status.idl @@ -0,0 +1,21 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Battery Status API (https://w3c.github.io/battery/) + +[SecureContext] +partial interface Navigator { + Promise getBattery(); +}; + +[SecureContext, Exposed=Window] +interface BatteryManager : EventTarget { + readonly attribute boolean charging; + readonly attribute unrestricted double chargingTime; + readonly attribute unrestricted double dischargingTime; + readonly attribute double level; + attribute EventHandler onchargingchange; + attribute EventHandler onchargingtimechange; + attribute EventHandler ondischargingtimechange; + attribute EventHandler onlevelchange; +}; diff --git a/test/wpt/tests/interfaces/beacon.idl b/test/wpt/tests/interfaces/beacon.idl new file mode 100644 index 0000000..103a999 --- /dev/null +++ b/test/wpt/tests/interfaces/beacon.idl @@ -0,0 +1,8 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Beacon (https://w3c.github.io/beacon/) + +partial interface Navigator { + boolean sendBeacon(USVString url, optional BodyInit? data = null); +}; diff --git a/test/wpt/tests/interfaces/capture-handle-identity.idl b/test/wpt/tests/interfaces/capture-handle-identity.idl new file mode 100644 index 0000000..37b2c61 --- /dev/null +++ b/test/wpt/tests/interfaces/capture-handle-identity.idl @@ -0,0 +1,27 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Capture Handle - Bootstrapping Collaboration when Screensharing (https://w3c.github.io/mediacapture-handle/identity/) + +dictionary CaptureHandleConfig { + boolean exposeOrigin = false; + DOMString handle = ""; + sequence permittedOrigins = []; +}; + +partial interface MediaDevices { + undefined setCaptureHandleConfig(optional CaptureHandleConfig config = {}); +}; + +dictionary CaptureHandle { + DOMString origin; + DOMString handle; +}; + +partial interface MediaStreamTrack { + CaptureHandle? getCaptureHandle(); +}; + +partial interface MediaStreamTrack { + attribute EventHandler oncapturehandlechange; +}; diff --git a/test/wpt/tests/interfaces/captured-mouse-events.tentative.idl b/test/wpt/tests/interfaces/captured-mouse-events.tentative.idl new file mode 100644 index 0000000..7b081cd --- /dev/null +++ b/test/wpt/tests/interfaces/captured-mouse-events.tentative.idl @@ -0,0 +1,25 @@ +// https://screen-share.github.io/mouse-events/ + +enum CaptureStartFocusBehavior { + "focus-captured-surface", + "no-focus-change" +}; + +[Exposed=Window, SecureContext] +interface CaptureController : EventTarget { + constructor(); + undefined setFocusBehavior(CaptureStartFocusBehavior focusBehavior); + attribute EventHandler oncapturedmousechange; +}; + +[Exposed=Window] +interface CapturedMouseEvent : Event { + constructor(DOMString type, optional CapturedMouseEventInit eventInitDict = {}); + readonly attribute long surfaceX; + readonly attribute long surfaceY; +}; + +dictionary CapturedMouseEventInit : EventInit { + long surfaceX = -1; + long surfaceY = -1; +}; diff --git a/test/wpt/tests/interfaces/clipboard-apis.idl b/test/wpt/tests/interfaces/clipboard-apis.idl new file mode 100644 index 0000000..3f2c9ba --- /dev/null +++ b/test/wpt/tests/interfaces/clipboard-apis.idl @@ -0,0 +1,51 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Clipboard API and events (https://w3c.github.io/clipboard-apis/) + +dictionary ClipboardEventInit : EventInit { + DataTransfer? clipboardData = null; +}; + +[Exposed=Window] +interface ClipboardEvent : Event { + constructor(DOMString type, optional ClipboardEventInit eventInitDict = {}); + readonly attribute DataTransfer? clipboardData; +}; + +partial interface Navigator { + [SecureContext, SameObject] readonly attribute Clipboard clipboard; +}; + +typedef Promise<(DOMString or Blob)> ClipboardItemData; + +[SecureContext, Exposed=Window] +interface ClipboardItem { + constructor(record items, + optional ClipboardItemOptions options = {}); + + readonly attribute PresentationStyle presentationStyle; + readonly attribute FrozenArray types; + + Promise getType(DOMString type); +}; + +enum PresentationStyle { "unspecified", "inline", "attachment" }; + +dictionary ClipboardItemOptions { + PresentationStyle presentationStyle = "unspecified"; +}; + +typedef sequence ClipboardItems; + +[SecureContext, Exposed=Window] +interface Clipboard : EventTarget { + Promise read(); + Promise readText(); + Promise write(ClipboardItems data); + Promise writeText(DOMString data); +}; + +dictionary ClipboardPermissionDescriptor : PermissionDescriptor { + boolean allowWithoutGesture = false; +}; diff --git a/test/wpt/tests/interfaces/close-watcher.idl b/test/wpt/tests/interfaces/close-watcher.idl new file mode 100644 index 0000000..de7940c --- /dev/null +++ b/test/wpt/tests/interfaces/close-watcher.idl @@ -0,0 +1,19 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Close Watcher API (https://wicg.github.io/close-watcher/) + +[Exposed=Window] +interface CloseWatcher : EventTarget { + constructor(optional CloseWatcherOptions options = {}); + + undefined destroy(); + undefined close(); + + attribute EventHandler oncancel; + attribute EventHandler onclose; +}; + +dictionary CloseWatcherOptions { + AbortSignal signal; +}; diff --git a/test/wpt/tests/interfaces/compat.idl b/test/wpt/tests/interfaces/compat.idl new file mode 100644 index 0000000..8106c2d --- /dev/null +++ b/test/wpt/tests/interfaces/compat.idl @@ -0,0 +1,13 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Compatibility Standard (https://compat.spec.whatwg.org/) + +partial interface Window { + readonly attribute short orientation; + attribute EventHandler onorientationchange; +}; + +partial interface HTMLBodyElement { + attribute EventHandler onorientationchange; +}; diff --git a/test/wpt/tests/interfaces/compression.idl b/test/wpt/tests/interfaces/compression.idl new file mode 100644 index 0000000..7525d7c --- /dev/null +++ b/test/wpt/tests/interfaces/compression.idl @@ -0,0 +1,22 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Compression Streams (https://wicg.github.io/compression/) + +enum CompressionFormat { + "deflate", + "deflate-raw", + "gzip", +}; + +[Exposed=*] +interface CompressionStream { + constructor(CompressionFormat format); +}; +CompressionStream includes GenericTransformStream; + +[Exposed=*] +interface DecompressionStream { + constructor(CompressionFormat format); +}; +DecompressionStream includes GenericTransformStream; diff --git a/test/wpt/tests/interfaces/compute-pressure.idl b/test/wpt/tests/interfaces/compute-pressure.idl new file mode 100644 index 0000000..3e35dc4 --- /dev/null +++ b/test/wpt/tests/interfaces/compute-pressure.idl @@ -0,0 +1,37 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Compute Pressure Level 1 (https://w3c.github.io/compute-pressure/) + +enum PressureSource { "thermals", "cpu" }; + +enum PressureState { "nominal", "fair", "serious", "critical" }; + +callback PressureUpdateCallback = undefined ( + sequence changes, + PressureObserver observer +); + +[Exposed=(DedicatedWorker,SharedWorker,Window), SecureContext] +interface PressureObserver { + constructor(PressureUpdateCallback callback, optional PressureObserverOptions options = {}); + + Promise observe(PressureSource source); + undefined unobserve(PressureSource source); + undefined disconnect(); + sequence takeRecords(); + + [SameObject] static readonly attribute FrozenArray supportedSources; +}; + +[Exposed=(DedicatedWorker,SharedWorker,Window), SecureContext] +interface PressureRecord { + readonly attribute PressureSource source; + readonly attribute PressureState state; + readonly attribute DOMHighResTimeStamp time; + [Default] object toJSON(); +}; + +dictionary PressureObserverOptions { + double sampleRate = 1.0; +}; diff --git a/test/wpt/tests/interfaces/console.idl b/test/wpt/tests/interfaces/console.idl new file mode 100644 index 0000000..fdf1d0d --- /dev/null +++ b/test/wpt/tests/interfaces/console.idl @@ -0,0 +1,34 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Console Standard (https://console.spec.whatwg.org/) + +[Exposed=*] +namespace console { // but see namespace object requirements below + // Logging + undefined assert(optional boolean condition = false, any... data); + undefined clear(); + undefined debug(any... data); + undefined error(any... data); + undefined info(any... data); + undefined log(any... data); + undefined table(optional any tabularData, optional sequence properties); + undefined trace(any... data); + undefined warn(any... data); + undefined dir(optional any item, optional object? options); + undefined dirxml(any... data); + + // Counting + undefined count(optional DOMString label = "default"); + undefined countReset(optional DOMString label = "default"); + + // Grouping + undefined group(any... data); + undefined groupCollapsed(any... data); + undefined groupEnd(); + + // Timing + undefined time(optional DOMString label = "default"); + undefined timeLog(optional DOMString label = "default", any... data); + undefined timeEnd(optional DOMString label = "default"); +}; diff --git a/test/wpt/tests/interfaces/contact-picker.idl b/test/wpt/tests/interfaces/contact-picker.idl new file mode 100644 index 0000000..0119d0e --- /dev/null +++ b/test/wpt/tests/interfaces/contact-picker.idl @@ -0,0 +1,44 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Contact Picker API (https://w3c.github.io/contact-picker/) + +[Exposed=Window] +partial interface Navigator { + [SecureContext, SameObject] readonly attribute ContactsManager contacts; +}; + +enum ContactProperty { "address", "email", "icon", "name", "tel" }; + +[Exposed=Window] +interface ContactAddress { + [Default] object toJSON(); + readonly attribute DOMString city; + readonly attribute DOMString country; + readonly attribute DOMString dependentLocality; + readonly attribute DOMString organization; + readonly attribute DOMString phone; + readonly attribute DOMString postalCode; + readonly attribute DOMString recipient; + readonly attribute DOMString region; + readonly attribute DOMString sortingCode; + readonly attribute FrozenArray addressLine; +}; + +dictionary ContactInfo { + sequence address; + sequence email; + sequence icon; + sequence name; + sequence tel; +}; + +dictionary ContactsSelectOptions { + boolean multiple = false; +}; + +[Exposed=Window,SecureContext] +interface ContactsManager { + Promise> getProperties(); + Promise> select(sequence properties, optional ContactsSelectOptions options = {}); +}; diff --git a/test/wpt/tests/interfaces/content-index.idl b/test/wpt/tests/interfaces/content-index.idl new file mode 100644 index 0000000..177c5b9 --- /dev/null +++ b/test/wpt/tests/interfaces/content-index.idl @@ -0,0 +1,46 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Content Index (https://wicg.github.io/content-index/spec/) + +partial interface ServiceWorkerGlobalScope { + attribute EventHandler oncontentdelete; +}; + +partial interface ServiceWorkerRegistration { + [SameObject] readonly attribute ContentIndex index; +}; + +enum ContentCategory { + "", + "homepage", + "article", + "video", + "audio", +}; + +dictionary ContentDescription { + required DOMString id; + required DOMString title; + required DOMString description; + ContentCategory category = ""; + sequence icons = []; + required USVString url; +}; + +[Exposed=(Window,Worker)] +interface ContentIndex { + Promise add(ContentDescription description); + Promise delete(DOMString id); + Promise> getAll(); +}; + +dictionary ContentIndexEventInit : ExtendableEventInit { + required DOMString id; +}; + +[Exposed=ServiceWorker] +interface ContentIndexEvent : ExtendableEvent { + constructor(DOMString type, ContentIndexEventInit init); + readonly attribute DOMString id; +}; diff --git a/test/wpt/tests/interfaces/cookie-store.idl b/test/wpt/tests/interfaces/cookie-store.idl new file mode 100644 index 0000000..f44b4c6 --- /dev/null +++ b/test/wpt/tests/interfaces/cookie-store.idl @@ -0,0 +1,110 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Cookie Store API (https://wicg.github.io/cookie-store/) + +[Exposed=(ServiceWorker,Window), + SecureContext] +interface CookieStore : EventTarget { + Promise get(USVString name); + Promise get(optional CookieStoreGetOptions options = {}); + + Promise getAll(USVString name); + Promise getAll(optional CookieStoreGetOptions options = {}); + + Promise set(USVString name, USVString value); + Promise set(CookieInit options); + + Promise delete(USVString name); + Promise delete(CookieStoreDeleteOptions options); + + [Exposed=Window] + attribute EventHandler onchange; +}; + +dictionary CookieStoreGetOptions { + USVString name; + USVString url; +}; + +enum CookieSameSite { + "strict", + "lax", + "none" +}; + +dictionary CookieInit { + required USVString name; + required USVString value; + DOMHighResTimeStamp? expires = null; + USVString? domain = null; + USVString path = "/"; + CookieSameSite sameSite = "strict"; +}; + +dictionary CookieStoreDeleteOptions { + required USVString name; + USVString? domain = null; + USVString path = "/"; +}; + +dictionary CookieListItem { + USVString name; + USVString value; + USVString? domain; + USVString path; + DOMHighResTimeStamp? expires; + boolean secure; + CookieSameSite sameSite; +}; + +typedef sequence CookieList; + +[Exposed=(ServiceWorker,Window), + SecureContext] +interface CookieStoreManager { + Promise subscribe(sequence subscriptions); + Promise> getSubscriptions(); + Promise unsubscribe(sequence subscriptions); +}; + +[Exposed=(ServiceWorker,Window)] +partial interface ServiceWorkerRegistration { + [SameObject] readonly attribute CookieStoreManager cookies; +}; + +[Exposed=Window, + SecureContext] +interface CookieChangeEvent : Event { + constructor(DOMString type, optional CookieChangeEventInit eventInitDict = {}); + [SameObject] readonly attribute FrozenArray changed; + [SameObject] readonly attribute FrozenArray deleted; +}; + +dictionary CookieChangeEventInit : EventInit { + CookieList changed; + CookieList deleted; +}; + +[Exposed=ServiceWorker] +interface ExtendableCookieChangeEvent : ExtendableEvent { + constructor(DOMString type, optional ExtendableCookieChangeEventInit eventInitDict = {}); + [SameObject] readonly attribute FrozenArray changed; + [SameObject] readonly attribute FrozenArray deleted; +}; + +dictionary ExtendableCookieChangeEventInit : ExtendableEventInit { + CookieList changed; + CookieList deleted; +}; + +[SecureContext] +partial interface Window { + [SameObject] readonly attribute CookieStore cookieStore; +}; + +partial interface ServiceWorkerGlobalScope { + [SameObject] readonly attribute CookieStore cookieStore; + + attribute EventHandler oncookiechange; +}; diff --git a/test/wpt/tests/interfaces/credential-management.idl b/test/wpt/tests/interfaces/credential-management.idl new file mode 100644 index 0000000..e9fab13 --- /dev/null +++ b/test/wpt/tests/interfaces/credential-management.idl @@ -0,0 +1,105 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Credential Management Level 1 (https://w3c.github.io/webappsec-credential-management/) + +[Exposed=Window, SecureContext] +interface Credential { + readonly attribute USVString id; + readonly attribute DOMString type; + static Promise isConditionalMediationAvailable(); +}; + +[SecureContext] +interface mixin CredentialUserData { + readonly attribute USVString name; + readonly attribute USVString iconURL; +}; + +partial interface Navigator { + [SecureContext, SameObject] readonly attribute CredentialsContainer credentials; +}; + +[Exposed=Window, SecureContext] +interface CredentialsContainer { + Promise get(optional CredentialRequestOptions options = {}); + Promise store(Credential credential); + Promise create(optional CredentialCreationOptions options = {}); + Promise preventSilentAccess(); +}; + +dictionary CredentialData { + required USVString id; +}; + +dictionary CredentialRequestOptions { + CredentialMediationRequirement mediation = "optional"; + AbortSignal signal; +}; + +enum CredentialMediationRequirement { + "silent", + "optional", + "conditional", + "required" +}; + +dictionary CredentialCreationOptions { + AbortSignal signal; +}; + +[Exposed=Window, + SecureContext] +interface PasswordCredential : Credential { + constructor(HTMLFormElement form); + constructor(PasswordCredentialData data); + readonly attribute USVString password; +}; +PasswordCredential includes CredentialUserData; + +partial dictionary CredentialRequestOptions { + boolean password = false; +}; + +dictionary PasswordCredentialData : CredentialData { + USVString name; + USVString iconURL; + required USVString origin; + required USVString password; +}; + +typedef (PasswordCredentialData or HTMLFormElement) PasswordCredentialInit; + +partial dictionary CredentialCreationOptions { + PasswordCredentialInit password; +}; + +[Exposed=Window, + SecureContext] +interface FederatedCredential : Credential { + constructor(FederatedCredentialInit data); + readonly attribute USVString provider; + readonly attribute DOMString? protocol; +}; +FederatedCredential includes CredentialUserData; + +dictionary FederatedCredentialRequestOptions { + sequence providers; + sequence protocols; +}; + +partial dictionary CredentialRequestOptions { + FederatedCredentialRequestOptions federated; +}; + +dictionary FederatedCredentialInit : CredentialData { + USVString name; + USVString iconURL; + required USVString origin; + required USVString provider; + DOMString protocol; +}; + +partial dictionary CredentialCreationOptions { + FederatedCredentialInit federated; +}; diff --git a/test/wpt/tests/interfaces/csp-embedded-enforcement.idl b/test/wpt/tests/interfaces/csp-embedded-enforcement.idl new file mode 100644 index 0000000..a980630 --- /dev/null +++ b/test/wpt/tests/interfaces/csp-embedded-enforcement.idl @@ -0,0 +1,8 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Content Security Policy: Embedded Enforcement (https://w3c.github.io/webappsec-cspee/) + +partial interface HTMLIFrameElement { + [CEReactions] attribute DOMString csp; +}; diff --git a/test/wpt/tests/interfaces/csp-next.idl b/test/wpt/tests/interfaces/csp-next.idl new file mode 100644 index 0000000..d94b36c --- /dev/null +++ b/test/wpt/tests/interfaces/csp-next.idl @@ -0,0 +1,21 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: Scripting Policy (https://wicg.github.io/csp-next/scripting-policy.html) + +enum ScriptingPolicyViolationType { + "externalScript", + "inlineScript", + "inlineEventHandler", + "eval" +}; + +[Exposed=(Window,Worker), SecureContext] +interface ScriptingPolicyReportBody : ReportBody { + [Default] object toJSON(); + readonly attribute DOMString violationType; + readonly attribute USVString? violationURL; + readonly attribute USVString? violationSample; + readonly attribute unsigned long lineno; + readonly attribute unsigned long colno; +}; diff --git a/test/wpt/tests/interfaces/css-anchor-position.idl b/test/wpt/tests/interfaces/css-anchor-position.idl new file mode 100644 index 0000000..c5da3f4 --- /dev/null +++ b/test/wpt/tests/interfaces/css-anchor-position.idl @@ -0,0 +1,11 @@ +// Source: CSS Anchor Positioning (https://drafts.csswg.org/css-anchor-position-1/) + +[Exposed=Window] +interface CSSPositionFallbackRule : CSSGroupingRule { + readonly attribute CSSOMString name; +}; + +[Exposed=Window] +interface CSSTryRule : CSSRule { + [SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style; +}; diff --git a/test/wpt/tests/interfaces/css-animation-worklet.idl b/test/wpt/tests/interfaces/css-animation-worklet.idl new file mode 100644 index 0000000..82d34a3 --- /dev/null +++ b/test/wpt/tests/interfaces/css-animation-worklet.idl @@ -0,0 +1,37 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Animation Worklet API (https://drafts.css-houdini.org/css-animationworklet-1/) + +[Exposed=Window] +partial namespace CSS { + [SameObject] readonly attribute Worklet animationWorklet; +}; + +[ Global=(Worklet,AnimationWorklet), Exposed=AnimationWorklet ] +interface AnimationWorkletGlobalScope : WorkletGlobalScope { + undefined registerAnimator(DOMString name, AnimatorInstanceConstructor animatorCtor); +}; + +callback AnimatorInstanceConstructor = any (any options, optional any state); + +[ Exposed=AnimationWorklet ] +interface WorkletAnimationEffect { + EffectTiming getTiming(); + ComputedEffectTiming getComputedTiming(); + attribute double? localTime; +}; + +[Exposed=Window] +interface WorkletAnimation : Animation { + constructor(DOMString animatorName, + optional (AnimationEffect or sequence)? effects = null, + optional AnimationTimeline? timeline, + optional any options); + readonly attribute DOMString animatorName; +}; + +[Exposed=AnimationWorklet] +interface WorkletGroupEffect { + sequence getChildren(); +}; diff --git a/test/wpt/tests/interfaces/css-animations-2.idl b/test/wpt/tests/interfaces/css-animations-2.idl new file mode 100644 index 0000000..84f138e --- /dev/null +++ b/test/wpt/tests/interfaces/css-animations-2.idl @@ -0,0 +1,9 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Animations Level 2 (https://drafts.csswg.org/css-animations-2/) + +[Exposed=Window] +interface CSSAnimation : Animation { + readonly attribute CSSOMString animationName; +}; diff --git a/test/wpt/tests/interfaces/css-animations.idl b/test/wpt/tests/interfaces/css-animations.idl new file mode 100644 index 0000000..6620e01 --- /dev/null +++ b/test/wpt/tests/interfaces/css-animations.idl @@ -0,0 +1,47 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Animations Level 1 (https://drafts.csswg.org/css-animations-1/) + +[Exposed=Window] +interface AnimationEvent : Event { + constructor(CSSOMString type, optional AnimationEventInit animationEventInitDict = {}); + readonly attribute CSSOMString animationName; + readonly attribute double elapsedTime; + readonly attribute CSSOMString pseudoElement; +}; +dictionary AnimationEventInit : EventInit { + CSSOMString animationName = ""; + double elapsedTime = 0.0; + CSSOMString pseudoElement = ""; +}; + +partial interface CSSRule { + const unsigned short KEYFRAMES_RULE = 7; + const unsigned short KEYFRAME_RULE = 8; +}; + +[Exposed=Window] +interface CSSKeyframeRule : CSSRule { + attribute CSSOMString keyText; + [SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style; +}; + +[Exposed=Window] +interface CSSKeyframesRule : CSSRule { + attribute CSSOMString name; + readonly attribute CSSRuleList cssRules; + readonly attribute unsigned long length; + + getter CSSKeyframeRule (unsigned long index); + undefined appendRule(CSSOMString rule); + undefined deleteRule(CSSOMString select); + CSSKeyframeRule? findRule(CSSOMString select); +}; + +partial interface mixin GlobalEventHandlers { + attribute EventHandler onanimationstart; + attribute EventHandler onanimationiteration; + attribute EventHandler onanimationend; + attribute EventHandler onanimationcancel; +}; diff --git a/test/wpt/tests/interfaces/css-cascade-6.idl b/test/wpt/tests/interfaces/css-cascade-6.idl new file mode 100644 index 0000000..3bdf6ba --- /dev/null +++ b/test/wpt/tests/interfaces/css-cascade-6.idl @@ -0,0 +1,10 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Cascading and Inheritance Level 6 (https://drafts.csswg.org/css-cascade-6/) + +[Exposed=Window] +interface CSSScopeRule : CSSGroupingRule { + readonly attribute CSSOMString? start; + readonly attribute CSSOMString? end; +}; diff --git a/test/wpt/tests/interfaces/css-cascade.idl b/test/wpt/tests/interfaces/css-cascade.idl new file mode 100644 index 0000000..0dd9969 --- /dev/null +++ b/test/wpt/tests/interfaces/css-cascade.idl @@ -0,0 +1,14 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Cascading and Inheritance Level 5 (https://drafts.csswg.org/css-cascade-5/) + +[Exposed=Window] +interface CSSLayerBlockRule : CSSGroupingRule { + readonly attribute CSSOMString name; +}; + +[Exposed=Window] +interface CSSLayerStatementRule : CSSRule { + readonly attribute FrozenArray nameList; +}; diff --git a/test/wpt/tests/interfaces/css-color-5.idl b/test/wpt/tests/interfaces/css-color-5.idl new file mode 100644 index 0000000..6f5c6df --- /dev/null +++ b/test/wpt/tests/interfaces/css-color-5.idl @@ -0,0 +1,12 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Color Module Level 5 (https://drafts.csswg.org/css-color-5/) + +[Exposed=Window] +interface CSSColorProfileRule : CSSRule { + readonly attribute CSSOMString name ; + readonly attribute CSSOMString src ; + readonly attribute CSSOMString renderingIntent ; + readonly attribute CSSOMString components ; +}; diff --git a/test/wpt/tests/interfaces/css-conditional.idl b/test/wpt/tests/interfaces/css-conditional.idl new file mode 100644 index 0000000..d87f305 --- /dev/null +++ b/test/wpt/tests/interfaces/css-conditional.idl @@ -0,0 +1,27 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Conditional Rules Module Level 3 (https://drafts.csswg.org/css-conditional-3/) + +partial interface CSSRule { + const unsigned short SUPPORTS_RULE = 12; +}; + +[Exposed=Window] +interface CSSConditionRule : CSSGroupingRule { + readonly attribute CSSOMString conditionText; +}; + +[Exposed=Window] +interface CSSMediaRule : CSSConditionRule { + [SameObject, PutForwards=mediaText] readonly attribute MediaList media; +}; + +[Exposed=Window] +interface CSSSupportsRule : CSSConditionRule { +}; + +partial namespace CSS { + boolean supports(CSSOMString property, CSSOMString value); + boolean supports(CSSOMString conditionText); +}; diff --git a/test/wpt/tests/interfaces/css-contain-3.idl b/test/wpt/tests/interfaces/css-contain-3.idl new file mode 100644 index 0000000..0ecf380 --- /dev/null +++ b/test/wpt/tests/interfaces/css-contain-3.idl @@ -0,0 +1,10 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Containment Module Level 3 (https://drafts.csswg.org/css-contain-3/) + +[Exposed=Window] +interface CSSContainerRule : CSSConditionRule { + readonly attribute CSSOMString containerName; + readonly attribute CSSOMString containerQuery; +}; diff --git a/test/wpt/tests/interfaces/css-contain.idl b/test/wpt/tests/interfaces/css-contain.idl new file mode 100644 index 0000000..be2137a --- /dev/null +++ b/test/wpt/tests/interfaces/css-contain.idl @@ -0,0 +1,13 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Containment Module Level 2 (https://drafts.csswg.org/css-contain-2/) + +[Exposed=Window] +interface ContentVisibilityAutoStateChangeEvent : Event { + constructor(DOMString type, optional ContentVisibilityAutoStateChangeEventInit eventInitDict = {}); + readonly attribute boolean skipped; +}; +dictionary ContentVisibilityAutoStateChangeEventInit : EventInit { + boolean skipped = false; +}; diff --git a/test/wpt/tests/interfaces/css-counter-styles.idl b/test/wpt/tests/interfaces/css-counter-styles.idl new file mode 100644 index 0000000..f679e0f --- /dev/null +++ b/test/wpt/tests/interfaces/css-counter-styles.idl @@ -0,0 +1,23 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Counter Styles Level 3 (https://drafts.csswg.org/css-counter-styles-3/) + +partial interface CSSRule { + const unsigned short COUNTER_STYLE_RULE = 11; +}; + +[Exposed=Window] +interface CSSCounterStyleRule : CSSRule { + attribute CSSOMString name; + attribute CSSOMString system; + attribute CSSOMString symbols; + attribute CSSOMString additiveSymbols; + attribute CSSOMString negative; + attribute CSSOMString prefix; + attribute CSSOMString suffix; + attribute CSSOMString range; + attribute CSSOMString pad; + attribute CSSOMString speakAs; + attribute CSSOMString fallback; +}; diff --git a/test/wpt/tests/interfaces/css-font-loading.idl b/test/wpt/tests/interfaces/css-font-loading.idl new file mode 100644 index 0000000..6f2e16d --- /dev/null +++ b/test/wpt/tests/interfaces/css-font-loading.idl @@ -0,0 +1,134 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Font Loading Module Level 3 (https://drafts.csswg.org/css-font-loading-3/) + +typedef (ArrayBuffer or ArrayBufferView) BinaryData; + +dictionary FontFaceDescriptors { + CSSOMString style = "normal"; + CSSOMString weight = "normal"; + CSSOMString stretch = "normal"; + CSSOMString unicodeRange = "U+0-10FFFF"; + CSSOMString variant = "normal"; + CSSOMString featureSettings = "normal"; + CSSOMString variationSettings = "normal"; + CSSOMString display = "auto"; + CSSOMString ascentOverride = "normal"; + CSSOMString descentOverride = "normal"; + CSSOMString lineGapOverride = "normal"; +}; + +enum FontFaceLoadStatus { "unloaded", "loading", "loaded", "error" }; + +[Exposed=(Window,Worker)] +interface FontFace { + constructor(CSSOMString family, (CSSOMString or BinaryData) source, + optional FontFaceDescriptors descriptors = {}); + attribute CSSOMString family; + attribute CSSOMString style; + attribute CSSOMString weight; + attribute CSSOMString stretch; + attribute CSSOMString unicodeRange; + attribute CSSOMString variant; + attribute CSSOMString featureSettings; + attribute CSSOMString variationSettings; + attribute CSSOMString display; + attribute CSSOMString ascentOverride; + attribute CSSOMString descentOverride; + attribute CSSOMString lineGapOverride; + + readonly attribute FontFaceLoadStatus status; + + Promise load(); + readonly attribute Promise loaded; +}; + +[Exposed=(Window,Worker)] +interface FontFaceFeatures { + /* The CSSWG is still discussing what goes in here */ +}; + +[Exposed=(Window,Worker)] +interface FontFaceVariationAxis { + readonly attribute DOMString name; + readonly attribute DOMString axisTag; + readonly attribute double minimumValue; + readonly attribute double maximumValue; + readonly attribute double defaultValue; +}; + +[Exposed=(Window,Worker)] +interface FontFaceVariations { + readonly setlike; +}; + +[Exposed=(Window,Worker)] +interface FontFacePalette { + iterable; + readonly attribute unsigned long length; + getter DOMString (unsigned long index); + readonly attribute boolean usableWithLightBackground; + readonly attribute boolean usableWithDarkBackground; +}; + +[Exposed=(Window,Worker)] +interface FontFacePalettes { + iterable; + readonly attribute unsigned long length; + getter FontFacePalette (unsigned long index); +}; + +partial interface FontFace { + readonly attribute FontFaceFeatures features; + readonly attribute FontFaceVariations variations; + readonly attribute FontFacePalettes palettes; +}; + +dictionary FontFaceSetLoadEventInit : EventInit { + sequence fontfaces = []; +}; + +[Exposed=(Window,Worker)] +interface FontFaceSetLoadEvent : Event { + constructor(CSSOMString type, optional FontFaceSetLoadEventInit eventInitDict = {}); + [SameObject] readonly attribute FrozenArray fontfaces; +}; + +enum FontFaceSetLoadStatus { "loading", "loaded" }; + +[Exposed=(Window,Worker)] +interface FontFaceSet : EventTarget { + constructor(sequence initialFaces); + + setlike; + FontFaceSet add(FontFace font); + boolean delete(FontFace font); + undefined clear(); + + // events for when loading state changes + attribute EventHandler onloading; + attribute EventHandler onloadingdone; + attribute EventHandler onloadingerror; + + // check and start loads if appropriate + // and fulfill promise when all loads complete + Promise> load(CSSOMString font, optional CSSOMString text = " "); + + // return whether all fonts in the fontlist are loaded + // (does not initiate load if not available) + boolean check(CSSOMString font, optional CSSOMString text = " "); + + // async notification that font loading and layout operations are done + readonly attribute Promise ready; + + // loading state, "loading" while one or more fonts loading, "loaded" otherwise + readonly attribute FontFaceSetLoadStatus status; +}; + +interface mixin FontFaceSource { + readonly attribute FontFaceSet fonts; +}; + +Document includes FontFaceSource; +WorkerGlobalScope includes FontFaceSource; diff --git a/test/wpt/tests/interfaces/css-fonts.idl b/test/wpt/tests/interfaces/css-fonts.idl new file mode 100644 index 0000000..eddfc02 --- /dev/null +++ b/test/wpt/tests/interfaces/css-fonts.idl @@ -0,0 +1,36 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Fonts Module Level 4 (https://drafts.csswg.org/css-fonts-4/) + +[Exposed=Window] +interface CSSFontFaceRule : CSSRule { + readonly attribute CSSStyleDeclaration style; +}; + +partial interface CSSRule { const unsigned short FONT_FEATURE_VALUES_RULE = 14; +}; +[Exposed=Window] +interface CSSFontFeatureValuesRule : CSSRule { + attribute CSSOMString fontFamily; + readonly attribute CSSFontFeatureValuesMap annotation; + readonly attribute CSSFontFeatureValuesMap ornaments; + readonly attribute CSSFontFeatureValuesMap stylistic; + readonly attribute CSSFontFeatureValuesMap swash; + readonly attribute CSSFontFeatureValuesMap characterVariant; + readonly attribute CSSFontFeatureValuesMap styleset; +}; + +[Exposed=Window] +interface CSSFontFeatureValuesMap { + maplike>; + undefined set(CSSOMString featureValueName, + (unsigned long or sequence) values); +}; + +[Exposed=Window]interface CSSFontPaletteValuesRule : CSSRule { + readonly attribute CSSOMString name; + readonly attribute CSSOMString fontFamily; + readonly attribute CSSOMString basePalette; + readonly attribute CSSOMString overrideColors; +}; diff --git a/test/wpt/tests/interfaces/css-highlight-api.idl b/test/wpt/tests/interfaces/css-highlight-api.idl new file mode 100644 index 0000000..f3c6b2e --- /dev/null +++ b/test/wpt/tests/interfaces/css-highlight-api.idl @@ -0,0 +1,27 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Custom Highlight API Module Level 1 (https://drafts.csswg.org/css-highlight-api-1/) + +enum HighlightType { + "highlight", + "spelling-error", + "grammar-error" +}; + +[Exposed=Window] +interface Highlight { + constructor(AbstractRange... initialRanges); + setlike; + attribute long priority; + attribute HighlightType type; +}; + +partial namespace CSS { + readonly attribute HighlightRegistry highlights; +}; + +[Exposed=Window] +interface HighlightRegistry { + maplike; +}; diff --git a/test/wpt/tests/interfaces/css-images-4.idl b/test/wpt/tests/interfaces/css-images-4.idl new file mode 100644 index 0000000..8866b00 --- /dev/null +++ b/test/wpt/tests/interfaces/css-images-4.idl @@ -0,0 +1,8 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Images Module Level 4 (https://drafts.csswg.org/css-images-4/) + +partial namespace CSS { + [SameObject] readonly attribute any elementSources; +}; diff --git a/test/wpt/tests/interfaces/css-layout-api.idl b/test/wpt/tests/interfaces/css-layout-api.idl new file mode 100644 index 0000000..2b772d5 --- /dev/null +++ b/test/wpt/tests/interfaces/css-layout-api.idl @@ -0,0 +1,144 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Layout API Level 1 (https://drafts.css-houdini.org/css-layout-api-1/) + +partial namespace CSS { + [SameObject] readonly attribute Worklet layoutWorklet; +}; + +[Global=(Worklet,LayoutWorklet),Exposed=LayoutWorklet] +interface LayoutWorkletGlobalScope : WorkletGlobalScope { + undefined registerLayout(DOMString name, VoidFunction layoutCtor); +}; + +dictionary LayoutOptions { + ChildDisplayType childDisplay = "block"; + LayoutSizingMode sizing = "block-like"; +}; + +enum ChildDisplayType { + "block", // default - "blockifies" the child boxes. + "normal", +}; + +enum LayoutSizingMode { + "block-like", // default - Sizing behaves like block containers. + "manual", // Sizing is specified by the web developer. +}; + +[Exposed=LayoutWorklet] +interface LayoutChild { + readonly attribute StylePropertyMapReadOnly styleMap; + + Promise intrinsicSizes(); + Promise layoutNextFragment(LayoutConstraintsOptions constraints, ChildBreakToken breakToken); +}; + +[Exposed=LayoutWorklet] +interface LayoutFragment { + readonly attribute double inlineSize; + readonly attribute double blockSize; + + attribute double inlineOffset; + attribute double blockOffset; + + readonly attribute any data; + + readonly attribute ChildBreakToken? breakToken; +}; + +[Exposed=LayoutWorklet] +interface IntrinsicSizes { + readonly attribute double minContentSize; + readonly attribute double maxContentSize; +}; + +[Exposed=LayoutWorklet] +interface LayoutConstraints { + readonly attribute double availableInlineSize; + readonly attribute double availableBlockSize; + + readonly attribute double? fixedInlineSize; + readonly attribute double? fixedBlockSize; + + readonly attribute double percentageInlineSize; + readonly attribute double percentageBlockSize; + + readonly attribute double? blockFragmentationOffset; + readonly attribute BlockFragmentationType blockFragmentationType; + + readonly attribute any data; +}; + +enum BlockFragmentationType { "none", "page", "column", "region" }; + +dictionary LayoutConstraintsOptions { + double availableInlineSize; + double availableBlockSize; + + double fixedInlineSize; + double fixedBlockSize; + + double percentageInlineSize; + double percentageBlockSize; + + double blockFragmentationOffset; + BlockFragmentationType blockFragmentationType = "none"; + + any data; +}; + +[Exposed=LayoutWorklet] +interface ChildBreakToken { + readonly attribute BreakType breakType; + readonly attribute LayoutChild child; +}; + +[Exposed=LayoutWorklet] +interface BreakToken { + readonly attribute FrozenArray childBreakTokens; + readonly attribute any data; +}; + +dictionary BreakTokenOptions { + sequence childBreakTokens; + any data = null; +}; + +enum BreakType { "none", "line", "column", "page", "region" }; + +[Exposed=LayoutWorklet] +interface LayoutEdges { + readonly attribute double inlineStart; + readonly attribute double inlineEnd; + + readonly attribute double blockStart; + readonly attribute double blockEnd; + + // Convenience attributes for the sum in one direction. + readonly attribute double inline; + readonly attribute double block; +}; + +// This is the final return value from the author defined layout() method. +dictionary FragmentResultOptions { + double inlineSize = 0; + double blockSize = 0; + double autoBlockSize = 0; + sequence childFragments = []; + any data = null; + BreakTokenOptions breakToken = null; +}; + +[Exposed=LayoutWorklet] +interface FragmentResult { + constructor(optional FragmentResultOptions options = {}); + readonly attribute double inlineSize; + readonly attribute double blockSize; +}; + +dictionary IntrinsicSizesResultOptions { + double maxContentSize; + double minContentSize; +}; diff --git a/test/wpt/tests/interfaces/css-masking.idl b/test/wpt/tests/interfaces/css-masking.idl new file mode 100644 index 0000000..72fbd9a --- /dev/null +++ b/test/wpt/tests/interfaces/css-masking.idl @@ -0,0 +1,20 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Masking Module Level 1 (https://drafts.fxtf.org/css-masking-1/) + +[Exposed=Window] +interface SVGClipPathElement : SVGElement { + readonly attribute SVGAnimatedEnumeration clipPathUnits; + readonly attribute SVGAnimatedTransformList transform; +}; + +[Exposed=Window] +interface SVGMaskElement : SVGElement { + readonly attribute SVGAnimatedEnumeration maskUnits; + readonly attribute SVGAnimatedEnumeration maskContentUnits; + readonly attribute SVGAnimatedLength x; + readonly attribute SVGAnimatedLength y; + readonly attribute SVGAnimatedLength width; + readonly attribute SVGAnimatedLength height; +}; diff --git a/test/wpt/tests/interfaces/css-nav.idl b/test/wpt/tests/interfaces/css-nav.idl new file mode 100644 index 0000000..03f039e --- /dev/null +++ b/test/wpt/tests/interfaces/css-nav.idl @@ -0,0 +1,48 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Spatial Navigation Level 1 (https://drafts.csswg.org/css-nav-1/) + +enum SpatialNavigationDirection { + "up", + "down", + "left", + "right", +}; + +partial interface Window { + undefined navigate(SpatialNavigationDirection dir); +}; + +enum FocusableAreaSearchMode { + "visible", + "all" +}; + +dictionary FocusableAreasOption { + FocusableAreaSearchMode mode; +}; + +dictionary SpatialNavigationSearchOptions { + sequence? candidates; + Node? container; +}; + +partial interface Element { + Node getSpatialNavigationContainer(); + sequence focusableAreas(optional FocusableAreasOption option = {}); + Node? spatialNavigationSearch(SpatialNavigationDirection dir, optional SpatialNavigationSearchOptions options = {}); +}; + +[Exposed=Window] +interface NavigationEvent : UIEvent { + constructor(DOMString type, + optional NavigationEventInit eventInitDict = {}); + readonly attribute SpatialNavigationDirection dir; + readonly attribute EventTarget? relatedTarget; +}; + +dictionary NavigationEventInit : UIEventInit { + SpatialNavigationDirection dir; + EventTarget? relatedTarget = null; +}; diff --git a/test/wpt/tests/interfaces/css-nesting.idl b/test/wpt/tests/interfaces/css-nesting.idl new file mode 100644 index 0000000..01f27ab --- /dev/null +++ b/test/wpt/tests/interfaces/css-nesting.idl @@ -0,0 +1,10 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Nesting Module (https://drafts.csswg.org/css-nesting-1/) + +partial interface CSSStyleRule { + [SameObject] readonly attribute CSSRuleList cssRules; + unsigned long insertRule(CSSOMString rule, optional unsigned long index = 0); + undefined deleteRule(unsigned long index); +}; diff --git a/test/wpt/tests/interfaces/css-paint-api.idl b/test/wpt/tests/interfaces/css-paint-api.idl new file mode 100644 index 0000000..0924c53 --- /dev/null +++ b/test/wpt/tests/interfaces/css-paint-api.idl @@ -0,0 +1,39 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Painting API Level 1 (https://drafts.css-houdini.org/css-paint-api-1/) + +partial namespace CSS { + [SameObject] readonly attribute Worklet paintWorklet; +}; + +[Global=(Worklet,PaintWorklet),Exposed=PaintWorklet] +interface PaintWorkletGlobalScope : WorkletGlobalScope { + undefined registerPaint(DOMString name, VoidFunction paintCtor); + readonly attribute unrestricted double devicePixelRatio; +}; + +dictionary PaintRenderingContext2DSettings { + boolean alpha = true; +}; + +[Exposed=PaintWorklet] +interface PaintRenderingContext2D { +}; +PaintRenderingContext2D includes CanvasState; +PaintRenderingContext2D includes CanvasTransform; +PaintRenderingContext2D includes CanvasCompositing; +PaintRenderingContext2D includes CanvasImageSmoothing; +PaintRenderingContext2D includes CanvasFillStrokeStyles; +PaintRenderingContext2D includes CanvasShadowStyles; +PaintRenderingContext2D includes CanvasRect; +PaintRenderingContext2D includes CanvasDrawPath; +PaintRenderingContext2D includes CanvasDrawImage; +PaintRenderingContext2D includes CanvasPathDrawingStyles; +PaintRenderingContext2D includes CanvasPath; + +[Exposed=PaintWorklet] +interface PaintSize { + readonly attribute double width; + readonly attribute double height; +}; diff --git a/test/wpt/tests/interfaces/css-parser-api.idl b/test/wpt/tests/interfaces/css-parser-api.idl new file mode 100644 index 0000000..4e34a3f --- /dev/null +++ b/test/wpt/tests/interfaces/css-parser-api.idl @@ -0,0 +1,76 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Parser API (https://wicg.github.io/css-parser-api/) + +typedef (DOMString or ReadableStream) CSSStringSource; +typedef (DOMString or CSSStyleValue or CSSParserValue) CSSToken; + +partial namespace CSS { + Promise> parseStylesheet(CSSStringSource css, optional CSSParserOptions options = {}); + Promise> parseRuleList(CSSStringSource css, optional CSSParserOptions options = {}); + Promise parseRule(CSSStringSource css, optional CSSParserOptions options = {}); + Promise> parseDeclarationList(CSSStringSource css, optional CSSParserOptions options = {}); + CSSParserDeclaration parseDeclaration(DOMString css, optional CSSParserOptions options = {}); + CSSToken parseValue(DOMString css); + sequence parseValueList(DOMString css); + sequence> parseCommaValueList(DOMString css); +}; + +dictionary CSSParserOptions { + object atRules; + /* dict of at-rule name => at-rule type + (contains decls or contains qualified rules) */ +}; + +[Exposed=Window] +interface CSSParserRule { + /* Just a superclass. */ +}; + +[Exposed=Window] +interface CSSParserAtRule : CSSParserRule { + constructor(DOMString name, sequence prelude, optional sequence? body); + readonly attribute DOMString name; + readonly attribute FrozenArray prelude; + readonly attribute FrozenArray? body; + /* nullable to handle at-statements */ + stringifier; +}; + +[Exposed=Window] +interface CSSParserQualifiedRule : CSSParserRule { + constructor(sequence prelude, optional sequence? body); + readonly attribute FrozenArray prelude; + readonly attribute FrozenArray body; + stringifier; +}; + +[Exposed=Window] +interface CSSParserDeclaration : CSSParserRule { + constructor(DOMString name, optional sequence body); + readonly attribute DOMString name; + readonly attribute FrozenArray body; + stringifier; +}; + +[Exposed=Window] +interface CSSParserValue { + /* Just a superclass. */ +}; + +[Exposed=Window] +interface CSSParserBlock : CSSParserValue { + constructor(DOMString name, sequence body); + readonly attribute DOMString name; /* "[]", "{}", or "()" */ + readonly attribute FrozenArray body; + stringifier; +}; + +[Exposed=Window] +interface CSSParserFunction : CSSParserValue { + constructor(DOMString name, sequence> args); + readonly attribute DOMString name; + readonly attribute FrozenArray> args; + stringifier; +}; diff --git a/test/wpt/tests/interfaces/css-properties-values-api.idl b/test/wpt/tests/interfaces/css-properties-values-api.idl new file mode 100644 index 0000000..eb7d7b0 --- /dev/null +++ b/test/wpt/tests/interfaces/css-properties-values-api.idl @@ -0,0 +1,23 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Properties and Values API Level 1 (https://drafts.css-houdini.org/css-properties-values-api-1/) + +dictionary PropertyDefinition { + required DOMString name; + DOMString syntax = "*"; + required boolean inherits; + DOMString initialValue; +}; + +partial namespace CSS { + undefined registerProperty(PropertyDefinition definition); +}; + +[Exposed=Window] +interface CSSPropertyRule : CSSRule { + readonly attribute CSSOMString name; + readonly attribute CSSOMString syntax; + readonly attribute boolean inherits; + readonly attribute CSSOMString? initialValue; +}; diff --git a/test/wpt/tests/interfaces/css-pseudo.idl b/test/wpt/tests/interfaces/css-pseudo.idl new file mode 100644 index 0000000..dbe4c54 --- /dev/null +++ b/test/wpt/tests/interfaces/css-pseudo.idl @@ -0,0 +1,16 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Pseudo-Elements Module Level 4 (https://drafts.csswg.org/css-pseudo-4/) + +[Exposed=Window] +interface CSSPseudoElement : EventTarget { + readonly attribute CSSOMString type; + readonly attribute Element element; + readonly attribute (Element or CSSPseudoElement) parent; + CSSPseudoElement? pseudo(CSSOMString type); +}; + +partial interface Element { + CSSPseudoElement? pseudo(CSSOMString type); +}; diff --git a/test/wpt/tests/interfaces/css-regions.idl b/test/wpt/tests/interfaces/css-regions.idl new file mode 100644 index 0000000..113438f --- /dev/null +++ b/test/wpt/tests/interfaces/css-regions.idl @@ -0,0 +1,29 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Regions Module Level 1 (https://drafts.csswg.org/css-regions-1/) + +partial interface Document { + readonly attribute NamedFlowMap namedFlows; +}; + +[Exposed=Window] interface NamedFlowMap { + maplike; +}; + +[Exposed=Window] +interface NamedFlow : EventTarget { + readonly attribute CSSOMString name; + readonly attribute boolean overset; + sequence getRegions(); + readonly attribute short firstEmptyRegionIndex; + sequence getContent(); + sequence getRegionsByContent(Node node); +}; + +interface mixin Region { + readonly attribute CSSOMString regionOverset; + sequence? getRegionFlowRanges(); +}; + +Element includes Region; diff --git a/test/wpt/tests/interfaces/css-shadow-parts.idl b/test/wpt/tests/interfaces/css-shadow-parts.idl new file mode 100644 index 0000000..3759199 --- /dev/null +++ b/test/wpt/tests/interfaces/css-shadow-parts.idl @@ -0,0 +1,8 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Shadow Parts (https://drafts.csswg.org/css-shadow-parts-1/) + +partial interface Element { + [SameObject, PutForwards=value] readonly attribute DOMTokenList part; +}; diff --git a/test/wpt/tests/interfaces/css-toggle.tentative.idl b/test/wpt/tests/interfaces/css-toggle.tentative.idl new file mode 100644 index 0000000..5587019 --- /dev/null +++ b/test/wpt/tests/interfaces/css-toggle.tentative.idl @@ -0,0 +1,51 @@ +partial interface Element { + [SameObject] readonly attribute CSSToggleMap toggles; +}; + +interface CSSToggleMap { + maplike; + CSSToggleMap set(DOMString key, CSSToggle value); +}; + +interface CSSToggle { + attribute (unsigned long or DOMString) value; + attribute unsigned long? valueAsNumber; + attribute DOMString? valueAsString; + + attribute (unsigned long or FrozenArray) states; + attribute boolean group; + attribute CSSToggleScope scope; + attribute CSSToggleCycle cycle; + + constructor(optional CSSToggleData options); +}; + +dictionary CSSToggleData { + (unsigned long or DOMString) value = 0; + (unsigned long or sequence) states = 1; + boolean group = false; + CSSToggleScope scope = "wide"; + CSSToggleCycle cycle = "cycle"; +}; + +enum CSSToggleScope { + "narrow", + "wide", +}; + +enum CSSToggleCycle { + "cycle", + "cycle-on", + "sticky", +}; + +interface CSSToggleEvent : Event { + constructor(DOMString type, optional CSSToggleEventInit eventInitDict = {}); + readonly attribute DOMString toggleName; + readonly attribute CSSToggle? toggle; +}; + +dictionary CSSToggleEventInit : EventInit { + DOMString toggleName = ""; + CSSToggle? toggle = null; +}; diff --git a/test/wpt/tests/interfaces/css-transitions-2.idl b/test/wpt/tests/interfaces/css-transitions-2.idl new file mode 100644 index 0000000..9d06f3c --- /dev/null +++ b/test/wpt/tests/interfaces/css-transitions-2.idl @@ -0,0 +1,9 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Transitions Level 2 (https://drafts.csswg.org/css-transitions-2/) + +[Exposed=Window] +interface CSSTransition : Animation { + readonly attribute CSSOMString transitionProperty; +}; diff --git a/test/wpt/tests/interfaces/css-transitions.idl b/test/wpt/tests/interfaces/css-transitions.idl new file mode 100644 index 0000000..0f00b2c --- /dev/null +++ b/test/wpt/tests/interfaces/css-transitions.idl @@ -0,0 +1,25 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Transitions (https://drafts.csswg.org/css-transitions-1/) + +[Exposed=Window] +interface TransitionEvent : Event { + constructor(CSSOMString type, optional TransitionEventInit transitionEventInitDict = {}); + readonly attribute CSSOMString propertyName; + readonly attribute double elapsedTime; + readonly attribute CSSOMString pseudoElement; +}; + +dictionary TransitionEventInit : EventInit { + CSSOMString propertyName = ""; + double elapsedTime = 0.0; + CSSOMString pseudoElement = ""; +}; + +partial interface mixin GlobalEventHandlers { + attribute EventHandler ontransitionrun; + attribute EventHandler ontransitionstart; + attribute EventHandler ontransitionend; + attribute EventHandler ontransitioncancel; +}; diff --git a/test/wpt/tests/interfaces/css-typed-om.idl b/test/wpt/tests/interfaces/css-typed-om.idl new file mode 100644 index 0000000..0df6a03 --- /dev/null +++ b/test/wpt/tests/interfaces/css-typed-om.idl @@ -0,0 +1,423 @@ +// GENERATED CONTENT - DO NOT EDIT +// Content was automatically extracted by Reffy into webref +// (https://github.com/w3c/webref) +// Source: CSS Typed OM Level 1 (https://drafts.css-houdini.org/css-typed-om-1/) + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSStyleValue { + stringifier; + [Exposed=Window] static CSSStyleValue parse(USVString property, USVString cssText); + [Exposed=Window] static sequence parseAll(USVString property, USVString cssText); +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface StylePropertyMapReadOnly { + iterable>; + (undefined or CSSStyleValue) get(USVString property); + sequence getAll(USVString property); + boolean has(USVString property); + readonly attribute unsigned long size; +}; + +[Exposed=Window] +interface StylePropertyMap : StylePropertyMapReadOnly { + undefined set(USVString property, (CSSStyleValue or USVString)... values); + undefined append(USVString property, (CSSStyleValue or USVString)... values); + undefined delete(USVString property); + undefined clear(); +}; + +partial interface Element { + [SameObject] StylePropertyMapReadOnly computedStyleMap(); +}; + +partial interface CSSStyleRule { + [SameObject] readonly attribute StylePropertyMap styleMap; +}; + +partial interface mixin ElementCSSInlineStyle { + [SameObject] readonly attribute StylePropertyMap attributeStyleMap; +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSUnparsedValue : CSSStyleValue { + constructor(sequence members); + iterable; + readonly attribute unsigned long length; + getter CSSUnparsedSegment (unsigned long index); + setter CSSUnparsedSegment (unsigned long index, CSSUnparsedSegment val); +}; + +typedef (USVString or CSSVariableReferenceValue) CSSUnparsedSegment; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSVariableReferenceValue { + constructor(USVString variable, optional CSSUnparsedValue? fallback = null); + attribute USVString variable; + readonly attribute CSSUnparsedValue? fallback; +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSKeywordValue : CSSStyleValue { + constructor(USVString value); + attribute USVString value; +}; + +typedef (DOMString or CSSKeywordValue) CSSKeywordish; + +typedef (double or CSSNumericValue) CSSNumberish; + +enum CSSNumericBaseType { + "length", + "angle", + "time", + "frequency", + "resolution", + "flex", + "percent", +}; + +dictionary CSSNumericType { + long length; + long angle; + long time; + long frequency; + long resolution; + long flex; + long percent; + CSSNumericBaseType percentHint; +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSNumericValue : CSSStyleValue { + CSSNumericValue add(CSSNumberish... values); + CSSNumericValue sub(CSSNumberish... values); + CSSNumericValue mul(CSSNumberish... values); + CSSNumericValue div(CSSNumberish... values); + CSSNumericValue min(CSSNumberish... values); + CSSNumericValue max(CSSNumberish... values); + + boolean equals(CSSNumberish... value); + + CSSUnitValue to(USVString unit); + CSSMathSum toSum(USVString... units); + CSSNumericType type(); + + [Exposed=Window] static CSSNumericValue parse(USVString cssText); +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSUnitValue : CSSNumericValue { + constructor(double value, USVString unit); + attribute double value; + readonly attribute USVString unit; +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSMathValue : CSSNumericValue { + readonly attribute CSSMathOperator operator; +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSMathSum : CSSMathValue { + constructor(CSSNumberish... args); + readonly attribute CSSNumericArray values; +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSMathProduct : CSSMathValue { + constructor(CSSNumberish... args); + readonly attribute CSSNumericArray values; +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSMathNegate : CSSMathValue { + constructor(CSSNumberish arg); + readonly attribute CSSNumericValue value; +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSMathInvert : CSSMathValue { + constructor(CSSNumberish arg); + readonly attribute CSSNumericValue value; +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSMathMin : CSSMathValue { + constructor(CSSNumberish... args); + readonly attribute CSSNumericArray values; +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSMathMax : CSSMathValue { + constructor(CSSNumberish... args); + readonly attribute CSSNumericArray values; +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSMathClamp : CSSMathValue { + constructor(CSSNumberish lower, CSSNumberish value, CSSNumberish upper); + readonly attribute CSSNumericValue lower; + readonly attribute CSSNumericValue value; + readonly attribute CSSNumericValue upper; +}; + +[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)] +interface CSSNumericArray { + iterable; + readonly attribute unsigned long length; + getter CSSNumericValue (unsigned long index); +}; + +enum CSSMathOperator { + "sum", + "product", + "negate", + "invert", + "min", + "max", + "clamp", +}; + +partial namespace CSS { + CSSUnitValue number(double value); + CSSUnitValue percent(double value); + + // + CSSUnitValue em(double value); + CSSUnitValue ex(double value); + CSSUnitValue ch(double value); + CSSUnitValue ic(double value); + CSSUnitValue rem(double value); + CSSUnitValue lh(double value); + CSSUnitValue rlh(double value); + CSSUnitValue vw(double value); + CSSUnitValue vh(double value); + CSSUnitValue vi(double value); + CSSUnitValue vb(double value); + CSSUnitValue vmin(double value); + CSSUnitValue vmax(double value); + CSSUnitValue svw(double value); + CSSUnitValue svh(double value); + CSSUnitValue svi(double value); + CSSUnitValue svb(double value); + CSSUnitValue svmin(double value); + CSSUnitValue svmax(double value); + CSSUnitValue lvw(double value); + CSSUnitValue lvh(double value); + CSSUnitValue lvi(double value); + CSSUnitValue lvb(double value); + CSSUnitValue lvmin(double value); + CSSUnitValue lvmax(double value); + CSSUnitValue dvw(double value); + CSSUnitValue dvh(double value); + CSSUnitValue dvi(double value); + CSSUnitValue dvb(double value); + CSSUnitValue dvmin(double value); + CSSUnitValue dvmax(double value); + CSSUnitValue cqw(double value); + CSSUnitValue cqh(double value); + CSSUnitValue cqi(double value); + CSSUnitValue cqb(double value); + CSSUnitValue cqmin(double value); + CSSUnitValue cqmax(double value); + CSSUnitValue cm(double value); + CSSUnitValue mm(double value); + CSSUnitValue Q(double value); + CSSUnitValue in(double value); + CSSUnitValue pt(double value); + CSSUnitValue pc(double value); + CSSUnitValue px(double value); + + // + CSSUnitValue deg(double value); + CSSUnitValue grad(double value); + CSSUnitValue rad(double value); + CSSUnitValue turn(double value); + + //