Skip to content
Permalink
Browse files
Add support to the Permissions API for Service Workers and Shared Wor…
…kers

https://bugs.webkit.org/show_bug.cgi?id=244241

Reviewed by Chris Dumez and Sihui Liu.

Permissions::query() should be exposed for both window and workers. Currently,
it is only exposed for window and dedicated workers. This patch adds support
for service and shared workers.

* LayoutTests/http/tests/notifications/permission/service-worker-permissions-query-expected.txt: Added.
* LayoutTests/http/tests/notifications/permission/service-worker-permissions-query.html: Added.
* LayoutTests/http/tests/notifications/permission/service-worker-permissions-query.js: Added.
(self.onmessage):
* LayoutTests/http/tests/notifications/permission/shared-worker-permission-query.js: Added.
(port.onmessage):
(onconnect):
* LayoutTests/http/tests/notifications/permission/shared-worker-permissions-query-expected.txt: Added.
* LayoutTests/http/tests/notifications/permission/shared-worker-permissions-query.html: Added.
* Source/WTF/wtf/ObjectIdentifier.h:
(WTF::ObjectIdentifier::operator> const):
* Source/WebCore/Headers.cmake:
* Source/WebCore/Modules/permissions/PermissionController.h:
* Source/WebCore/Modules/permissions/PermissionQuerySource.h: Copied from Source/WebKit/UIProcess/WebPermissionControllerProxy.messages.in.
* Source/WebCore/Modules/permissions/Permissions.cpp:
(WebCore::sourceFromContext):
(WebCore::Permissions::query):
* Source/WebCore/Modules/permissions/Permissions.idl:
* Source/WebCore/WebCore.xcodeproj/project.pbxproj:
* Source/WebKit/UIProcess/WebPermissionControllerProxy.cpp:
(WebKit::WebPermissionControllerProxy::query):
(WebKit::WebPermissionControllerProxy::mostReasonableWebPageProxy const):
* Source/WebKit/UIProcess/WebPermissionControllerProxy.h:
* Source/WebKit/UIProcess/WebPermissionControllerProxy.messages.in:
* Source/WebKit/UIProcess/WebProcessProxy.cpp:
(WebKit::WebProcessProxy::serviceWorkerClientProcesses const):
(WebKit::WebProcessProxy::sharedWorkerClientProcesses const):
* Source/WebKit/UIProcess/WebProcessProxy.h:
* Source/WebKit/WebProcess/WebCoreSupport/WebPermissionController.cpp:
(WebKit::WebPermissionController::query):
(WebKit::WebPermissionController::tryProcessingRequests):
* Source/WebKit/WebProcess/WebCoreSupport/WebPermissionController.h:

Canonical link: https://commits.webkit.org/253752@main
  • Loading branch information
RupinMittal authored and szewai committed Aug 24, 2022
1 parent e468229 commit f4b92456d1a2b2abccfa88cf91cbb551be428038
Show file tree
Hide file tree
Showing 20 changed files with 380 additions and 24 deletions.
@@ -0,0 +1,17 @@
This test checks that Permissions::query() works for service workers

On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".


PASS message.data is "prompt"
PASS receivedPostMessageResponse became true
PASS requestPermissionResult is "granted"
PASS message.data is "granted"
PASS receivedPostMessageResponse became true
PASS requestPermissionResult is "denied"
PASS message.data is "denied"
PASS receivedPostMessageResponse became true
PASS successfullyParsed is true

TEST COMPLETE

@@ -0,0 +1,78 @@
<!DOCTYPE html>
<html>
<head>
<script src="/resources/js-test-pre.js"></script>
<script src="/resources/notifications-test-pre.js"></script>
</head>
<body>
<script>

description("This test checks that Permissions::query() works for service workers")

jsTestIsAsync = true;

var expectedData = null;
var receivedPostMessageResponse = true;

navigator.serviceWorker.register('service-worker-permissions-query.js');
navigator.serviceWorker.addEventListener('message', (message) => {
window.message = message;
shouldBeEqualToString("message.data", expectedData);
receivedPostMessageResponse = true;
});

