Requests handled by Service Worker should not go through preflighting
authorcommit-queue@webkit.org <commit-queue@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 3 Nov 2017 23:09:28 +0000 (23:09 +0000)
committercommit-queue@webkit.org <commit-queue@webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 3 Nov 2017 23:09:28 +0000 (23:09 +0000)
https://bugs.webkit.org/show_bug.cgi?id=179250

Patch by Youenn Fablet <youenn@apple.com> on 2017-11-03
Reviewed by Alex Christensen.

Source/WebCore:

Test: http/tests/workers/service/service-worker-crossorigin-fetch.html
In case of cross origin requests needed preflighting that may be served through SW, the following is done:
- Bypass preflight
- Put service workers mode as Only so that if SW is not handling the request, the load will fail
- If load fails, restart DocumentThreadableLoader load with preflight.

Additional testing should be added when we properly handle the case where no fetch event handler is registered in the service worker.

* loader/DocumentThreadableLoader.cpp:
(WebCore::DocumentThreadableLoader::makeCrossOriginAccessRequest):
(WebCore::DocumentThreadableLoader::didFail):
* loader/DocumentThreadableLoader.h:
* loader/ResourceLoaderOptions.h:
* loader/cache/CachedResourceRequest.cpp:
(WebCore::CachedResourceRequest::setSelectedServiceWorkerIdentifierIfNeeded):
* platform/network/ResourceErrorBase.h:

Source/WebKit:

* WebProcess/Network/WebLoaderStrategy.cpp:
(WebKit::WebLoaderStrategy::scheduleLoad):
* WebProcess/Storage/WebSWClientConnection.cpp:
(WebKit::WebSWClientConnection::startFetch):
* WebProcess/Storage/WebServiceWorkerProvider.cpp:
(WebKit::shouldHandleFetch):

LayoutTests:

* http/tests/workers/service/resources/service-worker-crossorigin-fetch-worker.js: Added.
(event.event.request.url.indexOf):
(event.event.request.url.endsWith):
* http/tests/workers/service/resources/service-worker-crossorigin-fetch.js: Added.
(done):
(async.logStatus):
(async.test):
* http/tests/workers/service/service-worker-crossorigin-fetch-expected.txt: Added.
* http/tests/workers/service/service-worker-crossorigin-fetch.html: Added.

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@224439 268f45cc-cd09-0410-ab3c-d52691b4dbfc

15 files changed:
LayoutTests/ChangeLog
LayoutTests/http/tests/workers/service/resources/service-worker-crossorigin-fetch-worker.js [new file with mode: 0644]
LayoutTests/http/tests/workers/service/resources/service-worker-crossorigin-fetch.js [new file with mode: 0644]
LayoutTests/http/tests/workers/service/service-worker-crossorigin-fetch-expected.txt [new file with mode: 0644]
LayoutTests/http/tests/workers/service/service-worker-crossorigin-fetch.html [new file with mode: 0644]
Source/WebCore/ChangeLog
Source/WebCore/loader/DocumentThreadableLoader.cpp
Source/WebCore/loader/DocumentThreadableLoader.h
Source/WebCore/loader/ResourceLoaderOptions.h
Source/WebCore/loader/cache/CachedResourceRequest.cpp
Source/WebCore/platform/network/ResourceErrorBase.h
Source/WebKit/ChangeLog
Source/WebKit/WebProcess/Network/WebLoaderStrategy.cpp
Source/WebKit/WebProcess/Storage/WebSWClientConnection.cpp
Source/WebKit/WebProcess/Storage/WebServiceWorkerProvider.cpp

index ee112c4..f761942 100644 (file)
@@ -1,3 +1,20 @@
+2017-11-03  Youenn Fablet  <youenn@apple.com>
+
+        Requests handled by Service Worker should not go through preflighting
+        https://bugs.webkit.org/show_bug.cgi?id=179250
+
+        Reviewed by Alex Christensen.
+
+        * http/tests/workers/service/resources/service-worker-crossorigin-fetch-worker.js: Added.
+        (event.event.request.url.indexOf):
+        (event.event.request.url.endsWith):
+        * http/tests/workers/service/resources/service-worker-crossorigin-fetch.js: Added.
+        (done):
+        (async.logStatus):
+        (async.test):
+        * http/tests/workers/service/service-worker-crossorigin-fetch-expected.txt: Added.
+        * http/tests/workers/service/service-worker-crossorigin-fetch.html: Added.
+
 2017-11-03  Alex Christensen  <achristensen@webkit.org>
 
         LayoutTest http/tests/loading/basic-auth-resend-wrong-credentials.html is flaky on WK2
