File: trusted_vault_encryption_keys_tab_helper_browsertest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; 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 (1129 lines) | stat: -rw-r--r-- 46,569 bytes parent folder | download | duplicates (3)
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
// Copyright 2022 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/trusted_vault/trusted_vault_encryption_keys_tab_helper.h"

#include <string>
#include <tuple>
#include <vector>

#include "base/feature_list.h"
#include "base/path_service.h"
#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "build/build_config.h"
#include "chrome/browser/trusted_vault/trusted_vault_service_factory.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/chrome_test_utils.h"
#include "chrome/test/base/platform_browser_test.h"
#include "components/metrics/content/subprocess_metrics_provider.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "components/signin/public/identity_manager/account_info.h"
#include "components/trusted_vault/features.h"
#include "components/trusted_vault/trusted_vault_client.h"
#include "components/trusted_vault/trusted_vault_server_constants.h"
#include "components/trusted_vault/trusted_vault_service.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/fenced_frame_test_util.h"
#include "content/public/test/prerender_test_util.h"
#include "google_apis/gaia/gaia_id.h"
#include "google_apis/gaia/gaia_switches.h"
#include "google_apis/gaia/gaia_urls.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_ANDROID)
#include "components/site_isolation/features.h"
#else
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/webauthn/enclave_manager.h"
#include "chrome/browser/webauthn/enclave_manager_factory.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/trusted_vault/standalone_trusted_vault_client.h"
#endif  // BUILDFLAG(IS_ANDROID)

namespace {

using testing::ElementsAre;
using testing::ElementsAreArray;
using testing::Eq;
using testing::IsEmpty;

constexpr GaiaId::Literal kFakeGaiaId("fake_gaia_id");

#if !BUILDFLAG(IS_ANDROID)
const AccountInfo& FakeAccount() {
  static const base::NoDestructor<AccountInfo> account([]() {
    AccountInfo account;
    account.gaia = kFakeGaiaId;
    return account;
  }());
  return *account;
}
#endif

const char kConsoleSuccessMessage[] = "trusted_vault_encryption_keys:OK";
const char kConsoleFailureMessage[] = "trusted_vault_encryption_keys:FAIL";
#if !BUILDFLAG(IS_ANDROID)
const char kConsoleUncaughtTypeErrorMessagePattern[] =
    "Uncaught TypeError: Error processing argument at index *";
#endif

// Executes JS to call chrome.setSyncEncryptionKeys(). Either
// |kConsoleSuccessMessage| or |kConsoleFailureMessage| is logged to the console
// upon completion.
void ExecJsSetSyncEncryptionKeys(content::RenderFrameHost* render_frame_host,
                                 const std::vector<uint8_t>& key,
                                 int key_version) {
  // To simplify the test, it limits the size of `key` to 1.
  DCHECK_EQ(key.size(), 1u);
  const std::string script = base::StringPrintf(
      R"(
      if (chrome.setSyncEncryptionKeys === undefined) {
        console.log('%s');
      } else {
        let buffer = new ArrayBuffer(1);
        let view = new Uint8Array(buffer);
        view[0] = %d;
        chrome.setSyncEncryptionKeys(
            () => {console.log('%s');},
            "%s", [buffer], %d);
      }
    )",
      kConsoleFailureMessage, key[0], kConsoleSuccessMessage,
      kFakeGaiaId.ToString(), key_version);

  std::ignore = content::ExecJs(render_frame_host, script);
}

void ExecJsSetClientEncryptionKeysForSecurityDomain(
    content::RenderFrameHost* render_frame_host,
    const char* security_domain_name,
    const std::vector<uint8_t>& key) {
  // To simplify the test, it limits the size of `key` to 1.
  DCHECK_EQ(key.size(), 1u);
  const std::string script = base::StringPrintf(
      R"(
      if (chrome.setClientEncryptionKeys === undefined) {
        console.log('%s');
      } else {
        let key = new ArrayBuffer(1);
        let view = new Uint8Array(key);
        view[0] = %d;
        chrome.setClientEncryptionKeys(
            () => {console.log('%s');},
            "%s",
            new Map([['%s', [{epoch: 0, key}]]]));
      }
    )",
      kConsoleFailureMessage, key[0], kConsoleSuccessMessage,
      kFakeGaiaId.ToString(), security_domain_name);

  std::ignore = content::ExecJs(render_frame_host, script);
}

void ExecJsSetClientEncryptionKeys(content::RenderFrameHost* render_frame_host,
                                   const std::vector<uint8_t>& key) {
  ExecJsSetClientEncryptionKeysForSecurityDomain(
      render_frame_host, trusted_vault::kSyncSecurityDomainName, key);
}

#if !BUILDFLAG(IS_ANDROID)
void ExecJsSetClientEncryptionKeysForInvalidSecurityDomain(
    content::RenderFrameHost* render_frame_host,
    const std::vector<uint8_t>& key) {
  // To simplify the test, it limits the size of `key` to 1.
  DCHECK_EQ(key.size(), 1u);
  const std::string script = base::StringPrintf(
      R"(
      if (chrome.setClientEncryptionKeys === undefined) {
        console.log('%s');
      } else {
        let key = new ArrayBuffer(1);
        let view = new Uint8Array(key);
        view[0] = %d;
        chrome.setClientEncryptionKeys(
            () => {console.log('%s');},
            "%s",
            new Map([['invalid', [{epoch: 0, key}]]]));
      }
    )",
      kConsoleFailureMessage, key[0], kConsoleSuccessMessage,
      kFakeGaiaId.ToString());

  std::ignore = content::ExecJs(render_frame_host, script);
}

