Use NetworkLoadChecker for XHR/fetch loads
https://bugs.webkit.org/show_bug.cgi?id=184741

Reviewed by Chris Dumez.

LayoutTests/imported/w3c:

* web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt:
* web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt:
* web-platform-tests/cors/late-upload-events-expected.txt:
* web-platform-tests/fetch/api/basic/mode-same-origin.any-expected.txt:
* web-platform-tests/fetch/api/basic/scheme-about.any-expected.txt:
* web-platform-tests/fetch/api/basic/scheme-about.any.worker-expected.txt:
* web-platform-tests/fetch/api/redirect/redirect-to-dataurl-expected.txt:
* web-platform-tests/service-workers/service-worker/redirected-response.https-expected.txt:

Source/WebCore:

Covered by existing tests.

* loader/DocumentThreadableLoader.cpp:
(WebCore::DocumentThreadableLoader::shouldSetHTTPHeadersToKeep const):
We need to set this option for CORS done in NetworkProcess.
(WebCore::DocumentThreadableLoader::DocumentThreadableLoader):
Set httpHeadersTokeep when needed (service worker or CORS loads).
Remove the synchronous disabling of preflight since this is now also done for asynchronous loads.
(WebCore::DocumentThreadableLoader::checkURLSchemeAsCORSEnabled):
Helper routine to make the same check for both simple and preflight case.
This allows more consistent error logging between WK1 and WK2.
(WebCore::DocumentThreadableLoader::makeCrossOriginAccessRequest):
Skip preflight in case this is done in NetworkProcess.
(WebCore::DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest):
(WebCore::isResponseComingFromNetworkProcess):
(WebCore::DocumentThreadableLoader::redirectReceived):
Bypass security checks when they are already done in NetworkProcess.
(WebCore::DocumentThreadableLoader::didFail):
In case of AccessControl error, it might be due to a CSP check done in NetworkProcess.
Check it again to enable specific CSP console logging and error reporting.
(WebCore::DocumentThreadableLoader::loadRequest):
Recreating the error in case of synchronous loads to be able to log it adequately.
(WebCore::DocumentThreadableLoader::isDoingSecurityChecksInNetworkProcess const):
* loader/DocumentThreadableLoader.h:
* loader/SubresourceLoader.cpp:
(WebCore::SubresourceLoader::checkResponseCrossOriginAccessControl):
Specific handling of SameOrigin credential mode for which cross-origin load will not use any credential.
(WebCore::SubresourceLoader::checkRedirectionCrossOriginAccessControl):
We keep the application headers so that DocumentThreadableLoader does not have to restart a brand new load.
* loader/cache/CachedResourceLoader.cpp:
(WebCore::CachedResourceLoader::requestResource):
DocumentThreadableLoader is setting referrer and origin directly. Until we fix that, we remove them from the original requests
as applications are not supposed to set these headers.

Source/WebKit:

* NetworkProcess/NetworkCORSPreflightChecker.cpp:
(WebKit::NetworkCORSPreflightChecker::didCompleteWithError):
Pass the preflight error as completion error if any.
* NetworkProcess/NetworkLoad.cpp:
(WebKit::NetworkLoad::willPerformHTTPRedirection):
Set response source to Network so that checks relying on that are correct.
* NetworkProcess/NetworkLoadChecker.cpp:
(WebKit::NetworkLoadChecker::validateResponse):
Adding Oppaqueredirect tainting.
(NetworkLoadChecker::doesNotNeedCORSCheck):
Adding a check to only activate CORS checks for CORS enabled schemes.
Non CORS enabled schemes loads should have failed in WebProcess already.
(WebKit::NetworkLoadChecker::checkCORSRedirectedRequest):
Remove Authorization header as done by SubresourceLoader.
(WebKit::NetworkLoadChecker::checkCORSRequestWithPreflight):
If error is cancellation, we still want to call the completion handler.
* NetworkProcess/NetworkResourceLoader.cpp:
Activate network load checker for all types of loads.
(WebKit::NetworkResourceLoader::willSendRedirectedRequest):
Handle manual redirection by directly calling didReceiveResponse.

LayoutTests:

* TestExpectations:
* http/tests/security/contentSecurityPolicy/1.1/child-src/worker-redirect-blocked-expected.txt:
* http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt:
* http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt:
* http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt:
* http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt:
* http/tests/xmlhttprequest/access-control-and-redirects-expected.txt:
* platform/mac-wk1/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt: Added.
* platform/mac-wk1/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt: Added.
* platform/mac-wk1/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt: Added.
* platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/late-upload-events-expected.txt: Added.
* platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt: Added.
* platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt: Added.
* platform/win/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt: Added.
* platform/win/http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt: Added.
* platform/win/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt: Added.
* platform/win/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt: Added.
* platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/late-upload-events-expected.txt: Added.
* platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt: Added.
* platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt: Added.


git-svn-id: http://svn.webkit.org/repository/webkit/trunk@231107 268f45cc-cd09-0410-ab3c-d52691b4dbfc
diff --git a/LayoutTests/ChangeLog b/LayoutTests/ChangeLog
index 5e5d3b0..bb0a5c0 100644
--- a/LayoutTests/ChangeLog
+++ b/LayoutTests/ChangeLog
@@ -1,3 +1,31 @@
+2018-04-27  Youenn Fablet  <youenn@apple.com>
+
+        Use NetworkLoadChecker for XHR/fetch loads
+        https://bugs.webkit.org/show_bug.cgi?id=184741
+
+        Reviewed by Chris Dumez.
+
+        * TestExpectations:
+        * http/tests/security/contentSecurityPolicy/1.1/child-src/worker-redirect-blocked-expected.txt:
+        * http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt:
+        * http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt:
+        * http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt:
+        * http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt:
+        * http/tests/xmlhttprequest/access-control-and-redirects-expected.txt:
+        * platform/mac-wk1/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt: Added.
+        * platform/mac-wk1/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt: Added.
+        * platform/mac-wk1/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt: Added.
+        * platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/late-upload-events-expected.txt: Added.
+        * platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt: Added.
+        * platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt: Added.
+        * platform/win/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt: Added.
+        * platform/win/http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt: Added.
+        * platform/win/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt: Added.
+        * platform/win/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt: Added.
+        * platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/late-upload-events-expected.txt: Added.
+        * platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt: Added.
+        * platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt: Added.
+
 2018-04-27  Simon Fraser  <simon.fraser@apple.com>
 
         Make color-filter transform gradient colors
diff --git a/LayoutTests/TestExpectations b/LayoutTests/TestExpectations
index cd42ce2..8dc8eb4 100644
--- a/LayoutTests/TestExpectations
+++ b/LayoutTests/TestExpectations
@@ -203,6 +203,12 @@
 http/tests/security/frame-loading-via-document-write.html [ DumpJSConsoleLogInStdErr ]
 http/tests/security/frame-loading-via-document-write-async-delegates.html [ DumpJSConsoleLogInStdErr ]
 
+imported/w3c/web-platform-tests/fetch/api/basic/mode-same-origin.any.html [ DumpJSConsoleLogInStdErr ]
+imported/w3c/web-platform-tests/fetch/api/basic/scheme-about.any.html [ DumpJSConsoleLogInStdErr ]
+imported/w3c/web-platform-tests/fetch/api/basic/scheme-about.any.worker.html [ DumpJSConsoleLogInStdErr ]
+imported/w3c/web-platform-tests/fetch/api/redirect/redirect-mode-worker.html [ DumpJSConsoleLogInStdErr ]
+imported/w3c/web-platform-tests/fetch/api/redirect/redirect-to-dataurl.html [ DumpJSConsoleLogInStdErr ]
+
 webkit.org/b/181901 imported/w3c/web-platform-tests/service-workers/service-worker/fetch-cors-xhr.https.html [ DumpJSConsoleLogInStdErr ]
 webkit.org/b/181897 imported/w3c/web-platform-tests/service-workers/service-worker/fetch-canvas-tainting.https.html [ DumpJSConsoleLogInStdErr ]
 webkit.org/b/181900 imported/w3c/web-platform-tests/service-workers/service-worker/fetch-canvas-tainting-cache.https.html [ DumpJSConsoleLogInStdErr ]
diff --git a/LayoutTests/http/tests/quicklook/same-origin-xmlhttprequest-allowed-expected.txt b/LayoutTests/http/tests/quicklook/same-origin-xmlhttprequest-allowed-expected.txt
index 3bbb4b0..5d07e46 100644
--- a/LayoutTests/http/tests/quicklook/same-origin-xmlhttprequest-allowed-expected.txt
+++ b/LayoutTests/http/tests/quicklook/same-origin-xmlhttprequest-allowed-expected.txt
@@ -1,3 +1,5 @@
+CONSOLE MESSAGE: Blocked by Content Security Policy
+CONSOLE MESSAGE: XMLHttpRequest cannot load about: due to access control checks.
 CONSOLE MESSAGE: line 1: PASS: XMLHttpRequest allowed
 
 
