summaryrefslogtreecommitdiffstats
path: root/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/PermissionDelegateTest.kt
blob: 6b39d410ebc27963fe3b49334c9a5f16e549d83f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
 * Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

package org.mozilla.geckoview.test

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Build
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.test.platform.app.InstrumentationRegistry
import org.hamcrest.Matchers.* // ktlint-disable no-wildcard-imports
import org.json.JSONArray
import org.junit.Assert.fail
import org.junit.Assume.assumeThat
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.mozilla.geckoview.GeckoResult
import org.mozilla.geckoview.GeckoSession
import org.mozilla.geckoview.GeckoSession.NavigationDelegate
import org.mozilla.geckoview.GeckoSession.PermissionDelegate
import org.mozilla.geckoview.GeckoSession.PermissionDelegate.ContentPermission
import org.mozilla.geckoview.GeckoSession.PermissionDelegate.MediaCallback
import org.mozilla.geckoview.GeckoSession.PermissionDelegate.MediaSource
import org.mozilla.geckoview.GeckoSessionSettings
import org.mozilla.geckoview.StorageController.ClearFlags
import org.mozilla.geckoview.test.TrackingPermissionService.TrackingPermissionInstance
import org.mozilla.geckoview.test.rule.GeckoSessionTestRule.AssertCalled
import org.mozilla.geckoview.test.rule.GeckoSessionTestRule.ClosedSessionAtStart
import org.mozilla.geckoview.test.rule.GeckoSessionTestRule.RejectedPromiseException

@RunWith(AndroidJUnit4::class)
@MediumTest
class PermissionDelegateTest : BaseSessionTest() {
    private val targetContext
        get() = InstrumentationRegistry.getInstrumentation().targetContext

    private fun hasPermission(permission: String): Boolean {
        if (Build.VERSION.SDK_INT < 23) {
            return true
        }
        return PackageManager.PERMISSION_GRANTED ==
            InstrumentationRegistry.getInstrumentation().targetContext.checkSelfPermission(permission)
    }

    private fun isEmulator(): Boolean {
        return "generic" == Build.DEVICE || Build.DEVICE.startsWith("generic_")
    }

    private val storageController
        get() = sessionRule.runtime.storageController

    @Test fun media() {
        // TODO: needs bug 1700243
        assumeThat(sessionRule.env.isIsolatedProcess, equalTo(false))

        assertInAutomationThat(
            "Should have camera permission",
            hasPermission(Manifest.permission.CAMERA),
            equalTo(true),
        )

        assertInAutomationThat(
            "Should have microphone permission",
            hasPermission(Manifest.permission.RECORD_AUDIO),
            equalTo(true),
        )

        mainSession.loadTestPath(HELLO_HTML_PATH)
        mainSession.waitForPageStop()

        val devices = mainSession.evaluateJS(
            "window.navigator.mediaDevices.enumerateDevices()",
        ) as JSONArray

        var hasVideo = false
        var hasAudio = false
        for (i in 0 until devices.length()) {
            if (devices.getJSONObject(i).getString("kind") == "videoinput") {
                hasVideo = true
            }
            if (devices.getJSONObject(i).getString("kind") == "audioinput") {
                hasAudio = true
            }
        }

        assertThat(
            "Device list should contain camera device",
            hasVideo,
            equalTo(true),
        )
        assertThat(
            "Device list should contain microphone device",
            hasAudio,
            equalTo(true),
        )

        mainSession.delegateDuringNextWait(object : PermissionDelegate {
            @AssertCalled(count = 1)
            override fun onMediaPermissionRequest(
                session: GeckoSession,
                uri: String,
                video: Array<out MediaSource>?,
                audio: Array<out MediaSource>?,
                callback: MediaCallback,
            ) {
                assertThat("URI should match", uri, endsWith(HELLO_HTML_PATH))
                assertThat("Video source should be valid", video, not(emptyArray()))

                if (isEmulator()) {
                    callback.grant(video!![0], null)
                } else {
                    assertThat("Audio source should be valid", audio, not(emptyArray()))
                    callback.grant(video!![0], audio!![0])
                }
            }
        })

        // Start a video stream, with audio if on a real device.
        val code = if (isEmulator()) {
            """this.stream = window.navigator.mediaDevices.getUserMedia({
                           video: { width: 320, height: 240, frameRate: 10 },
                       });"""
        } else {
            """this.stream = window.navigator.mediaDevices.getUserMedia({
                           video: { width: 320, height: 240, frameRate: 10 },
                           audio: true
                       });"""
        }

        // Stop the stream and check active flag and id
        val isActive = mainSession.waitForJS(
            """$code
                   this.stream.then(stream => {
                     if (!stream.active || stream.id == '') {
                       return false;
                     }

                     stream.getTracks().forEach(track => track.stop());
                     return true;
                   })
            """.trimMargin(),
        ) as Boolean

        assertThat("Stream should be active and id should not be empty.", isActive, equalTo(true))

        // Now test rejecting the request.
        mainSession.delegateDuringNextWait(object : PermissionDelegate {
            @AssertCalled(count = 1)
            override fun onMediaPermissionRequest(
                session: GeckoSession,
                uri: String,
                video: Array<out MediaSource>?,
                audio: Array<out MediaSource>?,
                callback: MediaCallback,
            ) {
                callback.reject()
            }
        })

        try {
            if (isEmulator()) {
                mainSession.waitForJS(
                    """
                        window.navigator.mediaDevices.getUserMedia({ video: true })""",
                )
            } else {
                mainSession.waitForJS(
                    """
                        window.navigator.mediaDevices.getUserMedia({ audio: true, video: true })""",
                )
            }
            fail("Request should have failed")
        } catch (e: RejectedPromiseException) {
            assertThat(
                "Error should be correct",
                e.reason as String,
                containsString("NotAllowedError"),
            )
        }
    }