async function defaultTest()
{
receivedPostMessageResponse = false;
expectedData = "prompt";
navigator.serviceWorker.ready.then((registration) => {
registration.active.postMessage(1);
});
await shouldBecomeEqual("receivedPostMessageResponse", "true");
}

async function grantTest()
{
receivedPostMessageResponse = false;
expectedData = "granted";
internals.withUserGesture(() => {
// Permission is granted by default when requestPermission() is called.
window.Notification.requestPermission().then((result)=> {
requestPermissionResult = result;
shouldBeEqualToString("requestPermissionResult", "granted");
navigator.serviceWorker.ready.then((registration) => {
registration.active.postMessage(2);
});
});
});
await shouldBecomeEqual("receivedPostMessageResponse", "true");
}

async function denyTest()
{
receivedPostMessageResponse = false;
expectedData = "denied";
internals.withUserGesture(() => {
testRunner.denyWebNotificationPermissionOnPrompt(testURL);
window.Notification.requestPermission().then((result)=> {
requestPermissionResult = result;
shouldBeEqualToString("requestPermissionResult", "denied");
navigator.serviceWorker.ready.then((registration) => {
registration.active.postMessage(3);
});
});
});
await shouldBecomeEqual("receivedPostMessageResponse", "true");
}

(async function () {
await defaultTest();
await grantTest();
await denyTest();
finishJSTest();
})();

</script>
<script src="/resources/js-test-post.js"></script>
</body>
</html>
@@ -0,0 +1,5 @@
self.onmessage = (event) => {
navigator.permissions.query({ name: "notifications" }).then((status) => {
event.source.postMessage(status.state);
});
};
@@ -0,0 +1,9 @@
onconnect = function (e) {
var port = e.ports[0];

port.onmessage = function (e) {
navigator.permissions.query({ name: "notifications" }).then((status) => {
port.postMessage(status.state);
});
};
}
@@ -0,0 +1,17 @@
This test checks that Permissions::query() works for shared workers

On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".


PASS message.data is "prompt"
PASS receivedPostMessageResponse became true
PASS requestPermissionResult is "granted"
PASS message.data is "granted"
PASS receivedPostMessageResponse became true
PASS requestPermissionResult is "denied"
PASS message.data is "denied"
PASS receivedPostMessageResponse became true
PASS successfullyParsed is true

TEST COMPLETE

@@ -0,0 +1,72 @@
<!DOCTYPE html>
<html>
<head>
<script src="/resources/js-test-pre.js"></script>
<script src="/resources/notifications-test-pre.js"></script>
</head>
<body>
<script>

description("This test checks that Permissions::query() works for shared workers")

jsTestIsAsync = true;

var expectedData = null;
var receivedPostMessageResponse = true;

var worker = new SharedWorker('shared-worker-permission-query.js');
worker.port.onmessage = function(message) {
window.message = message;
shouldBeEqualToString("message.data", expectedData);
receivedPostMessageResponse = true;
}

async function defaultTest()
{
receivedPostMessageResponse = false;
expectedData = "prompt";
worker.port.postMessage(1);
await shouldBecomeEqual("receivedPostMessageResponse", "true");
}

async function grantTest()
{
receivedPostMessageResponse = false;
expectedData = "granted";
internals.withUserGesture(() => {
// Permission is granted by default when requestPermission() is called.
window.Notification.requestPermission().then((result)=> {
requestPermissionResult = result;
shouldBeEqualToString("requestPermissionResult", "granted");
worker.port.postMessage(2);
});
});
await shouldBecomeEqual("receivedPostMessageResponse", "true");
}

async function denyTest()
{
receivedPostMessageResponse = false;
expectedData = "denied";
internals.withUserGesture(() => {
testRunner.denyWebNotificationPermissionOnPrompt(testURL);
window.Notification.requestPermission().then((result)=> {
requestPermissionResult = result;
shouldBeEqualToString("requestPermissionResult", "denied");
worker.port.postMessage(3);
});
});
await shouldBecomeEqual("receivedPostMessageResponse", "true");
}

(async function () {
await defaultTest();
await grantTest();
await denyTest();
finishJSTest();
})();

