Add CSP support to service workers
[WebKit-https.git] / Source / WebCore / workers / service / context / ServiceWorkerThread.cpp
1 /*
2  * Copyright (C) 2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "ServiceWorkerThread.h"
28
29 #if ENABLE(SERVICE_WORKER)
30
31 #include "CacheStorageProvider.h"
32 #include "ContentSecurityPolicyResponseHeaders.h"
33 #include "EventNames.h"
34 #include "ExtendableMessageEvent.h"
35 #include "JSDOMPromise.h"
36 #include "NetworkStateNotifier.h"
37 #include "SecurityOrigin.h"
38 #include "ServiceWorkerFetch.h"
39 #include "ServiceWorkerGlobalScope.h"
40 #include "ServiceWorkerWindowClient.h"
41 #include "WorkerDebuggerProxy.h"
42 #include "WorkerLoaderProxy.h"
43 #include "WorkerObjectProxy.h"
44 #include <inspector/IdentifiersFactory.h>
45 #include <pal/SessionID.h>
46 #include <runtime/RuntimeFlags.h>
47 #include <wtf/NeverDestroyed.h>
48
49 using namespace PAL;
50
51 namespace WebCore {
52
53 class DummyServiceWorkerThreadProxy : public WorkerObjectProxy {
54 public:
55     static DummyServiceWorkerThreadProxy& shared()
56     {
57         static NeverDestroyed<DummyServiceWorkerThreadProxy> proxy;
58         return proxy;
59     }
60
61 private:
62     void postExceptionToWorkerObject(const String&, int, int, const String&) final { };
63     void workerGlobalScopeDestroyed() final { };
64     void postMessageToWorkerObject(Ref<SerializedScriptValue>&&, std::unique_ptr<MessagePortChannelArray>&&) final { };
65     void confirmMessageFromWorkerObject(bool) final { };
66     void reportPendingActivity(bool) final { };
67 };
68
69 // FIXME: Use a valid WorkerReportingProxy
70 // FIXME: Use a valid WorkerObjectProxy
71 // FIXME: Use valid runtime flags
72
73 ServiceWorkerThread::ServiceWorkerThread(const ServiceWorkerContextData& data, PAL::SessionID, String&& userAgent, WorkerLoaderProxy& loaderProxy, WorkerDebuggerProxy& debuggerProxy, IDBClient::IDBConnectionProxy* idbConnectionProxy, SocketProvider* socketProvider)
74     : WorkerThread(data.scriptURL, "serviceworker:" + Inspector::IdentifiersFactory::createIdentifier(), WTFMove(userAgent), NetworkStateNotifier::singleton().onLine(), data.script, loaderProxy, debuggerProxy, DummyServiceWorkerThreadProxy::shared(), WorkerThreadStartMode::Normal, data.contentSecurityPolicy, false, SecurityOrigin::create(data.scriptURL).get(), MonotonicTime::now(), idbConnectionProxy, socketProvider, JSC::RuntimeFlags::createAllEnabled(), SessionID::defaultSessionID())
75     , m_data(data.isolatedCopy())
76     , m_workerObjectProxy(DummyServiceWorkerThreadProxy::shared())
77 {
78     AtomicString::init();
79 }
80
81 ServiceWorkerThread::~ServiceWorkerThread() = default;
82
83 Ref<WorkerGlobalScope> ServiceWorkerThread::createWorkerGlobalScope(const URL& url, const String& identifier, const String& userAgent, bool isOnline, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicy, bool shouldBypassMainWorldContentSecurityPolicy, Ref<SecurityOrigin>&& topOrigin, MonotonicTime timeOrigin, PAL::SessionID sessionID)
84 {
85     return ServiceWorkerGlobalScope::create(m_data, url, identifier, userAgent, isOnline, *this, contentSecurityPolicy, shouldBypassMainWorldContentSecurityPolicy, WTFMove(topOrigin), timeOrigin, idbConnectionProxy(), socketProvider(), sessionID);
86 }
87
88 void ServiceWorkerThread::runEventLoop()
89 {
90     // FIXME: There will be ServiceWorker specific things to do here.
91     WorkerThread::runEventLoop();
92 }
93
94 void ServiceWorkerThread::postFetchTask(Ref<ServiceWorkerFetch::Client>&& client, std::optional<ServiceWorkerClientIdentifier>&& clientId, ResourceRequest&& request, String&& referrer, FetchOptions&& options)
95 {
96     // FIXME: instead of directly using runLoop(), we should be using something like WorkerGlobalScopeProxy.
97     // FIXME: request and options come straigth from IPC so are already isolated. We should be able to take benefit of that.
98     runLoop().postTaskForMode([client = WTFMove(client), clientId, request = request.isolatedCopy(), referrer = referrer.isolatedCopy(), options = options.isolatedCopy()] (ScriptExecutionContext& context) mutable {
99         ServiceWorkerFetch::dispatchFetchEvent(WTFMove(client), downcast<ServiceWorkerGlobalScope>(context), clientId, WTFMove(request), WTFMove(referrer), WTFMove(options));
100     }, WorkerRunLoop::defaultMode());
101 }
102
103 static void fireMessageEvent(ServiceWorkerGlobalScope& scope, Ref<SerializedScriptValue>&& message, std::unique_ptr<MessagePortChannelArray>&& channels, ExtendableMessageEventSource&& source, Ref<SecurityOrigin>&& sourceOrigin)
104 {
105     auto ports = MessagePort::entanglePorts(scope, WTFMove(channels));
106     auto messageEvent = ExtendableMessageEvent::create(WTFMove(ports), WTFMove(message), sourceOrigin->toString(), { }, source);
107     scope.dispatchEvent(messageEvent);
108     scope.thread().workerObjectProxy().confirmMessageFromWorkerObject(scope.hasPendingActivity());
109     scope.updateExtendedEventsSet(messageEvent.ptr());
110 }
111
112 void ServiceWorkerThread::postMessageToServiceWorker(Ref<SerializedScriptValue>&& message, std::unique_ptr<MessagePortChannelArray>&& channels, ServiceWorkerOrClientData&& sourceData)
113 {
114     runLoop().postTask([channels = WTFMove(channels), message = WTFMove(message), sourceData = WTFMove(sourceData)] (auto& context) mutable {
115         auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
116         RefPtr<SecurityOrigin> sourceOrigin;
117         ExtendableMessageEventSource source;
118         if (WTF::holds_alternative<ServiceWorkerClientData>(sourceData)) {
119             RefPtr<ServiceWorkerClient> sourceClient = ServiceWorkerClient::getOrCreate(serviceWorkerGlobalScope, WTFMove(WTF::get<ServiceWorkerClientData>(sourceData)));
120             sourceOrigin = SecurityOrigin::create(sourceClient->url());
121             source = WTFMove(sourceClient);
122         } else {
123             RefPtr<ServiceWorker> sourceWorker = ServiceWorker::getOrCreate(serviceWorkerGlobalScope, WTFMove(WTF::get<ServiceWorkerData>(sourceData)));
124             sourceOrigin = SecurityOrigin::create(sourceWorker->scriptURL());
125             source = WTFMove(sourceWorker);
126         }
127         fireMessageEvent(serviceWorkerGlobalScope, WTFMove(message), WTFMove(channels), ExtendableMessageEventSource { source }, sourceOrigin.releaseNonNull());
128     });
129 }
130
131 void ServiceWorkerThread::fireInstallEvent()
132 {
133     ScriptExecutionContext::Task task([jobDataIdentifier = m_data.jobDataIdentifier, serviceWorkerIdentifier = this->identifier()] (ScriptExecutionContext& context) mutable {
134         context.postTask([jobDataIdentifier, serviceWorkerIdentifier](ScriptExecutionContext& context) {
135             auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
136             auto installEvent = ExtendableEvent::create(eventNames().installEvent, { }, ExtendableEvent::IsTrusted::Yes);
137             serviceWorkerGlobalScope.dispatchEvent(installEvent);
138
139             installEvent->whenAllExtendLifetimePromisesAreSettled([jobDataIdentifier, serviceWorkerIdentifier](HashSet<Ref<DOMPromise>>&& extendLifetimePromises) {
140                 bool hasRejectedAnyPromise = false;
141                 for (auto& promise : extendLifetimePromises) {
142                     if (promise->status() == DOMPromise::Status::Rejected) {
143                         hasRejectedAnyPromise = true;
144                         break;
145                     }
146                 }
147                 callOnMainThread([jobDataIdentifier, serviceWorkerIdentifier, hasRejectedAnyPromise] () mutable {
148                     if (auto* connection = SWContextManager::singleton().connection())
149                         connection->didFinishInstall(jobDataIdentifier, serviceWorkerIdentifier, !hasRejectedAnyPromise);
150                 });
151             });
152         });
153     });
154     runLoop().postTask(WTFMove(task));
155 }
156
157 void ServiceWorkerThread::fireActivateEvent()
158 {
159     ScriptExecutionContext::Task task([serviceWorkerIdentifier = this->identifier()] (ScriptExecutionContext& context) mutable {
160         context.postTask([serviceWorkerIdentifier](ScriptExecutionContext& context) {
161             auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
162             auto activateEvent = ExtendableEvent::create(eventNames().activateEvent, { }, ExtendableEvent::IsTrusted::Yes);
163             serviceWorkerGlobalScope.dispatchEvent(activateEvent);
164
165             activateEvent->whenAllExtendLifetimePromisesAreSettled([serviceWorkerIdentifier](HashSet<Ref<DOMPromise>>&&) {
166                 callOnMainThread([serviceWorkerIdentifier] () mutable {
167                     if (auto* connection = SWContextManager::singleton().connection())
168                         connection->didFinishActivation(serviceWorkerIdentifier);
169                 });
170             });
171         });
172     });
173     runLoop().postTask(WTFMove(task));
174 }
175
176 } // namespace WebCore
177
178 #endif // ENABLE(SERVICE_WORKER)