void ExecJsSetClientEncryptionKeysWithIllformedArgs(
    content::RenderFrameHost* render_frame_host) {
  // Don't actually pass a key. This should trigger a render-side argument
  // parsing failure.
  const std::string script = base::StringPrintf(
      R"(
      if (chrome.setClientEncryptionKeys === undefined) {
        console.log('%s');
      } else {
        chrome.setClientEncryptionKeys(
            () => {console.log('%s');},
            "%s",
            new Map([['chromesync', [{epoch: 0}]]]));
      }
    )",
      kConsoleFailureMessage, kConsoleSuccessMessage, kFakeGaiaId.ToString());

  std::ignore = content::ExecJs(render_frame_host, script);
}
#endif

// Executes JS to call chrome.addTrustedSyncEncryptionRecoveryMethod. Either
// |kConsoleSuccessMessage| or |kConsoleFailureMessage| is logged to the console
// upon completion.
void ExecJsAddTrustedSyncEncryptionRecoveryMethod(
    content::RenderFrameHost* render_frame_host,
    const std::vector<uint8_t>& public_key) {
  // To simplify the test, it limits the size of `public_key` to 1.
  DCHECK_EQ(public_key.size(), 1u);
  const std::string script = base::StringPrintf(
      R"(
      if (chrome.addTrustedSyncEncryptionRecoveryMethod === undefined) {
        console.log('%s');
      } else {
        let buffer = new ArrayBuffer(1);
        let view = new Uint8Array(buffer);
        view[0] = %d;
        chrome.addTrustedSyncEncryptionRecoveryMethod(
            () => {console.log('%s');},
            "%s", buffer, 2);
      }
    )",
      kConsoleFailureMessage, public_key[0], kConsoleSuccessMessage,
      kFakeGaiaId.ToString());

  std::ignore = content::ExecJs(render_frame_host, script);
}

// Key retrieval doesn't exist on Android and cannot be verified.
#if !BUILDFLAG(IS_ANDROID)
std::vector<std::vector<uint8_t>> FetchTrustedVaultKeysForProfile(
    Profile* profile,
    trusted_vault::SecurityDomainId security_domain,
    const AccountInfo& account_info) {
  // Waits until the sync trusted vault keys have been received and stored.
  base::RunLoop loop;
  std::vector<std::vector<uint8_t>> actual_keys;

  TrustedVaultServiceFactory::GetForProfile(profile)
      ->GetTrustedVaultClient(security_domain)
      ->FetchKeys(account_info,
                  base::BindLambdaForTesting(
                      [&](const std::vector<std::vector<uint8_t>>& keys) {
                        actual_keys = keys;
                        loop.Quit();
                      }));
  loop.Run();
  return actual_keys;
}

int FetchLastTrustedVaultKeyVersionForProfile(
    Profile* profile,
    trusted_vault::SecurityDomainId security_domain,
    const AccountInfo& account_info) {
  base::RunLoop loop;
  int actual_last_key_version = -1;

  static_cast<trusted_vault::StandaloneTrustedVaultClient*>(
      TrustedVaultServiceFactory::GetForProfile(profile)->GetTrustedVaultClient(
          security_domain))
      ->GetLastKeyVersionForTesting(
          account_info.gaia,
          base::BindLambdaForTesting([&](int last_key_version) {
            actual_last_key_version = last_key_version;
            loop.Quit();
          }));
  loop.Run();
  return actual_last_key_version;
}

#endif  // !BUILDFLAG(IS_ANDROID)

class TrustedVaultEncryptionKeysTabHelperBrowserTest
    : public PlatformBrowserTest {
 public:
  TrustedVaultEncryptionKeysTabHelperBrowserTest()
      : https_server_(net::EmbeddedTestServer::TYPE_HTTPS),
        prerender_helper_(base::BindRepeating(
            &TrustedVaultEncryptionKeysTabHelperBrowserTest::web_contents,
            base::Unretained(this))) {
#if BUILDFLAG(IS_ANDROID)
    // Avoid the disabling of site isolation due to memory constraints, required
    // on Android so that ApplyGlobalIsolatedOrigins() takes effect regardless
    // of available memory when running the test (otherwise low-memory bots may
    // run into test failures).
    feature_list_.InitAndEnableFeatureWithParameters(
        site_isolation::features::kSiteIsolationMemoryThresholdsAndroid,
        {{site_isolation::features::
              kStrictSiteIsolationMemoryThresholdParamName,
          "0"},
         {site_isolation::features::
              kPartialSiteIsolationMemoryThresholdParamName,
          "0"}});
#else
    feature_list_.InitAndEnableFeature(
        trusted_vault::kSetClientEncryptionKeysJsApi);
#endif
  }

  ~TrustedVaultEncryptionKeysTabHelperBrowserTest() override {
    // An explicit reset is required here to avoid CHECK failures due to
    // unexpected reset ordering.
    feature_list_.Reset();
  }

 protected:
  content::WebContents* web_contents() {
    return chrome_test_utils::GetActiveWebContents(this);
  }

  net::EmbeddedTestServer* https_server() { return &https_server_; }

  content::test::PrerenderTestHelper& prerender_helper() {
    return prerender_helper_;
  }

  content::test::FencedFrameTestHelper& fenced_frame_test_helper() {
    return fenced_frame_test_helper_;
  }

  bool HasEncryptionKeysApi(content::RenderFrameHost* rfh) {
    auto* tab_helper =
        TrustedVaultEncryptionKeysTabHelper::FromWebContents(web_contents());
    return tab_helper->HasEncryptionKeysApiForTesting(rfh);
  }

  void SetUp() override {
    ASSERT_TRUE(https_server_.InitializeAndListen());
    PlatformBrowserTest::SetUp();
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    // Override the sign-in URL so that it includes correct port from the test
    // server.
    command_line->AppendSwitchASCII(
        ::switches::kGaiaUrl,
        https_server()->GetURL("accounts.google.com", "/").spec());

    // Ignore cert errors so that the sign-in URL can be loaded from a site
    // other than localhost (the EmbeddedTestServer serves a certificate that
    // is valid for localhost).
    command_line->AppendSwitch(switches::kIgnoreCertificateErrors);
    PlatformBrowserTest::SetUpCommandLine(command_line);
  }

  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
    https_server()->ServeFilesFromDirectory(
        base::PathService::CheckedGet(chrome::DIR_TEST_DATA));
    https_server()->StartAcceptingConnections();
  }

 private:
  base::test::ScopedFeatureList feature_list_;
  net::EmbeddedTestServer https_server_;
  content::test::FencedFrameTestHelper fenced_frame_test_helper_;
  content::test::PrerenderTestHelper prerender_helper_;
};

