File: glic_user_status_browsertest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (761 lines) | stat: -rw-r--r-- 29,863 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
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/json/json_writer.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/time.h"
#include "chrome/browser/enterprise/browser_management/management_service_factory.h"
#include "chrome/browser/glic/glic_enabling.h"
#include "chrome/browser/glic/glic_keyed_service.h"
#include "chrome/browser/glic/glic_keyed_service_factory.h"
#include "chrome/browser/glic/glic_pref_names.h"
#include "chrome/browser/glic/glic_user_status_code.h"
#include "chrome/browser/glic/glic_user_status_fetcher.h"
#include "chrome/browser/glic/test_support/glic_test_environment.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/chrome_signin_client_factory.h"
#include "chrome/browser/signin/chrome_signin_client_test_util.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/signin/identity_test_environment_profile_adaptor.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_profile.h"
#include "components/policy/core/common/management/scoped_management_service_override_for_testing.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/consent_level.h"
#include "components/signin/public/identity_manager/account_capabilities_test_mutator.h"
#include "components/signin/public/identity_manager/account_info.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "content/public/test/browser_test.h"
#include "google_apis/common/api_error_codes.h"
#include "net/base/net_errors.h"
#include "net/dns/mock_host_resolver.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/network/test/test_utils.h"
#include "url/gurl.h"

namespace glic {

namespace {
const char kGlicUserStatusRelativeTestUrl[] = "/userstatus";

// Simple wrapper to serves as a POD for the test accounts.
struct TestAccount {
  const std::string email;
  const std::string host_domain;
};

TestAccount nonEnterpriseAccount = {"foo@testbar.com", ""};
TestAccount enterpriseAccount = {"foo@testenterprise.com",
                                 "testenterprise.com"};
TestAccount googleDotComAccount = {"foo@google.com", "google.com"};

class GlicUserStatusBrowserTest : public InProcessBrowserTest {
 protected:
  GlicUserStatusBrowserTest() {
    feature_list_.InitWithFeaturesAndParameters(
        {{features::kGlic, {}},
         {features::kTabstripComboButton, {}},
         {features::kGlicRollout, {}},
         {features::kGlicUserStatusCheck,
          {{features::kGlicUserStatusRequestDelay.name, "200ms"},
           {features::kGlicUserStatusRequestDelayJitter.name, "0"}}}},
        {/* disabled_features */});

    RegisterGeminiSettingsPrefs(pref_service_.registry());
  }

  void SetUpBrowserContextKeyedServices(
      content::BrowserContext* context) override {
    IdentityTestEnvironmentProfileAdaptor::
        SetIdentityTestEnvironmentFactoriesOnBrowserContext(context);

    ChromeSigninClientFactory::GetInstance()->SetTestingFactory(
        context, base::BindRepeating(&BuildChromeSigninClientWithURLLoader,
                                     &test_url_loader_factory_));
  }
  void SetUpOnMainThread() override {
    InProcessBrowserTest::SetUpOnMainThread();

    adaptor_ =
        std::make_unique<IdentityTestEnvironmentProfileAdaptor>(profile());

    identity_test_env_ = adaptor_->identity_test_env();
    identity_test_env_->SetTestURLLoaderFactory(&test_url_loader_factory_);
    identity_manager_ = IdentityManagerFactory::GetForProfile(profile());

    embedded_test_server()->AddDefaultHandlers(GetChromeTestDataDir());
    host_resolver()->AddRule("*", "127.0.0.1");

    profile()->GetPrefs()->SetInteger(
        ::prefs::kGeminiSettings,
        static_cast<int>(glic::prefs::SettingsPolicyState::kEnabled));
  }

  void TearDownOnMainThread() override {
    ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
    identity_manager_ = nullptr;
    identity_test_env_ = nullptr;
    adaptor_.reset();

    InProcessBrowserTest::TearDownOnMainThread();
  }

