File: supervised_user_pending_state_navigation_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 (574 lines) | stat: -rw-r--r-- 24,323 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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <vector>

#include "base/functional/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "build/buildflag.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/supervised_user/child_accounts/child_account_service_factory.h"
#include "chrome/browser/supervised_user/supervised_user_browser_utils.h"
#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
#include "chrome/browser/supervised_user/supervised_user_test_util.h"
#include "chrome/browser/supervised_user/supervised_user_verification_controller_client.h"
#include "chrome/browser/supervised_user/supervised_user_verification_page.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/mixin_based_in_process_browser_test.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/supervised_user/child_account_test_utils.h"
#include "chrome/test/supervised_user/google_auth_state_waiter_mixin.h"
#include "chrome/test/supervised_user/supervision_mixin.h"
#include "components/google/core/common/google_util.h"
#include "components/grit/components_resources.h"
#include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h"
#include "components/signin/public/identity_manager/accounts_mutator.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/strings/grit/components_strings.h"
#include "components/supervised_user/core/browser/child_account_service.h"
#include "components/supervised_user/core/browser/supervised_user_service.h"
#include "components/supervised_user/core/common/features.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/mock_navigation_handle.h"
#include "content/public/test/test_navigation_observer.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/gurl.h"

namespace {

using ::testing::_;

static constexpr std::string_view
    kUmaReauthenticationBlockedSitedHistogramName =
        "FamilyLinkUser.BlockedSiteVerifyItsYouInterstitialState";
static constexpr std::string_view
    kUmaReauthenticationYoutubeSubframeHistogramName =
        "FamilyLinkUser.SubframeYoutubeReauthenticationInterstitial";

bool IsReauthenticationInterstitialBeingShown(content::WebContents* content) {
  CHECK(content);
  std::string command =
      "document.querySelector('.supervised-user-verify') != null";
  return content::EvalJs(content, command).ExtractBool();
}

bool IsBlockedUrlInterstitialBeingShown(content::WebContents* content) {
  CHECK(content);
  std::string command =
      "document.querySelector('.supervised-user-block') != null";
  return content::EvalJs(content, command).ExtractBool();
}

class SupervisedUserPendingStateNavigationTest
    : public MixinBasedInProcessBrowserTest {
 public:
 protected:
  void PreRunTestOnMainThread() override {
    InProcessBrowserTest::PreRunTestOnMainThread();
    // TestAutoSetUkmRecorder should be initialized before UKMs are recorded.
    ukm_recorder_ = std::make_unique<ukm::TestAutoSetUkmRecorder>();
  }

  content::WebContents* contents() {
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

  signin::IdentityManager* identity_manager() {
    return supervision_mixin_.GetIdentityTestEnvironment()->identity_manager();
  }

  int GetReauthInterstitialUKMTotalCount() {
    auto entries = ukm_recorder_->GetEntriesByName(
        ukm::builders::FamilyLinkUser_ReauthenticationInterstitial::kEntryName);
    return entries.size();
  }

  void WaitForPageTitle(const std::u16string& page_title) {
    ASSERT_TRUE(base::test::RunUntil(
        [&]() { return page_title == contents()->GetTitle(); }));
  }

  void SignInSupervisedUserAndWaitForInterstitialReload(
      content::WebContents* content,
      const GURL& url) {
    Profile* profile =
        Profile::FromBrowserContext(contents()->GetBrowserContext());
    ASSERT_TRUE(ChildAccountServiceFactory::GetForProfile(profile)
                    ->GetGoogleAuthState() !=
                supervised_user::ChildAccountService::AuthState::AUTHENTICATED);

    // Before sign-in the user still sees the re-authentication interstitial.
    ASSERT_TRUE(IsReauthenticationInterstitialBeingShown(content));
    ASSERT_FALSE(IsBlockedUrlInterstitialBeingShown(content));

    content::TestNavigationObserver observer(url);
    observer.WatchWebContents(content);
    kids_management_api_mock().AllowSubsequentClassifyUrl();

    supervision_mixin_.SignIn(
        supervised_user::SupervisionMixin::SignInMode::kSupervised);

    ASSERT_FALSE(
        identity_manager()->HasAccountWithRefreshTokenInPersistentErrorState(
            identity_manager()->GetPrimaryAccountId(
                signin::ConsentLevel::kSignin)));

    ASSERT_TRUE(
        identity_manager()->GetAccountsInCookieJar().AreAccountsFresh());

    observer.WaitForNavigationFinished();

    // Wait for the re-auth page to be asynchronously reloaded and replaced by
    // the blocked url interstitial.
    ASSERT_FALSE(IsReauthenticationInterstitialBeingShown(content));
    ASSERT_TRUE(IsBlockedUrlInterstitialBeingShown(content));
  }

  // Start sign-in flow by clicking on the primary button.
  bool StartSignInFlowFromContent(content::WebContents* interstitial_content) {
    return content::ExecJs(interstitial_content,
                           "document.querySelector('#primary-button').click()");
  }

  bool StartSignInFlowFromRenderFrameHost(content::RenderFrameHost* rfh) {
    return content::ExecJs(rfh,
                           "document.querySelector('#primary-button').click()");
  }

  void WaitForReauthenticationInterstitial() {
    WaitForPageTitle(l10n_util::GetStringUTF16(IDS_BLOCK_INTERSTITIAL_TITLE));
    // The "Next" button should be visible.
    EXPECT_FALSE(
        content::EvalJs(contents(),
                        "document.querySelector('#primary-button').hidden;")
            .ExtractBool());

    EXPECT_EQ(
        ui_test_utils::FindInPage(
            contents(),
            l10n_util::GetStringUTF16(IDS_CHILD_BLOCK_INTERSTITIAL_HEADER),
            /*forward=*/true, /*case_sensitive=*/true, /*ordinal=*/nullptr,
            /*selection_rect=*/nullptr),
        1);

    // The following string is found only on the the re-authentication
    // interstitial.
    EXPECT_EQ(
        ui_test_utils::FindInPage(
            contents(),
            l10n_util::GetStringUTF16(
                IDS_CHILD_BLOCK_INTERSTITIAL_MESSAGE_NOT_SIGNED_IN),
            /*forward=*/true, /*case_sensitive=*/true, /*ordinal=*/nullptr,
            /*selection_rect=*/nullptr),
        1);
  }

  supervised_user::KidsManagementApiServerMock& kids_management_api_mock() {
    return supervision_mixin_.api_mock_setup_mixin().api_mock();
  }

  supervised_user::SupervisionMixin supervision_mixin_{
      mixin_host_,
      this,
      embedded_test_server(),
      {.consent_level = signin::ConsentLevel::kSignin,
       .sign_in_mode =
           supervised_user::SupervisionMixin::SignInMode::kSupervised,
       .embedded_test_server_options = {.resolver_rules_map_host_list =
                                            "*.example.com"}}};

  void SetManualHost(const GURL& url, bool allowlist) {
    supervised_user_test_util::SetManualFilterForHost(browser()->profile(),
                                                      url.host(), allowlist);
  }

  content::RenderFrameHost* FindFrameByName(const std::string& name) {
    content::RenderFrameHost* rfh = content::FrameMatchingPredicate(
        contents()->GetPrimaryPage(),
        base::BindRepeating(&content::FrameMatchesName, name));
    CHECK(rfh);
    CHECK(rfh->IsRenderFrameLive());
    return rfh;
  }

  std::string GetInnerHTMLString(
      const content::ToRenderFrameHost& execution_target) {
    return content::EvalJs(execution_target,
                           "document.documentElement.innerHTML")
        .ExtractString();
  }

  int GetReauthInterstitialUKMCount(const std::string& metric_name) {
    int count = 0;
    auto entries = ukm_recorder_->GetEntriesByName(
        ukm::builders::FamilyLinkUser_ReauthenticationInterstitial::kEntryName);
    for (const ukm::mojom::UkmEntry* const entry : entries) {
      if (ukm_recorder_->GetEntryMetric(entry, metric_name)) {
        ++count;
      }
    }
    return count;
  }

  int GetTabCount() { return browser()->tab_strip_model()->count(); }

 private:
  std::unique_ptr<ukm::TestAutoSetUkmRecorder> ukm_recorder_;
  base::test::ScopedFeatureList scoped_feature_list_{
      supervised_user::kUncredentialedFilteringFallbackForSupervisedUsers};
};

// Tests the blocked site main frame re-authentication interstitial.
IN_PROC_BROWSER_TEST_F(SupervisedUserPendingStateNavigationTest,
                       TestBlockedSiteMainFrameReauthInterstitial) {
  kids_management_api_mock().RestrictSubsequentClassifyUrl();
  supervision_mixin_.SetPendingStateForPrimaryAccount();
  // Navigate to the requested URL and wait for the interstitial.
  const auto url =
      embedded_test_server()->GetURL("/supervised_user/simple.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
  ASSERT_TRUE(WaitForRenderFrameReady(contents()->GetPrimaryMainFrame()));

  // Verify that the blocked site interstitial is displayed.
  WaitForReauthenticationInterstitial();

  auto* interstitial_contents = contents();
  // Interact with the "Next" button, starting re-authentication.
  ASSERT_TRUE(StartSignInFlowFromContent(interstitial_contents));

  // Sign in a supervised user, which completes re-authentication.
  SignInSupervisedUserAndWaitForInterstitialReload(interstitial_contents, url);

  // UKM should not be recorded for the blocked site interstitial.
  EXPECT_EQ(GetReauthInterstitialUKMTotalCount(), 0);
}

// Tests that the sign-in tabs opened through the re-auth interstitial
// are closed on re-authentication.
IN_PROC_BROWSER_TEST_F(SupervisedUserPendingStateNavigationTest,
                       TestReauthInterstitialClosesSignInTabsAndReloads) {
  base::HistogramTester histogram_tester;

  kids_management_api_mock().RestrictSubsequentClassifyUrl();
  supervision_mixin_.SetPendingStateForPrimaryAccount();
  // Navigate to the requested URL and wait for the interstitial.
  auto original_tab_target_url =
      embedded_test_server()->GetURL("/supervised_user/simple.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), original_tab_target_url));
  ASSERT_TRUE(WaitForRenderFrameReady(contents()->GetPrimaryMainFrame()));

  // Wait for the re-authentication interstitial. It should be the only tab.
  WaitForReauthenticationInterstitial();
  histogram_tester.ExpectBucketCount(
      kUmaReauthenticationBlockedSitedHistogramName,
      static_cast<int>(SupervisedUserVerificationPage::Status::SHOWN), 1);
  auto* interstitial_contents = contents();
  EXPECT_EQ(1, GetTabCount());

  // Interact with the "Next" button, starting re-authentication in a new tab, 3
  // times.
  for (int i = 1; i <= 3; i++) {
    ASSERT_TRUE(StartSignInFlowFromContent(interstitial_contents));
    histogram_tester.ExpectBucketCount(
        kUmaReauthenticationBlockedSitedHistogramName,
        static_cast<int>(
            SupervisedUserVerificationPage::Status::REAUTH_STARTED),
        i);
    EXPECT_EQ(i + 1, GetTabCount());

    // Wait for the navigation to finish in the sign-in tabs.
    if (browser()
            ->tab_strip_model()
            ->GetWebContentsAt(i)
            ->GetLastCommittedURL()
            .is_empty()) {
      content::TestNavigationObserver observer(
          browser()->tab_strip_model()->GetWebContentsAt(i));
      observer.WaitForNavigationFinished();
    }
    ASSERT_FALSE(browser()
                     ->tab_strip_model()
                     ->GetWebContentsAt(i)
                     ->GetLastCommittedURL()
                     .is_empty());
  }

  // Use one tab to navigate elsewhere.
  // We use a manually allow-listed url to avoid creating more
  // interstitials that would complicate the metrics checks.
  browser()->tab_strip_model()->ActivateTabAt(3);
  const GURL allowlisted_url = GURL("https://example.com/");
  SetManualHost(allowlisted_url, /*allowlist=*/true);
  // The `spawned_tab_url` is used to navigate away from the sign-in
  // content in one of the sign-in spawned tabs.
  // This url is not related to the `original_tab_target_url` that we visit
  // on the first -original- tab.
  const GURL spawned_tab_url = GURL(allowlisted_url.spec() + "/simple.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), spawned_tab_url));

  // Sign in a supervised user, which completes re-authentication.
  // This results in closing the sign-in tabs (2 tabs).
  // Two tabs, the interstitial and the tab where the user performed a
  // navigation, remain open.
  SignInSupervisedUserAndWaitForInterstitialReload(interstitial_contents,
                                                   original_tab_target_url);
  histogram_tester.ExpectBucketCount(
      kUmaReauthenticationBlockedSitedHistogramName,
      static_cast<int>(
          SupervisedUserVerificationPage::Status::REAUTH_COMPLETED),
      1);
  EXPECT_EQ(2, GetTabCount());
}

IN_PROC_BROWSER_TEST_F(SupervisedUserPendingStateNavigationTest,
                       TestManualBlockedSiteMainFrameReauthInterstitial) {
  supervision_mixin_.SetPendingStateForPrimaryAccount();

  // Add exampleURL to the manual blocklist
  GURL exampleURL = GURL("https://example.com/");
  SetManualHost(exampleURL, /*allowlist=*/false);

  // Navigate to the requested URL and wait for the interstitial.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), exampleURL));
  ASSERT_TRUE(WaitForRenderFrameReady(contents()->GetPrimaryMainFrame()));

  WaitForReauthenticationInterstitial();
}

// Tests the YouTube main frame re-authentication interstitial.
IN_PROC_BROWSER_TEST_F(SupervisedUserPendingStateNavigationTest,
                       TestYouTubeMainFrameReauthInterstitial) {
  supervision_mixin_.SetPendingStateForPrimaryAccount();
  kids_management_api_mock().AllowSubsequentClassifyUrl();

  // Navigate to YouTube and wait for the interstitial.
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), GURL("https://youtube.com/")));
  ASSERT_TRUE(WaitForRenderFrameReady(contents()->GetPrimaryMainFrame()));
  WaitForPageTitle(
      l10n_util::GetStringUTF16(IDS_SUPERVISED_USER_VERIFY_PAGE_TAB_TITLE));
  EXPECT_EQ(GetReauthInterstitialUKMCount("InterstitialShown"), 1);

  // Check that the YouTube interstitial contains the correct text.
  EXPECT_EQ(ui_test_utils::FindInPage(
                contents(),
                l10n_util::GetStringUTF16(
                    IDS_SUPERVISED_USER_VERIFY_PAGE_PRIMARY_PARAGRAPH),
                /*forward=*/true, /*case_sensitive=*/true, /*ordinal=*/nullptr,
                /*selection_rect=*/nullptr),
            1);

  // Open re-authentication in a new tab.
  ASSERT_TRUE(StartSignInFlowFromContent(contents()));
  EXPECT_EQ(GetReauthInterstitialUKMCount("ReauthenticationStarted"), 1);
  EXPECT_EQ(2, GetTabCount());

  // Sign in a supervised user, which completes re-authentication.
  // This should records UKM metrics and close the sign-in tab.
  supervision_mixin_.SignIn(
      supervised_user::SupervisionMixin::SignInMode::kSupervised);
  ASSERT_TRUE(base::test::RunUntil([&]() {
    return GetReauthInterstitialUKMCount("ReauthenticationCompleted") == 1;
  }));
  EXPECT_EQ(1, GetTabCount());

  EXPECT_EQ(GetReauthInterstitialUKMTotalCount(), 3);
}

// Tests the blocked site subframe re-authentication interstitial.
IN_PROC_BROWSER_TEST_F(SupervisedUserPendingStateNavigationTest,
                       TestBlockedSiteSubFrameReauthInterstitial) {
  supervision_mixin_.SetPendingStateForPrimaryAccount();

  // Filter the iframe URL.
  GURL exampleURL = GURL("https://iframe2.com/");
  SetManualHost(exampleURL, /*allowlist=*/false);
  kids_management_api_mock().AllowSubsequentClassifyUrl();

  GURL allowed_url_with_iframes = embedded_test_server()->GetURL(
      "www.example.com", "/supervised_user/with_iframes.html");

  // Navigate to the custom html containing 2 iframes.
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), allowed_url_with_iframes));
  ASSERT_TRUE(WaitForRenderFrameReady(contents()->GetPrimaryMainFrame()));

  // Verify that the iframes are loaded.
  WaitForPageTitle(u"Supervised User test: page with iframes");
  EXPECT_TRUE(content::EvalJs(contents(), "loaded1()").ExtractBool());
  EXPECT_TRUE(content::EvalJs(contents(), "loaded2()").ExtractBool());

  SCOPED_TRACE("iframe2");
  content::RenderFrameHost* iframe2 = FindFrameByName("iframe2");

  // Check that the subframe interstitial contains the correct text.
  EXPECT_THAT(
      GetInnerHTMLString(iframe2),
      testing::HasSubstr(l10n_util::GetStringUTF8(
          IDS_SUPERVISED_USER_VERIFY_PAGE_SUBFRAME_BLOCKED_SITE_HEADING)));

  // Click the "Next" button, which should open re-authentication in a new tab.
  ASSERT_TRUE(StartSignInFlowFromRenderFrameHost(iframe2));
  EXPECT_EQ(2, GetTabCount());

  // Sign in a supervised user, which completes re-authentication.
  // This should close the sign-in tab.
  supervision_mixin_.SignIn(
      supervised_user::SupervisionMixin::SignInMode::kSupervised);
  ASSERT_TRUE(base::test::RunUntil([&]() { return GetTabCount() == 1; }));

  // TODO(https://crbug.com/365531704): Wait until the blocked site interstitial
  // is displayed.

  // UKM should not be recorded for the subframe interstitial.
  EXPECT_EQ(GetReauthInterstitialUKMTotalCount(), 0);
}

