File: permissions_api_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1588 lines) | stat: -rw-r--r-- 66,518 bytes parent folder | download | duplicates (2)
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
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/permissions/permissions_api.h"

#include <memory>
#include <optional>
#include <string>

#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/extensions/extension_api_unittest.h"
#include "chrome/browser/extensions/extension_service_test_with_install.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/permissions/active_tab_permission_granter.h"
#include "chrome/browser/extensions/permissions/permissions_test_util.h"
#include "chrome/browser/extensions/permissions/permissions_updater.h"
#include "chrome/browser/extensions/permissions/scripting_permissions_modifier.h"
#include "chrome/test/base/testing_profile.h"
#include "components/crx_file/id_util.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/web_contents_tester.h"
#include "extensions/browser/api_test_utils.h"
#include "extensions/browser/extension_api_frame_id_map.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/browser/extension_util.h"
#include "extensions/browser/permissions_manager.h"
#include "extensions/browser/test_extension_registry_observer.h"
#include "extensions/common/extension_builder.h"
#include "extensions/common/extension_features.h"
#include "extensions/common/manifest_handlers/permissions_parser.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/test/test_extension_dir.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace extensions {

namespace {

constexpr char kNotInManifestError[] =
    "Only permissions specified in the manifest may be requested.";

using permissions_test_util::GetPatternsAsStrings;

scoped_refptr<const Extension> CreateExtensionWithPermissions(
    base::Value::List permissions,
    const std::string& name,
    bool allow_file_access) {
  int creation_flags = Extension::NO_FLAGS;
  if (allow_file_access)
    creation_flags |= Extension::ALLOW_FILE_ACCESS;
  return ExtensionBuilder()
      .SetLocation(mojom::ManifestLocation::kInternal)
      .SetManifest(base::Value::Dict()
                       .Set("name", name)
                       .Set("description", "foo")
                       .Set("manifest_version", 2)
                       .Set("version", "0.1.2.3")
                       .Set("permissions", std::move(permissions)))
      .AddFlags(creation_flags)
      .SetID(crx_file::id_util::GenerateId(name))
      .Build();
}

// Runs permissions.request() with the provided |args|, and returns the result
// of the API call. Expects the function to succeed.
// Populates |did_prompt_user| with whether the user would be prompted for the
// new permissions.
bool RunRequestFunction(
    const Extension& extension,
    content::BrowserContext* browser_context,
    const char* args,
    std::unique_ptr<const PermissionSet>* prompted_permissions_out) {
  auto function = base::MakeRefCounted<PermissionsRequestFunction>();
  function->set_user_gesture(true);
  function->set_extension(&extension);
  std::optional<base::Value> result =
      api_test_utils::RunFunctionAndReturnSingleResult(
          function.get(), args, browser_context,
          api_test_utils::FunctionMode::kNone);
  if (!function->GetError().empty()) {
    ADD_FAILURE() << "Unexpected function error: " << function->GetError();
    return false;
  }

  if (!result || !result->is_bool()) {
    ADD_FAILURE() << "Unexpected function result.";
    return false;
  }

  *prompted_permissions_out = function->TakePromptedPermissionsForTesting();

  return result->GetBool();
}

}  // namespace

class PermissionsAPIUnitTest : public ExtensionServiceTestWithInstall {
 public:
  PermissionsAPIUnitTest() = default;

  PermissionsAPIUnitTest(const PermissionsAPIUnitTest&) = delete;
  PermissionsAPIUnitTest& operator=(const PermissionsAPIUnitTest&) = delete;

  ~PermissionsAPIUnitTest() override = default;
  Browser* browser() { return browser_.get(); }

  // Runs chrome.permissions.contains(|json_query|).
  bool RunContainsFunction(const std::string& manifest_permission,
                           const std::string& args_string,
                           bool allow_file_access) {
    SCOPED_TRACE(args_string);
    scoped_refptr<const Extension> extension = CreateExtensionWithPermissions(
        base::Value::List().Append(manifest_permission), "My Extension",
        allow_file_access);
    ExtensionPrefs::Get(profile())->SetAllowFileAccess(extension->id(),
                                                       allow_file_access);
    scoped_refptr<PermissionsContainsFunction> function(
        new PermissionsContainsFunction());
    function->set_extension(extension.get());
    bool run_result =
        api_test_utils::RunFunction(function.get(), args_string, profile(),
                                    api_test_utils::FunctionMode::kNone);
    EXPECT_TRUE(run_result) << function->GetError();

    const auto& args_list = *function->GetResultListForTest();
    if (args_list.empty()) {
      ADD_FAILURE() << "Result unexpectedly empty.";
      return false;
    }
    if (!args_list[0].is_bool()) {
      ADD_FAILURE() << "Result is not a boolean.";
      return false;
    }
    return args_list[0].GetBool();
  }

  // Adds the extension to the ExtensionService, and grants any initial
  // permissions.
  void AddExtensionAndGrantPermissions(const Extension& extension) {
    PermissionsUpdater updater(profile());
    updater.InitializePermissions(&extension);
    updater.GrantActivePermissions(&extension);
    registrar()->AddExtension(&extension);
  }

  // Adds the extension to the ExtensionService, and withheld any initial
  // permissions.
  void AddExtensionAndWithheldPermissions(const Extension& extension) {
    PermissionsUpdater updater(profile());
    updater.InitializePermissions(&extension);
    ScriptingPermissionsModifier(profile(), &extension)
        .SetWithholdHostPermissions(true);
    registrar()->AddExtension(&extension);
  }

 protected:
  // ExtensionServiceTestBase:
  void SetUp() override {
    ExtensionServiceTestWithInstall::SetUp();
    dialog_action_ = PermissionsRequestFunction::SetDialogActionForTests(
        PermissionsRequestFunction::DialogAction::kAutoConfirm);
    InitializeEmptyExtensionService();
    browser_window_ = std::make_unique<TestBrowserWindow>();
    Browser::CreateParams params(profile(), true);
    params.type = Browser::TYPE_NORMAL;
    params.window = browser_window_.get();
    browser_.reset(Browser::Create(params));
  }
  // ExtensionServiceTestBase:
  void TearDown() override {
    dialog_action_.reset();
    browser_.reset();
    browser_window_.reset();
    ExtensionServiceTestWithInstall::TearDown();
  }

 private:
  std::unique_ptr<TestBrowserWindow> browser_window_;
  std::unique_ptr<Browser> browser_;
  std::optional<base::AutoReset<PermissionsRequestFunction::DialogAction>>
      dialog_action_;
};