  void RegisterUserStatusHandler(net::HttpStatusCode status_code,
                                 std::string response_body) {
    embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
        [=](const net::test_server::HttpRequest& request)
            -> std::unique_ptr<net::test_server::HttpResponse> {
          if (request.relative_url != kGlicUserStatusRelativeTestUrl) {
            return nullptr;
          }
          auto response =
              std::make_unique<net::test_server::BasicHttpResponse>();

          response->set_code(status_code);
          response->set_content(response_body);
          response->set_content_type("application/json");

          return response;
        }));
  }
  // Simulates user signing in and getting a refresh token.
  void SimulatePrimaryAccountChangedSignIn(TestAccount* account) {
    identity_test_env_->SetAutomaticIssueOfAccessTokens(true);

    AccountInfo account_info = identity_test_env_->MakePrimaryAccountAvailable(
        account->email, signin::ConsentLevel::kSync);

    AccountCapabilitiesTestMutator mutator(&account_info.capabilities);
    mutator.set_can_use_model_execution_features(true);
    identity_test_env_->UpdateAccountInfoForAccount(account_info);

    SimulateSuccessfulFetchOfAccountInfo(account, &account_info);
  }

  void SimulateSuccessfulFetchOfAccountInfo(const TestAccount* test_account,
                                            const AccountInfo* account_info) {
    identity_test_env_->SimulateSuccessfulFetchOfAccountInfo(
        account_info->account_id, account_info->email, account_info->gaia,
        test_account->host_domain,
        base::StrCat({"full_name-", test_account->email}),
        base::StrCat({"given_name-", test_account->email}),
        base::StrCat({"local-", test_account->email}),
        base::StrCat({"full_name-", test_account->email}));
  }

  void SetGlicUserStatusUrlForTest() {
    GlicKeyedServiceFactory::GetGlicKeyedService(browser()->profile())
        ->enabling()
        .SetGlicUserStatusUrlForTest(
            embedded_test_server()->GetURL(kGlicUserStatusRelativeTestUrl));
  }

  // Gets the user status code from the pref.
  std::optional<UserStatusCode> GetCachedStatusCode() {
    PrefService* prefs = profile()->GetPrefs();
    const base::Value::Dict& dict = prefs->GetDict(prefs::kGlicUserStatus);
    if (!dict.FindInt(kUserStatus)) {
      return std::nullopt;
    }
    return static_cast<UserStatusCode>(dict.FindInt(kUserStatus).value());
  }

  std::string GetGaiaIdHashBase64() {
    auto* identity_manager = IdentityManagerFactory::GetForProfile(profile());
    CoreAccountInfo primary_account =
        identity_manager->GetPrimaryAccountInfo(signin::ConsentLevel::kSignin);
    if (primary_account.IsEmpty()) {
      return "";
    }
    return signin::GaiaIdHash::FromGaiaId(primary_account.gaia).ToBase64();
  }

  void SetGlicUserStatus(UserStatusCode code) {
    base::Value::Dict data;
    data.Set(kAccountId, GetGaiaIdHashBase64());
    data.Set(kUserStatus, code);
    data.Set(kUpdatedAt, base::Time::Now().InSecondsFSinceUnixEpoch());
    profile()->GetPrefs()->SetDict(glic::prefs::kGlicUserStatus,
                                   std::move(data));
  }

  // Gets the full user status details from prefs.
  std::optional<base::Value::Dict> GetCachedStatusDict() {
    PrefService* prefs = profile()->GetPrefs();
    const base::Value::Dict& dict = prefs->GetDict(prefs::kGlicUserStatus);
    if (dict.empty()) {
      return std::nullopt;
    }
    return dict.Clone();
  }

  bool IsGlicEnabled() { return GlicEnabling::IsEnabledForProfile(profile()); }

  Profile* profile() { return browser()->profile(); }