// Tests the YouTube subframe re-authentication interstitial.
IN_PROC_BROWSER_TEST_F(SupervisedUserPendingStateNavigationTest,
                       TestYouTubeSubFrameReauthInterstitial) {
  base::HistogramTester histogram_tester;
  supervision_mixin_.SetPendingStateForPrimaryAccount();
  kids_management_api_mock().AllowSubsequentClassifyUrl();

  GURL url_with_youtube_iframes = embedded_test_server()->GetURL(
      "www.example.com", "/supervised_user/with_embedded_youtube_videos.html");

  // Navigate to the custom html containing 2 YouTube iframes.
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), url_with_youtube_iframes));
  ASSERT_TRUE(WaitForRenderFrameReady(contents()->GetPrimaryMainFrame()));

  // Verify that the iframes are loaded.
  WaitForPageTitle(u"Supervised User test: page with embedded YouTube videos");
  EXPECT_TRUE(content::EvalJs(contents(), "loaded1()").ExtractBool());
  EXPECT_TRUE(content::EvalJs(contents(), "loaded2()").ExtractBool());

  content::RenderFrameHost* iframe1 = FindFrameByName("iframe1");
  content::RenderFrameHost* iframe2 = FindFrameByName("iframe2");

  // Check that the subframe interstitial contains the correct text.
  std::string subframe_description = l10n_util::GetStringUTF8(
      IDS_SUPERVISED_USER_VERIFY_PAGE_SUBFRAME_YOUTUBE_HEADING);
  EXPECT_THAT(GetInnerHTMLString(iframe1),
              testing::HasSubstr(subframe_description));
  EXPECT_THAT(GetInnerHTMLString(iframe2),
              testing::HasSubstr(subframe_description));
  // Verify the Uma subframe interstitial metrics.
  histogram_tester.ExpectBucketCount(
      kUmaReauthenticationYoutubeSubframeHistogramName,
      static_cast<int>(SupervisedUserVerificationPage::Status::SHOWN), 2);

  // Click the "Next" buttons in both interstitials, which should open
  // re-authentication in two new tabs.
  ASSERT_TRUE(StartSignInFlowFromRenderFrameHost(iframe1));
  ASSERT_TRUE(StartSignInFlowFromRenderFrameHost(iframe2));
  EXPECT_EQ(3, GetTabCount());
  histogram_tester.ExpectBucketCount(
      kUmaReauthenticationYoutubeSubframeHistogramName,
      static_cast<int>(SupervisedUserVerificationPage::Status::REAUTH_STARTED),
      2);

  // Sign in a supervised user, which completes re-authentication.
  // This should close the sign-in tabs.
  supervision_mixin_.SignIn(
      supervised_user::SupervisionMixin::SignInMode::kSupervised);
  ASSERT_TRUE(base::test::RunUntil([&]() { return GetTabCount() == 1; }));

  // TODO(https://crbug.com/365531704): Wait until the re-auth subframe
  // interstitials are no longer displayed. Only then check for the
  // re-authentication completion histograms.

  // UKM should not be recorded for the subframe interstitial.
  EXPECT_EQ(GetReauthInterstitialUKMTotalCount(), 0);
}