TEST_F(PermissionsAPIUnitTest, Contains) {
  // 1. Since the extension does not have file:// origin access, expect it
  // to return false;
  bool expected_has_permission = false;
  bool has_permission = RunContainsFunction(
      "tabs", "[{\"origins\":[\"file://*\"]}]", false /* allow_file_access */);
  EXPECT_EQ(expected_has_permission, has_permission);

  // 2. Extension has tabs permission, expect to return true.
  expected_has_permission = true;
  has_permission = RunContainsFunction("tabs", "[{\"permissions\":[\"tabs\"]}]",
                                       false /* allow_file_access */);
  EXPECT_EQ(expected_has_permission, has_permission);

  // 3. Extension has file permission, but not active. Expect to return false.
  expected_has_permission = false;
  has_permission =
      RunContainsFunction("file://*", "[{\"origins\":[\"file://*\"]}]",
                          false /* allow_file_access */);
  EXPECT_EQ(expected_has_permission, has_permission);

  // 4. Same as #3, but this time with file access allowed.
  expected_has_permission = true;
  has_permission =
      RunContainsFunction("file:///*", "[{\"origins\":[\"file:///*\"]}]",
                          true /* allow_file_access */);
  EXPECT_EQ(expected_has_permission, has_permission);

  // Tests calling contains() with <all_urls> with and without file access.
  // Regression test for https://crbug.com/931816.
  EXPECT_TRUE(RunContainsFunction("<all_urls>",
                                  R"([{"origins": ["<all_urls>"]}])",
                                  false /* allow file access */));
  EXPECT_TRUE(RunContainsFunction("<all_urls>",
                                  R"([{"origins": ["<all_urls>"]}])",
                                  true /* allow file access */));
}

TEST_F(PermissionsAPIUnitTest, ContainsAndGetAllWithRuntimeHostPermissions) {
  constexpr char kExampleCom[] = "https://example.com/*";
  constexpr char kContentScriptCom[] = "https://contentscript.com/*";
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("extension")
          .AddHostPermission(kExampleCom)
          .AddContentScript("foo.js", {kContentScriptCom, kExampleCom})
          .Build();

  AddExtensionAndGrantPermissions(*extension);
  PermissionsUpdater updater(profile());
  updater.InitializePermissions(extension.get());
  updater.GrantActivePermissions(extension.get());
  registrar()->AddExtension(extension.get());

  auto contains_origin = [this, &extension](const char* origin) {
    SCOPED_TRACE(origin);
    auto function = base::MakeRefCounted<PermissionsContainsFunction>();
    function->set_extension(extension.get());
    if (!api_test_utils::RunFunction(
            function.get(),
            base::StringPrintf(R"([{"origins": ["%s"]}])", origin), profile(),
            api_test_utils::FunctionMode::kNone)) {
      ADD_FAILURE() << "Running function failed: " << function->GetError();
    }

    return (*function->GetResultListForTest())[0].GetBool();
  };

  auto get_all = [this, &extension]() {
    auto function = base::MakeRefCounted<PermissionsGetAllFunction>();
    function->set_extension(extension.get());

    std::vector<std::string> origins;
    if (!api_test_utils::RunFunction(function.get(), "[]", profile(),
                                     api_test_utils::FunctionMode::kNone)) {
      ADD_FAILURE() << "Running function failed: " << function->GetError();
      return origins;
    }

    const base::Value::List* results = function->GetResultListForTest();
    if (results->size() != 1u || !(*results)[0].is_dict()) {
      ADD_FAILURE() << "Invalid result value";
      return origins;
    }

    const base::Value::List* origins_value =
        (*results)[0].GetDict().FindList("origins");
    for (const auto& value : *origins_value) {
      origins.push_back(value.GetString());
    }

    return origins;
  };

  // Currently, the extension should have access to example.com and
  // contentscript.com (since permissions are not withheld).
  EXPECT_TRUE(contains_origin(kExampleCom));
  EXPECT_TRUE(contains_origin(kContentScriptCom));
  EXPECT_THAT(get_all(),
              testing::UnorderedElementsAre(kExampleCom, kContentScriptCom));

  ScriptingPermissionsModifier modifier(profile(), extension);
  modifier.SetWithholdHostPermissions(true);

  // Once we withhold the permission, the contains function should correctly
  // report the value.
  EXPECT_FALSE(contains_origin(kExampleCom));
  EXPECT_FALSE(contains_origin(kContentScriptCom));
  EXPECT_THAT(get_all(), testing::IsEmpty());

  constexpr char kChromiumOrg[] = "https://chromium.org/";
  modifier.GrantHostPermission(GURL(kChromiumOrg));

  // The permissions API only reports active permissions, rather than granted
  // permissions. This means it will not report values for permissions that
  // aren't requested. This is probably good, because the extension wouldn't be
  // able to use them anyway (since they aren't active).
  EXPECT_FALSE(contains_origin(kChromiumOrg));
  EXPECT_THAT(get_all(), testing::IsEmpty());

  // Fun edge case: example.com is requested as both a scriptable and an
  // explicit host. It is technically possible that it may be granted *only* as
  // one of the two (e.g., only explicit granted).
  {
    URLPatternSet explicit_hosts(
        {URLPattern(Extension::kValidHostPermissionSchemes, kExampleCom)});
    permissions_test_util::GrantRuntimePermissionsAndWaitForCompletion(
        profile(), *extension,
        PermissionSet(APIPermissionSet(), ManifestPermissionSet(),
                      std::move(explicit_hosts), URLPatternSet()));
    const GURL example_url("https://example.com");
    const PermissionSet& active_permissions =
        extension->permissions_data()->active_permissions();
    EXPECT_TRUE(active_permissions.explicit_hosts().MatchesURL(example_url));
    EXPECT_FALSE(active_permissions.scriptable_hosts().MatchesURL(example_url));
  }
  // In this case, contains() should return *false* (because not all the
  // permissions are active, but getAll() should include example.com (because it
  // has been [partially] granted). In practice, this case should be
  // exceptionally rare, and we're mostly just making sure that there's some
  // sane behavior.
  EXPECT_FALSE(contains_origin(kExampleCom));
  EXPECT_THAT(get_all(), testing::ElementsAre(kExampleCom));
}

// Tests requesting permissions that are already granted with the
// permissions.request() API.
TEST_F(PermissionsAPIUnitTest, RequestingGrantedPermissions) {
  // Create an extension with requires all urls, and grant the permission.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("extension").AddHostPermission("<all_urls>").Build();
  AddExtensionAndGrantPermissions(*extension);

  // Request access to any host permissions. No permissions should be prompted,
  // since permissions that are already granted are not taken into account.
  std::unique_ptr<const PermissionSet> prompted_permissions;
  EXPECT_TRUE(RunRequestFunction(*extension, profile(),
                                 R"([{"origins": ["https://*/*"]}])",
                                 &prompted_permissions));
  EXPECT_EQ(prompted_permissions, nullptr);
}