    @Test fun geolocation() {
        assertInAutomationThat(
            "Should have location permission",
            hasPermission(Manifest.permission.ACCESS_FINE_LOCATION),
            equalTo(true),
        )

        val url = createTestUrl(HELLO_HTML_PATH)
        mainSession.loadUri(url)
        mainSession.waitForPageStop()

        // Set location for test
        sessionRule.setPrefsUntilTestEnd(mapOf("geo.provider.testing" to false))
        var context = InstrumentationRegistry.getInstrumentation().targetContext
        var locManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        var locProvider = sessionRule.MockLocationProvider(
            locManager,
            "permissionsLocationProvider",
            1.1111,
            2.2222,
            false,
        )
        locProvider.postLocation()

        mainSession.delegateDuringNextWait(object : PermissionDelegate {
            // Ensure the content permission is asked first, before the Android permission.
            @AssertCalled(count = 1, order = [1])
            override fun onContentPermissionRequest(
                session: GeckoSession,
                perm: ContentPermission,
            ): GeckoResult<Int> {
                assertThat("URI should match", perm.uri, endsWith(url))
                assertThat(
                    "Type should match",
                    perm.permission,
                    equalTo(PermissionDelegate.PERMISSION_GEOLOCATION),
                )
                return GeckoResult.fromValue(ContentPermission.VALUE_ALLOW)
            }

            @AssertCalled(count = 1, order = [2])
            override fun onAndroidPermissionsRequest(
                session: GeckoSession,
                permissions: Array<out String>?,
                callback: PermissionDelegate.Callback,
            ) {
                assertThat(
                    "Permissions list should be correct",
                    listOf(*permissions!!),
                    hasItems(Manifest.permission.ACCESS_FINE_LOCATION),
                )
                callback.grant()
            }
        })

        try {
            val hasPosition = mainSession.waitForJS(
                """new Promise((resolve, reject) =>
                    window.navigator.geolocation.getCurrentPosition(
                        position => resolve(
                            position.coords.latitude !== undefined &&
                            position.coords.longitude !== undefined),
                        error => reject(error.code)))""",
            ) as Boolean

            assertThat("Request should succeed", hasPosition, equalTo(true))
        } catch (ex: RejectedPromiseException) {
            assertThat(
                "Error should not because the permission was denied.",
                ex.reason as String,
                not("1"),
            )
        }

        val perms = sessionRule.waitForResult(storageController.getPermissions(url))

        assertThat("Permissions should not be null", perms, notNullValue())
        var permFound = false
        for (perm in perms) {
            if (perm.permission == PermissionDelegate.PERMISSION_GEOLOCATION &&
                url.startsWith(perm.uri) && perm.value == ContentPermission.VALUE_ALLOW
            ) {
                permFound = true
            }
        }

        assertThat("Geolocation permission should be set to allow", permFound, equalTo(true))

        mainSession.delegateDuringNextWait(object : NavigationDelegate {
            @AssertCalled(count = 1)
            override fun onLocationChange(session: GeckoSession, url: String?, perms: MutableList<ContentPermission>, hasUserGesture: Boolean) {
                var permFound2 = false
                for (perm in perms) {
                    if (perm.permission == PermissionDelegate.PERMISSION_GEOLOCATION &&
                        perm.value == ContentPermission.VALUE_ALLOW
                    ) {
                        permFound2 = true
                    }
                }
                assertThat("Geolocation permission must be present on refresh", permFound2, equalTo(true))
            }
        })
        mainSession.reload()
        mainSession.waitForPageStop()
        locProvider.removeMockLocationProvider()
    }