diff --git a/LayoutTests/http/tests/workers/service/resources/service-worker-crossorigin-fetch-worker.js b/LayoutTests/http/tests/workers/service/resources/service-worker-crossorigin-fetch-worker.js
new file mode 100644 (file)
index 0000000..060e2e4
--- /dev/null
@@ -0,0 +1,15 @@
+var status = "no status";
+self.addEventListener("fetch", (event) => {
+    if (event.request.url.indexOf("status") !== -1) {
+        event.respondWith(new Response(null, {status: 200, statusText: status}));
+        return;
+    }
+    if (!event.request.url.endsWith(".fromserviceworker")) {
+        state = "unknown url";
+        event.respondWith(new Response(null, {status: 404, statusText: "Not Found"}));
+        return;
+    }
+    // Changing cors fetch into same origin fetch.
+    status = event.request.url.substring(21, event.request.url.length - 18) + " through " + "fetch";
+    event.respondWith(fetch(event.request.url.substring(21, event.request.url.length - 18)));
+});
diff --git a/LayoutTests/http/tests/workers/service/resources/service-worker-crossorigin-fetch.js b/LayoutTests/http/tests/workers/service/resources/service-worker-crossorigin-fetch.js
new file mode 100644 (file)
index 0000000..220b81f
--- /dev/null
@@ -0,0 +1,36 @@
+function done()
+{
+    finishSWTest();
+}
+
+async function logStatus()
+{
+    var response = await fetch("status");
+    log("Status is " + response.statusText);
+}
+
+async function test()
+{
+    try {
+        // Triggering potential prefligh through custom header.
+        try {
+            var response = await fetch("http://localhost:8080/resources/square100.png.fromserviceworker", {headers: {"custom": "header"}});
+            log("Failed: fetch suceeded unexpectedly");
+        } catch(e) {
+            log("PASS: Fetch failed as expected with: " + e);
+        }        
+
+        await navigator.serviceWorker.register("resources/service-worker-crossorigin-fetch-worker.js", { });
+
+        var response = await fetch("http://localhost:8080/resources/square100.png.fromserviceworker", {headers: {"custom": "header"}});
+        var buffer =  await response.arrayBuffer();
+        log("PASS: Got response with buffer byte length being " + buffer.byteLength);
+
+        await logStatus();
+    } catch(e) {
+        log("Got exception: " + e);
+    }
+    finishSWTest();
+}
+
+test();
diff --git a/LayoutTests/http/tests/workers/service/service-worker-crossorigin-fetch-expected.txt b/LayoutTests/http/tests/workers/service/service-worker-crossorigin-fetch-expected.txt
new file mode 100644 (file)
index 0000000..c4c23e4
--- /dev/null
@@ -0,0 +1,5 @@
+CONSOLE MESSAGE: Fetch API cannot load http://localhost:8080/resources/square100.png.fromserviceworker. Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.
+PASS: Fetch failed as expected with: TypeError: Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.
+PASS: Got response with buffer byte length being 12940
+Status is /resources/square100.png through fetch
+
diff --git a/LayoutTests/http/tests/workers/service/service-worker-crossorigin-fetch.html b/LayoutTests/http/tests/workers/service/service-worker-crossorigin-fetch.html
new file mode 100644 (file)
index 0000000..0f431de
--- /dev/null
@@ -0,0 +1,8 @@
+<html>
+<head>
+<script src="resources/sw-test-pre.js"></script>
+</head>
+<body>
+<script src="resources/service-worker-crossorigin-fetch.js"></script>
+</body>
+</html>
index db11cc4..6d23b53 100644 (file)
@@ -1,3 +1,27 @@
+2017-11-03  Youenn Fablet  <youenn@apple.com>
+
+        Requests handled by Service Worker should not go through preflighting
+        https://bugs.webkit.org/show_bug.cgi?id=179250
+
+        Reviewed by Alex Christensen.
+
+        Test: http/tests/workers/service/service-worker-crossorigin-fetch.html
+        In case of cross origin requests needed preflighting that may be served through SW, the following is done:
+        - Bypass preflight
+        - Put service workers mode as Only so that if SW is not handling the request, the load will fail
+        - If load fails, restart DocumentThreadableLoader load with preflight.
+
+        Additional testing should be added when we properly handle the case where no fetch event handler is registered in the service worker.
+
+        * loader/DocumentThreadableLoader.cpp:
+        (WebCore::DocumentThreadableLoader::makeCrossOriginAccessRequest):
+        (WebCore::DocumentThreadableLoader::didFail):
+        * loader/DocumentThreadableLoader.h:
+        * loader/ResourceLoaderOptions.h:
+        * loader/cache/CachedResourceRequest.cpp:
+        (WebCore::CachedResourceRequest::setSelectedServiceWorkerIdentifierIfNeeded):
+        * platform/network/ResourceErrorBase.h:
+
 2017-11-03  Zalan Bujtas  <zalan@apple.com>
 
         Remove redundant LayoutStateMaintainer argument (RenderView&)