// Tests requesting withheld permissions with the permissions.request() API.
TEST_F(PermissionsAPIUnitTest, RequestingWithheldPermissions) {
  // Create an extension with required host permissions, and withhold those
  // permissions.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("extension")
          .AddHostPermissions({"https://example.com/*", "https://google.com/*"})
          .Build();
  AddExtensionAndGrantPermissions(*extension);
  ScriptingPermissionsModifier(profile(), extension)
      .SetWithholdHostPermissions(true);

  const GURL kExampleCom("https://example.com");
  const GURL kGoogleCom("https://google.com");
  const PermissionsData* permissions_data = extension->permissions_data();
  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().is_empty());

  // Request one of the withheld permissions.
  std::unique_ptr<const PermissionSet> prompted_permissions;
  EXPECT_TRUE(RunRequestFunction(*extension, profile(),
                                 R"([{"origins": ["https://example.com/*"]}])",
                                 &prompted_permissions));
  ASSERT_TRUE(prompted_permissions);
  EXPECT_THAT(GetPatternsAsStrings(prompted_permissions->effective_hosts()),
              testing::UnorderedElementsAre("https://example.com/*"));

  // The withheld permission should be granted.
  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().MatchesURL(
          kExampleCom));
  EXPECT_FALSE(
      permissions_data->active_permissions().effective_hosts().MatchesURL(
          kGoogleCom));
}

// Tests requesting withheld content script permissions with the
// permissions.request() API.
TEST_F(PermissionsAPIUnitTest, RequestingWithheldContentScriptPermissions) {
  constexpr char kContentScriptPattern[] = "https://contentscript.com/*";
  // Create an extension with required host permissions, and withhold those
  // permissions.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("extension")
          .AddContentScript("foo.js", {kContentScriptPattern})
          .Build();
  AddExtensionAndGrantPermissions(*extension);
  ScriptingPermissionsModifier(profile(), extension)
      .SetWithholdHostPermissions(true);

  const GURL kContentScriptCom("https://contentscript.com");
  const PermissionsData* permissions_data = extension->permissions_data();
  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().is_empty());

  // Request one of the withheld permissions.
  std::unique_ptr<const PermissionSet> prompted_permissions;
  EXPECT_TRUE(
      RunRequestFunction(*extension, profile(),
                         R"([{"origins": ["https://contentscript.com/*"]}])",
                         &prompted_permissions));
  ASSERT_TRUE(prompted_permissions);
  EXPECT_THAT(GetPatternsAsStrings(prompted_permissions->effective_hosts()),
              testing::UnorderedElementsAre(kContentScriptPattern));

  // The withheld permission should be granted.
  EXPECT_THAT(GetPatternsAsStrings(
                  permissions_data->active_permissions().effective_hosts()),
              testing::UnorderedElementsAre(kContentScriptPattern));
  EXPECT_TRUE(
      permissions_data->withheld_permissions().effective_hosts().is_empty());
}

// Tests requesting a withheld host permission that is both an explicit and a
// scriptable host with the permissions.request() API.
TEST_F(PermissionsAPIUnitTest,
       RequestingWithheldExplicitAndScriptablePermissionsInTheSameCall) {
  constexpr char kContentScriptPattern[] = "https://example.com/*";
  // Create an extension with required host permissions, and withhold those
  // permissions.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("extension")
          .AddHostPermission("https://example.com/*")
          .AddContentScript("foo.js", {kContentScriptPattern})
          .Build();
  AddExtensionAndGrantPermissions(*extension);
  ScriptingPermissionsModifier(profile(), extension)
      .SetWithholdHostPermissions(true);

  const GURL kExampleCom("https://example.com");
  const PermissionsData* permissions_data = extension->permissions_data();
  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().is_empty());

  // Request one of the withheld permissions.
  std::unique_ptr<const PermissionSet> prompted_permissions;
  EXPECT_TRUE(RunRequestFunction(*extension, profile(),
                                 R"([{"origins": ["https://example.com/*"]}])",
                                 &prompted_permissions));
  ASSERT_TRUE(prompted_permissions);
  EXPECT_THAT(GetPatternsAsStrings(prompted_permissions->effective_hosts()),
              testing::UnorderedElementsAre(kContentScriptPattern));

  // The withheld permission should be granted to both explicit and scriptable
  // hosts.
  EXPECT_TRUE(
      permissions_data->active_permissions().explicit_hosts().MatchesURL(
          kExampleCom));
  EXPECT_TRUE(
      permissions_data->active_permissions().scriptable_hosts().MatchesURL(
          kExampleCom));
}

// Tests an extension re-requesting an optional host after the user removes it.
TEST_F(PermissionsAPIUnitTest, ReRequestingWithheldOptionalPermissions) {
  // Create an extension an optional host permissions, and withhold those
  // permissions.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("extension")
          .AddOptionalHostPermission("https://chromium.org/*")
          .Build();
  AddExtensionAndGrantPermissions(*extension);

  const GURL kChromiumOrg("https://chromium.org");
  const PermissionsData* permissions_data = extension->permissions_data();
  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().is_empty());
  {
    std::unique_ptr<const PermissionSet> prompted_permissions;
    EXPECT_TRUE(RunRequestFunction(
        *extension, profile(), R"([{"origins": ["https://chromium.org/*"]}])",
        &prompted_permissions));
    ASSERT_TRUE(prompted_permissions);
    EXPECT_THAT(GetPatternsAsStrings(prompted_permissions->effective_hosts()),
                testing::UnorderedElementsAre("https://chromium.org/*"));
  }

  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().MatchesURL(
          kChromiumOrg));

  {
    URLPattern chromium_org_pattern(Extension::kValidHostPermissionSchemes,
                                    "https://chromium.org/*");
    PermissionSet permissions(APIPermissionSet(), ManifestPermissionSet(),
                              URLPatternSet({chromium_org_pattern}),
                              URLPatternSet());
    permissions_test_util::RevokeRuntimePermissionsAndWaitForCompletion(
        profile(), *extension, permissions);
  }
  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().is_empty());

  auto dialog_action_reset =
      PermissionsRequestFunction::SetDialogActionForTests(
          PermissionsRequestFunction::DialogAction::kAutoReject);
  {
    std::unique_ptr<const PermissionSet> prompted_permissions;
    EXPECT_FALSE(RunRequestFunction(
        *extension, profile(), R"([{"origins": ["https://chromium.org/*"]}])",
        &prompted_permissions));
    ASSERT_TRUE(prompted_permissions);
    EXPECT_THAT(GetPatternsAsStrings(prompted_permissions->effective_hosts()),
                testing::UnorderedElementsAre("https://chromium.org/*"));
  }
  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().is_empty());
}