    @Test fun geolocation_reject() {
        val url = createTestUrl(HELLO_HTML_PATH)
        mainSession.loadUri(url)
        mainSession.waitForPageStop()

        mainSession.delegateDuringNextWait(object : PermissionDelegate {
            @AssertCalled(count = 1)
            override fun onContentPermissionRequest(
                session: GeckoSession,
                perm: ContentPermission,
            ): GeckoResult<Int> {
                return GeckoResult.fromValue(ContentPermission.VALUE_DENY)
            }

            @AssertCalled(count = 0)
            override fun onAndroidPermissionsRequest(
                session: GeckoSession,
                permissions: Array<out String>?,
                callback: PermissionDelegate.Callback,
            ) {
            }
        })

        val errorCode = mainSession.waitForJS(
            """new Promise((resolve, reject) =>
                window.navigator.geolocation.getCurrentPosition(reject,
                  error => resolve(error.code)
                ))""",
        )

        // Error code 1 means permission denied.
        assertThat("Request should fail", errorCode as Double, equalTo(1.0))

        val perms = sessionRule.waitForResult(storageController.getPermissions(url))

        assertThat("Permissions should not be null", perms, notNullValue())
        var permFound = false
        for (perm in perms) {
            if (perm.permission == PermissionDelegate.PERMISSION_GEOLOCATION &&
                url.startsWith(perm.uri) && perm.value == ContentPermission.VALUE_DENY
            ) {
                permFound = true
            }
        }

        assertThat("Geolocation permission should be set to allow", permFound, equalTo(true))

        mainSession.delegateDuringNextWait(object : NavigationDelegate {
            @AssertCalled(count = 1)
            override fun onLocationChange(session: GeckoSession, url: String?, perms: MutableList<ContentPermission>, hasUserGesture: Boolean) {
                var permFound2 = false
                for (perm in perms) {
                    if (perm.permission == PermissionDelegate.PERMISSION_GEOLOCATION &&
                        perm.value == ContentPermission.VALUE_DENY
                    ) {
                        permFound2 = true
                    }
                }
                assertThat("Geolocation permission must be present on refresh", permFound2, equalTo(true))
            }
        })
        mainSession.reload()
        mainSession.waitForPageStop()
    }

    @ClosedSessionAtStart
    @Test
    fun trackingProtection() {
        // Tests that we get a tracking protection permission for every load, we
        // can set the value of the permission and that the permission persists
        // across sessions
        trackingProtection(privateBrowsing = false, permanent = true)
    }

    @ClosedSessionAtStart
    @Test
    fun trackingProtectionPrivateBrowsing() {
        // Tests that we get a tracking protection permission for every load, we
        // can set the value of the permission in private browsing and that the
        // permission does not persists across private sessions
        trackingProtection(privateBrowsing = true, permanent = false)
    }

    @ClosedSessionAtStart
    @Test
    fun trackingProtectionPrivateBrowsingPermanent() {
        // Tests that we get a tracking protection permission for every load, we
        // can set the value of the permission permanently in private browsing
        // and that the permanent permission _does_ persists across private sessions
        trackingProtection(privateBrowsing = true, permanent = true)
    }