// Tests that chrome.setSyncEncryptionKeys() works in the main frame, except on
// Android. On Android, this particular Javascript API isn't defined.
#if BUILDFLAG(IS_ANDROID)

IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ShouldNotBindEncryptionKeysApiOnAndroid) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), initial_url));
  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  EXPECT_TRUE(HasEncryptionKeysApi(web_contents()->GetPrimaryMainFrame()));

  content::WebContentsConsoleObserver console_observer(web_contents());
  console_observer.SetPattern(kConsoleFailureMessage);

  // Calling setSyncEncryptionKeys() or setClientEncryptionKeys() in the main
  // frame shouldn't work.
  const std::vector<uint8_t> kEncryptionKey = {7};
  ExecJsSetSyncEncryptionKeys(web_contents()->GetPrimaryMainFrame(),
                              kEncryptionKey, /*key_version=*/1);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());
  ExecJsSetClientEncryptionKeys(web_contents()->GetPrimaryMainFrame(),
                                kEncryptionKey);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(2u, console_observer.messages().size());
}

#else

void ExecJsSetClientEncryptionKeysWithMultipleKeys(
    content::RenderFrameHost* render_frame_host,
    const std::vector<uint8_t>& key1,
    const std::vector<uint8_t>& key2) {
  DCHECK_EQ(key1.size(), 1u);
  DCHECK_EQ(key2.size(), 1u);
  const std::string script = base::StringPrintf(
      R"(
      if (chrome.setClientEncryptionKeys === undefined) {
        console.log('%s');
      } else {
        let key1 = new ArrayBuffer(1);
        let view1 = new Uint8Array(key1);
        view1[0] = %d;
        let key2 = new ArrayBuffer(1);
        let view2 = new Uint8Array(key2);
        view2[0] = %d;
        chrome.setClientEncryptionKeys(
            () => {console.log('%s');},
            "%s",
            new Map([
                ['chromesync',
                 [{epoch: 1, key: key1}, {epoch: 2, key: key2}]]
            ]));
      }
    )",
      kConsoleFailureMessage, key1[0], key2[0], kConsoleSuccessMessage,
      kFakeGaiaId.ToString());

  std::ignore = content::ExecJs(render_frame_host, script);
}

IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ShouldBindSyncEncryptionKeysApiInMainFrame) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), initial_url));
  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  EXPECT_TRUE(HasEncryptionKeysApi(web_contents()->GetPrimaryMainFrame()));

  content::WebContentsConsoleObserver console_observer(web_contents());
  console_observer.SetPattern(kConsoleSuccessMessage);

  base::HistogramTester histogram_tester;

  // Calling setSyncEncryptionKeys() in the main frame works and it gets
  // the callback by setSyncEncryptionKeys().
  const std::vector<uint8_t> kEncryptionKey = {7};
  const int kEncryptionKeyVersion = 24;
  ExecJsSetSyncEncryptionKeys(web_contents()->GetPrimaryMainFrame(),
                              kEncryptionKey, kEncryptionKeyVersion);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());

  // Collect histograms from the renderer process, since otherwise
  // HistogramTester cannot verify the ones instrumented in the renderer.
  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  histogram_tester.ExpectUniqueSample(
      "Sync.TrustedVaultJavascriptSetEncryptionKeysValidArgs", 1 /*Valid*/, 1);

  histogram_tester.ExpectUniqueSample(
      "Sync.TrustedVaultJavascriptSetEncryptionKeysIsIncognito",
      0 /*Not Incognito*/, 1);

  std::vector<std::vector<uint8_t>> actual_keys =
      FetchTrustedVaultKeysForProfile(
          browser()->profile(), trusted_vault::SecurityDomainId::kChromeSync,
          FakeAccount());
  EXPECT_THAT(actual_keys, ElementsAre(kEncryptionKey));
  EXPECT_THAT(FetchLastTrustedVaultKeyVersionForProfile(
                  browser()->profile(),
                  trusted_vault::SecurityDomainId::kChromeSync, FakeAccount()),
              Eq(kEncryptionKeyVersion));
}

IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ShouldBindClientEncryptionKeysApiInMainFrame) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), initial_url));
  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  EXPECT_TRUE(HasEncryptionKeysApi(web_contents()->GetPrimaryMainFrame()));

  content::WebContentsConsoleObserver console_observer(web_contents());
  console_observer.SetPattern(kConsoleSuccessMessage);

  base::HistogramTester histogram_tester;

  // Calling setClientEncryptionKeys() in the main frame works.
  const std::vector<uint8_t> kEncryptionKey = {7};
  ExecJsSetClientEncryptionKeys(web_contents()->GetPrimaryMainFrame(),
                                kEncryptionKey);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());

  // Collect histograms from the renderer process, since otherwise
  // HistogramTester cannot verify the ones instrumented in the renderer.
  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  histogram_tester.ExpectUniqueSample(
      "TrustedVault.JavascriptSetClientEncryptionKeysValidArgs", 1 /*Valid*/,
      1);
  histogram_tester.ExpectUniqueSample(
      "TrustedVault.JavascriptSetClientEncryptionKeysForSecurityDomain",
      1 /*Chrome Sync*/, 1);

  histogram_tester.ExpectUniqueSample(
      "TrustedVault.SetEncryptionKeysForSecurityDomain.AllProfiles",
      1 /*Chrome Sync*/, 1);
  histogram_tester.ExpectUniqueSample(
      "TrustedVault.SetEncryptionKeysForSecurityDomain.OffTheRecordOnly",
      1 /*Chrome Sync*/, 0);

  histogram_tester.ExpectUniqueSample(
      "Sync.TrustedVaultJavascriptSetEncryptionKeysIsIncognito",
      0 /*Not Incognito*/, 1);

  std::vector<std::vector<uint8_t>> actual_keys =
      FetchTrustedVaultKeysForProfile(
          browser()->profile(), trusted_vault::SecurityDomainId::kChromeSync,
          FakeAccount());
  EXPECT_THAT(actual_keys, ElementsAre(kEncryptionKey));
}

IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ClientEncryptionKeysApiShouldSetMultipleKeys) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), initial_url));
  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  EXPECT_TRUE(HasEncryptionKeysApi(web_contents()->GetPrimaryMainFrame()));

  content::WebContentsConsoleObserver console_observer(web_contents());
  console_observer.SetPattern(kConsoleSuccessMessage);

  base::HistogramTester histogram_tester;

  const std::vector<std::vector<uint8_t>> kEncryptionKeys = {{7}, {8}};
  ExecJsSetClientEncryptionKeysWithMultipleKeys(
      web_contents()->GetPrimaryMainFrame(), kEncryptionKeys[0],
      kEncryptionKeys[1]);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());

  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  histogram_tester.ExpectUniqueSample(
      "TrustedVault.JavascriptSetClientEncryptionKeysValidArgs", 1 /*Valid*/,
      1);
  histogram_tester.ExpectUniqueSample(
      "TrustedVault.JavascriptSetClientEncryptionKeysForSecurityDomain",
      1 /*Chrome Sync*/, 1);

  histogram_tester.ExpectUniqueSample(
      "TrustedVault.SetEncryptionKeysForSecurityDomain.AllProfiles",
      1 /*Chrome Sync*/, 1);
  histogram_tester.ExpectUniqueSample(
      "TrustedVault.SetEncryptionKeysForSecurityDomain.OffTheRecordOnly",
      1 /*Chrome Sync*/, 0);

  histogram_tester.ExpectUniqueSample(
      "Sync.TrustedVaultJavascriptSetEncryptionKeysIsIncognito",
      0 /*Not Incognito*/, 1);

  std::vector<std::vector<uint8_t>> actual_keys =
      FetchTrustedVaultKeysForProfile(
          browser()->profile(), trusted_vault::SecurityDomainId::kChromeSync,
          FakeAccount());
  EXPECT_THAT(actual_keys, ElementsAreArray(kEncryptionKeys));
}

#if !BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       SetPasskeysKeyInEnclaveManager) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), initial_url));
  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  EXPECT_TRUE(HasEncryptionKeysApi(web_contents()->GetPrimaryMainFrame()));

  content::WebContentsConsoleObserver console_observer(web_contents());
  console_observer.SetPattern(kConsoleSuccessMessage);

  base::HistogramTester histogram_tester;

  EnclaveManager* const enclave_manager =
      EnclaveManagerFactory::GetAsEnclaveManagerForProfile(
          browser()->profile());
  const unsigned initial_count = enclave_manager->store_keys_count();

  const std::vector<uint8_t> kEncryptionKey = {7};
  ExecJsSetClientEncryptionKeysForSecurityDomain(
      web_contents()->GetPrimaryMainFrame(),
      trusted_vault::kPasskeysSecurityDomainName, kEncryptionKey);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(console_observer.messages().size(), 1u);

  // The keys should have been stored to the `EnclaveManager`.
  EXPECT_EQ(enclave_manager->store_keys_count(), initial_count + 1);

  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  histogram_tester.ExpectUniqueSample(
      "TrustedVault.JavascriptSetClientEncryptionKeysValidArgs", 1 /*Valid*/,
      1);
  histogram_tester.ExpectUniqueSample(
      "TrustedVault.JavascriptSetClientEncryptionKeysForSecurityDomain",
      2 /*Passkeys*/, 1);

  histogram_tester.ExpectUniqueSample(
      "TrustedVault.SetEncryptionKeysForSecurityDomain.AllProfiles",
      2 /*Passkeys*/, 1);
  histogram_tester.ExpectUniqueSample(
      "TrustedVault.SetEncryptionKeysForSecurityDomain.OffTheRecordOnly",
      2 /*Passkeys*/, 0);

  histogram_tester.ExpectUniqueSample(
      "Sync.TrustedVaultJavascriptSetEncryptionKeysIsIncognito",
      0 /*Not Incognito*/, 1);

  // No security domain client for passkeys, so no keys could have been set.
  EXPECT_EQ(
      TrustedVaultServiceFactory::GetForProfile(browser()->profile())
          ->GetTrustedVaultClient(trusted_vault::SecurityDomainId::kPasskeys),
      nullptr);

  // No keys should have been set for chromesync either.
  EXPECT_THAT(FetchTrustedVaultKeysForProfile(
                  browser()->profile(),
                  trusted_vault::SecurityDomainId::kChromeSync, FakeAccount()),
              IsEmpty());
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