// Tests requesting both optional and withheld permissions in the same call to
// permissions.request().
TEST_F(PermissionsAPIUnitTest, RequestingWithheldAndOptionalPermissions) {
  // Create an extension with required and optional host permissions, and
  // withhold the required permissions.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("extension")
          .AddHostPermissions({"https://example.com/*", "https://google.com/*"})
          .AddOptionalHostPermission("https://chromium.org/*")
          .Build();
  AddExtensionAndGrantPermissions(*extension);
  ScriptingPermissionsModifier(profile(), extension)
      .SetWithholdHostPermissions(true);

  const GURL kExampleCom("https://example.com");
  const GURL kGoogleCom("https://google.com");
  const GURL kChromiumOrg("https://chromium.org");
  const PermissionsData* permissions_data = extension->permissions_data();
  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().is_empty());

  // Request one of the withheld host permissions and an optional host
  // permission in the same call.
  std::unique_ptr<const PermissionSet> prompted_permissions;
  EXPECT_TRUE(RunRequestFunction(
      *extension, profile(),
      R"([{"origins": ["https://example.com/*", "https://chromium.org/*"]}])",
      &prompted_permissions));
  ASSERT_TRUE(prompted_permissions);
  EXPECT_THAT(GetPatternsAsStrings(prompted_permissions->effective_hosts()),
              testing::UnorderedElementsAre("https://chromium.org/*",
                                            "https://example.com/*"));

  // The requested permissions should be added.
  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().MatchesURL(
          kExampleCom));
  EXPECT_FALSE(
      permissions_data->active_permissions().effective_hosts().MatchesURL(
          kGoogleCom));
  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().MatchesURL(
          kChromiumOrg));
}

// Tests requesting permissions that weren't specified in the manifest (either
// in optional permissions or in required permissions).
TEST_F(PermissionsAPIUnitTest, RequestingPermissionsNotSpecifiedInManifest) {
  // Create an extension with required and optional host permissions, and
  // withhold the required permissions.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("extension")
          .AddHostPermission("https://example.com/*")
          .AddOptionalHostPermission("https://chromium.org/*")
          .Build();
  AddExtensionAndGrantPermissions(*extension);
  ScriptingPermissionsModifier(profile(), extension)
      .SetWithholdHostPermissions(true);

  const GURL kExampleCom("https://example.com");
  const GURL kGoogleCom("https://google.com");
  const GURL kChromiumOrg("https://chromium.org");

  // Request permission for an optional and required permission, as well as a
  // permission that wasn't specified in the manifest. The call should fail.
  // Note: Not using RunRequestFunction(), since that expects function success.
  auto function = base::MakeRefCounted<PermissionsRequestFunction>();
  function->set_user_gesture(true);
  function->set_extension(extension.get());
  EXPECT_EQ(kNotInManifestError,
            api_test_utils::RunFunctionAndReturnError(
                function.get(),
                R"([{
               "origins": [
                 "https://example.com/*",
                 "https://chromium.org/*",
                 "https://google.com/*"
               ]
             }])",
                profile(), api_test_utils::FunctionMode::kNone));
}

// Tests requesting withheld permissions that have already been granted.
TEST_F(PermissionsAPIUnitTest, RequestingAlreadyGrantedWithheldPermissions) {
  // Create an extension with required host permissions, withhold host
  // permissions, and then grant one of the hosts.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("extension")
          .AddHostPermissions({"https://example.com/*", "https://google.com/*"})
          .Build();
  AddExtensionAndGrantPermissions(*extension);
  ScriptingPermissionsModifier modifier(profile(), extension);
  modifier.SetWithholdHostPermissions(true);

  const GURL kExampleCom("https://example.com");
  const GURL kGoogleCom("https://google.com");
  modifier.GrantHostPermission(kExampleCom);

  const PermissionsData* permissions_data = extension->permissions_data();
  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().MatchesURL(
          kExampleCom));
  EXPECT_FALSE(
      permissions_data->active_permissions().effective_hosts().MatchesURL(
          kGoogleCom));

  // Request the already-granted host permission. The function should succeed
  // (without even prompting the user), and the permission should (still) be
  // granted.
  auto dialog_action_reset =
      PermissionsRequestFunction::SetDialogActionForTests(
          PermissionsRequestFunction::DialogAction::kAutoReject);

  std::unique_ptr<const PermissionSet> prompted_permissions;
  EXPECT_TRUE(RunRequestFunction(*extension, profile(),
                                 R"([{"origins": ["https://example.com/*"]}])",
                                 &prompted_permissions));
  ASSERT_FALSE(prompted_permissions);

  // The withheld permission should be granted.
  EXPECT_TRUE(
      permissions_data->active_permissions().effective_hosts().MatchesURL(
          kExampleCom));
  EXPECT_FALSE(
      permissions_data->active_permissions().effective_hosts().MatchesURL(
          kGoogleCom));
}

// Test that requesting chrome:-scheme URLs is disallowed in the permissions
// API.
TEST_F(PermissionsAPIUnitTest, RequestingChromeURLs) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("extension")
          .AddOptionalHostPermission("<all_urls>")
          .Build();
  AddExtensionAndGrantPermissions(*extension);

  const GURL chrome_url("chrome://settings");

  // By default, the extension should not have access to chrome://settings.
  EXPECT_FALSE(extension->permissions_data()->HasHostPermission(chrome_url));
  // The optional permissions should also omit the chrome:-scheme for the
  // <all_urls> pattern.
  EXPECT_FALSE(PermissionsParser::GetOptionalPermissions(extension.get())
                   .explicit_hosts()
                   .MatchesURL(chrome_url));

  {
    // Trying to request "chrome://settings/*" should fail, since it's not in
    // the optional permissions.
    auto function = base::MakeRefCounted<PermissionsRequestFunction>();
    function->set_user_gesture(true);
    function->set_extension(extension.get());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(), R"([{"origins": ["chrome://settings/*"]}])", profile(),
        api_test_utils::FunctionMode::kNone);
    EXPECT_EQ(kNotInManifestError, error);
  }
  // chrome://settings should still be restricted.
  EXPECT_FALSE(extension->permissions_data()->HasHostPermission(chrome_url));

  // The extension can request <all_urls>, but it should not grant access to the
  // chrome:-scheme.
  std::unique_ptr<const PermissionSet> prompted_permissions;
  RunRequestFunction(*extension, profile(), R"([{"origins": ["<all_urls>"]}])",
                     &prompted_permissions);
  EXPECT_THAT(GetPatternsAsStrings(prompted_permissions->effective_hosts()),
              testing::UnorderedElementsAre("<all_urls>"));

  EXPECT_FALSE(extension->permissions_data()->HasHostPermission(chrome_url));
  EXPECT_TRUE(extension->permissions_data()->HasHostPermission(
      GURL("https://example.com")));
}