</script>
<script src="/resources/js-test-post.js"></script>
</body>
</html>
@@ -90,6 +90,11 @@ template<typename T> class ObjectIdentifier : private ObjectIdentifierBase {
return m_identifier != other.m_identifier;
}

bool operator>(const ObjectIdentifier& other) const
{
return toUInt64() > other.toUInt64();
}

uint64_t toUInt64() const { return m_identifier; }
explicit operator bool() const { return m_identifier; }

@@ -309,6 +309,7 @@ set(WebCore_PRIVATE_FRAMEWORK_HEADERS
Modules/permissions/PermissionDescriptor.h
Modules/permissions/PermissionName.h
Modules/permissions/PermissionObserver.h
Modules/permissions/PermissionQuerySource.h
Modules/permissions/PermissionState.h

Modules/plugins/PluginReplacement.h
@@ -31,6 +31,7 @@

namespace WebCore {

enum class PermissionQuerySource : uint8_t;
enum class PermissionState : uint8_t;
class Page;
class PermissionObserver;
@@ -43,7 +44,7 @@ class PermissionController : public ThreadSafeRefCounted<PermissionController> {
WEBCORE_EXPORT static void setSharedController(Ref<PermissionController>&&);

virtual ~PermissionController() = default;
virtual void query(WebCore::ClientOrigin&&, PermissionDescriptor&&, Page&, CompletionHandler<void(std::optional<PermissionState>)>&&) = 0;
virtual void query(WebCore::ClientOrigin&&, PermissionDescriptor&&, Page*, PermissionQuerySource, CompletionHandler<void(std::optional<PermissionState>)>&&) = 0;
virtual void addObserver(PermissionObserver&) = 0;
virtual void removeObserver(PermissionObserver&) = 0;
protected:
@@ -55,7 +56,7 @@ class DummyPermissionController final : public PermissionController {
static Ref<DummyPermissionController> create() { return adoptRef(*new DummyPermissionController); }
private:
DummyPermissionController() = default;
void query(WebCore::ClientOrigin&&, PermissionDescriptor&&, Page&, CompletionHandler<void(std::optional<PermissionState>)>&& callback) final { callback({ }); }
void query(WebCore::ClientOrigin&&, PermissionDescriptor&&, Page*, PermissionQuerySource, CompletionHandler<void(std::optional<PermissionState>)>&& callback) final { callback({ }); }
void addObserver(PermissionObserver&) final { }
void removeObserver(PermissionObserver&) final { }
};
@@ -0,0 +1,53 @@
/*
* Copyright (C) 2022 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/

#pragma once

#include <wtf/EnumTraits.h>

namespace WebCore {

enum class PermissionQuerySource : uint8_t {
Window,
DedicatedWorker,
SharedWorker,
ServiceWorker
};

} // namespace WebCore

namespace WTF {

template<> struct EnumTraits<WebCore::PermissionQuerySource> {
using values = EnumValues<
WebCore::PermissionQuerySource,
WebCore::PermissionQuerySource::Window,
WebCore::PermissionQuerySource::DedicatedWorker,
WebCore::PermissionQuerySource::SharedWorker,
WebCore::PermissionQuerySource::ServiceWorker
>;
};

} // namespace WTF
@@ -26,6 +26,7 @@
#include "config.h"
#include "Permissions.h"

#include "DedicatedWorkerGlobalScope.h"
#include "Document.h"
#include "Exception.h"
#include "FeaturePolicy.h"
@@ -37,8 +38,11 @@
#include "Page.h"
#include "PermissionController.h"
#include "PermissionDescriptor.h"
#include "PermissionQuerySource.h"
#include "ScriptExecutionContext.h"
#include "SecurityOrigin.h"
#include "ServiceWorkerGlobalScope.h"
#include "SharedWorkerGlobalScope.h"
#include "WorkerGlobalScope.h"
#include "WorkerLoaderProxy.h"
#include "WorkerThread.h"
@@ -80,6 +84,21 @@ static bool isAllowedByFeaturePolicy(const Document& document, PermissionName na
}
}

static std::optional<PermissionQuerySource> sourceFromContext(const ScriptExecutionContext& context)
{
if (is<Document>(context))
return PermissionQuerySource::Window;
if (is<DedicatedWorkerGlobalScope>(context))
return PermissionQuerySource::DedicatedWorker;
if (is<SharedWorkerGlobalScope>(context))
return PermissionQuerySource::SharedWorker;
#if ENABLE(SERVICE_WORKER)
if (is<ServiceWorkerGlobalScope>(context))
return PermissionQuerySource::ServiceWorker;
#endif
return std::nullopt;
}

void Permissions::query(JSC::Strong<JSC::JSObject> permissionDescriptorValue, DOMPromiseDeferred<IDLInterface<PermissionStatus>>&& promise)
{
auto* context = m_navigator ? m_navigator->scriptExecutionContext() : nullptr;
@@ -88,6 +107,12 @@ void Permissions::query(JSC::Strong<JSC::JSObject> permissionDescriptorValue, DO
return;
}

auto source = sourceFromContext(*context);
if (!source) {
promise.reject(Exception { NotSupportedError, "Permissions::query is not supported in this context"_s });
return;
}

auto* document = dynamicDowncast<Document>(*context);
if (document && !document->isFullyActive()) {
promise.reject(Exception { InvalidStateError, "The document is not fully active"_s });
@@ -116,7 +141,7 @@ void Permissions::query(JSC::Strong<JSC::JSObject> permissionDescriptorValue, DO
return;
}

PermissionController::shared().query(ClientOrigin { document->topOrigin().data(), WTFMove(originData) }, PermissionDescriptor { permissionDescriptor }, *document->page(), [document = Ref { *document }, permissionDescriptor, promise = WTFMove(promise)](auto permissionState) mutable {
PermissionController::shared().query(ClientOrigin { document->topOrigin().data(), WTFMove(originData) }, PermissionDescriptor { permissionDescriptor }, document->page(), *source, [document = Ref { *document }, permissionDescriptor, promise = WTFMove(promise)](auto permissionState) mutable {
if (!permissionState)
promise.reject(Exception { NotSupportedError, "Permissions::query does not support this API"_s });
else
@@ -126,7 +151,7 @@ void Permissions::query(JSC::Strong<JSC::JSObject> permissionDescriptorValue, DO
}

auto& workerGlobalScope = downcast<WorkerGlobalScope>(*context);
auto completionHandler = [originData = WTFMove(originData).isolatedCopy(), permissionDescriptor, contextIdentifier = workerGlobalScope.identifier(), promise = WTFMove(promise)] (auto& context) mutable {
auto completionHandler = [originData = WTFMove(originData).isolatedCopy(), permissionDescriptor, contextIdentifier = workerGlobalScope.identifier(), source = *source, promise = WTFMove(promise)] (auto& context) mutable {
ASSERT(isMainThread());

auto& document = downcast<Document>(context);
@@ -137,7 +162,7 @@ void Permissions::query(JSC::Strong<JSC::JSObject> permissionDescriptorValue, DO
return;
}

PermissionController::shared().query(ClientOrigin { document.topOrigin().data(), WTFMove(originData) }, PermissionDescriptor { permissionDescriptor }, *document.page(), [contextIdentifier, permissionDescriptor, promise = WTFMove(promise)](auto permissionState) mutable {
PermissionController::shared().query(ClientOrigin { document.topOrigin().data(), WTFMove(originData) }, PermissionDescriptor { permissionDescriptor }, document.page(), source, [contextIdentifier, permissionDescriptor, promise = WTFMove(promise)](auto permissionState) mutable {
ScriptExecutionContext::postTaskTo(contextIdentifier, [promise = WTFMove(promise), permissionState, permissionDescriptor](auto& context) mutable {
if (!permissionState)
promise.reject(Exception { NotSupportedError, "Permissions::query does not support this API"_s });
@@ -29,7 +29,7 @@
[
EnabledBySetting=PermissionsAPIEnabled,
GenerateIsReachable=ReachableFromNavigator,
Exposed=(Window,DedicatedWorker)
Exposed=(Window,Worker)
] interface Permissions {
Promise<PermissionStatus> query(object permissionDesc);
};

0 comments on commit f4b9245

Please sign in to comment.