index 902c89e..65b7ae9 100644 (file)
@@ -148,6 +148,17 @@ void DocumentThreadableLoader::makeCrossOriginAccessRequest(ResourceRequest&& re
     if ((m_options.preflightPolicy == ConsiderPreflight && isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields())) || m_options.preflightPolicy == PreventPreflight)
         makeSimpleCrossOriginAccessRequest(WTFMove(request));
     else {
+#if ENABLE(SERVICE_WORKER)
+        if (m_options.serviceWorkersMode == ServiceWorkersMode::All && m_async) {
+            if (m_options.serviceWorkerIdentifier || document().activeServiceWorker()) {
+                ASSERT(!m_bypassingPreflightForServiceWorkerRequest);
+                m_bypassingPreflightForServiceWorkerRequest = WTFMove(request);
+                m_options.serviceWorkersMode = ServiceWorkersMode::Only;
+                loadRequest(ResourceRequest { m_bypassingPreflightForServiceWorkerRequest.value() }, SkipSecurityCheck);
+                return;
+            }
+        }
+#endif
         m_simpleRequest = false;
         if (CrossOriginPreflightResultCache::singleton().canSkipPreflight(securityOrigin().toString(), request.url(), m_options.storedCredentialsPolicy, request.httpMethod(), request.httpHeaderFields()))
             preflightSuccess(WTFMove(request));
@@ -392,6 +403,13 @@ void DocumentThreadableLoader::didFinishLoading(unsigned long identifier)
 void DocumentThreadableLoader::didFail(unsigned long, const ResourceError& error)
 {
     ASSERT(m_client);
+#if ENABLE(SERVICE_WORKER)
+    if (m_bypassingPreflightForServiceWorkerRequest) {
+        m_options.serviceWorkersMode = ServiceWorkersMode::None;
+        makeCrossOriginAccessRequest(WTFMove(m_bypassingPreflightForServiceWorkerRequest.value()));
+        return;
+    }
+#endif
     logErrorAndFail(error);
 }
 
index e340dcb..10ef734 100644 (file)
@@ -133,6 +133,9 @@ namespace WebCore {
         std::optional<HTTPHeaderMap> m_originalHeaders;
 
         ShouldLogError m_shouldLogError;
+#if ENABLE(SERVICE_WORKER)
+        std::optional<ResourceRequest> m_bypassingPreflightForServiceWorkerRequest;
+#endif
     };
 
 } // namespace WebCore