// Tests requesting the a file:-scheme pattern with and without file
// access granted. Regression test for https://crbug.com/932703.
TEST_F(PermissionsAPIUnitTest, RequestingFilePermissions) {
  // We need a "real" extension here, since toggling file access requires
  // reloading the extension to re-initialize permissions.
  TestExtensionDir test_dir;
  test_dir.WriteManifest(
      R"({
           "name": "Extension",
           "manifest_version": 2,
           "version": "0.1",
           "optional_permissions": ["file:///*"]
         })");
  ChromeTestExtensionLoader loader(profile());
  loader.set_allow_file_access(false);
  scoped_refptr<const Extension> extension =
      loader.LoadExtension(test_dir.UnpackedPath());
  ASSERT_TRUE(extension);
  EXPECT_FALSE(util::AllowFileAccess(extension->id(), profile()));
  const GURL file_url("file:///foo");
  EXPECT_FALSE(extension->permissions_data()->HasHostPermission(file_url));

  {
    auto function = base::MakeRefCounted<PermissionsRequestFunction>();
    function->set_user_gesture(true);
    function->set_extension(extension.get());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(), R"([{"origins": ["file:///*"]}])", profile(),
        api_test_utils::FunctionMode::kNone);
    EXPECT_EQ("Extension must have file access enabled to request 'file:///*'.",
              error);
    EXPECT_FALSE(extension->permissions_data()->HasHostPermission(file_url));
  }
  {
    TestExtensionRegistryObserver observer(registry(), extension->id());
    // This will reload the extension, so we need to reset the extension
    // pointer.
    util::SetAllowFileAccess(extension->id(), profile(), true);
    extension = observer.WaitForExtensionLoaded();
    ASSERT_TRUE(extension);
  }

  std::unique_ptr<const PermissionSet> prompted_permissions;
  EXPECT_TRUE(RunRequestFunction(*extension, profile(),
                                 R"([{"origins": ["file:///*"]}])",
                                 &prompted_permissions));
  // Note: There are no permission warnings associated with requesting file
  // URLs (probably because there's a separate toggle to control it already);
  // they are filtered out of the permission ID set when we get permission
  // messages.
  EXPECT_FALSE(prompted_permissions);
  EXPECT_TRUE(extension->permissions_data()->HasHostPermission(file_url));
}

class PermissionsAPIHostAccessRequestsUnitTest : public PermissionsAPIUnitTest {
 public:
  PermissionsAPIHostAccessRequestsUnitTest() {
    scoped_feature_list_.InitAndEnableFeature(
        extensions_features::kApiPermissionsHostAccessRequests);
  }
  ~PermissionsAPIHostAccessRequestsUnitTest() override = default;
  PermissionsAPIHostAccessRequestsUnitTest(
      const PermissionsAPIHostAccessRequestsUnitTest&) = delete;
  PermissionsAPIHostAccessRequestsUnitTest& operator=(
      const PermissionsAPIHostAccessRequestsUnitTest&) = delete;

  // Navigate to `url` in the current web contents.
  void NavigateTo(const std::string& url) {
    web_contents_tester_->NavigateAndCommit(GURL(url));
  }

  // Returns the function params for permissions.add|removeHostAccessRequest for
  // a tab.
  std::string GetFunctionParams(int tab_id,
                                const std::string& pattern = std::string()) {
    if (pattern.empty()) {
      return base::StringPrintf(R"([{"tabId": %s}])",
                                base::NumberToString(tab_id).c_str());
    }
    return base::StringPrintf(R"([{"tabId": %s, "pattern": "%s"}])",
                              base::NumberToString(tab_id).c_str(),
                              pattern.c_str());
  }

 protected:
  // PermissionsAPIUnitTest:
  void SetUp() override {
    PermissionsAPIUnitTest::SetUp();

    std::unique_ptr<content::WebContents> web_contents =
        content::WebContentsTester::CreateTestWebContents(profile(), nullptr);
    content::WebContents* raw_web_contents = web_contents.get();
    browser()->tab_strip_model()->AppendWebContents(std::move(web_contents),
                                                    true);
    web_contents_tester_ = content::WebContentsTester::For(raw_web_contents);
  }

  void TearDown() override {
    // Detach the web contents.
    web_contents_tester_ = nullptr;
    browser()->tab_strip_model()->DetachAndDeleteWebContentsAt(/*index=*/0);

    PermissionsAPIUnitTest::TearDown();
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
  raw_ptr<content::WebContentsTester> web_contents_tester_;
};

// Test extension can add a host access request for a site it has host
// permissions for and has withheld host access.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       AddHostAccessRequest_RequestedSite) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension")
          .AddHostPermission("*://*.requested.com/*")
          .Build();
  AddExtensionAndGrantPermissions(*extension);

  // Open tab on a url requested by the extension.
  NavigateTo("http://www.requested.com");
  int tab_id = ExtensionTabUtil::GetTabId(
      browser()->tab_strip_model()->GetActiveWebContents());

  auto* permissions_manager = PermissionsManager::Get(profile());

  // Add host access request when extension has granted host access.
  {
    // Function should fail since extension already has host access.
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(), GetFunctionParams(tab_id), profile());
    EXPECT_EQ(
        "Extension cannot add a host access request for a host it already has "
        "access to.",
        error);

    // Verify host access request was not added.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }

  // Add host access request when extension has withheld host access.
  ScriptingPermissionsModifier(profile(), extension)
      .SetWithholdHostPermissions(true);
  {
    // Function should succeed since extension can be granted access.
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), GetFunctionParams(tab_id), profile(),
        api_test_utils::FunctionMode::kNone));

    // Verify host access request is active.
    EXPECT_TRUE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }
}

