Title: [291414] trunk
Revision
291414
Author
[email protected]
Date
2022-03-17 09:52:04 -0700 (Thu, 17 Mar 2022)

Log Message

Only show notification permission prompt on user gesture
https://bugs.webkit.org/show_bug.cgi?id=237946

Reviewed by Geoffrey Garen.

Source/WebCore:

We want to make Notification.requestPermission and PushManager.subscribe only prompt the
user for permission in response to a user gesture. This matches existing behavior in other
browsers.

We use the error string "Push notification prompting can only be done from a user gesture"
since that string was already used by safari.pushNotification.requestPermission.

* Modules/notifications/Notification.cpp:
(WebCore::Notification::requestPermission):
* Modules/push-api/PushManager.cpp:
(WebCore::PushManager::subscribe):

Tools:

Change existing permission tests to use evaluateJavaScript since that executes in the
context of a user gesture.

* TestWebKitAPI/Tests/WebKitCocoa/UIDelegate.mm:
* TestWebKitAPI/Tests/WebKitCocoa/WebPushDaemon.mm:

LayoutTests:

Add test cases to make sure that prompting for notification permissions fails when not
handling a user gesture and succeeds when handling a user gesture.

* http/tests/notifications/notification-request-permission-no-callback.html:
* http/tests/notifications/notification-request-permission.html:
* http/tests/notifications/request-expected.txt:
* http/tests/notifications/request-with-promise-expected.txt:
* http/tests/notifications/request-with-promise.html:
* http/tests/notifications/request.html:
* http/tests/push-api/resources/subscribe-iframe-cross-origin.html:
* http/tests/push-api/resources/subscribe-iframe-same-origin.html:
* http/tests/push-api/resources/subscribe-tests.js:
(async testDocumentSubscribeWithUserGesture): Added.
(async testDocumentSubscribeWithoutUserGesture): Added.
(async testDocumentSubscribeImpl): Added.
(async testDocumentSubscribe): Deleted.
* http/tests/push-api/subscribe-default-permissions-expected.txt:
* http/tests/push-api/subscribe-default-permissions-iframe-cross-origin-expected.txt:
* http/tests/push-api/subscribe-default-permissions-iframe-same-origin-expected.txt:
* http/tests/push-api/subscribe-default-permissions.html:
* http/tests/push-api/subscribe-deny-permissions-expected.txt:
* http/tests/push-api/subscribe-deny-permissions.html:
* http/tests/push-api/subscribe-grant-permissions-expected.txt:
* http/tests/push-api/subscribe-grant-permissions.html:

Modified Paths

Diff

Modified: trunk/LayoutTests/ChangeLog (291413 => 291414)


--- trunk/LayoutTests/ChangeLog	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/ChangeLog	2022-03-17 16:52:04 UTC (rev 291414)
@@ -1,3 +1,35 @@
+2022-03-17  Ben Nham  <[email protected]>
+
+        Only show notification permission prompt on user gesture
+        https://bugs.webkit.org/show_bug.cgi?id=237946
+
+        Reviewed by Geoffrey Garen.
+
+        Add test cases to make sure that prompting for notification permissions fails when not
+        handling a user gesture and succeeds when handling a user gesture.
+
+        * http/tests/notifications/notification-request-permission-no-callback.html:
+        * http/tests/notifications/notification-request-permission.html:
+        * http/tests/notifications/request-expected.txt:
+        * http/tests/notifications/request-with-promise-expected.txt:
+        * http/tests/notifications/request-with-promise.html:
+        * http/tests/notifications/request.html:
+        * http/tests/push-api/resources/subscribe-iframe-cross-origin.html:
+        * http/tests/push-api/resources/subscribe-iframe-same-origin.html:
+        * http/tests/push-api/resources/subscribe-tests.js:
+        (async testDocumentSubscribeWithUserGesture): Added.
+        (async testDocumentSubscribeWithoutUserGesture): Added.
+        (async testDocumentSubscribeImpl): Added.
+        (async testDocumentSubscribe): Deleted.
+        * http/tests/push-api/subscribe-default-permissions-expected.txt:
+        * http/tests/push-api/subscribe-default-permissions-iframe-cross-origin-expected.txt:
+        * http/tests/push-api/subscribe-default-permissions-iframe-same-origin-expected.txt:
+        * http/tests/push-api/subscribe-default-permissions.html:
+        * http/tests/push-api/subscribe-deny-permissions-expected.txt:
+        * http/tests/push-api/subscribe-deny-permissions.html:
+        * http/tests/push-api/subscribe-grant-permissions-expected.txt:
+        * http/tests/push-api/subscribe-grant-permissions.html:
+
 2022-03-17  Andres Gonzalez  <[email protected]>
 
         Fix for accessibility/aria-tab-xxx.html tests in isolated tree mode.