    private fun trackingProtection(privateBrowsing: Boolean, permanent: Boolean) {
        // Make sure we start with a clean slate
        storageController.clearDataFromHost(TEST_HOST, ClearFlags.PERMISSIONS)

        assertThat(
            "Non-permanent only makes sense with private browsing " +
                "(because non-private browsing exceptions are always permanent",
            permanent || privateBrowsing,
            equalTo(true),
        )

        val runtime0 = TrackingPermissionInstance.start(
            targetContext,
            temporaryProfile.get(),
            privateBrowsing,
        )

        sessionRule.waitForResult(runtime0.loadTestPath(TRACKERS_PATH))
        var permission = sessionRule.waitForResult(runtime0.trackingPermission)

        assertThat(
            "Permission value should start at DENY",
            permission,
            equalTo(ContentPermission.VALUE_DENY),
        )

        if (privateBrowsing && permanent) {
            runtime0.setPrivateBrowsingPermanentTrackingPermission(
                ContentPermission.VALUE_ALLOW,
            )
        } else {
            runtime0.setTrackingPermission(ContentPermission.VALUE_ALLOW)
        }

        sessionRule.waitForResult(runtime0.reload())

        permission = sessionRule.waitForResult(runtime0.trackingPermission)
        assertThat(
            "Permission value should be ALLOW after setting",
            permission,
            equalTo(ContentPermission.VALUE_ALLOW),
        )

        sessionRule.waitForResult(runtime0.quit())

        // Restart the runtime and verifies that the value is still stored
        val runtime1 = TrackingPermissionInstance.start(
            targetContext,
            temporaryProfile.get(),
            privateBrowsing,
        )

        sessionRule.waitForResult(runtime1.loadTestPath(TRACKERS_PATH))

        val trackingPermission = sessionRule.waitForResult(runtime1.trackingPermission)
        assertThat(
            "Tracking permissions should persist only if permanent",
            trackingPermission,
            equalTo(
                when {
                    permanent -> ContentPermission.VALUE_ALLOW
                    else -> ContentPermission.VALUE_DENY
                },
            ),
        )

        sessionRule.waitForResult(runtime1.quit())
    }

    private fun assertTrackingProtectionPermission(value: Int?) {
        var found = false
        mainSession.waitUntilCalled(object : NavigationDelegate {
            @AssertCalled
            override fun onLocationChange(
                session: GeckoSession,
                url: String?,
                perms: MutableList<ContentPermission>,
                hasUserGesture: Boolean,
            ) {
                for (perm in perms) {
                    if (perm.permission == PermissionDelegate.PERMISSION_TRACKING) {
                        if (value != null) {
                            assertThat(
                                "Value should match",
                                perm.value,
                                equalTo(value),
                            )
                        }
                        found = true
                    }
                }
            }
        })

        assertThat(
            "Permission should have been found if expected",
            found,
            equalTo(value != null),
        )
    }

    // Tests that all pages have a PERMISSION_TRACKING permission,
    // except for pages that belong to Gecko like about:blank or about:config.
    @Test fun trackingProtectionPermissionOnAllPages() {
        val settings = sessionRule.runtime.settings
        val aboutConfigEnabled = settings.aboutConfigEnabled
        settings.aboutConfigEnabled = true

        mainSession.loadUri("about:config")
        assertTrackingProtectionPermission(null)

        settings.aboutConfigEnabled = aboutConfigEnabled

        mainSession.loadUri("about:blank")
        assertTrackingProtectionPermission(null)

        mainSession.loadTestPath(HELLO_HTML_PATH)
        mainSession.waitForPageStop()
        assertTrackingProtectionPermission(ContentPermission.VALUE_DENY)
    }

    @Test fun notification() {
        sessionRule.setPrefsUntilTestEnd(mapOf("dom.webnotifications.requireuserinteraction" to false))
        val url = createTestUrl(HELLO_HTML_PATH)
        mainSession.loadUri(url)
        mainSession.waitForPageStop()

        mainSession.delegateDuringNextWait(object : PermissionDelegate {
            @AssertCalled(count = 1)
            override fun onContentPermissionRequest(
                session: GeckoSession,
                perm: ContentPermission,
            ): GeckoResult<Int> {
                assertThat("URI should match", perm.uri, endsWith(url))
                assertThat(
                    "Type should match",
                    perm.permission,
                    equalTo(PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION),
                )
                return GeckoResult.fromValue(ContentPermission.VALUE_ALLOW)
            }
        })

        val result = mainSession.waitForJS("Notification.requestPermission()")

        assertThat(
            "Permission should be granted",
            result as String,
            equalTo("granted"),
        )

        val perms = sessionRule.waitForResult(storageController.getPermissions(url))

        assertThat("Permissions should not be null", perms, notNullValue())
        var permFound = false
        for (perm in perms) {
            if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                url.startsWith(perm.uri) && perm.value == ContentPermission.VALUE_ALLOW
            ) {
                permFound = true
            }
        }

        assertThat("Notification permission should be set to allow", permFound, equalTo(true))