// Test extension can add a host access request with a pattern for a host it has
// host permissions for and has withheld host access. Request is only valid if
// pattern matches the extension's host permissions.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       AddHostAccessRequestWithPattern_RequestedSite) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension")
          .AddHostPermission("*://*.requested.com/*")
          .Build();
  AddExtensionAndWithheldPermissions(*extension);

  // Open tab on a url requested by the extension.
  NavigateTo("http://www.requested.com");
  int tab_id = ExtensionTabUtil::GetTabId(
      browser()->tab_strip_model()->GetActiveWebContents());

  auto* permissions_manager = PermissionsManager::Get(profile());

  // Add host access request for a pattern that does not match the extension's
  // host permissions.
  {
    // Function should fail since pattern doesn't match the extension's host
    // permissions.
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(),
        GetFunctionParams(tab_id, "*://www.not-requested.com/*"), profile(),
        api_test_utils::FunctionMode::kNone);
    EXPECT_EQ(
        "Extension cannot add a host access request with a pattern that does "
        "match any of its host permissions.",
        error);

    // Verify host access request was not added.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }

  // Add host access request for a pattern that matches the extension's host
  // permissions and the current host.
  {
    // Function should succeed since pattern matches the extension's host
    // permissions.
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), GetFunctionParams(tab_id, "*://www.requested.com/*"),
        profile(), api_test_utils::FunctionMode::kNone));

    // Verify host access request was not added.
    EXPECT_TRUE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }

  // Add host access request for a pattern that matches the extension's host
  // permissions and does not match the current host but will match on a
  // cross-origin navigation.
  {
    // Function should succeed since extension can be granted access.
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), GetFunctionParams(tab_id, "*://*/path"), profile(),
        api_test_utils::FunctionMode::kNone));

    // Verify host access request was not added. Note that new requests will
    // overridden any existent ones.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));

    // Verify host access request was added when navigating to the same-origin
    // url that matches the pattern.
    NavigateTo("http://www.requested.com/path");
    EXPECT_TRUE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }
}

// Test extension can add a host access request for a host it doesn't have host
// permissions for, but request is not active.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       AddHostAccessRequest_NonRequestedSite) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension")
          .AddHostPermission("*://*.requested.com/*")
          .AddAPIPermission("activeTab")
          .Build();
  AddExtensionAndGrantPermissions(*extension);

  // Open tab on a url not requested by the extension.
  NavigateTo("http://www.not-requested.com");
  int tab_id = ExtensionTabUtil::GetTabId(
      browser()->tab_strip_model()->GetActiveWebContents());

  auto* permissions_manager = PermissionsManager::Get(profile());

  // Add host access request.
  {
    // Function should succeed since we don't want to reveal information
    // about the current host to the extension, but request is not added.
    // Even though extension could have access via activeTab, extension can only
    // add access requests for hosts it has previously requested host
    // permissions for.
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), GetFunctionParams(tab_id), profile(),
        api_test_utils::FunctionMode::kNone));

    // Verify host access request was not added.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }

  // Add host access request with a pattern that matches the current host but
  // doesn't match the extension's host permissions.
  {
    // Function should fail since pattern doesn't match the extension's host
    // permissions.
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(),
        GetFunctionParams(tab_id, "*://www.not-requested.com/*"), profile(),
        api_test_utils::FunctionMode::kNone);
    EXPECT_EQ(
        "Extension cannot add a host access request with a pattern that does "
        "match any of its host permissions.",
        error);

    // Verify host access request was not added.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }
}

// Test extension cannot add a host access request when it doesn't have any
// host permissions.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       AddHostAccessRequest_NoHostPermissions) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension").AddAPIPermission("activeTab").Build();
  registrar()->AddExtension(extension.get());

  // Open tab on any url.
  NavigateTo("http://www.example.com");
  int tab_id = ExtensionTabUtil::GetTabId(
      browser()->tab_strip_model()->GetActiveWebContents());

  auto* permissions_manager = PermissionsManager::Get(profile());

  // Add host access request. Function should fail since extension doesn't have
  // any host permissions.
  auto function =
      base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
  function->set_extension(extension.get());
  std::string error = api_test_utils::RunFunctionAndReturnError(
      function.get(), GetFunctionParams(tab_id), profile());
  EXPECT_EQ(
      "Extension cannot add a host access request when it does not have any "
      "host permissions.",
      error);

  // Verify host access request was not added.
  EXPECT_FALSE(
      permissions_manager->HasActiveHostAccessRequest(tab_id, extension->id()));
}

// Test extension can add a host access request for a restricted host, but
// request is not active.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       AddHostAccessRequest_TabId_RestrictedSite) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension")
          .AddHostPermission("*://*.requested.com/*")
          .Build();
  AddExtensionAndGrantPermissions(*extension);

  // Open tab on a url not requested by the extension.
  NavigateTo("chrome://extensions");
  int tab_id = ExtensionTabUtil::GetTabId(
      browser()->tab_strip_model()->GetActiveWebContents());

  auto* permissions_manager = PermissionsManager::Get(profile());

  // Add host access request.
  {
    // Function should succeed since we don't want to reveal information
    // about the current host to the extension, but request is not added.
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), GetFunctionParams(tab_id), profile(),
        api_test_utils::FunctionMode::kNone));

    // Verify host access request was not added.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }

  // TODO(crbug.com/330588494): Add tests with `pattern` once parameter is
  // added.
}

// Tests extension can add a host access request for a host where it has
// optional host permissions.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       AddHostAccessRequest_OptionalHostPermissions) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension")
          .SetManifestKey("optional_host_permissions",
                          base::Value::List().Append("*://*.optional.com/*"))
          .Build();
  registrar()->AddExtension(extension.get());

  auto* permissions_manager = PermissionsManager::Get(profile());

  // Navigate to url requested by the extension via optional host permissions.
  // Verify there is no host access request.
  NavigateTo("http://www.optional.com");
  int tab_id = ExtensionTabUtil::GetTabId(
      browser()->tab_strip_model()->GetActiveWebContents());
  EXPECT_FALSE(
      permissions_manager->HasActiveHostAccessRequest(tab_id, extension->id()));

  // Add host access request for tab with optional.com. Function should
  // succeed since extension can be granted access.
  auto function =
      base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
  function->set_extension(extension.get());
  EXPECT_TRUE(api_test_utils::RunFunction(function.get(),
                                          GetFunctionParams(tab_id), profile(),
                                          api_test_utils::FunctionMode::kNone));

  // Verify host access request was added.
  EXPECT_TRUE(
      permissions_manager->HasActiveHostAccessRequest(tab_id, extension->id()));
}

// Tests extension can add a host access request for a host where it wants to
// inject a content script.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       AddHostAccessRequest_ContentScriptMatches) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension")
          .AddContentScript("script.js", {"*://*.contentscript.com/*"})
          .Build();
  AddExtensionAndWithheldPermissions(*extension);

  auto* permissions_manager = PermissionsManager::Get(profile());

  // Navigate to url requested by the extension via the content script. Verify
  // there is no host access request.
  NavigateTo("http://www.contentscript.com");
  int tab_id = ExtensionTabUtil::GetTabId(
      browser()->tab_strip_model()->GetActiveWebContents());
  EXPECT_FALSE(
      permissions_manager->HasActiveHostAccessRequest(tab_id, extension->id()));

  // Add host access request for tab with contentscript.com. Function should
  // succeed since extension can be granted access.
  auto function =
      base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
  function->set_extension(extension.get());
  EXPECT_TRUE(api_test_utils::RunFunction(function.get(),
                                          GetFunctionParams(tab_id), profile(),
                                          api_test_utils::FunctionMode::kNone));

  // Verify host access request was added.
  EXPECT_TRUE(
      permissions_manager->HasActiveHostAccessRequest(tab_id, extension->id()));
}