diff --git a/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/child-src/worker-redirect-blocked-expected.txt b/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/child-src/worker-redirect-blocked-expected.txt
index bf190b1..9aba0fc 100644
--- a/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/child-src/worker-redirect-blocked-expected.txt
+++ b/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/child-src/worker-redirect-blocked-expected.txt
@@ -1,6 +1,8 @@
 CONSOLE MESSAGE: Unsafe attempt to load URL http://localhost:8000/security/contentSecurityPolicy/resources/alert-fail.js from origin http://127.0.0.1:8000. Domains, protocols and ports must match.
 
-CONSOLE MESSAGE: Cannot load http://localhost:8000/security/contentSecurityPolicy/resources/alert-fail.js due to access control checks.
+CONSOLE MESSAGE: Refused to load http://localhost:8000/security/contentSecurityPolicy/resources/alert-fail.js because it does not appear in the child-src directive of the Content Security Policy.
+CONSOLE MESSAGE: Cross-origin redirection denied by Content Security Policy.
+CONSOLE MESSAGE: Cannot load http://127.0.0.1:8000/security/contentSecurityPolicy/resources/redir.php?url=http://localhost:8000/security/contentSecurityPolicy/resources/alert-fail.js due to access control checks.
 This tests that the Content Security Policy of the page blocks loading a Web Worker's script from a different origin through a redirect.
 
 On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/LayoutTests/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt b/LayoutTests/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt
index 49f2671..4e4961e 100644
--- a/LayoutTests/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt
+++ b/LayoutTests/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt
@@ -1,3 +1,4 @@
+CONSOLE MESSAGE: Blocked http://localhost:8000/eventsource/resources/simple-event-stream.asis by Content Security Policy
 CONSOLE MESSAGE: Refused to connect to http://localhost:8000/eventsource/resources/simple-event-stream.asis because it does not appear in the connect-src directive of the Content Security Policy.
 CONSOLE MESSAGE: Cross-origin redirection denied by Content Security Policy.
 CONSOLE MESSAGE: EventSource cannot load http://127.0.0.1:8000/security/contentSecurityPolicy/resources/redir.php?url=http://localhost:8000/eventsource/resources/simple-event-stream.asis due to access control checks.
diff --git a/LayoutTests/http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt b/LayoutTests/http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt
index 8ecc3cb..87e8d03 100644
--- a/LayoutTests/http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt
+++ b/LayoutTests/http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt
@@ -1,3 +1,4 @@
+CONSOLE MESSAGE: Blocked http://localhost:8000/security/contentSecurityPolicy/resources/xhr-redirect-not-allowed.pl by Content Security Policy
 CONSOLE MESSAGE: Refused to connect to http://localhost:8000/security/contentSecurityPolicy/resources/xhr-redirect-not-allowed.pl because it does not appear in the connect-src directive of the Content Security Policy.
 CONSOLE MESSAGE: Cross-origin redirection denied by Content Security Policy.
 CONSOLE MESSAGE: XMLHttpRequest cannot load http://127.0.0.1:8000/security/contentSecurityPolicy/resources/redir.php?url=http://localhost:8000/security/contentSecurityPolicy/resources/xhr-redirect-not-allowed.pl due to access control checks.
diff --git a/LayoutTests/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt b/LayoutTests/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt
index f8e8d59..0423a3e 100644
--- a/LayoutTests/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt
+++ b/LayoutTests/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt
@@ -1,3 +1,4 @@
+CONSOLE MESSAGE: Blocked http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow.cgi by Content Security Policy
 This tests an XHR request made from a worker is blocked if it redirects to a cross-origin resource that is not listed as a connect-src in the CSP of the worker.
 
 PASS threw exception NetworkError:  A network error occurred..
diff --git a/LayoutTests/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt b/LayoutTests/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt
index b7fe744..593f6c6 100644
--- a/LayoutTests/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt
+++ b/LayoutTests/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt
@@ -1,5 +1,5 @@
 CONSOLE MESSAGE: Cross-origin redirection to http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi denied by Cross-Origin Resource Sharing policy: Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.
-CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi due to access control checks.
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi due to access control checks.
 CONSOLE MESSAGE: Cross-origin redirection to foo://bar.cgi denied by Cross-Origin Resource Sharing policy: URL is either a non-HTTP URL or contains credentials.
 CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=foo://bar.cgi&%20%20access-control-allow-origin=http://127.0.0.1:8000 due to access control checks.
 CONSOLE MESSAGE: Preflight response is not successful
diff --git a/LayoutTests/http/tests/xmlhttprequest/access-control-and-redirects-expected.txt b/LayoutTests/http/tests/xmlhttprequest/access-control-and-redirects-expected.txt
index 97418aa..ceca468 100644
--- a/LayoutTests/http/tests/xmlhttprequest/access-control-and-redirects-expected.txt
+++ b/LayoutTests/http/tests/xmlhttprequest/access-control-and-redirects-expected.txt
@@ -1,11 +1,11 @@
 CONSOLE MESSAGE: line 25: Cross-origin redirection to http://127.0.0.1:8000/xmlhttprequest/resources/access-control-basic-allow.cgi denied by Cross-Origin Resource Sharing policy: Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.
 CONSOLE MESSAGE: line 25: XMLHttpRequest cannot load http://127.0.0.1:8000/xmlhttprequest/resources/access-control-basic-allow.cgi due to access control checks.
 CONSOLE MESSAGE: Cross-origin redirection to http://127.0.0.1:8000/xmlhttprequest/resources/access-control-basic-allow.cgi denied by Cross-Origin Resource Sharing policy: Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.
-CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/resources/redirect.php?url=http://127.0.0.1:8000/xmlhttprequest/resources/access-control-basic-allow.cgi due to access control checks.
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://127.0.0.1:8000/xmlhttprequest/resources/access-control-basic-allow.cgi due to access control checks.
 CONSOLE MESSAGE: line 25: Cross-origin redirection to http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow.cgi denied by Cross-Origin Resource Sharing policy: Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.
 CONSOLE MESSAGE: line 25: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow.cgi due to access control checks.
 CONSOLE MESSAGE: Cross-origin redirection to http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow.cgi denied by Cross-Origin Resource Sharing policy: Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.
-CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/resources/redirect.php?url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow.cgi due to access control checks.
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow.cgi due to access control checks.
 Tests that redirects between origins are never allowed, even when access control is involved.
 
 Per the spec, these test cases should be allowed, but cross-origin redirects are currently unsupported in WebCore.
diff --git a/LayoutTests/imported/w3c/ChangeLog b/LayoutTests/imported/w3c/ChangeLog
index 23ba0bc..0166a68 100644
--- a/LayoutTests/imported/w3c/ChangeLog
+++ b/LayoutTests/imported/w3c/ChangeLog
@@ -1,3 +1,19 @@
+2018-04-27  Youenn Fablet  <youenn@apple.com>
+
+        Use NetworkLoadChecker for XHR/fetch loads
+        https://bugs.webkit.org/show_bug.cgi?id=184741
+
+        Reviewed by Chris Dumez.
+
+        * web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt:
+        * web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt:
+        * web-platform-tests/cors/late-upload-events-expected.txt:
+        * web-platform-tests/fetch/api/basic/mode-same-origin.any-expected.txt:
+        * web-platform-tests/fetch/api/basic/scheme-about.any-expected.txt:
+        * web-platform-tests/fetch/api/basic/scheme-about.any.worker-expected.txt:
+        * web-platform-tests/fetch/api/redirect/redirect-to-dataurl-expected.txt:
+        * web-platform-tests/service-workers/service-worker/redirected-response.https-expected.txt:
+
 2018-04-26  Youenn Fablet  <youenn@apple.com>
 
         preflight checker should add a console message when preflight load is blocked
diff --git a/LayoutTests/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt b/LayoutTests/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt
index 5037802..50328c6 100644
--- a/LayoutTests/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt
+++ b/LayoutTests/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt
@@ -1,5 +1,5 @@
-CONSOLE MESSAGE: CORS-preflight request was blocked
-CONSOLE MESSAGE: XMLHttpRequest cannot load http://www1.localhost:8800/XMLHttpRequest/resources/auth1/corsenabled.py due to access control checks.
+Blocked access to external URL http://www1.localhost:8800/XMLHttpRequest/resources/auth1/corsenabled.py
+CONSOLE MESSAGE: line 31: XMLHttpRequest cannot load http://www1.localhost:8800/XMLHttpRequest/resources/auth1/corsenabled.py due to access control checks.
 
 PASS XMLHttpRequest: send() - "Basic" authenticated CORS requests with user name and password passed to open() (asserts failure) 
 
diff --git a/LayoutTests/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt b/LayoutTests/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt
index b20bc2c..2f459f5 100644
--- a/LayoutTests/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt
+++ b/LayoutTests/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt
@@ -1,5 +1,5 @@
-CONSOLE MESSAGE: CORS-preflight request was blocked
-CONSOLE MESSAGE: XMLHttpRequest cannot load http://nonexistent-origin.localhost:8800/ due to access control checks.
+Blocked access to external URL http://nonexistent-origin.localhost:8800/
+CONSOLE MESSAGE: line 43: XMLHttpRequest cannot load http://nonexistent-origin.localhost:8800/ due to access control checks.
 
 PASS XMLHttpRequest: The send() method: Fire a progress event named error when Network error happens (synchronous flag is unset) 
 