// Accepts a net::test_server::HttpRequest and checks if the google
// api key is present in the headers.
MATCHER(ContainsGoogleApiKey, "") {
  return base::Contains(arg.headers, "X-Goog-Api-Key");
}

// Tests that when the user doesn't have a valid access token the request is
// sent with an api key and not an access token (i.e an anonymous request).
// TODO(https://crbug.com/385450025): Flaky on Win ASAN.
#if BUILDFLAG(IS_WIN) && defined(ADDRESS_SANITIZER)
#define MAYBE_TestPendingStateRequestHasGoogleApiInHeader \
  DISABLED_TestPendingStateRequestHasGoogleApiInHeader
#else
#define MAYBE_TestPendingStateRequestHasGoogleApiInHeader \
  TestPendingStateRequestHasGoogleApiInHeader
#endif
IN_PROC_BROWSER_TEST_F(SupervisedUserPendingStateNavigationTest,
                       MAYBE_TestPendingStateRequestHasGoogleApiInHeader) {
  // TODO(crbug.com/365529863): Move the methods SetAutomaticIssueOfAccessTokens
  // and WaitForAccessTokenRequestIfNecessaryAndRespondWithError to
  // supervisionMixin::SetPendingStateForPrimaryAccount.
  supervision_mixin_.GetIdentityTestEnvironment()
      ->SetAutomaticIssueOfAccessTokens(false);
  supervision_mixin_.SetPendingStateForPrimaryAccount();
  // Invalidates any pending access token requests.
  supervision_mixin_.GetIdentityTestEnvironment()
      ->WaitForAccessTokenRequestIfNecessaryAndRespondWithError(
          supervision_mixin_.GetIdentityTestEnvironment()
              ->identity_manager()
              ->GetPrimaryAccountId(signin::ConsentLevel::kSignin),
          GoogleServiceAuthError(
              GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS));
  kids_management_api_mock().AllowSubsequentClassifyUrl();

  ASSERT_TRUE(
      supervision_mixin_.GetIdentityTestEnvironment()
          ->identity_manager()
          ->HasAccountWithRefreshTokenInPersistentErrorState(
              supervision_mixin_.GetIdentityTestEnvironment()
                  ->identity_manager()
                  ->GetPrimaryAccountId(signin::ConsentLevel::kSignin)));

  EXPECT_CALL(kids_management_api_mock().classify_url_mock(),
              ClassifyUrl(ContainsGoogleApiKey()))
      .Times(1);

  content::TestNavigationObserver observer(contents());
  observer.set_expected_initial_url(GURL("https://example.com/"));

  contents()->GetController().LoadURLWithParams(
      content::NavigationController::LoadURLParams(
          GURL("https://example.com/")));

  // Any pending access token requests should respond with an error since the
  // access token is invalidated.
  supervision_mixin_.GetIdentityTestEnvironment()
      ->WaitForAccessTokenRequestIfNecessaryAndRespondWithError(
          supervision_mixin_.GetIdentityTestEnvironment()
              ->identity_manager()
              ->GetPrimaryAccountId(signin::ConsentLevel::kSignin),
          GoogleServiceAuthError(
              GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS));

  ASSERT_TRUE(WaitForRenderFrameReady(contents()->GetPrimaryMainFrame()));

  observer.Wait();
}

}  // namespace