// Tests extension can add a host access request for a host with access
// withheld, even if the host was blocked by the user. Having a valid request
// doesn't mean it will be signaled to the user.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       AddHostAccessRequest_UserBlockedSite) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension")
          .SetManifestKey("host_permissions",
                          base::Value::List().Append("*://*.requested.com/*"))
          .Build();
  AddExtensionAndGrantPermissions(*extension);

  // Navigate to url requested by the extension.
  NavigateTo("http://www.requested.com");
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  int tab_id = ExtensionTabUtil::GetTabId(web_contents);

  // Block all extensions on requested.com.
  auto* permissions_manager = PermissionsManager::Get(profile());
  permissions_manager->UpdateUserSiteSetting(
      url::Origin::Create(web_contents->GetLastCommittedURL()),
      PermissionsManager::UserSiteSetting::kBlockAllExtensions);

  // Add host access request for tab with requested.com. Request is invalid
  // because extension has granted host access, even though it can't access the
  // host since user blocked access for all extensions.
  {
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(), GetFunctionParams(tab_id), profile(),
        api_test_utils::FunctionMode::kNone);
    EXPECT_EQ(
        "Extension cannot add a host access request for a host it already has "
        "access to.",
        error);
  }

  // Withheld extension's host access.
  ScriptingPermissionsModifier(profile(), extension.get())
      .SetWithholdHostPermissions(true);

  // Add host access request for tab with requested.com. Request is valid
  // because extension wants host access, and host access was withheld. It
  // doesn't matter that extensions are blocked on the host, since that is a
  // user setting.
  {
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), GetFunctionParams(tab_id), profile(),
        api_test_utils::FunctionMode::kNone));
  }

  // Verify host access request was added.
  EXPECT_TRUE(
      permissions_manager->HasActiveHostAccessRequest(tab_id, extension->id()));
}

// An extension with granted tab permission (via granting activeTab or running
// an extension set on click) can't add a host request.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       AddHostAccessRequest_OneTimeGrantedAccess) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension")
          .SetManifestKey("host_permissions",
                          base::Value::List().Append("*://*.requested.com/*"))
          .Build();
  AddExtensionAndWithheldPermissions(*extension);

  // Navigate to url requested by the extension.
  NavigateTo("http://www.requested.com");
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  int tab_id = ExtensionTabUtil::GetTabId(web_contents);

  // Grant one-time host access.
  ActiveTabPermissionGranter::FromWebContents(web_contents)
      ->GrantIfRequested(extension.get());

  // Add host access request for requested.com. Request is invalid because
  // extension already has host access (even if it's just one-time).
  {
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(), GetFunctionParams(tab_id), profile(),
        api_test_utils::FunctionMode::kNone);
    EXPECT_EQ(
        "Extension cannot add a host access request for a host it already has "
        "access to.",
        error);
  }
}

// Test extension can add a host access request for a host it has host
// permissions for and has withheld host access by providing a document id.
// Note: Document id is converted to a tab id by the API after parsing. Thus,
// it's sufficient to test only some bases cases to make sure the documentId is
// properly parsed. Other scenarios are extensively tested using a tab id.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       AddHostAccessRequest_DocumentId) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension")
          .AddHostPermission("*://*.requested.com/*")
          .Build();
  AddExtensionAndGrantPermissions(*extension);

  // Open tab on a url requested by the extension.
  NavigateTo("http://www.requested.com");
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  int tab_id = ExtensionTabUtil::GetTabId(web_contents);
  std::string document_id =
      ExtensionApiFrameIdMap::GetDocumentId(web_contents->GetPrimaryMainFrame())
          .ToString();

  auto* permissions_manager = PermissionsManager::Get(profile());
  auto function_params = [](const std::string& document_id) {
    return base::StringPrintf(R"([{"documentId": "%s"}])", document_id.c_str());
  };

  // Add host access request when extension has granted host access.
  {
    // Function should fail since extension already has host access.
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(), function_params(document_id), profile());
    EXPECT_EQ(
        "Extension cannot add a host access request for a host it already has "
        "access to.",
        error);

    // Verify host access request was not added.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }

  // Add host access request when extension has withheld host access.
  ScriptingPermissionsModifier(profile(), extension)
      .SetWithholdHostPermissions(true);
  {
    // Function should succeed since extension can be granted access.
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), function_params(document_id), profile(),
        api_test_utils::FunctionMode::kNone));

    // Verify host access request is active.
    EXPECT_TRUE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }
}

// Tests extension cannot remove a host access request that doesn't exist.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       RemoveHostAccessRequest_TabId_Invalid) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension")
          .SetManifestKey("host_permissions",
                          base::Value::List().Append("*://*.requested.com/*"))
          .Build();
  AddExtensionAndWithheldPermissions(*extension);

  // Open tab on a url requested by the extension.
  NavigateTo("http://www.requested.com");
  int tab_id = ExtensionTabUtil::GetTabId(
      browser()->tab_strip_model()->GetActiveWebContents());

  auto* permissions_manager = PermissionsManager::Get(profile());

  // Extension cannot remove a request when there is no current request.
  {
    auto remove_function =
        base::MakeRefCounted<PermissionsRemoveHostAccessRequestFunction>();
    remove_function->set_extension(extension.get());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        remove_function.get(), GetFunctionParams(tab_id), profile(),
        api_test_utils::FunctionMode::kNone);
    EXPECT_EQ(
        "Extension cannot remove a host access request that doesn't exist.",
        error);

    // Verify there is no request.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }

  // Extension cannot remove a host access request with a pattern when it
  // doesn't match the active request (that matches all patterns).
  {
    // Add a host access request without a pattern. Not specifying a pattern
    // means request will be shown for all patterns.
    auto add_function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    add_function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        add_function.get(), GetFunctionParams(tab_id), profile(),
        api_test_utils::FunctionMode::kNone));

    // Verify host access request was added.
    EXPECT_TRUE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));

    // Remove a host access request with 'requested.com' pattern. Even though
    // existent request matches all patterns, the removal must exactly match
    // request. We do this because we don't support "all urls but <x>".
    auto remove_function =
        base::MakeRefCounted<PermissionsRemoveHostAccessRequestFunction>();
    remove_function->set_extension(extension.get());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        remove_function.get(),
        GetFunctionParams(tab_id, /*pattern=*/"*://*.requested.com/*"),
        profile(), api_test_utils::FunctionMode::kNone);
    EXPECT_EQ(
        "Extension cannot remove a host access request that doesn't exist.",
        error);

    // Verify request wasn't removed.
    EXPECT_TRUE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }

  // Extension cannot remove a host access request with a pattern when it
  // doesn't match the active request (with a different pattern specified).
  {
    // Add a host access request with 'requested.com' pattern. Adding a new
    // request overrides existent request.
    auto add_function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    add_function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        add_function.get(), GetFunctionParams(tab_id, "*://*.requested.com/*"),
        profile(), api_test_utils::FunctionMode::kNone));

    // Verify host access request was added.
    EXPECT_TRUE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));

    // Remove a host access request with a 'other.com' pattern. Function is
    // invalid because 'other.com' doesn't match with the current request for
    // 'requested.com'.
    auto remove_function =
        base::MakeRefCounted<PermissionsRemoveHostAccessRequestFunction>();
    remove_function->set_extension(extension.get());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        remove_function.get(), GetFunctionParams(tab_id, "*://*.other.com/*"),
        profile(), api_test_utils::FunctionMode::kNone);
    EXPECT_EQ(
        "Extension cannot remove a host access request that doesn't exist.",
        error);

    // Verify request wasn't removed.
    EXPECT_TRUE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }
}