Modified: trunk/LayoutTests/http/tests/notifications/notification-request-permission-no-callback.html (291413 => 291414)


--- trunk/LayoutTests/http/tests/notifications/notification-request-permission-no-callback.html	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/notifications/notification-request-permission-no-callback.html	2022-03-17 16:52:04 UTC (rev 291414)
@@ -9,16 +9,21 @@
 if (!window.Notification)
     testFailed("window.Notification does not exist.");
 
-window.Notification.requestPermission();
-testPassed("Notification.requestPermission does not crash.");
+if (!window.internals)
+    testFailed("This test requires internals.");
 
-testRunner.grantWebNotificationPermission(testURL);
-window.Notification.requestPermission();
-testPassed("Notification.requestPermission does not crash.");
+internals.withUserGesture(() => {
+    window.Notification.requestPermission();
+    testPassed("Notification.requestPermission does not crash.");
 
-testRunner.denyWebNotificationPermission(testURL);
-window.Notification.requestPermission();
-testPassed("Notification.requestPermission does not crash.");
+    testRunner.grantWebNotificationPermission(testURL);
+    window.Notification.requestPermission();
+    testPassed("Notification.requestPermission does not crash.");
+
+    testRunner.denyWebNotificationPermission(testURL);
+    window.Notification.requestPermission();
+    testPassed("Notification.requestPermission does not crash.");
+});
 </script>
 <script src=""
 </body>

Modified: trunk/LayoutTests/http/tests/notifications/notification-request-permission.html (291413 => 291414)


--- trunk/LayoutTests/http/tests/notifications/notification-request-permission.html	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/notifications/notification-request-permission.html	2022-03-17 16:52:04 UTC (rev 291414)
@@ -9,16 +9,21 @@
 if (!window.Notification)
     testFailed("window.Notification does not exist.");
 
-window.Notification.requestPermission(function() { });
-testPassed("Notification.requestPermission does not crash.");
+if (!window.internals)
+    testFailed("This test requires internals.");
 
-testRunner.grantWebNotificationPermission(testURL);
-window.Notification.requestPermission(function() { });
-testPassed("Notification.requestPermission does not crash.");
+internals.withUserGesture(() => {
+    window.Notification.requestPermission(function() { });
+    testPassed("Notification.requestPermission does not crash.");
 
-testRunner.denyWebNotificationPermission(testURL);
-window.Notification.requestPermission(function() { });
-testPassed("Notification.requestPermission does not crash.");
+    testRunner.grantWebNotificationPermission(testURL);
+    window.Notification.requestPermission(function() { });
+    testPassed("Notification.requestPermission does not crash.");
+
+    testRunner.denyWebNotificationPermission(testURL);
+    window.Notification.requestPermission(function() { });
+    testPassed("Notification.requestPermission does not crash.");
+});
 </script>
 <script src=""
 </body>

Modified: trunk/LayoutTests/http/tests/notifications/request-expected.txt (291413 => 291414)


--- trunk/LayoutTests/http/tests/notifications/request-expected.txt	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/notifications/request-expected.txt	2022-03-17 16:52:04 UTC (rev 291414)
@@ -1,10 +1,15 @@
+CONSOLE MESSAGE: Notification prompting can only be done from a user gesture.
 This test checks that a request for permission is made.
 
 On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
 
 
-Requesting permission with default permission
+Requesting permission with default permission without user gesture
 PASS Notification.permission is "default"
+PASS permission is denied
+PASS Notification.permission is "default"
+Requesting permission with default permission with user gesture
+PASS Notification.permission is "default"
 PASS permission is granted
 PASS Notification.permission is "granted"
 Requesting permission with non-default permission

Modified: trunk/LayoutTests/http/tests/notifications/request-with-promise-expected.txt (291413 => 291414)