diff --git a/LayoutTests/imported/w3c/web-platform-tests/cors/late-upload-events-expected.txt b/LayoutTests/imported/w3c/web-platform-tests/cors/late-upload-events-expected.txt
index 5d86ccf..53a4593 100644
--- a/LayoutTests/imported/w3c/web-platform-tests/cors/late-upload-events-expected.txt
+++ b/LayoutTests/imported/w3c/web-platform-tests/cors/late-upload-events-expected.txt
@@ -1,7 +1,7 @@
 Blocked access to external URL http://www1.localhost:8800/cors/resources/status.py?headers=custom-header
 CONSOLE MESSAGE: line 30: XMLHttpRequest cannot load http://www1.localhost:8800/cors/resources/status.py?headers=custom-header due to access control checks.
-CONSOLE MESSAGE: CORS-preflight request was blocked
-CONSOLE MESSAGE: XMLHttpRequest cannot load http://www1.localhost:8800/cors/resources/status.py?headers=custom-header due to access control checks.
+Blocked access to external URL http://www1.localhost:8800/cors/resources/status.py?headers=custom-header
+CONSOLE MESSAGE: line 30: XMLHttpRequest cannot load http://www1.localhost:8800/cors/resources/status.py?headers=custom-header due to access control checks.
 Adding upload event listeners after send()
 
 
diff --git a/LayoutTests/imported/w3c/web-platform-tests/fetch/api/basic/mode-same-origin.any-expected.txt b/LayoutTests/imported/w3c/web-platform-tests/fetch/api/basic/mode-same-origin.any-expected.txt
index b9b8b76..dee6efa 100644
--- a/LayoutTests/imported/w3c/web-platform-tests/fetch/api/basic/mode-same-origin.any-expected.txt
+++ b/LayoutTests/imported/w3c/web-platform-tests/fetch/api/basic/mode-same-origin.any-expected.txt
@@ -1,9 +1,3 @@
-CONSOLE MESSAGE: line 12: Fetch API cannot load https://localhost:9443/fetch/api/resources/top.txt.
-CONSOLE MESSAGE: line 12: Fetch API cannot load http://127.0.0.1:8800/fetch/api/resources/top.txt.
-CONSOLE MESSAGE: Unsafe attempt to load URL https://localhost:9443/fetch/api/resources/top.txt?location=https%3A%2F%2Flocalhost%3A9443%2Ffetch%2Fapi%2Fresources%2Ftop.txt&count=1 from origin http://localhost:8800. Domains, protocols and ports must match.
-
-CONSOLE MESSAGE: Unsafe attempt to load URL http://127.0.0.1:8800/fetch/api/resources/top.txt?location=http%3A%2F%2F127.0.0.1%3A8800%2Ffetch%2Fapi%2Fresources%2Ftop.txt&count=1 from origin http://localhost:8800. Domains, protocols and ports must match.
-
 
 PASS Fetch ../resources/top.txt with same-origin mode 
 PASS Fetch http://localhost:8800/fetch/api/resources/top.txt with same-origin mode 
diff --git a/LayoutTests/imported/w3c/web-platform-tests/fetch/api/basic/scheme-about.any-expected.txt b/LayoutTests/imported/w3c/web-platform-tests/fetch/api/basic/scheme-about.any-expected.txt
index 0b36df4..9944d1b 100644
--- a/LayoutTests/imported/w3c/web-platform-tests/fetch/api/basic/scheme-about.any-expected.txt
+++ b/LayoutTests/imported/w3c/web-platform-tests/fetch/api/basic/scheme-about.any-expected.txt
@@ -1,18 +1,6 @@
-CONSOLE MESSAGE: line 10: Cross origin requests are only supported for HTTP.
-CONSOLE MESSAGE: line 10: Fetch API cannot load about:blank due to access control checks.
-CONSOLE MESSAGE: Preflight response is not successful
-CONSOLE MESSAGE: Fetch API cannot load about:blank due to access control checks.
-CONSOLE MESSAGE: line 10: Cross origin requests are only supported for HTTP.
-CONSOLE MESSAGE: line 10: Fetch API cannot load about:blank due to access control checks.
-CONSOLE MESSAGE: line 27: Cross origin requests are only supported for HTTP.
-CONSOLE MESSAGE: line 27: Fetch API cannot load about:invalid.com due to access control checks.
-CONSOLE MESSAGE: line 27: Cross origin requests are only supported for HTTP.
-CONSOLE MESSAGE: line 27: Fetch API cannot load about:config due to access control checks.
-CONSOLE MESSAGE: line 27: Cross origin requests are only supported for HTTP.
-CONSOLE MESSAGE: line 27: Fetch API cannot load about:unicorn due to access control checks.
 
 FAIL Fetching about:blank (GET) is OK promise_test: Unhandled rejection with value: object "TypeError: Cross origin requests are only supported for HTTP."
-FAIL Fetching about:blank (PUT) is OK promise_test: Unhandled rejection with value: object "TypeError: Preflight response is not successful"
+FAIL Fetching about:blank (PUT) is OK promise_test: Unhandled rejection with value: object "TypeError: Cross origin requests are only supported for HTTP."
 FAIL Fetching about:blank (POST) is OK promise_test: Unhandled rejection with value: object "TypeError: Cross origin requests are only supported for HTTP."
 PASS Fetching about:invalid.com is KO 
 PASS Fetching about:config is KO 
diff --git a/LayoutTests/imported/w3c/web-platform-tests/fetch/api/basic/scheme-about.any.worker-expected.txt b/LayoutTests/imported/w3c/web-platform-tests/fetch/api/basic/scheme-about.any.worker-expected.txt
index 45cb150..9944d1b 100644
--- a/LayoutTests/imported/w3c/web-platform-tests/fetch/api/basic/scheme-about.any.worker-expected.txt
+++ b/LayoutTests/imported/w3c/web-platform-tests/fetch/api/basic/scheme-about.any.worker-expected.txt
@@ -1,7 +1,6 @@
-CONSOLE MESSAGE: Preflight response is not successful
 
 FAIL Fetching about:blank (GET) is OK promise_test: Unhandled rejection with value: object "TypeError: Cross origin requests are only supported for HTTP."
-FAIL Fetching about:blank (PUT) is OK promise_test: Unhandled rejection with value: object "TypeError: Preflight response is not successful"
+FAIL Fetching about:blank (PUT) is OK promise_test: Unhandled rejection with value: object "TypeError: Cross origin requests are only supported for HTTP."
 FAIL Fetching about:blank (POST) is OK promise_test: Unhandled rejection with value: object "TypeError: Cross origin requests are only supported for HTTP."
 PASS Fetching about:invalid.com is KO 
 PASS Fetching about:config is KO 
diff --git a/LayoutTests/imported/w3c/web-platform-tests/fetch/api/redirect/redirect-to-dataurl-expected.txt b/LayoutTests/imported/w3c/web-platform-tests/fetch/api/redirect/redirect-to-dataurl-expected.txt
index 96d0eae..f6edb42 100644
--- a/LayoutTests/imported/w3c/web-platform-tests/fetch/api/redirect/redirect-to-dataurl-expected.txt
+++ b/LayoutTests/imported/w3c/web-platform-tests/fetch/api/redirect/redirect-to-dataurl-expected.txt
@@ -1,13 +1,3 @@
-CONSOLE MESSAGE: Cross-origin redirection to data:text/plain;base64,cmVzcG9uc2UncyBib2R5 denied by Cross-Origin Resource Sharing policy: URL is either a non-HTTP URL or contains credentials.
-CONSOLE MESSAGE: Fetch API cannot load http://localhost:8800/fetch/api/resources/redirect.py?cors&location=data%3Atext%2Fplain%3Bbase64%2CcmVzcG9uc2UncyBib2R5 due to access control checks.
-CONSOLE MESSAGE: Redirection to URL with a scheme that is not HTTP(S).
-CONSOLE MESSAGE: Fetch API cannot load data:text/plain;base64,cmVzcG9uc2UncyBib2R5 due to access control checks.
-CONSOLE MESSAGE: Unsafe attempt to load URL data:text/plain;base64,cmVzcG9uc2UncyBib2R5 from origin http://localhost:8800. Domains, protocols and ports must match.
-
-CONSOLE MESSAGE: Cross-origin redirection to data:text/plain;base64,cmVzcG9uc2UncyBib2R5 denied by Cross-Origin Resource Sharing policy: URL is either a non-HTTP URL or contains credentials.
-CONSOLE MESSAGE: Fetch API cannot load http://127.0.0.1:8800/fetch/api/resources/redirect.py?cors&location=data%3Atext%2Fplain%3Bbase64%2CcmVzcG9uc2UncyBib2R5 due to access control checks.
-CONSOLE MESSAGE: Redirection to URL with a scheme that is not HTTP(S).
-CONSOLE MESSAGE: Fetch API cannot load data:text/plain;base64,cmVzcG9uc2UncyBib2R5 due to access control checks.
 
 PASS Testing data URL loading after same-origin redirection (cors mode) 
 PASS Testing data URL loading after same-origin redirection (no-cors mode) 