        mainSession.delegateDuringNextWait(object : NavigationDelegate {
            @AssertCalled(count = 1)
            override fun onLocationChange(session: GeckoSession, url: String?, perms: MutableList<ContentPermission>, hasUserGesture: Boolean) {
                var permFound2 = false
                for (perm in perms) {
                    if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                        perm.value == ContentPermission.VALUE_ALLOW
                    ) {
                        permFound2 = true
                    }
                }
                assertThat("Notification permission must be present on refresh", permFound2, equalTo(true))
            }
        })
        mainSession.reload()
        mainSession.waitForPageStop()

        val result2 = mainSession.waitForJS("Notification.permission")

        assertThat(
            "Permission should be granted",
            result2 as String,
            equalTo("granted"),
        )
    }

    @Ignore("disable test for frequently failing Bug 1542525")
    @Test
    fun notification_reject() {
        val url = createTestUrl(HELLO_HTML_PATH)
        mainSession.loadUri(url)
        mainSession.waitForPageStop()

        mainSession.delegateDuringNextWait(object : PermissionDelegate {
            @AssertCalled(count = 1)
            override fun onContentPermissionRequest(
                session: GeckoSession,
                perm: ContentPermission,
            ): GeckoResult<Int> {
                return GeckoResult.fromValue(ContentPermission.VALUE_DENY)
            }
        })

        val result = mainSession.waitForJS("Notification.requestPermission()")

        assertThat(
            "Permission should not be granted",
            result as String,
            equalTo("denied"),
        )

        val perms = sessionRule.waitForResult(storageController.getPermissions(url))

        assertThat("Permissions should not be null", perms, notNullValue())
        var permFound = false
        for (perm in perms) {
            if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                url.startsWith(perm.uri) && perm.value == ContentPermission.VALUE_DENY
            ) {
                permFound = true
            }
        }

        assertThat("Notification permission should be set to allow", permFound, equalTo(true))

        mainSession.delegateDuringNextWait(object : NavigationDelegate {
            @AssertCalled(count = 1)
            override fun onLocationChange(session: GeckoSession, url: String?, perms: MutableList<ContentPermission>, hasUserGesture: Boolean) {
                var permFound2 = false
                for (perm in perms) {
                    if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                        perm.value == ContentPermission.VALUE_DENY
                    ) {
                        permFound2 = true
                    }
                }
                assertThat("Notification permission must be present on refresh", permFound2, equalTo(true))
            }
        })
        mainSession.reload()
        mainSession.waitForPageStop()
    }

    @Test
    fun autoplayReject() {
        // Bug 1810736
        assumeThat(sessionRule.env.isIsolatedProcess, equalTo(false))

        // The profile used in automation sets this to false, so we need to hack it back to true here.
        sessionRule.setPrefsUntilTestEnd(
            mapOf(
                "media.geckoview.autoplay.request" to true,
            ),
        )

        mainSession.loadTestPath(AUTOPLAY_PATH)

        mainSession.waitUntilCalled(object : PermissionDelegate {
            @AssertCalled(count = 2)
            override fun onContentPermissionRequest(session: GeckoSession, perm: ContentPermission): GeckoResult<Int> {
                val expectedType = if (sessionRule.currentCall.counter == 1) PermissionDelegate.PERMISSION_AUTOPLAY_AUDIBLE else PermissionDelegate.PERMISSION_AUTOPLAY_INAUDIBLE
                assertThat("Type should match", perm.permission, equalTo(expectedType))
                return GeckoResult.fromValue(ContentPermission.VALUE_DENY)
            }
        })
    }

    @Test
    fun contextId() {
        sessionRule.setPrefsUntilTestEnd(mapOf("dom.webnotifications.requireuserinteraction" to false))
        val url = createTestUrl(HELLO_HTML_PATH)
        mainSession.loadUri(url)
        mainSession.waitForPageStop()

        mainSession.delegateDuringNextWait(object : PermissionDelegate {
            @AssertCalled(count = 1)
            override fun onContentPermissionRequest(
                session: GeckoSession,
                perm: ContentPermission,
            ): GeckoResult<Int> {
                assertThat("URI should match", perm.uri, endsWith(url))
                assertThat(
                    "Type should match",
                    perm.permission,
                    equalTo(PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION),
                )
                assertThat("Context ID should match", perm.contextId, equalTo(mainSession.settings.contextId))
                return GeckoResult.fromValue(ContentPermission.VALUE_ALLOW)
            }
        })

        val result = mainSession.waitForJS("Notification.requestPermission()")

        assertThat(
            "Permission should be granted",
            result as String,
            equalTo("granted"),
        )

        val perms = sessionRule.waitForResult(storageController.getPermissions(url, false))

        assertThat("Permissions should not be null", perms, notNullValue())
        var permFound = false
        for (perm in perms) {
            if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                url.startsWith(perm.uri) && perm.value == ContentPermission.VALUE_ALLOW
            ) {
                permFound = true
            }
        }

        assertThat("Notification permission should be set to allow", permFound, equalTo(true))

        mainSession.delegateDuringNextWait(object : NavigationDelegate {
            @AssertCalled(count = 1)
            override fun onLocationChange(session: GeckoSession, url: String?, perms: MutableList<ContentPermission>, hasUserGesture: Boolean) {
                var permFound2 = false
                for (perm in perms) {
                    if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                        perm.value == ContentPermission.VALUE_ALLOW
                    ) {
                        permFound2 = true
                    }
                }
                assertThat("Notification permission must be present on refresh", permFound2, equalTo(true))
            }
        })
        mainSession.reload()
        mainSession.waitForPageStop()

        val session2 = sessionRule.createOpenSession(
            GeckoSessionSettings.Builder()
                .contextId("foo")
                .build(),
        )

        session2.loadUri(url)
        session2.waitForPageStop()

        session2.delegateDuringNextWait(object : PermissionDelegate {
            @AssertCalled(count = 1)
            override fun onContentPermissionRequest(
                session: GeckoSession,
                perm: ContentPermission,
            ): GeckoResult<Int> {
                assertThat("URI should match", perm.uri, endsWith(url))
                assertThat(
                    "Type should match",
                    perm.permission,
                    equalTo(PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION),
                )
                assertThat(
                    "Context ID should match",
                    perm.contextId,
                    equalTo(session2.settings.contextId),
                )
                return GeckoResult.fromValue(ContentPermission.VALUE_ALLOW)
            }
        })

        val result2 = session2.waitForJS("Notification.requestPermission()")

        assertThat(
            "Permission should be granted",
            result2 as String,
            equalTo("granted"),
        )

        val perms2 = sessionRule.waitForResult(storageController.getPermissions(url, false))

        assertThat("Permissions should not be null", perms, notNullValue())
        permFound = false
        for (perm in perms2) {
            if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                url.startsWith(perm.uri) && perm.value == ContentPermission.VALUE_ALLOW
            ) {
                permFound = true
            }
        }

        assertThat("Notification permission should be set to allow", permFound, equalTo(true))

        session2.delegateDuringNextWait(object : NavigationDelegate {
            @AssertCalled(count = 1)
            override fun onLocationChange(session: GeckoSession, url: String?, perms: MutableList<ContentPermission>, hasUserGesture: Boolean) {
                var permFound2 = false
                for (perm in perms) {
                    if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                        perm.value == ContentPermission.VALUE_ALLOW &&
                        perm.contextId == session2.settings.contextId
                    ) {
                        permFound2 = true
                    }
                }
                assertThat("Notification permission must be present on refresh", permFound2, equalTo(true))
            }
        })
        session2.reload()
        session2.waitForPageStop()
    }

    @Test fun setPermissionAllow() {
        sessionRule.setPrefsUntilTestEnd(mapOf("dom.webnotifications.requireuserinteraction" to false))
        val url = createTestUrl(HELLO_HTML_PATH)
        mainSession.loadUri(url)
        mainSession.waitForPageStop()

        mainSession.delegateDuringNextWait(object : PermissionDelegate {
            @AssertCalled(count = 1)
            override fun onContentPermissionRequest(
                session: GeckoSession,
                perm: ContentPermission,
            ): GeckoResult<Int> {
                assertThat("URI should match", perm.uri, endsWith(url))
                assertThat(
                    "Type should match",
                    perm.permission,
                    equalTo(PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION),
                )
                return GeckoResult.fromValue(ContentPermission.VALUE_DENY)
            }
        })
        mainSession.waitForJS("Notification.requestPermission()")

        val perms = sessionRule.waitForResult(storageController.getPermissions(url))

        assertThat("Permissions should not be null", perms, notNullValue())
        var permFound = false
        var notificationPerm: ContentPermission? = null
        for (perm in perms) {
            if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                url.startsWith(perm.uri) && perm.value == ContentPermission.VALUE_DENY
            ) {
                notificationPerm = perm
                permFound = true
            }
        }

        assertThat("Notification permission should be set to allow", permFound, equalTo(true))

        storageController.setPermission(
            notificationPerm!!,
            ContentPermission.VALUE_ALLOW,
        )

        mainSession.delegateDuringNextWait(object : NavigationDelegate {
            @AssertCalled(count = 1)
            override fun onLocationChange(session: GeckoSession, url: String?, perms: MutableList<ContentPermission>, hasUserGesture: Boolean) {
                var permFound2 = false
                for (perm in perms) {
                    if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                        perm.value == ContentPermission.VALUE_ALLOW
                    ) {
                        permFound2 = true
                    }
                }
                assertThat("Notification permission must be present on refresh", permFound2, equalTo(true))
            }
        })
        mainSession.reload()
        mainSession.waitForPageStop()

        val result = mainSession.waitForJS("Notification.permission")

        assertThat(
            "Permission should be granted",
            result as String,
            equalTo("granted"),
        )
    }

    @Test fun setPermissionDeny() {
        sessionRule.setPrefsUntilTestEnd(mapOf("dom.webnotifications.requireuserinteraction" to false))
        val url = createTestUrl(HELLO_HTML_PATH)
        mainSession.loadUri(url)
        mainSession.waitForPageStop()

        mainSession.delegateDuringNextWait(object : PermissionDelegate {
            @AssertCalled(count = 1)
            override fun onContentPermissionRequest(
                session: GeckoSession,
                perm: ContentPermission,
            ): GeckoResult<Int> {
                assertThat("URI should match", perm.uri, endsWith(url))
                assertThat(
                    "Type should match",
                    perm.permission,
                    equalTo(PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION),
                )
                return GeckoResult.fromValue(ContentPermission.VALUE_ALLOW)
            }
        })

        val result = mainSession.waitForJS("Notification.requestPermission()")

        assertThat(
            "Permission should be granted",
            result as String,
            equalTo("granted"),
        )

        val perms = sessionRule.waitForResult(storageController.getPermissions(url))

        assertThat("Permissions should not be null", perms, notNullValue())
        var permFound = false
        var notificationPerm: ContentPermission? = null
        for (perm in perms) {
            if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                url.startsWith(perm.uri) && perm.value == ContentPermission.VALUE_ALLOW
            ) {
                notificationPerm = perm
                permFound = true
            }
        }

        assertThat("Notification permission should be set to allow", permFound, equalTo(true))

        storageController.setPermission(
            notificationPerm!!,
            ContentPermission.VALUE_DENY,
        )

        mainSession.delegateDuringNextWait(object : NavigationDelegate {
            @AssertCalled(count = 1)
            override fun onLocationChange(session: GeckoSession, url: String?, perms: MutableList<ContentPermission>, hasUserGesture: Boolean) {
                var permFound2 = false
                for (perm in perms) {
                    if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                        perm.value == ContentPermission.VALUE_DENY
                    ) {
                        permFound2 = true
                    }
                }
                assertThat("Notification permission must be present on refresh", permFound2, equalTo(true))
            }
        })
        mainSession.reload()
        mainSession.waitForPageStop()

        val result2 = mainSession.waitForJS("Notification.permission")

        assertThat(
            "Permission should be denied",
            result2 as String,
            equalTo("denied"),
        )
    }

    @Test fun setPermissionPrompt() {
        sessionRule.setPrefsUntilTestEnd(mapOf("dom.webnotifications.requireuserinteraction" to false))
        val url = createTestUrl(HELLO_HTML_PATH)
        mainSession.loadUri(url)
        mainSession.waitForPageStop()

        mainSession.delegateDuringNextWait(object : PermissionDelegate {
            @AssertCalled(count = 1)
            override fun onContentPermissionRequest(
                session: GeckoSession,
                perm: ContentPermission,
            ): GeckoResult<Int> {
                assertThat("URI should match", perm.uri, endsWith(url))
                assertThat(
                    "Type should match",
                    perm.permission,
                    equalTo(PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION),
                )
                return GeckoResult.fromValue(ContentPermission.VALUE_ALLOW)
            }
        })

        val result = mainSession.waitForJS("Notification.requestPermission()")

        assertThat(
            "Permission should be granted",
            result as String,
            equalTo("granted"),
        )

        val perms = sessionRule.waitForResult(storageController.getPermissions(url))

        assertThat("Permissions should not be null", perms, notNullValue())
        var permFound = false
        var notificationPerm: ContentPermission? = null
        for (perm in perms) {
            if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                url.startsWith(perm.uri) && perm.value == ContentPermission.VALUE_ALLOW
            ) {
                notificationPerm = perm
                permFound = true
            }
        }

        assertThat("Notification permission should be set to allow", permFound, equalTo(true))

        storageController.setPermission(
            notificationPerm!!,
            ContentPermission.VALUE_PROMPT,
        )

        mainSession.delegateDuringNextWait(object : PermissionDelegate {
            @AssertCalled(count = 1)
            override fun onContentPermissionRequest(
                session: GeckoSession,
                perm: ContentPermission,
            ): GeckoResult<Int> {
                return GeckoResult.fromValue(ContentPermission.VALUE_PROMPT)
            }
        })

        val result2 = mainSession.waitForJS("Notification.requestPermission()")

        assertThat(
            "Permission should be default",
            result2 as String,
            equalTo("default"),
        )
    }

    @Test fun permissionJsonConversion() {
        sessionRule.setPrefsUntilTestEnd(mapOf("dom.webnotifications.requireuserinteraction" to false))
        val url = createTestUrl(HELLO_HTML_PATH)
        mainSession.loadUri(url)
        mainSession.waitForPageStop()

        mainSession.delegateDuringNextWait(object : PermissionDelegate {
            @AssertCalled(count = 1)
            override fun onContentPermissionRequest(
                session: GeckoSession,
                perm: ContentPermission,
            ): GeckoResult<Int> {
                assertThat("URI should match", perm.uri, endsWith(url))
                assertThat(
                    "Type should match",
                    perm.permission,
                    equalTo(PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION),
                )
                return GeckoResult.fromValue(ContentPermission.VALUE_ALLOW)
            }
        })

        val result = mainSession.waitForJS("Notification.requestPermission()")

        assertThat(
            "Permission should be granted",
            result as String,
            equalTo("granted"),
        )

        val perms = sessionRule.waitForResult(storageController.getPermissions(url))

        assertThat("Permissions should not be null", perms, notNullValue())
        var permFound = false
        var notificationPerm: ContentPermission? = null
        for (perm in perms) {
            if (perm.permission == PermissionDelegate.PERMISSION_DESKTOP_NOTIFICATION &&
                url.startsWith(perm.uri) && perm.value == ContentPermission.VALUE_ALLOW
            ) {
                notificationPerm = perm
                permFound = true
            }
        }

        assertThat("Notification permission should be set to allow", permFound, equalTo(true))

        val jsonPerm = notificationPerm?.toJson()
        assertThat("JSON export should not be null", jsonPerm, notNullValue())

        val importedPerm = ContentPermission.fromJson(jsonPerm!!)
        assertThat("JSON import should not be null", importedPerm, notNullValue())

        assertThat("URIs should match", importedPerm?.uri, equalTo(notificationPerm?.uri))
        assertThat("Types should match", importedPerm?.permission, equalTo(notificationPerm?.permission))
        assertThat("Values should match", importedPerm?.value, equalTo(notificationPerm?.value))
        assertThat("Context IDs should match", importedPerm?.contextId, equalTo(notificationPerm?.contextId))
        assertThat("Private mode should match", importedPerm?.privateMode, equalTo(notificationPerm?.privateMode))
    }

    // @Test fun persistentStorage() {
    //     mainSession.loadTestPath(HELLO_HTML_PATH)
    //     mainSession.waitForPageStop()

    //     // Persistent storage can be rejected
    //     mainSession.delegateDuringNextWait(object : PermissionDelegate {
    //         @AssertCalled(count = 1)
    //         override fun onContentPermissionRequest(
    //                 session: GeckoSession, uri: String?, type: Int,
    //                 callback: PermissionDelegate.Callback) {
    //             callback.reject()
    //         }
    //     })

    //     var success = mainSession.waitForJS("""window.navigator.storage.persist()""")

    //     assertThat("Request should fail",
    //             success as Boolean, equalTo(false))

    //     // Persistent storage can be granted
    //     mainSession.delegateDuringNextWait(object : PermissionDelegate {
    //         // Ensure the content permission is asked first, before the Android permission.
    //         @AssertCalled(count = 1, order = [1])
    //         override fun onContentPermissionRequest(
    //                 session: GeckoSession, uri: String?, type: Int,
    //                 callback: PermissionDelegate.Callback) {
    //             assertThat("URI should match", uri, endsWith(HELLO_HTML_PATH))
    //             assertThat("Type should match", type,
    //                     equalTo(PermissionDelegate.PERMISSION_PERSISTENT_STORAGE))
    //             callback.grant()
    //         }
    //     })

    //     success = mainSession.waitForJS("""window.navigator.storage.persist()""")

    //     assertThat("Request should succeed",
    //             success as Boolean,
    //             equalTo(true))

    //     // after permission granted further requests will always return true, regardless of response
    //     mainSession.delegateDuringNextWait(object : PermissionDelegate {
    //         @AssertCalled(count = 1)
    //         override fun onContentPermissionRequest(
    //                 session: GeckoSession, uri: String?, type: Int,
    //                 callback: PermissionDelegate.Callback) {
    //             callback.reject()
    //         }
    //     })

    //     success = mainSession.waitForJS("""window.navigator.storage.persist()""")

    //     assertThat("Request should succeed",
    //             success as Boolean, equalTo(true))
    // }
}