IN_PROC_BROWSER_TEST_F(
    TrustedVaultEncryptionKeysTabHelperBrowserTest,
    ShouldIgnoreClientEncryptionKeysForInvalidSecurityDomain) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), initial_url));
  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  EXPECT_TRUE(HasEncryptionKeysApi(web_contents()->GetPrimaryMainFrame()));

  content::WebContentsConsoleObserver console_observer(web_contents());
  console_observer.SetPattern(kConsoleSuccessMessage);

  base::HistogramTester histogram_tester;

  // Calling setClientEncryptionKeys() in the main frame works.
  const std::vector<uint8_t> kEncryptionKey = {7};
  ExecJsSetClientEncryptionKeysForInvalidSecurityDomain(
      web_contents()->GetPrimaryMainFrame(), kEncryptionKey);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());

  // Collect histograms from the renderer process, since otherwise
  // HistogramTester cannot verify the ones instrumented in the renderer.
  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  histogram_tester.ExpectUniqueSample(
      "TrustedVault.JavascriptSetClientEncryptionKeysValidArgs", 1 /*Valid*/,
      1);
  histogram_tester.ExpectUniqueSample(
      "TrustedVault.JavascriptSetClientEncryptionKeysForSecurityDomain",
      0 /*Invalid*/, 1);

  histogram_tester.ExpectUniqueSample(
      "TrustedVault.SetEncryptionKeysForSecurityDomain.AllProfiles",
      0 /*Invalid*/, 1);

  std::vector<std::vector<uint8_t>> actual_keys =
      FetchTrustedVaultKeysForProfile(
          browser()->profile(), trusted_vault::SecurityDomainId::kChromeSync,
          FakeAccount());
  EXPECT_THAT(actual_keys, IsEmpty());
}

IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ShouldIgnoreClientEncryptionKeysWithIllformedArgs) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), initial_url));
  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  EXPECT_TRUE(HasEncryptionKeysApi(web_contents()->GetPrimaryMainFrame()));

  content::WebContentsConsoleObserver console_observer(web_contents());
  console_observer.SetPattern(kConsoleUncaughtTypeErrorMessagePattern);

  base::HistogramTester histogram_tester;

  ExecJsSetClientEncryptionKeysWithIllformedArgs(
      web_contents()->GetPrimaryMainFrame());
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());

  // Collect histograms from the renderer process, since otherwise
  // HistogramTester cannot verify the ones instrumented in the renderer.
  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  histogram_tester.ExpectUniqueSample(
      "TrustedVault.JavascriptSetClientEncryptionKeysValidArgs", 0 /*Invalid*/,
      1);

  // Renderer makes no attempt of setting keys on the browser side.
  histogram_tester.ExpectTotalCount(
      "TrustedVault.JavascriptSetClientEncryptionKeysForSecurityDomain", 0);
  histogram_tester.ExpectTotalCount(
      "TrustedVault.SetEncryptionKeysForSecurityDomain.AllProfiles", 0);

  std::vector<std::vector<uint8_t>> actual_keys =
      FetchTrustedVaultKeysForProfile(
          browser()->profile(), trusted_vault::SecurityDomainId::kChromeSync,
          FakeAccount());
  EXPECT_THAT(actual_keys, IsEmpty());
}

// Tests that chrome.setSyncEncryptionKeys() works in a fenced frame.
IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ShouldBindSyncEncryptionKeysApiInFencedFrame) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), initial_url));
  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  ASSERT_TRUE(HasEncryptionKeysApi(web_contents()->GetPrimaryMainFrame()));

  const GURL main_url = https_server()->GetURL("accounts.google.com",
                                               "/fenced_frames/title1.html");
  auto* fenced_frame_host = fenced_frame_test_helper().CreateFencedFrame(
      web_contents()->GetPrimaryMainFrame(), main_url);
  // EncryptionKeysApi is also created for a fenced frame since it's a main
  // frame as well.
  EXPECT_TRUE(HasEncryptionKeysApi(fenced_frame_host));

  content::WebContentsConsoleObserver console_observer(web_contents());
  console_observer.SetPattern(kConsoleSuccessMessage);

  // Calling setSyncEncryptionKeys() in the fenced frame works and it gets
  // the callback by setSyncEncryptionKeys().
  const std::vector<uint8_t> kEncryptionKey = {7};
  const int kEncryptionKeyVersion = 24;
  ExecJsSetSyncEncryptionKeys(fenced_frame_host, kEncryptionKey,
                              kEncryptionKeyVersion);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());

  std::vector<std::vector<uint8_t>> actual_keys =
      FetchTrustedVaultKeysForProfile(
          browser()->profile(), trusted_vault::SecurityDomainId::kChromeSync,
          FakeAccount());
  EXPECT_THAT(actual_keys, ElementsAre(kEncryptionKey));
  EXPECT_THAT(FetchLastTrustedVaultKeyVersionForProfile(
                  browser()->profile(),
                  trusted_vault::SecurityDomainId::kChromeSync, FakeAccount()),
              Eq(kEncryptionKeyVersion));
}