diff --git a/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/redirected-response.https-expected.txt b/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/redirected-response.https-expected.txt
index 11bd135..a44bdd4 100644
--- a/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/redirected-response.https-expected.txt
+++ b/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/redirected-response.https-expected.txt
@@ -1,3 +1,4 @@
+CONSOLE MESSAGE: Redirections are not allowed
 CONSOLE MESSAGE: Fetch API cannot load https://localhost:9443/service-workers/service-worker/resources/redirect.py?Redirect=https%3A%2F%2Flocalhost%3A9443%2Fservice-workers%2Fservice-worker%2Fresources%2Fsimple.txt%3F&error due to access control checks.
 CONSOLE MESSAGE: Response served by service worker has redirections
 CONSOLE MESSAGE: Fetch API cannot load https://localhost:9443/service-workers/service-worker/resources/simple.txt? due to access control checks.
diff --git a/LayoutTests/platform/mac-wk1/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt b/LayoutTests/platform/mac-wk1/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt
new file mode 100644
index 0000000..49f2671
--- /dev/null
+++ b/LayoutTests/platform/mac-wk1/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt
@@ -0,0 +1,8 @@
+CONSOLE MESSAGE: Refused to connect to http://localhost:8000/eventsource/resources/simple-event-stream.asis because it does not appear in the connect-src directive of the Content Security Policy.
+CONSOLE MESSAGE: Cross-origin redirection denied by Content Security Policy.
+CONSOLE MESSAGE: EventSource cannot load http://127.0.0.1:8000/security/contentSecurityPolicy/resources/redir.php?url=http://localhost:8000/eventsource/resources/simple-event-stream.asis due to access control checks.
+PASS EventSource() did not follow the disallowed redirect.
+PASS successfullyParsed is true
+
+TEST COMPLETE
+
diff --git a/LayoutTests/platform/mac-wk1/http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt b/LayoutTests/platform/mac-wk1/http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt
new file mode 100644
index 0000000..8ecc3cb
--- /dev/null
+++ b/LayoutTests/platform/mac-wk1/http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt
@@ -0,0 +1,8 @@
+CONSOLE MESSAGE: Refused to connect to http://localhost:8000/security/contentSecurityPolicy/resources/xhr-redirect-not-allowed.pl because it does not appear in the connect-src directive of the Content Security Policy.
+CONSOLE MESSAGE: Cross-origin redirection denied by Content Security Policy.
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://127.0.0.1:8000/security/contentSecurityPolicy/resources/redir.php?url=http://localhost:8000/security/contentSecurityPolicy/resources/xhr-redirect-not-allowed.pl due to access control checks.
+PASS XMLHttpRequest.send() did not follow the disallowed redirect.
+PASS successfullyParsed is true
+
+TEST COMPLETE
+
diff --git a/LayoutTests/platform/mac-wk1/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt b/LayoutTests/platform/mac-wk1/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt
new file mode 100644
index 0000000..f8e8d59
--- /dev/null
+++ b/LayoutTests/platform/mac-wk1/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt
@@ -0,0 +1,3 @@
+This tests an XHR request made from a worker is blocked if it redirects to a cross-origin resource that is not listed as a connect-src in the CSP of the worker.
+
+PASS threw exception NetworkError:  A network error occurred..
diff --git a/LayoutTests/platform/mac-wk1/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt b/LayoutTests/platform/mac-wk1/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt
new file mode 100644
index 0000000..b7fe744
--- /dev/null
+++ b/LayoutTests/platform/mac-wk1/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt
@@ -0,0 +1,34 @@
+CONSOLE MESSAGE: Cross-origin redirection to http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi denied by Cross-Origin Resource Sharing policy: Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi due to access control checks.
+CONSOLE MESSAGE: Cross-origin redirection to foo://bar.cgi denied by Cross-Origin Resource Sharing policy: URL is either a non-HTTP URL or contains credentials.
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=foo://bar.cgi&%20%20access-control-allow-origin=http://127.0.0.1:8000 due to access control checks.
+CONSOLE MESSAGE: Preflight response is not successful
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?redirect-preflight=true&%20%20url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi&%20%20access-control-allow-origin=* due to access control checks.
+CONSOLE MESSAGE: Request header field x-webkit is not allowed by Access-Control-Allow-Headers.
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi due to access control checks.
+Tests that asynchronous XMLHttpRequests handle redirects according to the CORS standard.
+
+Testing http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi without credentials
+Expecting success: false
+PASS: 0
+Testing http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi&  access-control-allow-origin=http://127.0.0.1:8000 without credentials
+Expecting success: true
+PASS: PASS: Cross-domain access allowed.
+
+Testing http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=http://username:password@localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi&  access-control-allow-origin=http://127.0.0.1:8000 without credentials
+Expecting success: true
+PASS: PASS: Cross-domain access allowed.
+
+Testing http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=foo://bar.cgi&  access-control-allow-origin=http://127.0.0.1:8000 without credentials
+Expecting success: false
+PASS: 0
+Testing http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?redirect-preflight=true&  url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi&  access-control-allow-origin=* without credentials
+Expecting success: false
+PASS: 0
+Testing http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?redirect-preflight=false&  url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi&  access-control-allow-origin=*&  access-control-allow-headers=x-webkit without credentials
+Expecting success: false
+PASS: 0
+Testing resources/redirect-cors.php?url=http://127.0.0.1:8000/xmlhttprequest/resources/get.txt without credentials
+Expecting success: true
+PASS: PASS
+
diff --git a/LayoutTests/platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/late-upload-events-expected.txt b/LayoutTests/platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/late-upload-events-expected.txt
new file mode 100644
index 0000000..5d86ccf
--- /dev/null
+++ b/LayoutTests/platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/late-upload-events-expected.txt
@@ -0,0 +1,10 @@
+Blocked access to external URL http://www1.localhost:8800/cors/resources/status.py?headers=custom-header
+CONSOLE MESSAGE: line 30: XMLHttpRequest cannot load http://www1.localhost:8800/cors/resources/status.py?headers=custom-header due to access control checks.
+CONSOLE MESSAGE: CORS-preflight request was blocked
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://www1.localhost:8800/cors/resources/status.py?headers=custom-header due to access control checks.
+Adding upload event listeners after send()
+
+
+FAIL Late listeners: No preflight assert_equals: expected 200 but got 0
+FAIL Late listeners: Preflight assert_equals: expected 200 but got 0
+
diff --git a/LayoutTests/platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt b/LayoutTests/platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt
new file mode 100644
index 0000000..5037802
--- /dev/null
+++ b/LayoutTests/platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt
@@ -0,0 +1,5 @@
+CONSOLE MESSAGE: CORS-preflight request was blocked
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://www1.localhost:8800/XMLHttpRequest/resources/auth1/corsenabled.py due to access control checks.
+
+PASS XMLHttpRequest: send() - "Basic" authenticated CORS requests with user name and password passed to open() (asserts failure) 
+
diff --git a/LayoutTests/platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt b/LayoutTests/platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt
new file mode 100644
index 0000000..b20bc2c
--- /dev/null
+++ b/LayoutTests/platform/mac-wk1/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt
@@ -0,0 +1,5 @@
+CONSOLE MESSAGE: CORS-preflight request was blocked
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://nonexistent-origin.localhost:8800/ due to access control checks.
+
+PASS XMLHttpRequest: The send() method: Fire a progress event named error when Network error happens (synchronous flag is unset) 
+
diff --git a/LayoutTests/platform/mac-wk1/imported/w3c/web-platform-tests/cors/late-upload-events-expected.txt b/LayoutTests/platform/mac-wk1/imported/w3c/web-platform-tests/cors/late-upload-events-expected.txt
new file mode 100644
index 0000000..5d86ccf
--- /dev/null
+++ b/LayoutTests/platform/mac-wk1/imported/w3c/web-platform-tests/cors/late-upload-events-expected.txt
@@ -0,0 +1,10 @@
+Blocked access to external URL http://www1.localhost:8800/cors/resources/status.py?headers=custom-header
+CONSOLE MESSAGE: line 30: XMLHttpRequest cannot load http://www1.localhost:8800/cors/resources/status.py?headers=custom-header due to access control checks.
+CONSOLE MESSAGE: CORS-preflight request was blocked
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://www1.localhost:8800/cors/resources/status.py?headers=custom-header due to access control checks.
+Adding upload event listeners after send()
+
+
+FAIL Late listeners: No preflight assert_equals: expected 200 but got 0
+FAIL Late listeners: Preflight assert_equals: expected 200 but got 0
+
diff --git a/LayoutTests/platform/win/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt b/LayoutTests/platform/win/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt
new file mode 100644
index 0000000..49f2671
--- /dev/null
+++ b/LayoutTests/platform/win/http/tests/security/contentSecurityPolicy/connect-src-eventsource-redirect-to-blocked-expected.txt
@@ -0,0 +1,8 @@
+CONSOLE MESSAGE: Refused to connect to http://localhost:8000/eventsource/resources/simple-event-stream.asis because it does not appear in the connect-src directive of the Content Security Policy.
+CONSOLE MESSAGE: Cross-origin redirection denied by Content Security Policy.
+CONSOLE MESSAGE: EventSource cannot load http://127.0.0.1:8000/security/contentSecurityPolicy/resources/redir.php?url=http://localhost:8000/eventsource/resources/simple-event-stream.asis due to access control checks.
+PASS EventSource() did not follow the disallowed redirect.
+PASS successfullyParsed is true
+
+TEST COMPLETE
+
diff --git a/LayoutTests/platform/win/http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt b/LayoutTests/platform/win/http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt
new file mode 100644
index 0000000..8ecc3cb
--- /dev/null
+++ b/LayoutTests/platform/win/http/tests/security/contentSecurityPolicy/connect-src-xmlhttprequest-redirect-to-blocked-expected.txt
@@ -0,0 +1,8 @@
+CONSOLE MESSAGE: Refused to connect to http://localhost:8000/security/contentSecurityPolicy/resources/xhr-redirect-not-allowed.pl because it does not appear in the connect-src directive of the Content Security Policy.
+CONSOLE MESSAGE: Cross-origin redirection denied by Content Security Policy.
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://127.0.0.1:8000/security/contentSecurityPolicy/resources/redir.php?url=http://localhost:8000/security/contentSecurityPolicy/resources/xhr-redirect-not-allowed.pl due to access control checks.
+PASS XMLHttpRequest.send() did not follow the disallowed redirect.
+PASS successfullyParsed is true
+
+TEST COMPLETE
+
diff --git a/LayoutTests/platform/win/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt b/LayoutTests/platform/win/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt
new file mode 100644
index 0000000..f8e8d59
--- /dev/null
+++ b/LayoutTests/platform/win/http/tests/security/contentSecurityPolicy/worker-csp-blocks-xhr-redirect-cross-origin-expected.txt
@@ -0,0 +1,3 @@
+This tests an XHR request made from a worker is blocked if it redirects to a cross-origin resource that is not listed as a connect-src in the CSP of the worker.
+
+PASS threw exception NetworkError:  A network error occurred..
diff --git a/LayoutTests/platform/win/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt b/LayoutTests/platform/win/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt
new file mode 100644
index 0000000..b7fe744
--- /dev/null
+++ b/LayoutTests/platform/win/http/tests/xmlhttprequest/access-control-and-redirects-async-expected.txt
@@ -0,0 +1,34 @@
+CONSOLE MESSAGE: Cross-origin redirection to http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi denied by Cross-Origin Resource Sharing policy: Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi due to access control checks.
+CONSOLE MESSAGE: Cross-origin redirection to foo://bar.cgi denied by Cross-Origin Resource Sharing policy: URL is either a non-HTTP URL or contains credentials.
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=foo://bar.cgi&%20%20access-control-allow-origin=http://127.0.0.1:8000 due to access control checks.
+CONSOLE MESSAGE: Preflight response is not successful
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?redirect-preflight=true&%20%20url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi&%20%20access-control-allow-origin=* due to access control checks.
+CONSOLE MESSAGE: Request header field x-webkit is not allowed by Access-Control-Allow-Headers.
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi due to access control checks.
+Tests that asynchronous XMLHttpRequests handle redirects according to the CORS standard.
+
+Testing http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi without credentials
+Expecting success: false
+PASS: 0
+Testing http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi&  access-control-allow-origin=http://127.0.0.1:8000 without credentials
+Expecting success: true
+PASS: PASS: Cross-domain access allowed.
+
+Testing http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=http://username:password@localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi&  access-control-allow-origin=http://127.0.0.1:8000 without credentials
+Expecting success: true
+PASS: PASS: Cross-domain access allowed.
+
+Testing http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?url=foo://bar.cgi&  access-control-allow-origin=http://127.0.0.1:8000 without credentials
+Expecting success: false
+PASS: 0
+Testing http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?redirect-preflight=true&  url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi&  access-control-allow-origin=* without credentials
+Expecting success: false
+PASS: 0
+Testing http://localhost:8000/xmlhttprequest/resources/redirect-cors.php?redirect-preflight=false&  url=http://localhost:8000/xmlhttprequest/resources/access-control-basic-allow-star.cgi&  access-control-allow-origin=*&  access-control-allow-headers=x-webkit without credentials
+Expecting success: false
+PASS: 0
+Testing resources/redirect-cors.php?url=http://127.0.0.1:8000/xmlhttprequest/resources/get.txt without credentials
+Expecting success: true
+PASS: PASS
+
diff --git a/LayoutTests/platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/late-upload-events-expected.txt b/LayoutTests/platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/late-upload-events-expected.txt
new file mode 100644
index 0000000..5d86ccf
--- /dev/null
+++ b/LayoutTests/platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/late-upload-events-expected.txt
@@ -0,0 +1,10 @@
+Blocked access to external URL http://www1.localhost:8800/cors/resources/status.py?headers=custom-header
+CONSOLE MESSAGE: line 30: XMLHttpRequest cannot load http://www1.localhost:8800/cors/resources/status.py?headers=custom-header due to access control checks.
+CONSOLE MESSAGE: CORS-preflight request was blocked
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://www1.localhost:8800/cors/resources/status.py?headers=custom-header due to access control checks.
+Adding upload event listeners after send()
+
+
+FAIL Late listeners: No preflight assert_equals: expected 200 but got 0
+FAIL Late listeners: Preflight assert_equals: expected 200 but got 0
+
diff --git a/LayoutTests/platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt b/LayoutTests/platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt
new file mode 100644
index 0000000..5037802
--- /dev/null
+++ b/LayoutTests/platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/send-authentication-basic-cors-expected.txt
@@ -0,0 +1,5 @@
+CONSOLE MESSAGE: CORS-preflight request was blocked
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://www1.localhost:8800/XMLHttpRequest/resources/auth1/corsenabled.py due to access control checks.
+
+PASS XMLHttpRequest: send() - "Basic" authenticated CORS requests with user name and password passed to open() (asserts failure) 
+
diff --git a/LayoutTests/platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt b/LayoutTests/platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt
new file mode 100644
index 0000000..b20bc2c
--- /dev/null
+++ b/LayoutTests/platform/win/imported/w3c/web-platform-tests/XMLHttpRequest/send-network-error-async-events.sub-expected.txt
@@ -0,0 +1,5 @@
+CONSOLE MESSAGE: CORS-preflight request was blocked
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://nonexistent-origin.localhost:8800/ due to access control checks.
+
+PASS XMLHttpRequest: The send() method: Fire a progress event named error when Network error happens (synchronous flag is unset) 
+
diff --git a/LayoutTests/platform/win/imported/w3c/web-platform-tests/cors/late-upload-events-expected.txt b/LayoutTests/platform/win/imported/w3c/web-platform-tests/cors/late-upload-events-expected.txt
new file mode 100644
index 0000000..5d86ccf
--- /dev/null
+++ b/LayoutTests/platform/win/imported/w3c/web-platform-tests/cors/late-upload-events-expected.txt
@@ -0,0 +1,10 @@
+Blocked access to external URL http://www1.localhost:8800/cors/resources/status.py?headers=custom-header
+CONSOLE MESSAGE: line 30: XMLHttpRequest cannot load http://www1.localhost:8800/cors/resources/status.py?headers=custom-header due to access control checks.
+CONSOLE MESSAGE: CORS-preflight request was blocked
+CONSOLE MESSAGE: XMLHttpRequest cannot load http://www1.localhost:8800/cors/resources/status.py?headers=custom-header due to access control checks.
+Adding upload event listeners after send()
+
+
+FAIL Late listeners: No preflight assert_equals: expected 200 but got 0
+FAIL Late listeners: Preflight assert_equals: expected 200 but got 0
+
diff --git a/Source/WebCore/ChangeLog b/Source/WebCore/ChangeLog
index ea0f6c2..742c833 100644
--- a/Source/WebCore/ChangeLog
+++ b/Source/WebCore/ChangeLog
@@ -1,3 +1,44 @@
+2018-04-27  Youenn Fablet  <youenn@apple.com>
+
+        Use NetworkLoadChecker for XHR/fetch loads
+        https://bugs.webkit.org/show_bug.cgi?id=184741
+
+        Reviewed by Chris Dumez.
+
+        Covered by existing tests.
+
+        * loader/DocumentThreadableLoader.cpp:
+        (WebCore::DocumentThreadableLoader::shouldSetHTTPHeadersToKeep const):
+        We need to set this option for CORS done in NetworkProcess.
+        (WebCore::DocumentThreadableLoader::DocumentThreadableLoader):
+        Set httpHeadersTokeep when needed (service worker or CORS loads).
+        Remove the synchronous disabling of preflight since this is now also done for asynchronous loads.
+        (WebCore::DocumentThreadableLoader::checkURLSchemeAsCORSEnabled):
+        Helper routine to make the same check for both simple and preflight case.
+        This allows more consistent error logging between WK1 and WK2.
+        (WebCore::DocumentThreadableLoader::makeCrossOriginAccessRequest):
+        Skip preflight in case this is done in NetworkProcess.
+        (WebCore::DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest):
+        (WebCore::isResponseComingFromNetworkProcess):
+        (WebCore::DocumentThreadableLoader::redirectReceived):
+        Bypass security checks when they are already done in NetworkProcess.
+        (WebCore::DocumentThreadableLoader::didFail):
+        In case of AccessControl error, it might be due to a CSP check done in NetworkProcess.
+        Check it again to enable specific CSP console logging and error reporting.
+        (WebCore::DocumentThreadableLoader::loadRequest):
+        Recreating the error in case of synchronous loads to be able to log it adequately.
+        (WebCore::DocumentThreadableLoader::isDoingSecurityChecksInNetworkProcess const):
+        * loader/DocumentThreadableLoader.h:
+        * loader/SubresourceLoader.cpp:
+        (WebCore::SubresourceLoader::checkResponseCrossOriginAccessControl):
+        Specific handling of SameOrigin credential mode for which cross-origin load will not use any credential.
+        (WebCore::SubresourceLoader::checkRedirectionCrossOriginAccessControl):
+        We keep the application headers so that DocumentThreadableLoader does not have to restart a brand new load.
+        * loader/cache/CachedResourceLoader.cpp:
+        (WebCore::CachedResourceLoader::requestResource):
+        DocumentThreadableLoader is setting referrer and origin directly. Until we fix that, we remove them from the original requests
+        as applications are not supposed to set these headers.
+
 2018-04-27  Wenson Hsieh  <wenson_hsieh@apple.com>
 
         Add an experimental feature flag for viewport "min-device-width"