  base::test::ScopedFeatureList feature_list_;
  sync_preferences::TestingPrefServiceSyncable pref_service_;
  std::unique_ptr<IdentityTestEnvironmentProfileAdaptor> adaptor_;
  raw_ptr<signin::IdentityManager> identity_manager_;
  raw_ptr<signin::IdentityTestEnvironment> identity_test_env_;
  network::TestURLLoaderFactory test_url_loader_factory_;
};

IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTest, EnterpriseSignInEnabled) {
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  RegisterUserStatusHandler(
      net::HTTP_OK,
      R"({"isGlicEnabled": true, "isAccessDeniedByAdmin": false})");
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  // Verify Prefs
  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));

  std::optional<base::Value::Dict> cached_dict = GetCachedStatusDict();
  EXPECT_EQ(cached_dict->FindInt(kUserStatus).value_or(-1),
            UserStatusCode::ENABLED);
  EXPECT_EQ(*cached_dict->FindString(kAccountId), GetGaiaIdHashBase64());
  EXPECT_TRUE(cached_dict->FindDouble(kUpdatedAt).has_value());

  // Verify GlicEnabling status (assuming other criteria met)
  EXPECT_TRUE(IsGlicEnabled());
}

IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTest,
                       EnterpriseSignInEnabledGeminiSettings) {
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  // Verify request is sent by the non-existence of the Prefs initially and the
  // existence of it after sign-in simulation.
  ASSERT_FALSE(GetCachedStatusDict().has_value());

  bool request_received = false;
  embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
      [=, &request_received](const net::test_server::HttpRequest& request)
          -> std::unique_ptr<net::test_server::HttpResponse> {
        if (request.relative_url != kGlicUserStatusRelativeTestUrl) {
          return nullptr;
        }
        request_received = true;
        auto response = std::make_unique<net::test_server::BasicHttpResponse>();

        response->set_code(net::HTTP_OK);
        response->set_content(
            R"({"isGlicEnabled": true, "isAccessDeniedByAdmin": false})");
        response->set_content_type("application/json");

        return response;
      }));
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  // Verify request is sent by the existence of the Prefs and request handler is
  // inovked.
  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));
  ASSERT_TRUE(request_received);

  // Sign out to clear the Prefs and reset request_received.
  identity_test_env_->ClearPrimaryAccount();
  ASSERT_TRUE(base::test::RunUntil([&]() {
    return profile()->GetPrefs()->GetDict(prefs::kGlicUserStatus).empty();
  }));
  request_received = false;

  // Setting kGeminiSettings to disabled so that no RPC would be sent.
  profile()->GetPrefs()->SetInteger(
      ::prefs::kGeminiSettings,
      static_cast<int>(glic::prefs::SettingsPolicyState::kDisabled));

  // Sign in again and wait for a while.
  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  // Verifying the absence of a request by verifying the absence for a time
  // period longer than the polling interval.
  base::RunLoop run_loop;
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE, run_loop.QuitClosure(), base::Milliseconds(300));
  run_loop.Run();

  // Verify no request is sent.
  EXPECT_FALSE(request_received);
  ASSERT_FALSE(GetCachedStatusDict().has_value());

  // Sign out.
  identity_test_env_->ClearPrimaryAccount();

  // Make the account enterprise again by setting kGeminiSettings to enabled.
  profile()->GetPrefs()->SetInteger(
      ::prefs::kGeminiSettings,
      static_cast<int>(glic::prefs::SettingsPolicyState::kEnabled));

  // Sign in again.
  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  // Verify request is sent again by the existence of the Prefs and request
  // handler is inovked.
  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));
  ASSERT_TRUE(request_received);
}

IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTest,
                       EnterpriseGeminiSettingsChangeNoSignedOut) {
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  // Verify request is sent by the non-existence of the Prefs initially and the
  // existence of it after sign-in simulation.
  ASSERT_FALSE(GetCachedStatusDict().has_value());

  bool request_received = false;
  embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
      [=, &request_received](const net::test_server::HttpRequest& request)
          -> std::unique_ptr<net::test_server::HttpResponse> {
        if (request.relative_url != kGlicUserStatusRelativeTestUrl) {
          return nullptr;
        }
        request_received = true;
        auto response = std::make_unique<net::test_server::BasicHttpResponse>();

        response->set_code(net::HTTP_OK);
        response->set_content(
            R"({"isGlicEnabled": true, "isAccessDeniedByAdmin": false})");
        response->set_content_type("application/json");

        return response;
      }));
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  // Verify request is sent by the existence of the Prefs and request handler is
  // inovked.
  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));
  ASSERT_TRUE(request_received);

  // Setting kGeminiSettings to disabled so that no RPC would be sent.
  request_received = false;
  profile()->GetPrefs()->SetInteger(
      ::prefs::kGeminiSettings,
      static_cast<int>(glic::prefs::SettingsPolicyState::kDisabled));

  // Verifying the absence of a request by verifying the absence for a time
  // period longer than the polling interval.
  base::RunLoop run_loop;
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE, run_loop.QuitClosure(), base::Milliseconds(300));
  run_loop.Run();

  // Verify no request is sent.
  EXPECT_FALSE(request_received);

  // Make the account enterprise again by setting kGeminiSettings to enabled.
  profile()->GetPrefs()->SetInteger(
      ::prefs::kGeminiSettings,
      static_cast<int>(glic::prefs::SettingsPolicyState::kEnabled));

  // Verify request handler is inovked.
  ASSERT_TRUE(base::test::RunUntil([&]() { return request_received; }));
}

IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTest,
                       EnterpriseSignInDisabledByAdmin) {
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  RegisterUserStatusHandler(
      net::HTTP_OK,
      R"({"isGlicEnabled": false, "isAccessDeniedByAdmin": true})");
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  // Verify Prefs
  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));

  std::optional<base::Value::Dict> cached_dict = GetCachedStatusDict();
  EXPECT_EQ(cached_dict->FindInt(kUserStatus).value_or(-1),
            UserStatusCode::DISABLED_BY_ADMIN);
  EXPECT_EQ(*cached_dict->FindString(kAccountId), GetGaiaIdHashBase64());

  // Verify GlicEnabling status - Should be disabled by this status
  EXPECT_FALSE(IsGlicEnabled());
}

IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTest,
                       EnterpriseSignInDisabledOther) {
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  RegisterUserStatusHandler(
      net::HTTP_OK,
      R"({"isGlicEnabled": false, "isAccessDeniedByAdmin": false})");
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  // Verify Prefs
  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));

  std::optional<base::Value::Dict> cached_dict = GetCachedStatusDict();
  EXPECT_EQ(cached_dict->FindInt(kUserStatus).value_or(-1),
            UserStatusCode::DISABLED_OTHER);
  EXPECT_EQ(*cached_dict->FindString(kAccountId), GetGaiaIdHashBase64());

  // Verify GlicEnabling status - Should be disabled by this status
  EXPECT_FALSE(IsGlicEnabled());
}

IN_PROC_BROWSER_TEST_F(
    GlicUserStatusBrowserTest,
    EnterpriseSignInDisabledButManagedStatusNotImmediatelyKnown) {
  RegisterUserStatusHandler(
      net::HTTP_OK,
      R"({"isGlicEnabled": false, "isAccessDeniedByAdmin": true})");
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  identity_test_env_->SetAutomaticIssueOfAccessTokens(true);
  AccountInfo account_info = identity_test_env_->MakePrimaryAccountAvailable(
      enterpriseAccount.email, signin::ConsentLevel::kSync);
  AccountCapabilitiesTestMutator mutator(&account_info.capabilities);
  mutator.set_can_use_model_execution_features(true);
  identity_test_env_->UpdateAccountInfoForAccount(account_info);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(GetCachedStatusDict().has_value());

  // Only now, after the fetch would have happened, does the information about
  // the account's managed status become available. This should cause an RPC
  // to be sent.
  SimulateSuccessfulFetchOfAccountInfo(&enterpriseAccount, &account_info);
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  // Verify Prefs
  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));

  std::optional<base::Value::Dict> cached_dict = GetCachedStatusDict();
  EXPECT_EQ(cached_dict->FindInt(kUserStatus).value_or(-1),
            UserStatusCode::DISABLED_BY_ADMIN);
  EXPECT_EQ(*cached_dict->FindString(kAccountId), GetGaiaIdHashBase64());

  // Verify GlicEnabling status - Should be disabled by this status
  EXPECT_FALSE(IsGlicEnabled());
}