// Tests that chrome.setClientEncryptionKeys() works in a fenced frame.
IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ShouldBindClientEncryptionKeysApiInFencedFrame) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), initial_url));
  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  ASSERT_TRUE(HasEncryptionKeysApi(web_contents()->GetPrimaryMainFrame()));

  const GURL main_url = https_server()->GetURL("accounts.google.com",
                                               "/fenced_frames/title1.html");
  auto* fenced_frame_host = fenced_frame_test_helper().CreateFencedFrame(
      web_contents()->GetPrimaryMainFrame(), main_url);
  // EncryptionKeysApi is also created for a fenced frame since it's a main
  // frame as well.
  EXPECT_TRUE(HasEncryptionKeysApi(fenced_frame_host));

  content::WebContentsConsoleObserver console_observer(web_contents());
  console_observer.SetPattern(kConsoleSuccessMessage);

  // Calling setClientEncryptionKeys() in the fenced frame works.
  const std::vector<uint8_t> kEncryptionKey = {7};
  ExecJsSetClientEncryptionKeys(fenced_frame_host, kEncryptionKey);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());

  std::vector<std::vector<uint8_t>> actual_keys =
      FetchTrustedVaultKeysForProfile(
          browser()->profile(), trusted_vault::SecurityDomainId::kChromeSync,
          FakeAccount());
  EXPECT_THAT(actual_keys, ElementsAre(kEncryptionKey));
}

IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ShouldIgnoreSyncEncryptionsKeysInIncognito) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");

  Browser* incognito_browser =
      OpenURLOffTheRecord(browser()->profile(), initial_url);
  content::WebContents* incognito_web_contents =
      incognito_browser->tab_strip_model()->GetActiveWebContents();

  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  EXPECT_TRUE(
      HasEncryptionKeysApi(incognito_web_contents->GetPrimaryMainFrame()));

  content::WebContentsConsoleObserver console_observer(incognito_web_contents);
  console_observer.SetPattern(kConsoleSuccessMessage);

  base::HistogramTester histogram_tester;

  // Calling setSyncEncryptionKeys() in incognito completes successfully,
  // although it does nothing.
  const std::vector<uint8_t> kEncryptionKey = {7};
  ExecJsSetSyncEncryptionKeys(incognito_web_contents->GetPrimaryMainFrame(),
                              kEncryptionKey, /*key_version=*/1);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());

  // Collect histograms from the renderer process, since otherwise
  // HistogramTester cannot verify the ones instrumented in the renderer.
  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  histogram_tester.ExpectUniqueSample(
      "Sync.TrustedVaultJavascriptSetEncryptionKeysValidArgs", 1 /*Valid*/, 1);

  histogram_tester.ExpectUniqueSample(
      "TrustedVault.SetEncryptionKeysForSecurityDomain.AllProfiles",
      1 /*Chrome Sync*/, 1);
  histogram_tester.ExpectUniqueSample(
      "TrustedVault.SetEncryptionKeysForSecurityDomain.OffTheRecordOnly",
      1 /*Chrome Sync*/, 1);

  histogram_tester.ExpectUniqueSample(
      "Sync.TrustedVaultJavascriptSetEncryptionKeysIsIncognito",
      1 /*Incognito*/, 1);

  std::vector<std::vector<uint8_t>> actual_keys =
      FetchTrustedVaultKeysForProfile(
          browser()->profile(), trusted_vault::SecurityDomainId::kChromeSync,
          FakeAccount());
  // In incognito, the keys should actually be ignored, never forwarded to
  // TrustedVaultService.
  EXPECT_THAT(actual_keys, IsEmpty());
}

IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ShouldIgnoreClientEncryptionsKeysInIncognito) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");

  Browser* incognito_browser =
      OpenURLOffTheRecord(browser()->profile(), initial_url);
  content::WebContents* incognito_web_contents =
      incognito_browser->tab_strip_model()->GetActiveWebContents();

  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  EXPECT_TRUE(
      HasEncryptionKeysApi(incognito_web_contents->GetPrimaryMainFrame()));

  content::WebContentsConsoleObserver console_observer(incognito_web_contents);
  console_observer.SetPattern(kConsoleSuccessMessage);

  base::HistogramTester histogram_tester;

  // Calling setClientEncryptionKeys() in incognito completes successfully,
  // although it does nothing.
  const std::vector<uint8_t> kEncryptionKey = {7};
  ExecJsSetClientEncryptionKeys(incognito_web_contents->GetPrimaryMainFrame(),
                                kEncryptionKey);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());

  // Collect histograms from the renderer process, since otherwise
  // HistogramTester cannot verify the ones instrumented in the renderer.
  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  histogram_tester.ExpectUniqueSample(
      "TrustedVault.JavascriptSetClientEncryptionKeysValidArgs", 1 /*Valid*/,
      1);
  histogram_tester.ExpectUniqueSample(
      "TrustedVault.JavascriptSetClientEncryptionKeysForSecurityDomain",
      1 /*Chrome Sync*/, 1);

  histogram_tester.ExpectUniqueSample(
      "TrustedVault.SetEncryptionKeysForSecurityDomain.AllProfiles",
      1 /*Chrome Sync*/, 1);
  histogram_tester.ExpectUniqueSample(
      "TrustedVault.SetEncryptionKeysForSecurityDomain.OffTheRecordOnly",
      1 /*Chrome Sync*/, 1);

  histogram_tester.ExpectUniqueSample(
      "Sync.TrustedVaultJavascriptSetEncryptionKeysIsIncognito",
      1 /*Incognito*/, 1);

  std::vector<std::vector<uint8_t>> actual_keys =
      FetchTrustedVaultKeysForProfile(
          browser()->profile(), trusted_vault::SecurityDomainId::kChromeSync,
          FakeAccount());
  // In incognito, the keys should actually be ignored, never forwarded to
  // TrustedVaultService.
  EXPECT_THAT(actual_keys, IsEmpty());
}

IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ShouldIgnoreRecoveryMethodInIncognito) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");

  Browser* incognito_browser =
      OpenURLOffTheRecord(browser()->profile(), initial_url);
  content::WebContents* incognito_web_contents =
      incognito_browser->tab_strip_model()->GetActiveWebContents();

  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  EXPECT_TRUE(
      HasEncryptionKeysApi(incognito_web_contents->GetPrimaryMainFrame()));

  content::WebContentsConsoleObserver console_observer(incognito_web_contents);
  console_observer.SetPattern(kConsoleSuccessMessage);

  base::HistogramTester histogram_tester;

  // Calling addTrustedSyncEncryptionRecoveryMethod() in incognito completes
  // successfully, although it does nothing.
  const std::vector<uint8_t> kPublicKey = {7};
  ExecJsAddTrustedSyncEncryptionRecoveryMethod(
      incognito_web_contents->GetPrimaryMainFrame(), kPublicKey);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());

  histogram_tester.ExpectUniqueSample(
      "Sync.TrustedVaultJavascriptAddRecoveryMethodIsIncognito",
      1 /*Incognito*/, 1);
}

IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ShouldNotSetKeysIfCallingFrameIsDeleted_364338802) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/iframe.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), initial_url));

  const GURL frame_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  EXPECT_TRUE(NavigateIframeToURL(web_contents(), "test", frame_url));
  content::RenderFrameHost* child_frame =
      ChildFrameAt(web_contents()->GetPrimaryMainFrame(), 0);
  ASSERT_TRUE(child_frame);

  // EncryptionKeysApi is created for the child frame as the origin is allowed.
  ASSERT_TRUE(HasEncryptionKeysApi(child_frame));

  content::WebContentsConsoleObserver console_observer(web_contents());
  content::RenderFrameDeletedObserver frame_deleted_observer(child_frame);

  // Ensure that deleting the calling frame in the middle of the request doesn't
  // crash. Keys will not be set successfully.
  constexpr std::string_view script = R"(
      var childFrame = document.querySelector("iframe");
      let trustedVaultKey = new Object();
      childFrame.contentWindow.Object.defineProperty(
          trustedVaultKey, "key", { get: () => {
              document.body.remove(childFrame);
              return new ArrayBuffer(1);
      }});
      trustedVaultKey.key = new ArrayBuffer(1);
      trustedVaultKey.epoch = 1;
      childFrame.contentWindow.chrome.setClientEncryptionKeys(
          () => { console.log("test:OK") },
          "fake_gaia_id",
          new Map([['chromesync', [trustedVaultKey]]]));
    )";

  ASSERT_TRUE(content::ExecJs(web_contents(), script));
  EXPECT_TRUE(frame_deleted_observer.WaitUntilDeleted());
  EXPECT_EQ(console_observer.messages().size(), 0u);
  EXPECT_THAT(FetchTrustedVaultKeysForProfile(
                  browser()->profile(),
                  trusted_vault::SecurityDomainId::kChromeSync, FakeAccount()),
              IsEmpty());
}
#endif  // BUILDFLAG(IS_ANDROID)

// Tests that chrome.addTrustedSyncEncryptionRecoveryMethod() works in the main
// frame.
IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ShouldBindAddRecoveryMethodApiInMainFrame) {
  // Out desktop platforms using StandaloneTrustedVaultClient, a primary account
  // needs to be set for the Javascript operation to complete. Otherwise, the
  // logic is deferred until a primary account is set and the test would wait
  // indefinitely until it times out.
#if !BUILDFLAG(IS_ANDROID)
  signin::MakePrimaryAccountAvailable(
      IdentityManagerFactory::GetForProfile(browser()->profile()),
      "testusername", signin::ConsentLevel::kSync);
#endif  // !BUILDFLAG(IS_ANDROID)

  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), initial_url));
  // EncryptionKeysApi is created for the primary page as the origin is allowed.
  EXPECT_TRUE(HasEncryptionKeysApi(web_contents()->GetPrimaryMainFrame()));

  content::WebContentsConsoleObserver console_observer(web_contents());
  console_observer.SetPattern(kConsoleSuccessMessage);

  base::HistogramTester histogram_tester;

  // Calling addTrustedSyncEncryptionRecoveryMethod() in the main frame works.
  const std::vector<uint8_t> kPublicKey = {7};
  ExecJsAddTrustedSyncEncryptionRecoveryMethod(
      web_contents()->GetPrimaryMainFrame(), kPublicKey);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());

  // Collect histograms from the renderer process, since otherwise
  // HistogramTester cannot verify the ones instrumented in the renderer.
  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  histogram_tester.ExpectUniqueSample(
      "Sync.TrustedVaultJavascriptAddRecoveryMethodValidArgs", 1 /*Valid*/, 1);

  histogram_tester.ExpectUniqueSample(
      "Sync.TrustedVaultJavascriptAddRecoveryMethodIsIncognito",
      0 /*Not Incognito*/, 1);

#if BUILDFLAG(IS_ANDROID)
  // This metric is only instrumented on Android.
  histogram_tester.ExpectUniqueSample(
      "Sync.TrustedVaultJavascriptAddRecoveryMethodUserKnown", 0 /*Unknown*/,
      1);
#endif  // BUILDFLAG(IS_ANDROID)
}