--- trunk/LayoutTests/http/tests/notifications/request-with-promise-expected.txt	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/notifications/request-with-promise-expected.txt	2022-03-17 16:52:04 UTC (rev 291414)
@@ -1,10 +1,15 @@
+CONSOLE MESSAGE: Notification prompting can only be done from a user gesture.
 This tests Notification.permission's returned Promise
 
 On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
 
 
-Requesting permission with default permission
+Requesting permission with default permission without user gesture
 PASS Notification.permission is "default"
+PASS permission is denied
+PASS Notification.permission is "default"
+Requesting permission with default permission with user gesture
+PASS Notification.permission is "default"
 PASS permission is granted
 PASS Notification.permission is "granted"
 Requesting permission with non-default permission

Modified: trunk/LayoutTests/http/tests/notifications/request-with-promise.html (291413 => 291414)


--- trunk/LayoutTests/http/tests/notifications/request-with-promise.html	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/notifications/request-with-promise.html	2022-03-17 16:52:04 UTC (rev 291414)
@@ -4,29 +4,51 @@
 description("This tests Notification.permission's returned Promise");
 jsTestIsAsync = true;
 
+if (!window.internals)
+    finishJSTest();
+
 function step1() {
-    debug("Requesting permission with default permission");
+    debug("Requesting permission with default permission without user gesture");
     shouldBeEqualToString("Notification.permission", "default");
-    Notification.requestPermission().then((permission) => {
-        if (permission == 'granted')
-            testPassed("permission is granted");
-        else
-            testFailed("permission should be granted, but is " + permission);
-        shouldBeEqualToString("Notification.permission", "granted");
-        setTimeout(step2, 0);
+    internals.withoutUserGesture(() => {
+        Notification.requestPermission().then((permission) => {
+            if (permission == 'denied')
+                testPassed("permission is denied");
+            else
+                testFailed("permission should be denied, but is " + permission);
+            shouldBeEqualToString("Notification.permission", "default");
+            setTimeout(step2, 0);
+        });
     });
 }
 
 function step2() {
+    debug("Requesting permission with default permission with user gesture");
+    shouldBeEqualToString("Notification.permission", "default");
+    internals.withUserGesture(() => {
+        Notification.requestPermission().then((permission) => {
+            if (permission == 'granted')
+                testPassed("permission is granted");
+            else
+                testFailed("permission should be granted, but is " + permission);
+            shouldBeEqualToString("Notification.permission", "granted");
+            setTimeout(step3, 0);
+        });
+    });
+}
+
+function step3() {
     debug("Requesting permission with non-default permission");
     testRunner.denyWebNotificationPermission(self.origin);
-    Notification.requestPermission().then((permission) => {
-        if (permission == 'denied')
-            testPassed("permission is denied");
-        else
-            testFailed("permission should be denied, but is " + permission);
-        shouldBeEqualToString("Notification.permission", "denied");
-        finishJSTest();
+    internals.withUserGesture(() => {
+        Notification.requestPermission().then((permission) => {
+            if (permission == 'denied')
+                testPassed("permission is denied");
+            else
+                testFailed("permission should be denied, but is " + permission);
+            shouldBeEqualToString("Notification.permission", "denied");
+            finishJSTest();
+        });
     });
 }
 

Modified: trunk/LayoutTests/http/tests/notifications/request.html (291413 => 291414)


--- trunk/LayoutTests/http/tests/notifications/request.html	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/notifications/request.html	2022-03-17 16:52:04 UTC (rev 291414)
@@ -7,29 +7,51 @@
 <script>
 description("This test checks that a request for permission is made.");
 
+if (!window.internals)
+    finishJSTest();
+
 function step1() {
-    debug("Requesting permission with default permission");
+    debug("Requesting permission with default permission without user gesture");
     shouldBeEqualToString("Notification.permission", "default");
-    Notification.requestPermission(function(permission) {
-        if (permission == 'granted')
-            testPassed("permission is granted");
-        else
-            testFailed("permission should be granted, but is " + permission);
-        shouldBeEqualToString("Notification.permission", "granted");
-        setTimeout(step2, 0);
+    internals.withoutUserGesture(() => {
+        Notification.requestPermission(function(permission) {
+            if (permission == 'denied')
+                testPassed("permission is denied");
+            else
+                testFailed("permission should be denied, but is " + permission);
+            shouldBeEqualToString("Notification.permission", "default");
+            setTimeout(step2, 0);
+        });
     });
 }
 
 function step2() {
+    debug("Requesting permission with default permission with user gesture");
+    shouldBeEqualToString("Notification.permission", "default");
+    internals.withUserGesture(() => {
+        Notification.requestPermission(function(permission) {
+            if (permission == 'granted')
+                testPassed("permission is granted");
+            else
+                testFailed("permission should be granted, but is " + permission);
+            shouldBeEqualToString("Notification.permission", "granted");
+            setTimeout(step3, 0);
+        });
+    });
+}
+
+function step3() {
     debug("Requesting permission with non-default permission");
     testRunner.denyWebNotificationPermission(testURL);
-    Notification.requestPermission(function(permission) {
-        if (permission == 'denied')
-            testPassed("permission is denied");
-        else
-            testFailed("permission should be denied, but is " + permission);
-        shouldBeEqualToString("Notification.permission", "denied");
-        testCompleted();
+    internals.withUserGesture(() => {
+        Notification.requestPermission(function(permission) {
+            if (permission == 'denied')
+                testPassed("permission is denied");
+            else
+                testFailed("permission should be denied, but is " + permission);
+            shouldBeEqualToString("Notification.permission", "denied");
+            testCompleted();
+        });
     });
 }
 

Modified: trunk/LayoutTests/http/tests/push-api/resources/subscribe-iframe-cross-origin.html (291413 => 291414)


--- trunk/LayoutTests/http/tests/push-api/resources/subscribe-iframe-cross-origin.html	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/push-api/resources/subscribe-iframe-cross-origin.html	2022-03-17 16:52:04 UTC (rev 291414)
@@ -7,7 +7,8 @@
         await testServiceWorkerPermissionState(registration, 'prompt');
         await testDocumentPermissionState(registration, 'prompt');
         await testServiceWorkerSubscribe(registration, 'NotAllowedError');
-        await testDocumentSubscribe(registration, 'NotAllowedError');
+        await testDocumentSubscribeWithoutUserGesture(registration, 'NotAllowedError');
+        await testDocumentSubscribeWithUserGesture(registration, 'NotAllowedError');
     } catch (e) {
         log(`FAIL: unexpected exception ${e}`);
     } finally {

Modified: trunk/LayoutTests/http/tests/push-api/resources/subscribe-iframe-same-origin.html (291413 => 291414)


--- trunk/LayoutTests/http/tests/push-api/resources/subscribe-iframe-same-origin.html	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/push-api/resources/subscribe-iframe-same-origin.html	2022-03-17 16:52:04 UTC (rev 291414)
@@ -7,7 +7,8 @@
         await testServiceWorkerPermissionState(registration, 'prompt');
         await testDocumentPermissionState(registration, 'prompt');
         await testServiceWorkerSubscribe(registration, 'NotAllowedError');
-        await testDocumentSubscribe(registration);
+        await testDocumentSubscribeWithoutUserGesture(registration, 'NotAllowedError');
+        await testDocumentSubscribeWithUserGesture(registration);
     } catch (e) {
         log(`FAIL: unexpected exception ${e}`);
     } finally {

Modified: trunk/LayoutTests/http/tests/push-api/resources/subscribe-tests.js (291413 => 291414)


--- trunk/LayoutTests/http/tests/push-api/resources/subscribe-tests.js	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/push-api/resources/subscribe-tests.js	2022-03-17 16:52:04 UTC (rev 291414)
@@ -38,19 +38,41 @@
         log(`FAIL: service worker subscribe should be ${expected}, but was ${result}`);
 }
 
-async function testDocumentSubscribe(registration, domExceptionName)
+async function testDocumentSubscribeWithUserGesture(registration, domExceptionName)
 {
+    await testDocumentSubscribeImpl(registration, domExceptionName, true);
+}
+
+async function testDocumentSubscribeWithoutUserGesture(registration, domExceptionName)
+{
+    await testDocumentSubscribeImpl(registration, domExceptionName, false);
+}
+
+async function testDocumentSubscribeImpl(registration, domExceptionName, withUserGesture)
+{
     let expected = domExceptionName ? `error: ${domExceptionName}` : "successful";
     let result = null;
 
     let subscription = null;
     try {
-        // With default permissions, PushManager should request permission from TestController.
-        // TestController always calls WKNotificationPermissionRequestAllow so this should succeed.
-        subscription = await registration.pushManager.subscribe({
-            userVisibleOnly: true,
-            applicationServerKey: VALID_SERVER_KEY
-        });
+        let subscriptionPromise = null;
+        let subscribeFunc = function() {
+            // With default permissions, PushManager should request permission from TestController.
+            // TestController always calls WKNotificationPermissionRequestAllow so this should succeed.
+            subscriptionPromise = registration.pushManager.subscribe({
+                userVisibleOnly: true,
+                applicationServerKey: VALID_SERVER_KEY
+            });
+        }
+
+        if (!window.internals)
+            subscribeFunc();
+        else if (withUserGesture)
+            internals.withUserGesture(subscribeFunc);
+        else
+            internals.withoutUserGesture(subscribeFunc);
+
+        subscription = await subscriptionPromise;
         result = 'successful';
     } catch (e) {
         // Layout tests aren't connected to webpushd, so subscribe is successful if it gets to the
@@ -64,8 +86,10 @@
     if (subscription)
         await subscription.unsubscribe();
 
+    let gestureDescription = withUserGesture ? 'with user gesture' : 'without user gesture';
+
     if (result == expected)
-        log(`PASS: document subscribe was ${expected}`);
+        log(`PASS: document subscribe ${gestureDescription} was ${expected}`);
     else
-        log(`FAIL: document subscribe should be ${expected}, but was ${result}`);
+        log(`FAIL: document subscribe ${gestureDescription} should be ${expected}, but was ${result}`);
 }
\ No newline at end of file

Modified: trunk/LayoutTests/http/tests/push-api/subscribe-default-permissions-expected.txt (291413 => 291414)


--- trunk/LayoutTests/http/tests/push-api/subscribe-default-permissions-expected.txt	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/push-api/subscribe-default-permissions-expected.txt	2022-03-17 16:52:04 UTC (rev 291414)
@@ -1,5 +1,6 @@
 PASS: service worker permissionState was prompt
 PASS: document permissionState was prompt
 PASS: service worker subscribe was error: NotAllowedError
-PASS: document subscribe was successful
+PASS: document subscribe without user gesture was error: NotAllowedError
+PASS: document subscribe with user gesture was successful
 

Modified: trunk/LayoutTests/http/tests/push-api/subscribe-default-permissions-iframe-cross-origin-expected.txt (291413 => 291414)


--- trunk/LayoutTests/http/tests/push-api/subscribe-default-permissions-iframe-cross-origin-expected.txt	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/push-api/subscribe-default-permissions-iframe-cross-origin-expected.txt	2022-03-17 16:52:04 UTC (rev 291414)
@@ -2,5 +2,6 @@
 PASS: service worker permissionState was prompt
 PASS: document permissionState was prompt
 PASS: service worker subscribe was error: NotAllowedError
-PASS: document subscribe was error: NotAllowedError
+PASS: document subscribe without user gesture was error: NotAllowedError
+PASS: document subscribe with user gesture was error: NotAllowedError
 

Modified: trunk/LayoutTests/http/tests/push-api/subscribe-default-permissions-iframe-same-origin-expected.txt (291413 => 291414)


--- trunk/LayoutTests/http/tests/push-api/subscribe-default-permissions-iframe-same-origin-expected.txt	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/push-api/subscribe-default-permissions-iframe-same-origin-expected.txt	2022-03-17 16:52:04 UTC (rev 291414)
@@ -2,5 +2,6 @@
 PASS: service worker permissionState was prompt
 PASS: document permissionState was prompt
 PASS: service worker subscribe was error: NotAllowedError
-PASS: document subscribe was successful
+PASS: document subscribe without user gesture was error: NotAllowedError
+PASS: document subscribe with user gesture was successful
 

Modified: trunk/LayoutTests/http/tests/push-api/subscribe-default-permissions.html (291413 => 291414)


--- trunk/LayoutTests/http/tests/push-api/subscribe-default-permissions.html	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/push-api/subscribe-default-permissions.html	2022-03-17 16:52:04 UTC (rev 291414)
@@ -11,7 +11,8 @@
         await testServiceWorkerPermissionState(registration, 'prompt');
         await testDocumentPermissionState(registration, 'prompt');
         await testServiceWorkerSubscribe(registration, 'NotAllowedError');
-        await testDocumentSubscribe(registration);
+        await testDocumentSubscribeWithoutUserGesture(registration, 'NotAllowedError');
+        await testDocumentSubscribeWithUserGesture(registration);
     } catch (e) {
         log(`FAIL: unexpected exception ${e}`);
     } finally {

Modified: trunk/LayoutTests/http/tests/push-api/subscribe-deny-permissions-expected.txt (291413 => 291414)


--- trunk/LayoutTests/http/tests/push-api/subscribe-deny-permissions-expected.txt	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/push-api/subscribe-deny-permissions-expected.txt	2022-03-17 16:52:04 UTC (rev 291414)
@@ -1,5 +1,6 @@
 PASS: service worker permissionState was denied
 PASS: document permissionState was denied
 PASS: service worker subscribe was error: NotAllowedError
-PASS: document subscribe was error: NotAllowedError
+PASS: document subscribe without user gesture was error: NotAllowedError
+PASS: document subscribe with user gesture was error: NotAllowedError
 

Modified: trunk/LayoutTests/http/tests/push-api/subscribe-deny-permissions.html (291413 => 291414)


--- trunk/LayoutTests/http/tests/push-api/subscribe-deny-permissions.html	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/push-api/subscribe-deny-permissions.html	2022-03-17 16:52:04 UTC (rev 291414)
@@ -14,7 +14,8 @@
         await testServiceWorkerPermissionState(registration, 'denied');
         await testDocumentPermissionState(registration, 'denied');
         await testServiceWorkerSubscribe(registration, 'NotAllowedError');
-        await testDocumentSubscribe(registration, 'NotAllowedError');
+        await testDocumentSubscribeWithoutUserGesture(registration, 'NotAllowedError');
+        await testDocumentSubscribeWithUserGesture(registration, 'NotAllowedError');
     } catch (e) {
         log(`FAIL: unexpected exception ${e}`);
     } finally {

Modified: trunk/LayoutTests/http/tests/push-api/subscribe-grant-permissions-expected.txt (291413 => 291414)


--- trunk/LayoutTests/http/tests/push-api/subscribe-grant-permissions-expected.txt	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/push-api/subscribe-grant-permissions-expected.txt	2022-03-17 16:52:04 UTC (rev 291414)
@@ -1,5 +1,6 @@
 PASS: service worker permissionState was granted
 PASS: document permissionState was granted
 PASS: service worker subscribe was successful
-PASS: document subscribe was successful
+PASS: document subscribe without user gesture was successful
+PASS: document subscribe with user gesture was successful
 

Modified: trunk/LayoutTests/http/tests/push-api/subscribe-grant-permissions.html (291413 => 291414)


--- trunk/LayoutTests/http/tests/push-api/subscribe-grant-permissions.html	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/LayoutTests/http/tests/push-api/subscribe-grant-permissions.html	2022-03-17 16:52:04 UTC (rev 291414)
@@ -14,7 +14,8 @@
         await testServiceWorkerPermissionState(registration, 'granted');
         await testDocumentPermissionState(registration, 'granted');
         await testServiceWorkerSubscribe(registration);
-        await testDocumentSubscribe(registration);
+        await testDocumentSubscribeWithoutUserGesture(registration);
+        await testDocumentSubscribeWithUserGesture(registration);
     } catch (e) {
         log(`FAIL: unexpected exception ${e}`);
     } finally {

Modified: trunk/Source/WebCore/ChangeLog (291413 => 291414)


--- trunk/Source/WebCore/ChangeLog	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/Source/WebCore/ChangeLog	2022-03-17 16:52:04 UTC (rev 291414)
@@ -1,3 +1,22 @@
+2022-03-17  Ben Nham  <[email protected]>
+
+        Only show notification permission prompt on user gesture
+        https://bugs.webkit.org/show_bug.cgi?id=237946
+
+        Reviewed by Geoffrey Garen.
+
+        We want to make Notification.requestPermission and PushManager.subscribe only prompt the
+        user for permission in response to a user gesture. This matches existing behavior in other
+        browsers.
+
+        We use the error string "Push notification prompting can only be done from a user gesture"
+        since that string was already used by safari.pushNotification.requestPermission.
+
+        * Modules/notifications/Notification.cpp:
+        (WebCore::Notification::requestPermission):
+        * Modules/push-api/PushManager.cpp:
+        (WebCore::PushManager::subscribe):
+
 2022-03-17  Alan Bujtas  <[email protected]>
 
         [IFC][Integration] Replace enclosingTop/Bottom/height calls with Line::enclosingLogicalRect when applicable

Modified: trunk/Source/WebCore/Modules/notifications/Notification.cpp (291413 => 291414)


--- trunk/Source/WebCore/Modules/notifications/Notification.cpp	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/Source/WebCore/Modules/notifications/Notification.cpp	2022-03-17 16:52:04 UTC (rev 291414)
@@ -43,6 +43,7 @@
 #include "NotificationEvent.h"
 #include "NotificationPermissionCallback.h"
 #include "ServiceWorkerGlobalScope.h"
+#include "UserGestureIndicator.h"
 #include "WindowEventLoop.h"
 #include "WindowFocusAllowedIndicator.h"
 #include <wtf/CompletionHandler.h>
@@ -296,6 +297,11 @@
         return resolvePromiseAndCallback(Permission::Denied);
     }
 
+    if (!UserGestureIndicator::processingUserGesture()) {
+        document.addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Notification prompting can only be done from a user gesture."_s);
+        return resolvePromiseAndCallback(Permission::Denied);
+    }
+
     client->requestPermission(document, WTFMove(resolvePromiseAndCallback));
 }
 

Modified: trunk/Source/WebCore/Modules/push-api/PushManager.cpp (291413 => 291414)


--- trunk/Source/WebCore/Modules/push-api/PushManager.cpp	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/Source/WebCore/Modules/push-api/PushManager.cpp	2022-03-17 16:52:04 UTC (rev 291414)
@@ -37,6 +37,7 @@
 #include "PushCrypto.h"
 #include "ScriptExecutionContext.h"
 #include "ServiceWorkerRegistration.h"
+#include "UserGestureIndicator.h"
 #include <wtf/IsoMallocInlines.h>
 #include <wtf/Vector.h>
 #include <wtf/text/Base64.h>
@@ -70,8 +71,8 @@
 void PushManager::subscribe(ScriptExecutionContext& context, std::optional<PushSubscriptionOptionsInit>&& options, DOMPromiseDeferred<IDLInterface<PushSubscription>>&& promise)
 {
     RELEASE_ASSERT(context.isSecureContext());
-    
-    context.eventLoop().queueTask(TaskSource::Networking, [this, protectedThis = Ref { *this }, context = Ref { context }, options = WTFMove(options), promise = WTFMove(promise)]() mutable {
+
+    context.eventLoop().queueTask(TaskSource::Networking, [this, protectedThis = Ref { *this }, context = Ref { context }, options = WTFMove(options), promise = WTFMove(promise), processingUserGesture = UserGestureIndicator::processingUserGesture()]() mutable {
         if (!options || !options->userVisibleOnly) {
             promise.reject(Exception { NotAllowedError, "Subscribing for push requires userVisibleOnly to be true"_s });
             return;
@@ -135,6 +136,11 @@
                 return;
             }
 
+            if (!processingUserGesture) {
+                promise.reject(Exception { NotAllowedError, "Push notification prompting can only be done from a user gesture"_s });
+                return;
+            }
+
             client->requestPermission(context, [this, protectedThis = WTFMove(protectedThis), keyData = keyDataResult.releaseReturnValue(), promise = WTFMove(promise)](auto permission) mutable {
                 if (permission != NotificationPermission::Granted) {
                     promise.reject(Exception { NotAllowedError, "User denied push permission"_s });

Modified: trunk/Tools/ChangeLog (291413 => 291414)


--- trunk/Tools/ChangeLog	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/Tools/ChangeLog	2022-03-17 16:52:04 UTC (rev 291414)
@@ -1,5 +1,18 @@
 2022-03-17  Ben Nham  <[email protected]>
 
+        Only show notification permission prompt on user gesture
+        https://bugs.webkit.org/show_bug.cgi?id=237946
+
+        Reviewed by Geoffrey Garen.
+
+        Change existing permission tests to use evaluateJavaScript since that executes in the
+        context of a user gesture.
+
+        * TestWebKitAPI/Tests/WebKitCocoa/UIDelegate.mm:
+        * TestWebKitAPI/Tests/WebKitCocoa/WebPushDaemon.mm:
+
+2022-03-17  Ben Nham  <[email protected]>
+
         Allow push preference to be set programatically
         https://bugs.webkit.org/show_bug.cgi?id=238003
 

Modified: trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/UIDelegate.mm (291413 => 291414)


--- trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/UIDelegate.mm	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/UIDelegate.mm	2022-03-17 16:52:04 UTC (rev 291414)
@@ -705,16 +705,18 @@
 
 TEST(WebKit, NotificationPermission)
 {
-    NSString *html = @"<script>Notification.requestPermission(function(p){alert('permission '+p)})</script>";
-    auto webView = adoptNS([[WKWebView alloc] init]);
+    NSString *html = @"<script>function requestPermission() { Notification.requestPermission(function(p){alert('permission '+p)}); }</script>";
+    auto webView = adoptNS([[TestWKWebView alloc] initWithFrame:CGRectMake(0, 0, 800, 600) configuration:adoptNS([[WKWebViewConfiguration alloc] init]).get()]);
     auto uiDelegate = adoptNS([[NotificationDelegate alloc] initWithAllowNotifications:YES]);
     [webView setUIDelegate:uiDelegate.get()];
-    [webView loadHTMLString:html baseURL:[NSURL URLWithString:@"https://example.org"]];
+    [webView synchronouslyLoadHTMLString:html baseURL:[NSURL URLWithString:@"https://example.org"]];
+    [webView evaluateJavaScript:@"requestPermission()" completionHandler:nil];
     TestWebKitAPI::Util::run(&done);
     done = false;
     uiDelegate = adoptNS([[NotificationDelegate alloc] initWithAllowNotifications:NO]);
     [webView setUIDelegate:uiDelegate.get()];
-    [webView loadHTMLString:html baseURL:[NSURL URLWithString:@"https://example.com"]];
+    [webView synchronouslyLoadHTMLString:html baseURL:[NSURL URLWithString:@"https://example.com"]];
+    [webView evaluateJavaScript:@"requestPermission()" completionHandler:nil];
     TestWebKitAPI::Util::run(&done);
 }
 

Modified: trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/WebPushDaemon.mm (291413 => 291414)


--- trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/WebPushDaemon.mm	2022-03-17 16:45:37 UTC (rev 291413)
+++ trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/WebPushDaemon.mm	2022-03-17 16:52:04 UTC (rev 291414)
@@ -312,12 +312,6 @@
     cleanUpTestWebPushD(tempDir);
 }
 
-static const char* mainBytes = R"WEBPUSHRESOURCE(
-<script>
-    Notification.requestPermission().then(() => { alert("done") })
-</script>
-)WEBPUSHRESOURCE";
-
 TEST(WebPushD, PermissionManagement)
 {
     NSURL *tempDirectory = setUpTestWebPushD();
@@ -335,21 +329,11 @@
             [[configuration preferences] _setEnabled:YES forFeature:feature];
     }
 
-    auto handler = adoptNS([[TestURLSchemeHandler alloc] init]);
-    [configuration setURLSchemeHandler:handler.get() forURLScheme:@"testing"];
-
-    [handler setStartURLSchemeTaskHandler:^(WKWebView *, id<WKURLSchemeTask> task) {
-        auto response = adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:@"text/html" expectedContentLength:0 textEncodingName:nil]);
-        [task didReceiveResponse:response.get()];
-        [task didReceiveData:[NSData dataWithBytes:mainBytes length:strlen(mainBytes)]];
-        [task didFinish];
-    }];
-
     auto webView = adoptNS([[TestWKWebView alloc] initWithFrame:CGRectMake(0, 0, 800, 600) configuration:configuration.get()]);
     auto uiDelegate = adoptNS([[NotificationPermissionDelegate alloc] init]);
     [webView setUIDelegate:uiDelegate.get()];
-
-    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"testing://main/index.html"]]];
+    [webView synchronouslyLoadHTMLString:@"" baseURL:[NSURL URLWithString:@"https://example.org"]];
+    [webView evaluateJavaScript:@"Notification.requestPermission().then(() => { alert('done') })" completionHandler:nil];
     TestWebKitAPI::Util::run(&alertReceived);
 
     static bool originOperationDone = false;
@@ -362,8 +346,8 @@
 
     TestWebKitAPI::Util::run(&originOperationDone);
 
-    EXPECT_WK_STREQ(origin.get().protocol, "testing");
-    EXPECT_WK_STREQ(origin.get().host, "main");
+    EXPECT_WK_STREQ(origin.get().protocol, "https");
+    EXPECT_WK_STREQ(origin.get().host, "example.org");
 
     // If we failed to retrieve an expected origin, we will have failed the above checks
     if (!origin) {
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to