diff --git a/Source/WebCore/loader/DocumentThreadableLoader.cpp b/Source/WebCore/loader/DocumentThreadableLoader.cpp
index a7edc8b..79ae616 100644
--- a/Source/WebCore/loader/DocumentThreadableLoader.cpp
+++ b/Source/WebCore/loader/DocumentThreadableLoader.cpp
@@ -89,6 +89,24 @@
     return create(document, client, WTFMove(request), options, nullptr, nullptr, WTFMove(referrer), ShouldLogError::Yes);
 }
 
+static inline bool isDoingSecurityChecksInNetworkProcess()
+{
+    return platformStrategies()->loaderStrategy()->isDoingLoadingSecurityChecks();
+}
+
+bool DocumentThreadableLoader::shouldSetHTTPHeadersToKeep() const
+{
+    if (m_options.mode == FetchOptions::Mode::Cors && isDoingSecurityChecksInNetworkProcess())
+        return true;
+
+#if ENABLE(SERVICE_WORKER)
+    if (m_options.serviceWorkersMode == ServiceWorkersMode::All && m_async)
+        return m_options.serviceWorkerRegistrationIdentifier || m_document.activeServiceWorker();
+#endif
+
+    return false;
+}
+
 DocumentThreadableLoader::DocumentThreadableLoader(Document& document, ThreadableLoaderClient& client, BlockingBehavior blockingBehavior, ResourceRequest&& request, const ThreadableLoaderOptions& options, RefPtr<SecurityOrigin>&& origin, std::unique_ptr<ContentSecurityPolicy>&& contentSecurityPolicy, String&& referrer, ShouldLogError shouldLogError)
     : m_client(&client)
     , m_document(document)