// Tests extension can remove a host access request that matches an existent
// request.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       RemoveHostAccessRequest_TabId_Valid) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension")
          .SetManifestKey("host_permissions",
                          base::Value::List().Append("*://*.requested.com/*"))
          .Build();
  AddExtensionAndWithheldPermissions(*extension);

  // Open tab on a url requested by the extension.
  NavigateTo("http://www.requested.com");
  int tab_id = ExtensionTabUtil::GetTabId(
      browser()->tab_strip_model()->GetActiveWebContents());

  auto* permissions_manager = PermissionsManager::Get(profile());

  // Extension can remove a host access request that matches all patterns (by
  // not specifying one) when it matches the active request (that matches all
  // patterns).
  {
    // Add a host access request without a pattern.
    auto add_function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    add_function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        add_function.get(), GetFunctionParams(tab_id), profile(),
        api_test_utils::FunctionMode::kNone));

    // Verify host access request was added.
    EXPECT_TRUE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));

    // Remove a host access request without a pattern.
    auto remove_function =
        base::MakeRefCounted<PermissionsRemoveHostAccessRequestFunction>();
    remove_function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        remove_function.get(), GetFunctionParams(tab_id), profile(),
        api_test_utils::FunctionMode::kNone));

    // Verify request was removed.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }

  // Extension can remove a host access request with a pattern when it matches
  // the current request (with the same pattern).
  {
    // Add a host access request with 'requested.com' pattern.
    auto add_function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    add_function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        add_function.get(),
        GetFunctionParams(tab_id, /*pattern=*/"*://*.requested.com/*"),
        profile(), api_test_utils::FunctionMode::kNone));

    // Verify host access request was added.
    EXPECT_TRUE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));

    // Remove a host access request with 'requested.com' pattern.
    auto remove_function =
        base::MakeRefCounted<PermissionsRemoveHostAccessRequestFunction>();
    remove_function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        remove_function.get(), GetFunctionParams(tab_id), profile(),
        api_test_utils::FunctionMode::kNone));

    // Verify request was removed.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }

  // Extension can remove a host access request without a pattern when it
  // matches the active request (with a pattern).
  {
    // Add a host access request with 'requested.com' pattern.
    auto add_function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    add_function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        add_function.get(),
        GetFunctionParams(tab_id, /*pattern=*/"*://*.requested.com/*"),
        profile(), api_test_utils::FunctionMode::kNone));

    // Verify host access request was added.
    EXPECT_TRUE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));

    // Remove a host access request without specifying pattern (which matches to
    // all patterns). Function is valid because it matches the current request
    // ('all patterns' which matches current request on 'requested.com').
    auto remove_function =
        base::MakeRefCounted<PermissionsRemoveHostAccessRequestFunction>();
    remove_function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        remove_function.get(), GetFunctionParams(tab_id), profile(),
        api_test_utils::FunctionMode::kNone));

    // Verify request was removed.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }
}

// Tests extension can remove a host access request for a document, if request
// is existent.
// Note: Document id is converted to tab id. Thus, here we only need to test the
// base cases since we have extensive testing for removing requests with tab id.
TEST_F(PermissionsAPIHostAccessRequestsUnitTest,
       RemoveHostAccessRequest_DocumentId) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("Extension")
          .SetManifestKey("host_permissions",
                          base::Value::List().Append("*://*.requested.com/*"))
          .Build();
  AddExtensionAndWithheldPermissions(*extension);

  // Open tab on a url requested by the extension.
  NavigateTo("http://www.requested.com");
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  int tab_id = ExtensionTabUtil::GetTabId(web_contents);
  std::string document_id =
      ExtensionApiFrameIdMap::GetDocumentId(web_contents->GetPrimaryMainFrame())
          .ToString();

  auto* permissions_manager = PermissionsManager::Get(profile());
  auto function_params = [](const std::string& document_id) {
    return base::StringPrintf(R"([{"documentId": "%s"}])", document_id.c_str());
  };

  // Remove host access request for document, when it has no active requests.
  {
    auto function =
        base::MakeRefCounted<PermissionsRemoveHostAccessRequestFunction>();
    function->set_extension(extension.get());

    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(), function_params(document_id), profile(),
        api_test_utils::FunctionMode::kNone);
    EXPECT_EQ(
        "Extension cannot remove a host access request that doesn't exist.",
        error);

    // Verify there is no request.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }

  // Add host access request for document.
  {
    auto function =
        base::MakeRefCounted<PermissionsAddHostAccessRequestFunction>();
    function->set_extension(extension.get());
    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), function_params(document_id), profile(),
        api_test_utils::FunctionMode::kNone));

    // Verify host access request was added.
    EXPECT_TRUE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }

  // Remove host access request for document, when it has an active requests.
  {
    auto function =
        base::MakeRefCounted<PermissionsRemoveHostAccessRequestFunction>();
    function->set_extension(extension.get());

    EXPECT_TRUE(api_test_utils::RunFunction(
        function.get(), function_params(document_id), profile(),
        api_test_utils::FunctionMode::kNone));

    // Verify request was removed.
    EXPECT_FALSE(permissions_manager->HasActiveHostAccessRequest(
        tab_id, extension->id()));
  }
}

}  // namespace extensions