// It happens that google.com accounts are always considered enterprise
// accounts, even before extended account info is available.
IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTest,
                       EnterpriseSignInDisabledByAdminGoogleDotCom) {
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  RegisterUserStatusHandler(
      net::HTTP_OK,
      R"({"isGlicEnabled": false, "isAccessDeniedByAdmin": true})");
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&googleDotComAccount);

  // Verify Prefs
  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));

  std::optional<base::Value::Dict> cached_dict = GetCachedStatusDict();
  EXPECT_EQ(cached_dict->FindInt(kUserStatus).value_or(-1),
            UserStatusCode::DISABLED_BY_ADMIN);
  EXPECT_EQ(*cached_dict->FindString(kAccountId), GetGaiaIdHashBase64());

  // Verify GlicEnabling status - Should be disabled by this status
  EXPECT_FALSE(IsGlicEnabled());
}

// This ensures that the check using the policy management service still works,
// until/unless we need to switch back to it.
class GlicUserStatusBrowserTestWithPolicyManagementService
    : public GlicUserStatusBrowserTest {
 protected:
  GlicUserStatusBrowserTestWithPolicyManagementService() {
    scoped_feature_list_.InitAndEnableFeatureWithParameters(
        features::kGlicUserStatusCheck,
        {{features::kGlicUserStatusEnterpriseCheckStrategy.name, "policy"}});
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTestWithPolicyManagementService,
                       EnterpriseSignInDisabledByAdmin) {
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  RegisterUserStatusHandler(
      net::HTTP_OK,
      R"({"isGlicEnabled": false, "isAccessDeniedByAdmin": true})");
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  // Verify Prefs
  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));

  std::optional<base::Value::Dict> cached_dict = GetCachedStatusDict();
  EXPECT_EQ(cached_dict->FindInt(kUserStatus).value_or(-1),
            UserStatusCode::DISABLED_BY_ADMIN);
  EXPECT_EQ(*cached_dict->FindString(kAccountId), GetGaiaIdHashBase64());

  // Verify GlicEnabling status - Should be disabled by this status
  EXPECT_FALSE(IsGlicEnabled());
}

IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTest,
                       EnterpriseSignInServerUnavailableNoStoredResult) {
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  RegisterUserStatusHandler(
      net::HTTP_NOT_FOUND,
      R"({"isGlicEnabled": true, "isAccessDeniedByAdmin": false})");
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  // Verify that when the user status code is SERVER_UNAVAILABLE, the glic user
  // status result is not stored.
  std::optional<base::Value::Dict> cached_dict = GetCachedStatusDict();
  EXPECT_FALSE(cached_dict.has_value());

  EXPECT_TRUE(IsGlicEnabled());
}

IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTest,
                       EnterpriseSignInServerUnavailableHasStoredResult) {
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  RegisterUserStatusHandler(
      net::HTTP_NOT_FOUND,
      R"({"isGlicEnabled": true, "isAccessDeniedByAdmin": false})");
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  auto user_status_code = UserStatusCode::DISABLED_BY_ADMIN;
  SetGlicUserStatus(user_status_code);
  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));

  // Verify that when the user status code is SERVER_UNAVAILABLE, the previous
  // stored pref value is not overwritten.
  std::optional<base::Value::Dict> cached_dict = GetCachedStatusDict();
  EXPECT_TRUE(cached_dict.has_value());
  EXPECT_EQ(cached_dict->FindInt(kUserStatus).value_or(-1), user_status_code);

  EXPECT_FALSE(IsGlicEnabled());
}

IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTest, EnterpriseSignOut) {
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  // Sign in and set user status to enabled.
  RegisterUserStatusHandler(
      net::HTTP_OK,
      R"({"isGlicEnabled": true, "isAccessDeniedByAdmin": false})");
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));

  ASSERT_TRUE(IsGlicEnabled());

  // Sign out.
  identity_test_env_->ClearPrimaryAccount();

  ASSERT_TRUE(base::test::RunUntil([&]() {
    return profile()->GetPrefs()->GetDict(prefs::kGlicUserStatus).empty();
  }));

  // This is false because the IsNonEnterpriseEnabled() will return false if no
  // account is signed in. The UserStatusCheck is true when pref is cleared.
  EXPECT_FALSE(IsGlicEnabled());
}

IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTest, NonEnterpriseSignIn) {
  bool request_received = false;
  embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
      [=, &request_received](const net::test_server::HttpRequest& request)
          -> std::unique_ptr<net::test_server::HttpResponse> {
        if (request.relative_url != kGlicUserStatusRelativeTestUrl) {
          return nullptr;
        }
        request_received = true;
        auto response = std::make_unique<net::test_server::BasicHttpResponse>();

        response->set_code(net::HTTP_OK);
        response->set_content(
            R"({"isGlicEnabled": true, "isAccessDeniedByAdmin": false})");
        response->set_content_type("application/json");

        return response;
      }));

  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&nonEnterpriseAccount);

  // wait for a while.
  base::RunLoop run_loop;
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE, run_loop.QuitClosure(), base::Milliseconds(300));
  run_loop.Run();

  ASSERT_FALSE(request_received);
  ASSERT_FALSE(GetCachedStatusDict().has_value());

  ASSERT_TRUE(IsGlicEnabled());
}

IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTest, EnterpriseDataProtection) {
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  RegisterUserStatusHandler(
      net::HTTP_OK,
      R"({"isGlicEnabled": true, "isAccessDeniedByAdmin": false,
       "isEnterpriseAccountDataProtected": true })");
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));

  // Verify the isEnterpriseAccountDataProtected field.
  EXPECT_EQ(profile()
                ->GetPrefs()
                ->GetDict(prefs::kGlicUserStatus)
                .FindBool(kIsEnterpriseAccountDataProtected),
            true);
}

IN_PROC_BROWSER_TEST_F(GlicUserStatusBrowserTest,
                       EnterpriseDataProtectionMissingInServerResponse) {
  policy::ScopedManagementServiceOverrideForTesting platform_management(
      policy::ManagementServiceFactory::GetForProfile(profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  RegisterUserStatusHandler(
      net::HTTP_OK,
      R"({"isGlicEnabled": true, "isAccessDeniedByAdmin": false})");
  net::test_server::EmbeddedTestServerHandle test_server_handle;
  ASSERT_TRUE(test_server_handle =
                  embedded_test_server()->StartAndReturnHandle());

  SetGlicUserStatusUrlForTest();

  SimulatePrimaryAccountChangedSignIn(&enterpriseAccount);

  ASSERT_TRUE(base::test::RunUntil(
      [&]() { return GetCachedStatusDict().has_value(); }));

  // Verify the isEnterpriseAccountDataProtected field.
  EXPECT_EQ(profile()
                ->GetPrefs()
                ->GetDict(prefs::kGlicUserStatus)
                .FindBool(kIsEnterpriseAccountDataProtected),
            false);
}

}  // namespace
}  // namespace glic