@@ -107,10 +125,6 @@
     // Setting a referrer header is only supported in the async code path.
     ASSERT(m_async || m_referrer.isEmpty());
 
-    // No need to do preflight if the network stack will do it for us.
-    if (!m_async && platformStrategies()->loaderStrategy()->isDoingLoadingSecurityChecks())
-        m_options.preflightPolicy = PreflightPolicy::Prevent;
-
     // Referrer and Origin headers should be set after the preflight if any.
     ASSERT(!request.hasHTTPReferrer() && !request.hasHTTPOrigin());
 
@@ -121,21 +135,18 @@
     ASSERT(!request.httpHeaderFields().contains(HTTPHeaderName::Origin));
 
     // Copy headers if we need to replay the request after a redirection.
-    if (!m_async || m_options.mode == FetchOptions::Mode::Cors)
+    if (m_options.mode == FetchOptions::Mode::Cors)
         m_originalHeaders = request.httpHeaderFields();
 
-#if ENABLE(SERVICE_WORKER)
-    if (m_options.serviceWorkersMode == ServiceWorkersMode::All && m_async && (m_options.serviceWorkerRegistrationIdentifier || document.activeServiceWorker()))
+    if (shouldSetHTTPHeadersToKeep())
         m_options.httpHeadersToKeep = httpHeadersToKeepFromCleaning(request.httpHeaderFields());
-#endif
 
     if (document.page() && document.page()->isRunningUserScripts() && SchemeRegistry::isUserExtensionScheme(request.url().protocol().toStringWithoutCopying())) {
         m_options.mode = FetchOptions::Mode::NoCors;
         m_options.filteringPolicy = ResponseFilteringPolicy::Disable;
     }
 
-    if (m_contentSecurityPolicy || !document.shouldBypassMainWorldContentSecurityPolicy())
-        m_options.cspResponseHeaders = this->contentSecurityPolicy().responseHeaders();
+    m_options.cspResponseHeaders = m_options.contentSecurityPolicyEnforcement != ContentSecurityPolicyEnforcement::DoNotEnforce ? this->contentSecurityPolicy().responseHeaders() : ContentSecurityPolicyResponseHeaders { };
 
     // As per step 11 of https://fetch.spec.whatwg.org/#main-fetch, data scheme (if same-origin data-URL flag is set) and about scheme are considered same-origin.
     if (request.url().protocolIsData())
@@ -154,13 +165,24 @@
     makeCrossOriginAccessRequest(WTFMove(request));
 }
 
+bool DocumentThreadableLoader::checkURLSchemeAsCORSEnabled(const URL& url)
+{
+    // Cross-origin requests are only allowed for HTTP and registered schemes. We would catch this when checking response headers later, but there is no reason to send a request that's guaranteed to be denied.
+    if (!SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(url.protocol().toStringWithoutCopying())) {
+        logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, url, "Cross origin requests are only supported for HTTP.", ResourceError::Type::AccessControl));
+        return false;
+    }
+    return true;
+}
+
 void DocumentThreadableLoader::makeCrossOriginAccessRequest(ResourceRequest&& request)
 {
     ASSERT(m_options.mode == FetchOptions::Mode::Cors);
 
-    if ((m_options.preflightPolicy == PreflightPolicy::Consider && isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields())) || m_options.preflightPolicy == PreflightPolicy::Prevent)
-        makeSimpleCrossOriginAccessRequest(WTFMove(request));
-    else {
+    if ((m_options.preflightPolicy == PreflightPolicy::Consider && isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields())) || m_options.preflightPolicy == PreflightPolicy::Prevent || isDoingSecurityChecksInNetworkProcess()) {
+        if (checkURLSchemeAsCORSEnabled(request.url()))
+            makeSimpleCrossOriginAccessRequest(WTFMove(request));
+    } else {
 #if ENABLE(SERVICE_WORKER)
         if (m_options.serviceWorkersMode == ServiceWorkersMode::All && m_async) {
             if (m_options.serviceWorkerRegistrationIdentifier || document().activeServiceWorker()) {
@@ -172,6 +194,9 @@
             }
         }
 #endif
+        if (!checkURLSchemeAsCORSEnabled(request.url()))
+            return;
+
         m_simpleRequest = false;
         if (CrossOriginPreflightResultCache::singleton().canSkipPreflight(securityOrigin().toString(), request.url(), m_options.storedCredentialsPolicy, request.httpMethod(), request.httpHeaderFields()))
             preflightSuccess(WTFMove(request));
@@ -182,14 +207,8 @@
 
 void DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest(ResourceRequest&& request)
 {
-    ASSERT(m_options.preflightPolicy != PreflightPolicy::Force);
-    ASSERT(m_options.preflightPolicy == PreflightPolicy::Prevent || isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields()));
-
-    // Cross-origin requests are only allowed for HTTP and registered schemes. We would catch this when checking response headers later, but there is no reason to send a request that's guaranteed to be denied.
-    if (!SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(request.url().protocol().toStringWithoutCopying())) {
-        logErrorAndFail(ResourceError(errorDomainWebKitInternal, 0, request.url(), "Cross origin requests are only supported for HTTP.", ResourceError::Type::AccessControl));
-        return;
-    }
+    ASSERT(m_options.preflightPolicy != PreflightPolicy::Force || isDoingSecurityChecksInNetworkProcess());
+    ASSERT(m_options.preflightPolicy == PreflightPolicy::Prevent || isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields()) || isDoingSecurityChecksInNetworkProcess());
 
     updateRequestForAccessControl(request, securityOrigin(), m_options.storedCredentialsPolicy);
     loadRequest(WTFMove(request), DoSecurityCheck);