// Tests that chrome.setSyncEncryptionKeys() doesn't work in prerendering.
// If it is called in prerendering, it triggers canceling the prerendering
// and EncryptionKeyApi is not bound.
IN_PROC_BROWSER_TEST_F(TrustedVaultEncryptionKeysTabHelperBrowserTest,
                       ShouldNotBindEncryptionKeysApiInPrerendering) {
  // Out desktop platforms using StandaloneTrustedVaultClient, a primary account
  // needs to be set for the Javascript operation to complete. Otherwise, the
  // logic is deferred until a primary account is set and the test would wait
  // indefinitely until it times out.
#if !BUILDFLAG(IS_ANDROID)
  signin::MakePrimaryAccountAvailable(
      IdentityManagerFactory::GetForProfile(browser()->profile()),
      "testusername", signin::ConsentLevel::kSync);
#endif  // !BUILDFLAG(IS_ANDROID)

  base::HistogramTester histogram_tester;
  const GURL signin_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), signin_url));
  // EncryptionKeysApi is created for the primary page.
  EXPECT_TRUE(HasEncryptionKeysApi(web_contents()->GetPrimaryMainFrame()));

  const GURL prerendering_url =
      https_server()->GetURL("accounts.google.com", "/simple.html");

  content::FrameTreeNodeId host_id =
      prerender_helper().AddPrerender(prerendering_url);
  content::RenderFrameHostWrapper prerendered_frame_host(
      prerender_helper().GetPrerenderedMainFrameHost(host_id));

  // EncryptionKeysApi is also created for prerendering since it's a main frame
  // as well.
  EXPECT_TRUE(HasEncryptionKeysApi(prerendered_frame_host.get()));

  content::test::PrerenderHostObserver host_observer(*web_contents(), host_id);

  {
    content::WebContentsConsoleObserver console_observer(web_contents());
    console_observer.SetPattern(kConsoleSuccessMessage);

    // Calling addTrustedSyncEncryptionRecoveryMethod() in the prerendered page
    // triggers canceling the prerendering since it's a associated interface and
    // the default policy is `MojoBinderAssociatedPolicy::kCancel`. Calling  in
    // the main frame works.
    const std::vector<uint8_t> kPublicKey = {7};
    ExecJsAddTrustedSyncEncryptionRecoveryMethod(prerendered_frame_host.get(),
                                                 kPublicKey);
    host_observer.WaitForDestroyed();
    EXPECT_EQ(0u, console_observer.messages().size());
    histogram_tester.ExpectUniqueSample(
        "Prerender.Experimental.PrerenderCancelledInterface.SpeculationRule",
        4 /*PrerenderCancelledInterface::kTrustedVaultEncryptionKeys*/, 1);
    EXPECT_TRUE(prerendered_frame_host.IsRenderFrameDeleted());
  }

  prerender_helper().NavigatePrimaryPage(prerendering_url);
  // Ensure that loading `prerendering_url` is not activated from prerendering.
  EXPECT_FALSE(host_observer.was_activated());
  auto* primary_main_frame = web_contents()->GetPrimaryMainFrame();
  // Ensure that the main frame has EncryptionKeysApi.
  EXPECT_TRUE(HasEncryptionKeysApi(primary_main_frame));

  {
    content::WebContentsConsoleObserver console_observer(web_contents());
    console_observer.SetPattern(kConsoleSuccessMessage);

    // Calling addTrustedSyncEncryptionRecoveryMethod() in the primary page
    // works.
    const std::vector<uint8_t> kPublicKey = {7};
    ExecJsAddTrustedSyncEncryptionRecoveryMethod(primary_main_frame,
                                                 kPublicKey);
    ASSERT_TRUE(console_observer.Wait());
    EXPECT_EQ(1u, console_observer.messages().size());
  }
}

// Same as SyncEncryptionKeysTabHelperBrowserTest but switches::kGaiaUrl does
// NOT point to the embedded test server, which means it gets treated as
// disallowed origin.
class TrustedVaultEncryptionKeysTabHelperWithoutAllowedOriginBrowserTest
    : public TrustedVaultEncryptionKeysTabHelperBrowserTest {
 public:
  TrustedVaultEncryptionKeysTabHelperWithoutAllowedOriginBrowserTest() =
      default;
  ~TrustedVaultEncryptionKeysTabHelperWithoutAllowedOriginBrowserTest()
      override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    TrustedVaultEncryptionKeysTabHelperBrowserTest::SetUpCommandLine(
        command_line);
    // Override kGaiaUrl to the default so the embedded test server isn't
    // treated as an allowed origin.
    command_line->RemoveSwitch(::switches::kGaiaUrl);
  }
};

// Tests that chrome.setSyncEncryptionKeys() and
// chrome.setClientEncryptionKeys() doesn't work in disallowed origins.
IN_PROC_BROWSER_TEST_F(
    TrustedVaultEncryptionKeysTabHelperWithoutAllowedOriginBrowserTest,
    ShouldNotBindEncryptionKeys) {
  const GURL initial_url =
      https_server()->GetURL("accounts.google.com", "/title1.html");
  ASSERT_TRUE(content::NavigateToURL(web_contents(), initial_url));
  // EncryptionKeysApi is NOT created for the primary page as the origin is
  // disallowed.
  EXPECT_FALSE(HasEncryptionKeysApi(web_contents()->GetPrimaryMainFrame()));

  content::WebContentsConsoleObserver console_observer(web_contents());
  console_observer.SetPattern(kConsoleFailureMessage);

  // setSyncEncryptionKeys() and setClientEncryptionKeys() should fail because
  // they aren't defined.
  const std::vector<uint8_t> kEncryptionKey = {7};
  ExecJsSetSyncEncryptionKeys(web_contents()->GetPrimaryMainFrame(),
                              kEncryptionKey, /*key_version=*/1);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(1u, console_observer.messages().size());
  ExecJsSetClientEncryptionKeys(web_contents()->GetPrimaryMainFrame(),
                                kEncryptionKey);
  ASSERT_TRUE(console_observer.Wait());
  EXPECT_EQ(2u, console_observer.messages().size());
}

}  // namespace