index 1f01a7f..676dbc7 100644 (file)
@@ -96,6 +96,7 @@ enum class InitiatorContext {
 enum class ServiceWorkersMode {
     All,
     None,
+    Only // An error will happen if service worker is not handling the fetch. Used to bypass preflight safely.
 };
 
 enum class ContentEncodingSniffingPolicy {
index 905e104..cf95844 100644 (file)
@@ -281,7 +281,7 @@ void CachedResourceRequest::setSelectedServiceWorkerIdentifierIfNeeded(ServiceWo
     if (isPotentialNavigationOrSubresourceRequest(m_options.destination))
         return;
 
-    if (m_options.serviceWorkersMode != ServiceWorkersMode::All)
+    if (m_options.serviceWorkersMode == ServiceWorkersMode::None)
         return;
     if (m_options.serviceWorkerIdentifier)
         return;
index 658c9ca..1e6e7a0 100644 (file)
@@ -60,7 +60,7 @@ public:
 
     static bool compare(const ResourceError&, const ResourceError&);
 
-    void setType(Type);
+    WEBCORE_EXPORT void setType(Type);
     Type type() const { return m_type; }
 
 protected:
index a85272e..3e69cd0 100644 (file)
@@ -1,3 +1,17 @@
+2017-11-03  Youenn Fablet  <youenn@apple.com>
+
+        Requests handled by Service Worker should not go through preflighting
+        https://bugs.webkit.org/show_bug.cgi?id=179250
+
+        Reviewed by Alex Christensen.
+
+        * WebProcess/Network/WebLoaderStrategy.cpp:
+        (WebKit::WebLoaderStrategy::scheduleLoad):
+        * WebProcess/Storage/WebSWClientConnection.cpp:
+        (WebKit::WebSWClientConnection::startFetch):
+        * WebProcess/Storage/WebServiceWorkerProvider.cpp:
+        (WebKit::shouldHandleFetch):
+
 2017-11-03  Chris Dumez  <cdumez@apple.com>
 
         REGRESSION(r223718): Leaking WebProcessPool after reconfiguration
index e25bc79..c75ba58 100644 (file)
@@ -219,6 +219,14 @@ void WebLoaderStrategy::scheduleLoad(ResourceLoader& resourceLoader, CachedResou
     WebServiceWorkerProvider::singleton().handleFetch(resourceLoader, resource, sessionID, [trackingParameters, sessionID, shouldClearReferrerOnHTTPSToHTTPRedirect, maximumBufferingTime = maximumBufferingTime(resource), resourceLoader = makeRef(resourceLoader)] (ServiceWorkerClientFetch::Result result) mutable {
         if (result != ServiceWorkerClientFetch::Result::Unhandled)
             return;
+        if (resourceLoader->options().serviceWorkersMode == ServiceWorkersMode::Only) {
+            callOnMainThread([resourceLoader = WTFMove(resourceLoader)] {
+                auto error = internalError(resourceLoader->request().url());
+                error.setType(ResourceError::Type::AccessControl);
+                resourceLoader->didFail(error);
+            });
+            return;
+        }
 
         LOG(NetworkScheduling, "(WebProcess) WebLoaderStrategy::scheduleLoad, url '%s' will be scheduled through ServiceWorker handle fetch algorithm", resourceLoader->url().string().latin1().data());
         WebProcess::singleton().webLoaderStrategy().scheduleLoadFromNetworkProcess(resourceLoader.get(), resourceLoader->originalRequest(), trackingParameters, sessionID, shouldClearReferrerOnHTTPSToHTTPRedirect, maximumBufferingTime);
index 9a56e2f..2e3823d 100644 (file)
@@ -114,7 +114,7 @@ void WebSWClientConnection::matchRegistration(const SecurityOrigin& topOrigin, c
 
 Ref<ServiceWorkerClientFetch> WebSWClientConnection::startFetch(WebServiceWorkerProvider& provider, Ref<WebCore::ResourceLoader>&& loader, uint64_t identifier, ServiceWorkerClientFetch::Callback&& callback)
 {
-    ASSERT(loader->options().serviceWorkersMode == ServiceWorkersMode::All);
+    ASSERT(loader->options().serviceWorkersMode != ServiceWorkersMode::None);
     // FIXME: Decide whether to assert for loader->options().serviceWorkerIdentifier once we have a story for navigation loads.
 
     send(Messages::WebSWServerConnection::StartFetch(identifier, loader->options().serviceWorkerIdentifier, loader->originalRequest(), loader->options()));
index 837df51..761e3ed 100644 (file)
@@ -61,7 +61,7 @@ WebCore::SWClientConnection& WebServiceWorkerProvider::serviceWorkerConnectionFo
 
 static inline bool shouldHandleFetch(const WebSWClientConnection& connection, CachedResource* resource, const ResourceLoaderOptions& options)
 {
-    if (options.serviceWorkersMode != ServiceWorkersMode::All)
+    if (options.serviceWorkersMode == ServiceWorkersMode::None)
         return false;
 
     if (isPotentialNavigationOrSubresourceRequest(options.destination))