@@ -247,6 +266,12 @@
         m_preflightChecker = std::nullopt;
 }
 
+static inline bool isResponseComingFromNetworkProcess(const ResourceResponse& response)
+{
+    auto source = response.source();
+    return source == ResourceResponse::Source::Network || source == ResourceResponse::Source::DiskCache || source == ResourceResponse::Source::DiskCacheAfterValidation;
+}
+
 void DocumentThreadableLoader::redirectReceived(CachedResource& resource, ResourceRequest&& request, const ResourceResponse& redirectResponse, CompletionHandler<void(ResourceRequest&&)>&& completionHandler)
 {
     ASSERT(m_client);
@@ -270,6 +295,11 @@
         return completionHandler(WTFMove(request));
     }
 
+    if (isDoingSecurityChecksInNetworkProcess() && isResponseComingFromNetworkProcess(redirectResponse)) {
+        completionHandler(WTFMove(request));
+        return;
+    }
+
     // Allow same origin requests to continue after allowing clients to audit the redirect.
     if (isAllowedRedirect(request.url()))
         return completionHandler(WTFMove(request));
@@ -436,6 +466,15 @@
         return;
     }
 #endif
+
+    // NetworkProcess might return a CSP violation as an AccessControl error in case of redirection.
+    // Let's recheck CSP to generate the report if needed.
+    // FIXME: We should introduce an error dedicated to CSP violation.
+    if (isDoingSecurityChecksInNetworkProcess() && error.isAccessControl() && error.failingURL().protocolIsInHTTPFamily() && !isAllowedByContentSecurityPolicy(error.failingURL(), ContentSecurityPolicy::RedirectResponseReceived::Yes)) {
+        reportContentSecurityPolicyError(m_resource->resourceRequest().url());
+        return;
+    }
+
     if (m_shouldLogError == ShouldLogError::Yes)
         logError(m_document, error, m_options.initiator);
 
@@ -540,7 +579,7 @@
         return;
     }
 
-    if (!platformStrategies()->loaderStrategy()->isDoingLoadingSecurityChecks()) {
+    if (!isDoingSecurityChecksInNetworkProcess()) {
         // FIXME: FrameLoader::loadSynchronously() does not tell us whether a redirect happened or not, so we guess by comparing the
         // request and response URLs. This isn't a perfect test though, since a server can serve a redirect to the same URL that was
         // requested. Also comparing the request and response URLs as strings will fail if the requestURL still has its credentials.
diff --git a/Source/WebCore/loader/DocumentThreadableLoader.h b/Source/WebCore/loader/DocumentThreadableLoader.h
index c2bbc4d..38382ed 100644
--- a/Source/WebCore/loader/DocumentThreadableLoader.h
+++ b/Source/WebCore/loader/DocumentThreadableLoader.h
@@ -118,6 +118,9 @@
         void reportIntegrityMetadataError(const URL&);
         void logErrorAndFail(const ResourceError&);
 
+        bool shouldSetHTTPHeadersToKeep() const;
+        bool checkURLSchemeAsCORSEnabled(const URL&);
+
         CachedResourceHandle<CachedRawResource> m_resource;
         ThreadableLoaderClient* m_client;
         Document& m_document;
diff --git a/Source/WebCore/loader/ResourceLoaderOptions.h b/Source/WebCore/loader/ResourceLoaderOptions.h
index e792dde..7be5f98 100644
--- a/Source/WebCore/loader/ResourceLoaderOptions.h
+++ b/Source/WebCore/loader/ResourceLoaderOptions.h
@@ -155,11 +155,8 @@
     ApplicationCacheMode applicationCacheMode { ApplicationCacheMode::Use };
 #if ENABLE(SERVICE_WORKER)
     std::optional<ServiceWorkerRegistrationIdentifier> serviceWorkerRegistrationIdentifier;
-    // WebKit loading code is adding some HTTP headers between the application and the time service worker intercepts the fetch.
-    // We keep a list of these headers so that we only remove the ones that are set by the loading code and not by the application.
-    // FIXME: Remove this when service worker fetch interception happens before the setting of these headers in the loading code.
-    HashSet<HTTPHeaderName, WTF::IntHash<HTTPHeaderName>, WTF::StrongEnumHashTraits<HTTPHeaderName>> httpHeadersToKeep;
 #endif
+    HashSet<HTTPHeaderName, WTF::IntHash<HTTPHeaderName>, WTF::StrongEnumHashTraits<HTTPHeaderName>> httpHeadersToKeep;
 
     ClientCredentialPolicy clientCredentialPolicy { ClientCredentialPolicy::CannotAskClientForCredentials };
     unsigned maxRedirectCount { 20 };
diff --git a/Source/WebCore/loader/SubresourceLoader.cpp b/Source/WebCore/loader/SubresourceLoader.cpp
index 08d766d..f547035 100644
--- a/Source/WebCore/loader/SubresourceLoader.cpp
+++ b/Source/WebCore/loader/SubresourceLoader.cpp
@@ -530,7 +530,8 @@
 #endif
 
     ASSERT(m_origin);
-    return passesAccessControlCheck(response, options().storedCredentialsPolicy, *m_origin, errorDescription);
+
+    return passesAccessControlCheck(response, options().credentials == FetchOptions::Credentials::Include ? StoredCredentialsPolicy::Use : StoredCredentialsPolicy::DoNotUse, *m_origin, errorDescription);
 }
 
 bool SubresourceLoader::checkRedirectionCrossOriginAccessControl(const ResourceRequest& previousRequest, const ResourceResponse& redirectResponse, ResourceRequest& newRequest, String& errorMessage)
@@ -571,7 +572,7 @@
     updateReferrerPolicy(redirectResponse.httpHeaderField(HTTPHeaderName::ReferrerPolicy));
     
     if (redirectingToNewOrigin) {
-        cleanHTTPRequestHeadersForAccessControl(newRequest);
+        cleanHTTPRequestHeadersForAccessControl(newRequest, options().httpHeadersToKeep);
         updateRequestForAccessControl(newRequest, *m_origin, options().storedCredentialsPolicy);
     }
     
diff --git a/Source/WebCore/loader/cache/CachedResourceLoader.cpp b/Source/WebCore/loader/cache/CachedResourceLoader.cpp
index ca68167..85daf03 100644
--- a/Source/WebCore/loader/cache/CachedResourceLoader.cpp
+++ b/Source/WebCore/loader/cache/CachedResourceLoader.cpp
@@ -776,8 +776,11 @@
 
     // Entry point to https://fetch.spec.whatwg.org/#main-fetch.
     std::unique_ptr<ResourceRequest> originalRequest;
-    if (CachedResource::shouldUsePingLoad(type))
+    if (CachedResource::shouldUsePingLoad(type) || request.options().destination == FetchOptions::Destination::EmptyString) {
         originalRequest = std::make_unique<ResourceRequest>(request.resourceRequest());
+        originalRequest->clearHTTPReferrer();
+        originalRequest->clearHTTPOrigin();
+    }
 
     if (Document* document = this->document())
         request.upgradeInsecureRequestIfNeeded(*document);
diff --git a/Source/WebCore/platform/SchemeRegistry.h b/Source/WebCore/platform/SchemeRegistry.h
index 0b93bdb..7992f90 100644
--- a/Source/WebCore/platform/SchemeRegistry.h
+++ b/Source/WebCore/platform/SchemeRegistry.h
@@ -82,7 +82,7 @@
 
     // Allow non-HTTP schemes to be registered to allow CORS requests.
     WEBCORE_EXPORT static void registerURLSchemeAsCORSEnabled(const String& scheme);
-    static bool shouldTreatURLSchemeAsCORSEnabled(const String& scheme);
+    WEBCORE_EXPORT static bool shouldTreatURLSchemeAsCORSEnabled(const String& scheme);
 
     // Allow resources from some schemes to load on a page, regardless of its
     // Content Security Policy.
diff --git a/Source/WebKit/ChangeLog b/Source/WebKit/ChangeLog
index 70f977f..0101447 100644
--- a/Source/WebKit/ChangeLog
+++ b/Source/WebKit/ChangeLog
@@ -1,3 +1,31 @@
+2018-04-27  Youenn Fablet  <youenn@apple.com>
+
+        Use NetworkLoadChecker for XHR/fetch loads
+        https://bugs.webkit.org/show_bug.cgi?id=184741
+
+        Reviewed by Chris Dumez.
+
+        * NetworkProcess/NetworkCORSPreflightChecker.cpp:
+        (WebKit::NetworkCORSPreflightChecker::didCompleteWithError):
+        Pass the preflight error as completion error if any.
+        * NetworkProcess/NetworkLoad.cpp:
+        (WebKit::NetworkLoad::willPerformHTTPRedirection):
+        Set response source to Network so that checks relying on that are correct.
+        * NetworkProcess/NetworkLoadChecker.cpp:
+        (WebKit::NetworkLoadChecker::validateResponse):
+        Adding Oppaqueredirect tainting.
+        (NetworkLoadChecker::doesNotNeedCORSCheck):
+        Adding a check to only activate CORS checks for CORS enabled schemes.
+        Non CORS enabled schemes loads should have failed in WebProcess already.
+        (WebKit::NetworkLoadChecker::checkCORSRedirectedRequest):
+        Remove Authorization header as done by SubresourceLoader.
+        (WebKit::NetworkLoadChecker::checkCORSRequestWithPreflight):
+        If error is cancellation, we still want to call the completion handler.
+        * NetworkProcess/NetworkResourceLoader.cpp:
+        Activate network load checker for all types of loads.
+        (WebKit::NetworkResourceLoader::willSendRedirectedRequest):
+        Handle manual redirection by directly calling didReceiveResponse.
+
 2018-04-27  Wenson Hsieh  <wenson_hsieh@apple.com>
 
         Add an experimental feature flag for viewport "min-device-width"
diff --git a/Source/WebKit/NetworkProcess/NetworkCORSPreflightChecker.cpp b/Source/WebKit/NetworkProcess/NetworkCORSPreflightChecker.cpp
index de833d6..7b770a7 100644
--- a/Source/WebKit/NetworkProcess/NetworkCORSPreflightChecker.cpp
+++ b/Source/WebKit/NetworkProcess/NetworkCORSPreflightChecker.cpp
@@ -97,11 +97,15 @@
     RELEASE_LOG_IF_ALLOWED("didReceiveData");
 }
 
-void NetworkCORSPreflightChecker::didCompleteWithError(const WebCore::ResourceError& error, const WebCore::NetworkLoadMetrics&)
+void NetworkCORSPreflightChecker::didCompleteWithError(const WebCore::ResourceError& preflightError, const WebCore::NetworkLoadMetrics&)
 {
-    if (!error.isNull()) {
+    if (!preflightError.isNull()) {
         RELEASE_LOG_IF_ALLOWED("didCompleteWithError");
-        m_completionCallback(ResourceError { errorDomainWebKitInternal, 0, m_parameters.originalRequest.url(), ASCIILiteral("Preflight response is not successful"), ResourceError::Type::AccessControl });
+        auto error = preflightError;
+        if (error.isNull() || error.isGeneral())
+            error.setType(ResourceError::Type::AccessControl);
+
+        m_completionCallback(WTFMove(error));
         return;
     }
 
diff --git a/Source/WebKit/NetworkProcess/NetworkLoad.cpp b/Source/WebKit/NetworkProcess/NetworkLoad.cpp
index d5e2825..fdb6e13 100644
--- a/Source/WebKit/NetworkProcess/NetworkLoad.cpp
+++ b/Source/WebKit/NetworkProcess/NetworkLoad.cpp
@@ -239,6 +239,7 @@
     ASSERT(RunLoop::isMain());
     ASSERT(!m_redirectCompletionHandler);
 
+    redirectResponse.setSource(ResourceResponse::Source::Network);
     m_redirectCompletionHandler = WTFMove(completionHandler);
 
 #if ENABLE(NETWORK_CAPTURE)
diff --git a/Source/WebKit/NetworkProcess/NetworkLoadChecker.cpp b/Source/WebKit/NetworkProcess/NetworkLoadChecker.cpp
index a7c5eb8..ec2461d 100644
--- a/Source/WebKit/NetworkProcess/NetworkLoadChecker.cpp
+++ b/Source/WebKit/NetworkProcess/NetworkLoadChecker.cpp
@@ -35,6 +35,7 @@
 #include <WebCore/CrossOriginAccessControl.h>
 #include <WebCore/CrossOriginPreflightResultCache.h>
 #include <WebCore/HTTPParsers.h>
+#include <WebCore/SchemeRegistry.h>
 
 #define RELEASE_LOG_IF_ALLOWED(fmt, ...) RELEASE_LOG_IF(m_sessionID.isAlwaysOnLoggingAllowed(), Network, "%p - NetworkLoadChecker::" fmt, this, ##__VA_ARGS__)
 
@@ -122,6 +123,11 @@
     if (m_redirectCount)
         response.setRedirected(true);
 
+    if (response.type() == ResourceResponse::Type::Opaqueredirect) {
+        response.setTainting(ResourceResponse::Tainting::Opaqueredirect);
+        return { };
+    }
+
     if (m_isSameOriginRequest) {
         response.setTainting(ResourceResponse::Tainting::Basic);
         return { };
@@ -237,13 +243,13 @@
         // https://fetch.spec.whatwg.org/#concept-http-redirect-fetch (Step 10).
         if (!m_origin || !m_origin->isUnique())
             m_origin = SecurityOrigin::createUnique();
-
-        // FIXME: Add support for SameOrigin credentials.
     }
 
     // FIXME: We should set the request referrer according the referrer policy.
 
     // Let's fetch the request with the original headers (equivalent to request cloning specified by fetch algorithm).
+    if (!request.httpHeaderFields().contains(HTTPHeaderName::Authorization))
+        m_firstRequestHeaders.remove(HTTPHeaderName::Authorization);
     request.setHTTPHeaderFields(m_firstRequestHeaders);
 
     checkCORSRequest(WTFMove(request), WTFMove(handler));
@@ -272,11 +278,8 @@
         m_sessionID,
         m_storedCredentialsPolicy
     };
-    m_corsPreflightChecker = std::make_unique<NetworkCORSPreflightChecker>(WTFMove(parameters), [this, request = WTFMove(request), handler = WTFMove(handler)](auto&& error) mutable {
-        if (error.isCancellation())
-            return;
-
-        RELEASE_LOG_IF_ALLOWED("checkCORSRequestWithPreflight - makeCrossOriginAccessRequestWithPreflight preflight complete, success: %d forRedirect? %d", error.isNull(), isRedirected());
+    m_corsPreflightChecker = std::make_unique<NetworkCORSPreflightChecker>(WTFMove(parameters), [this, request = WTFMove(request), handler = WTFMove(handler), isRedirected = isRedirected()](auto&& error) mutable {
+        RELEASE_LOG_IF_ALLOWED("checkCORSRequestWithPreflight - makeCrossOriginAccessRequestWithPreflight preflight complete, success: %d forRedirect? %d", error.isNull(), isRedirected);
 
         if (!error.isNull()) {
             handler(makeUnexpected(WTFMove(error)));
@@ -295,6 +298,9 @@
     if (m_options.mode == FetchOptions::Mode::NoCors || m_options.mode == FetchOptions::Mode::Navigate)
         return true;
 
+    if (!SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(url.protocol().toStringWithoutCopying()))
+        return true;
+
     return m_isSameOriginRequest && m_origin->canRequest(url);
 }
 
diff --git a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp b/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp
index a0ed08e..4fadfe7 100644
--- a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp
+++ b/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp
@@ -90,18 +90,6 @@
     data.delayedReply = nullptr;
 }
 
-static inline bool shouldUseNetworkLoadChecker(bool isSynchronous, const NetworkResourceLoadParameters& parameters)
-{
-    if (isSynchronous)
-        return true;
-
-    if (!parameters.shouldRestrictHTTPResponseAccess)
-        return false;
-
-    // FIXME: Add support for Document and EmptyString.
-    return parameters.options.destination != FetchOptions::Destination::Document && parameters.options.destination != FetchOptions::Destination::EmptyString;
-}
-
 NetworkResourceLoader::NetworkResourceLoader(NetworkResourceLoadParameters&& parameters, NetworkConnectionToWebProcess& connection, RefPtr<Messages::NetworkConnectionToWebProcess::PerformSynchronousLoad::DelayedReply>&& synchronousReply)
     : m_parameters { WTFMove(parameters) }
     , m_connection { connection }
@@ -122,7 +110,7 @@
         }
     }
 
-    if (shouldUseNetworkLoadChecker(!!synchronousReply, m_parameters)) {
+    if (synchronousReply || parameters.shouldRestrictHTTPResponseAccess) {
         m_networkLoadChecker = NetworkLoadChecker::create(FetchOptions { m_parameters.options }, m_parameters.sessionID, HTTPHeaderMap { m_parameters.originalRequestHeaders }, URL { m_parameters.request.url() }, m_parameters.sourceOrigin.copyRef(), m_parameters.preflightPolicy);
         if (m_parameters.cspResponseHeaders)
             m_networkLoadChecker->setCSPResponseHeaders(ContentSecurityPolicyResponseHeaders { m_parameters.cspResponseHeaders.value() });
@@ -561,6 +549,14 @@
             if (!result.has_value()) {
                 if (result.error().isCancellation())
                     return;
+
+                if (m_parameters.options.redirect == FetchOptions::Redirect::Manual) {
+                    redirectResponse.setType(ResourceResponse::Type::Opaqueredirect);
+                    this->didReceiveResponse(WTFMove(redirectResponse));
+                    this->didFinishLoading({ });
+                    return;
+                }
+
                 this->didFailLoading(result.error());
                 return;
             }