File: update_service_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 (747 lines) | stat: -rw-r--r-- 31,003 bytes parent folder | download | duplicates (5)
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>
#include <optional>

#include "base/check_deref.h"
#include "base/command_line.h"
#include "base/json/json_reader.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/task_environment.h"
#include "base/values.h"
#include "chrome/browser/browser_features.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/content_verifier_test_utils.h"
#include "chrome/browser/extensions/extension_management_test_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/external_provider_manager.h"
#include "chrome/browser/extensions/updater/chrome_update_client_config.h"
#include "chrome/browser/extensions/updater/extension_update_client_base_browsertest.h"
#include "chrome/browser/extensions/updater/extension_updater.h"
#include "chrome/browser/profiles/keep_alive/profile_keep_alive_types.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_switches.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/update_client/net/url_loader_post_interceptor.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "extensions/browser/content_verifier/content_verifier.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/external_install_info.h"
#include "extensions/browser/mock_external_provider.h"
#include "extensions/browser/test_extension_registry_observer.h"
#include "extensions/browser/updater/extension_downloader.h"
#include "extensions/browser/updater/manifest_fetch_data.h"
#include "extensions/common/extension_updater_uma.h"
#include "extensions/common/extension_urls.h"
#include "extensions/common/mojom/manifest.mojom-shared.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "chromeos/ash/components/install_attributes/stub_install_attributes.h"
#endif

using extensions::mojom::ManifestLocation;

namespace extensions {

namespace {

const char kExtensionId[] = "aohghmighlieiainnegkcijnfilokake";

}  // namespace

class UpdateServiceTest : public ExtensionUpdateClientBaseTest {
 public:
  UpdateServiceTest() = default;
  ~UpdateServiceTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    ExtensionUpdateClientBaseTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(
        switches::kExtensionContentVerification,
        switches::kExtensionContentVerificationEnforce);
  }

  bool ShouldEnableContentVerification() override { return true; }

  void ExpectProfileKeepAlive(bool expected) {
    if (!base::FeatureList::IsEnabled(features::kDestroyProfileOnBrowserClose))
      return;
    EXPECT_EQ(expected,
              g_browser_process->profile_manager()->HasKeepAliveForTesting(
                  profile(), ProfileKeepAliveOrigin::kExtensionUpdater));
  }

  std::optional<base::Value::Dict> GetRequest(size_t index) {
    const std::vector<
        update_client::URLLoaderPostInterceptor::InterceptedRequest>& requests =
        update_interceptor_->GetRequests();
    if (requests.size() < index) {
      return std::nullopt;
    }

    const std::string update_request = std::get<0>(requests[index]);
    std::optional<base::Value> root = base::JSONReader::Read(update_request);
    if (!root) {
      return std::nullopt;
    }

    return std::move(root.value()).TakeDict();
  }

  base::Value::Dict GetApp(const base::Value::Dict& root, size_t index) {
    const base::Value::List* app_list =
        root.FindDict("request")->FindList("apps");
    EXPECT_GT(app_list->size(), index);
    return CHECK_DEREF(app_list)[index].Clone().TakeDict();
  }

  base::Value::Dict GetFirstApp(const base::Value::Dict& root) {
    return GetApp(root, 0);
  }

  ExtensionUpdater* extension_updater() {
    return ExtensionUpdater::Get(profile());
  }
};

IN_PROC_BROWSER_TEST_F(UpdateServiceTest, NoUpdate) {
  // Verify that UpdateService runs correctly when there's no update.
  base::ScopedAllowBlockingForTesting allow_io;
  base::HistogramTester histogram_tester;

  // Mock a no-update response.
  ASSERT_TRUE(update_interceptor_->ExpectRequest(
      std::make_unique<update_client::PartialMatch>(R"("updatecheck":{)"),
      test_data_dir_.AppendASCII("updater/updatecheck_reply_noupdate_1.json")));

  const base::FilePath crx_path = test_data_dir_.AppendASCII("updater/v1.crx");
  const Extension* extension =
      InstallExtension(crx_path, 1, ManifestLocation::kExternalPolicyDownload);
  ASSERT_TRUE(extension);
  EXPECT_EQ(kExtensionId, extension->id());

  extensions::ExtensionUpdater::CheckParams params;
  params.ids = {kExtensionId};
  extension_updater()->CheckNow(std::move(params));

  // UpdateService should emit a not-updated event.
  EXPECT_EQ(update_client::ComponentState::kUpToDate,
            WaitOnComponentUpdaterCompleteEvent(kExtensionId));

  ASSERT_EQ(1, update_interceptor_->GetCount())
      << update_interceptor_->GetRequestsAsString();

  // No update, thus no download nor ping activities.
  EXPECT_EQ(0, get_interceptor_count());
  EXPECT_EQ(0, ping_interceptor_->GetCount())
      << ping_interceptor_->GetRequestsAsString();

  const std::optional<base::Value::Dict> root = GetRequest(0);
  ASSERT_TRUE(root);
  const base::Value::Dict& app = GetFirstApp(root.value());
  EXPECT_EQ(kExtensionId, CHECK_DEREF(app.FindString("appid")));
  EXPECT_EQ("0.10", CHECK_DEREF(app.FindString("version")));
  EXPECT_TRUE(app.FindBool("enabled").value_or(false));
}

IN_PROC_BROWSER_TEST_F(UpdateServiceTest, UpdateCheckError) {
  // Verify that UpdateService works correctly when there's an error in the
  // update check phase.
  base::ScopedAllowBlockingForTesting allow_io;
  base::HistogramTester histogram_tester;

  // Mock an update check error.
    ASSERT_TRUE(update_interceptor_->ExpectRequest(
        std::make_unique<update_client::PartialMatch>(R"("updatecheck":{)"),
        net::HTTP_FORBIDDEN));

  const base::FilePath crx_path = test_data_dir_.AppendASCII("updater/v1.crx");
  const Extension* extension =
      InstallExtension(crx_path, 1, ManifestLocation::kExternalPolicyDownload);
  ASSERT_TRUE(extension);
  EXPECT_EQ(kExtensionId, extension->id());

  extensions::ExtensionUpdater::CheckParams params;
  params.ids = {kExtensionId};
  extension_updater()->CheckNow(std::move(params));

  // UpdateService should emit an error update event.
  EXPECT_EQ(update_client::ComponentState::kUpdateError,
            WaitOnComponentUpdaterCompleteEvent(kExtensionId));

  ASSERT_EQ(1, update_interceptor_->GetCount())
      << update_interceptor_->GetRequestsAsString();

  // Error, thus no download nor ping activities.
  EXPECT_EQ(0, get_interceptor_count());
  EXPECT_EQ(0, ping_interceptor_->GetCount())
      << ping_interceptor_->GetRequestsAsString();

  const std::optional<base::Value::Dict> root = GetRequest(0);
  ASSERT_TRUE(root);
  const base::Value::Dict& app = GetFirstApp(root.value());
  EXPECT_EQ(kExtensionId, CHECK_DEREF(app.FindString("appid")));
  EXPECT_EQ("0.10", CHECK_DEREF(app.FindString("version")));
  EXPECT_TRUE(app.FindBool("enabled").value_or(false));
}

IN_PROC_BROWSER_TEST_F(UpdateServiceTest, TwoUpdateCheckErrors) {
  // Verify that the UMA counters are emitted properly when there are 2 update
  // checks with different number of extensions, both of which result in errors.
  base::ScopedAllowBlockingForTesting allow_io;
  base::HistogramTester histogram_tester;

  // Mock update check errors.
    ASSERT_TRUE(update_interceptor_->ExpectRequest(
        std::make_unique<update_client::PartialMatch>(R"("updatecheck":{)"),
        net::HTTP_NOT_MODIFIED));
    ASSERT_TRUE(update_interceptor_->ExpectRequest(
        std::make_unique<update_client::PartialMatch>(R"("updatecheck":{)"),
        net::HTTP_USE_PROXY));

  const base::FilePath crx_path1 = test_data_dir_.AppendASCII("updater/v1.crx");
  const base::FilePath crx_path2 = test_data_dir_.AppendASCII("updater/v2.crx");
  const Extension* extension1 =
      InstallExtension(crx_path1, 1, ManifestLocation::kExternalPolicyDownload);
  const Extension* extension2 =
      InstallExtension(crx_path2, 1, ManifestLocation::kExternalPolicyDownload);
  ASSERT_TRUE(extension1 && extension2);

  base::RunLoop run_loop1;
  extensions::ExtensionUpdater::CheckParams params1;
  params1.ids = {extension1->id(), extension2->id()};
  params1.callback = run_loop1.QuitClosure();
  extension_updater()->CheckNow(std::move(params1));
  run_loop1.Run();

  base::RunLoop run_loop2;
  extensions::ExtensionUpdater::CheckParams params2;
  params2.ids = {extension1->id()};
  params2.callback = run_loop2.QuitClosure();
  extension_updater()->CheckNow(std::move(params2));
  run_loop2.Run();

  ASSERT_EQ(2, update_interceptor_->GetCount())
      << update_interceptor_->GetRequestsAsString();

  // Error, thus no download nor ping activities.
  EXPECT_EQ(0, get_interceptor_count());
  EXPECT_EQ(0, ping_interceptor_->GetCount())
      << ping_interceptor_->GetRequestsAsString();
}

IN_PROC_BROWSER_TEST_F(UpdateServiceTest, SuccessfulUpdate) {
  base::ScopedAllowBlockingForTesting allow_io;
  base::HistogramTester histogram_tester;

  // Mock an update response.
    const base::FilePath update_response =
        test_data_dir_.AppendASCII("updater/updatecheck_reply_update_1.json");
    const base::FilePath ping_response =
        test_data_dir_.AppendASCII("updater/ping_reply_1.json");
    ASSERT_TRUE(update_interceptor_->ExpectRequest(
        std::make_unique<update_client::PartialMatch>(R"("updatecheck":{)"),
        update_response));
    ASSERT_TRUE(ping_interceptor_->ExpectRequest(
        std::make_unique<update_client::PartialMatch>(R"("eventtype":)"),
        ping_response));

  const base::FilePath crx_path = test_data_dir_.AppendASCII("updater/v1.crx");
  set_interceptor_hook(base::BindLambdaForTesting(
      [&](content::URLLoaderInterceptor::RequestParams* params) {
        if (params->url_request.url.path() != "/download/v1.crx")
          return false;

        content::URLLoaderInterceptor::WriteResponse(crx_path,
                                                     params->client.get());
        return true;
      }));

  ExpectProfileKeepAlive(false);

  const Extension* extension =
      InstallExtension(crx_path, 1, ManifestLocation::kExternalPolicyDownload);
  ASSERT_TRUE(extension);
  EXPECT_EQ(kExtensionId, extension->id());

  base::RunLoop run_loop;

  extensions::ExtensionUpdater::CheckParams params;
  params.ids = {kExtensionId};
  params.callback = run_loop.QuitClosure();
  extension_updater()->CheckNow(std::move(params));

  ExpectProfileKeepAlive(true);

  EXPECT_EQ(update_client::ComponentState::kUpdated,
            WaitOnComponentUpdaterCompleteEvent(kExtensionId));

  run_loop.Run();

  ASSERT_EQ(1, update_interceptor_->GetCount())
      << update_interceptor_->GetRequestsAsString();
  EXPECT_EQ(1, get_interceptor_count());

  const std::optional<base::Value::Dict> root = GetRequest(0);
  ASSERT_TRUE(root);
  const base::Value::Dict& app = GetFirstApp(root.value());
  EXPECT_EQ(kExtensionId, CHECK_DEREF(app.FindString("appid")));
  EXPECT_EQ("0.10", CHECK_DEREF(app.FindString("version")));
  EXPECT_TRUE(app.FindBool("enabled").value_or(false));
}

IN_PROC_BROWSER_TEST_F(UpdateServiceTest, PolicyCorrupted) {
  base::ScopedAllowBlockingForTesting allow_io;

  ExtensionSystem* system = ExtensionSystem::Get(profile());
  const base::FilePath update_response =
      test_data_dir_.AppendASCII("updater/updatecheck_reply_update_1.json");
  const base::FilePath ping_response =
      test_data_dir_.AppendASCII("updater/ping_reply_1.json");
  ASSERT_TRUE(update_interceptor_->ExpectRequest(
      std::make_unique<update_client::PartialMatch>(R"("updatecheck":{)"),
      update_response));
  ASSERT_TRUE(ping_interceptor_->ExpectRequest(
      std::make_unique<update_client::PartialMatch>(R"("eventtype":)"),
      ping_response));

  const base::FilePath crx_path = test_data_dir_.AppendASCII("updater/v1.crx");
  set_interceptor_hook(base::BindLambdaForTesting(
      [&](content::URLLoaderInterceptor::RequestParams* params) {
        if (params->url_request.url.path() != "/download/v1.crx")
          return false;

        content::URLLoaderInterceptor::WriteResponse(crx_path,
                                                     params->client.get());
        return true;
      }));

  // Setup fake policy and update check objects.
  content_verifier_test::ForceInstallProvider policy(kExtensionId);
  system->management_policy()->RegisterProvider(&policy);
  ExternalProviderManager* external_provider_manager =
      ExternalProviderManager::Get(profile());
  auto external_provider = std::make_unique<MockExternalProvider>(
      external_provider_manager, ManifestLocation::kExternalPolicyDownload);
  external_provider->UpdateOrAddExtension(
      std::make_unique<ExternalInstallInfoUpdateUrl>(
          kExtensionId, std::string() /* install_parameter */,
          extension_urls::GetWebstoreUpdateUrl(),
          ManifestLocation::kExternalPolicyDownload, 0 /* creation_flags */,
          true /* mark_acknowledged */));
  external_provider_manager->AddProviderForTesting(
      std::move(external_provider));

  const Extension* extension =
      InstallExtension(crx_path, 1, ManifestLocation::kExternalPolicyDownload);
  ASSERT_TRUE(extension);
  EXPECT_EQ(kExtensionId, extension->id());

  TestExtensionRegistryObserver registry_observer(
      ExtensionRegistry::Get(profile()), kExtensionId);
  ContentVerifier* verifier = system->content_verifier();
  verifier->VerifyFailedForTest(kExtensionId, ContentVerifyJob::HASH_MISMATCH);

  // Make sure the extension first got disabled due to corruption.
  EXPECT_TRUE(registry_observer.WaitForExtensionUnloaded());
  ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
  DisableReasonSet reasons = prefs->GetDisableReasons(kExtensionId);
  EXPECT_TRUE(reasons.contains(disable_reason::DISABLE_CORRUPTED));

  // Make sure the extension then got re-installed, and that after reinstall it
  // is no longer disabled due to corruption.
  EXPECT_EQ(update_client::ComponentState::kUpdated,
            WaitOnComponentUpdaterCompleteEvent(kExtensionId));

  reasons = prefs->GetDisableReasons(kExtensionId);
  EXPECT_FALSE(reasons.contains(disable_reason::DISABLE_CORRUPTED));

  ASSERT_EQ(1, update_interceptor_->GetCount())
      << update_interceptor_->GetRequestsAsString();
  EXPECT_EQ(1, get_interceptor_count());

  // Make sure that the update check request is formed correctly when the
  // extension is corrupted:
  // - version="0.0.0.0"
  // - installsource="reinstall"
  // - installedby="policy"
  // - enabled="0"
  // - <disabled reason="1024"/>
  const std::optional<base::Value::Dict> root = GetRequest(0);
  ASSERT_TRUE(root);
  const base::Value::Dict& app = GetFirstApp(root.value());
  EXPECT_EQ(kExtensionId, CHECK_DEREF(app.FindString("appid")));
  EXPECT_EQ("0.0.0.0", CHECK_DEREF(app.FindString("version")));
  EXPECT_EQ("reinstall", CHECK_DEREF(app.FindString("installsource")));
  EXPECT_EQ("policy", CHECK_DEREF(app.FindString("installedby")));
  EXPECT_FALSE(app.FindBool("enabled").value_or(true));
  const base::Value::Dict& disabled =
      CHECK_DEREF(app.FindList("disabled"))[0].GetDict();
  EXPECT_EQ(disable_reason::DISABLE_CORRUPTED, disabled.FindInt("reason"));
}

IN_PROC_BROWSER_TEST_F(UpdateServiceTest, UninstallExtensionWhileUpdating) {
  // This test is to verify that the extension updater engine (update client)
  // works correctly when an extension is uninstalled when the extension updater
  // is in progress.
  base::ScopedAllowBlockingForTesting allow_io;

  const base::FilePath crx_path = test_data_dir_.AppendASCII("updater/v1.crx");

  const Extension* extension =
      InstallExtension(crx_path, 1, ManifestLocation::kExternalPolicyDownload);
  ASSERT_TRUE(extension);
  EXPECT_EQ(kExtensionId, extension->id());

  base::RunLoop run_loop;

  extensions::ExtensionUpdater::CheckParams params;
  params.ids = {kExtensionId};
  params.callback = run_loop.QuitClosure();
  extension_updater()->CheckNow(std::move(params));

  // Uninstall the extension right before the message loop is executed to
  // emulate uninstalling an extension in the middle of an extension update.
  extension_registrar()->UninstallExtension(
      kExtensionId, extensions::UNINSTALL_REASON_COMPONENT_REMOVED, nullptr);

  // Update client should issue an update error event for this extension.
  ASSERT_EQ(update_client::ComponentState::kUpdateError,
            WaitOnComponentUpdaterCompleteEvent(kExtensionId));

  run_loop.Run();

  EXPECT_EQ(0, update_interceptor_->GetCount())
      << update_interceptor_->GetRequestsAsString();
  EXPECT_EQ(0, get_interceptor_count());
}

class PolicyUpdateServiceTest : public ExtensionUpdateClientBaseTest,
                                public testing::WithParamInterface<bool> {
 public:
  PolicyUpdateServiceTest() = default;
  ~PolicyUpdateServiceTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    ExtensionUpdateClientBaseTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(
        switches::kExtensionContentVerification,
        switches::kExtensionContentVerificationEnforce);
  }

  void SetUpInProcessBrowserTestFixture() override {
    ExtensionUpdateClientBaseTest::SetUpInProcessBrowserTestFixture();

    policy_provider_.SetDefaultReturns(
        /*is_initialization_complete_return=*/true,
        /*is_first_policy_load_complete_return=*/true);

    policy::BrowserPolicyConnector::SetPolicyProviderForTesting(
        &policy_provider_);
    // ExtensionManagementPolicyUpdater requires a single-threaded context to
    // call RunLoop::RunUntilIdle internally, and it isn't ready at this setup
    // moment.
    base::test::TaskEnvironment env;
    ExtensionManagementPolicyUpdater management_policy(&policy_provider_);
    management_policy.SetIndividualExtensionAutoInstalled(
        id_, extension_urls::kChromeWebstoreUpdateURL, true /* forced */);

    // The policy will force the new install of an extension, which the
    // component updater doesn't support yet. We still rely on the old updater
    // to install a new extension.
    const base::FilePath crx_path =
        test_data_dir_.AppendASCII("updater/v1.crx");
    ExtensionDownloader::set_test_delegate(&downloader_);
    downloader_.AddResponse(id_, "0.10", crx_path);
  }

  void SetUpNetworkInterceptors() override {
    ExtensionUpdateClientBaseTest::SetUpNetworkInterceptors();

    const base::FilePath crx_path =
        test_data_dir_.AppendASCII("updater/v1.crx");
    set_interceptor_hook(base::BindLambdaForTesting(
        [=](content::URLLoaderInterceptor::RequestParams* params) {
          if (params->url_request.url.path() != "/download/v1.crx")
            return false;

          content::URLLoaderInterceptor::WriteResponse(crx_path,
                                                       params->client.get());
          return true;
        }));
      const base::FilePath update_response =
          test_data_dir_.AppendASCII("updater/updatecheck_reply_update_1.json");
      const base::FilePath ping_response =
          test_data_dir_.AppendASCII("updater/ping_reply_1.json");

      ASSERT_TRUE(update_interceptor_->ExpectRequest(
          std::make_unique<update_client::PartialMatch>(R"("updatecheck":{)"),
          update_response));
      ASSERT_TRUE(update_interceptor_->ExpectRequest(
          std::make_unique<update_client::PartialMatch>(R"("updatecheck":{)"),
          update_response));
      ASSERT_TRUE(update_interceptor_->ExpectRequest(
          std::make_unique<update_client::PartialMatch>(R"("updatecheck":{)"),
          update_response));
      ASSERT_TRUE(update_interceptor_->ExpectRequest(
          std::make_unique<update_client::PartialMatch>(R"("updatecheck":{)"),
          update_response));
      ASSERT_TRUE(ping_interceptor_->ExpectRequest(
          std::make_unique<update_client::PartialMatch>(R"("eventtype":)"),
          ping_response));
      ASSERT_TRUE(ping_interceptor_->ExpectRequest(
          std::make_unique<update_client::PartialMatch>(R"("eventtype":)"),
          ping_response));
      ASSERT_TRUE(ping_interceptor_->ExpectRequest(
          std::make_unique<update_client::PartialMatch>(R"("eventtype":)"),
          ping_response));
      ASSERT_TRUE(ping_interceptor_->ExpectRequest(
          std::make_unique<update_client::PartialMatch>(R"("eventtype":)"),
          ping_response));
  }

  std::vector<GURL> GetUpdateUrls() const override {
    return {
        https_server_for_update_.GetURL("/policy-updatehost/service/update")};
  }

  std::vector<GURL> GetPingUrls() const override {
    return {https_server_for_ping_.GetURL("/policy-pinghost/service/ping")};
  }

 protected:
  std::optional<base::Value::Dict> GetRequest(size_t index) {
    const std::vector<
        update_client::URLLoaderPostInterceptor::InterceptedRequest>& requests =
        update_interceptor_->GetRequests();
    if (requests.size() < index) {
      return std::nullopt;
    }

    const std::string update_request = std::get<0>(requests[index]);
    std::optional<base::Value> root = base::JSONReader::Read(update_request);
    if (!root) {
      return std::nullopt;
    }

    return std::move(root.value()).TakeDict();
  }

  base::Value::Dict GetApp(const base::Value::Dict& root, size_t index) {
    const base::Value::List* app_list =
        root.FindDict("request")->FindList("apps");
    EXPECT_GT(app_list->size(), index);
    return CHECK_DEREF(app_list)[index].Clone().TakeDict();
  }

  base::Value::Dict GetFirstApp(const base::Value::Dict& root) {
    return GetApp(root, 0);
  }

  // The id of the extension we want to have force-installed.
  std::string id_ = "aohghmighlieiainnegkcijnfilokake";

 private:
#if BUILDFLAG(IS_CHROMEOS)
  // Set up managed environment.
  std::unique_ptr<ash::ScopedStubInstallAttributes> install_attributes_ =
      std::make_unique<ash::ScopedStubInstallAttributes>(
          ash::StubInstallAttributes::CreateCloudManaged("fake-domain.com",
                                                         "fake-id"));
#endif
  testing::NiceMock<policy::MockConfigurationPolicyProvider> policy_provider_;
  content_verifier_test::DownloaderTestDelegate downloader_;
};

// Tests that if CheckForExternalUpdates() fails, then we retry reinstalling
// corrupted policy extensions. For example: if network is unavailable,
// CheckForExternalUpdates() will fail.
IN_PROC_BROWSER_TEST_F(PolicyUpdateServiceTest, FailedUpdateRetries) {
  ExtensionRegistry* registry = ExtensionRegistry::Get(profile());
  ContentVerifier* verifier =
      ExtensionSystem::Get(profile())->content_verifier();

  // Wait for the extension to be installed by the policy we set up in
  // SetUpInProcessBrowserTestFixture.
  if (!registry->GetInstalledExtension(id_)) {
    TestExtensionRegistryObserver registry_observer(registry, id_);
    EXPECT_TRUE(registry_observer.WaitForExtensionInstalled());
  }

  content_verifier_test::DelayTracker delay_tracker;
  TestExtensionRegistryObserver registry_observer(registry, id_);
  {
    base::AutoReset<bool> disable_scope =
        ExternalProviderManager::DisableExternalUpdatesForTesting();

    verifier->VerifyFailedForTest(id_, ContentVerifyJob::HASH_MISMATCH);
    EXPECT_TRUE(registry_observer.WaitForExtensionUnloaded());

    const std::vector<base::TimeDelta>& calls = delay_tracker.calls();
    ASSERT_EQ(1u, calls.size());
    EXPECT_EQ(base::TimeDelta(), delay_tracker.calls()[0]);

    delay_tracker.Proceed();
  }

  // Update ExtensionService again without disabling external updates.
  // The extension should now get installed.
  delay_tracker.StopWatching();
  delay_tracker.Proceed();

  EXPECT_EQ(update_client::ComponentState::kUpdated,
            WaitOnComponentUpdaterCompleteEvent(id_));

  ASSERT_EQ(1, update_interceptor_->GetCount())
      << update_interceptor_->GetRequestsAsString();
  EXPECT_EQ(1, get_interceptor_count());

  // Make sure that the update check request is formed correctly when the
  // extension is corrupted:
  // - version="0.0.0.0"
  // - installsource="reinstall"
  // - installedby="policy"
  // - enabled="0"
  // - <disabled reason="1024"/>
  const std::optional<base::Value::Dict> root = GetRequest(0);
  ASSERT_TRUE(root);
  const base::Value::Dict& app = GetFirstApp(root.value());
  EXPECT_EQ(id_, CHECK_DEREF(app.FindString("appid")));
  EXPECT_EQ("0.0.0.0", CHECK_DEREF(app.FindString("version")));
  EXPECT_EQ("reinstall", CHECK_DEREF(app.FindString("installsource")));
  EXPECT_EQ("policy", CHECK_DEREF(app.FindString("installedby")));
  EXPECT_FALSE(app.FindBool("enabled").value_or(true));
  const base::Value::Dict& disabled =
      CHECK_DEREF(app.FindList("disabled"))[0].GetDict();
  EXPECT_EQ(disable_reason::DISABLE_CORRUPTED, disabled.FindInt("reason"));
}

IN_PROC_BROWSER_TEST_F(PolicyUpdateServiceTest, Backoff) {
  ExtensionRegistry* registry = ExtensionRegistry::Get(profile());
  ContentVerifier* verifier =
      ExtensionSystem::Get(profile())->content_verifier();

  // Wait for the extension to be installed by the policy we set up in
  // SetUpInProcessBrowserTestFixture.
  if (!registry->GetInstalledExtension(id_)) {
    TestExtensionRegistryObserver registry_observer(registry, id_);
    EXPECT_TRUE(registry_observer.WaitForExtensionInstalled());
  }

  // Setup to intercept reinstall action, so we can see what the delay would
  // have been for the real action.
  content_verifier_test::DelayTracker delay_tracker;

  // Do 4 iterations of disabling followed by reinstall.
  const size_t iterations = 4;
  for (size_t i = 0; i < iterations; i++) {
    TestExtensionRegistryObserver registry_observer(registry, id_);
    verifier->VerifyFailedForTest(id_, ContentVerifyJob::HASH_MISMATCH);
    EXPECT_TRUE(registry_observer.WaitForExtensionUnloaded());
    // Resolve the request to |delay_tracker|, so the reinstallation can
    // proceed.
    delay_tracker.Proceed();
    EXPECT_EQ(update_client::ComponentState::kUpdated,
              WaitOnComponentUpdaterCompleteEvent(id_));
  }

  ASSERT_EQ(4, update_interceptor_->GetCount())
      << update_interceptor_->GetRequestsAsString();
  // Only one download because retries are cached.
  EXPECT_EQ(1, get_interceptor_count());

  const std::vector<base::TimeDelta>& calls = delay_tracker.calls();

  // After |delay_tracker| resolves the 4 (|iterations|) reinstallation
  // requests, it will get an additional request (right away) for retrying
  // reinstallation.
  // Note: the additional request in non-test environment will arrive with
  // a (backoff) delay. But during test, |delay_tracker| issues the request
  // immediately.
  ASSERT_EQ(iterations, calls.size() - 1);
  // Assert that the first reinstall action happened with a delay of 0, and
  // then kept growing each additional time.
  EXPECT_EQ(base::TimeDelta(), delay_tracker.calls()[0]);
  for (size_t i = 1; i < delay_tracker.calls().size(); i++) {
    EXPECT_LT(calls[i - 1], calls[i]);
  }
}

#if !(defined(ADDRESS_SANITIZER) && BUILDFLAG(IS_CHROMEOS))
// We want to test what happens at startup with a corroption-disabled policy
// force installed extension. So we set that up in the PRE test here.
IN_PROC_BROWSER_TEST_F(PolicyUpdateServiceTest, PRE_PolicyCorruptedOnStartup) {
  // This is to not allow any corrupted resintall to proceed.
  content_verifier_test::DelayTracker delay_tracker;
  ExtensionRegistry* registry = ExtensionRegistry::Get(profile());
  TestExtensionRegistryObserver registry_observer(registry, id_);

  // Wait for the extension to be installed by policy we set up in
  // SetUpInProcessBrowserTestFixture.
  if (!registry->GetInstalledExtension(id_))
    EXPECT_TRUE(registry_observer.WaitForExtensionInstalled());

  // Simulate corruption of the extension so that we can test what happens
  // at startup in the non-PRE test.
  ContentVerifier* verifier =
      ExtensionSystem::Get(profile())->content_verifier();
  verifier->VerifyFailedForTest(id_, ContentVerifyJob::HASH_MISMATCH);
  EXPECT_TRUE(registry_observer.WaitForExtensionUnloaded());

  ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
  DisableReasonSet reasons = prefs->GetDisableReasons(id_);
  EXPECT_TRUE(reasons.contains(disable_reason::DISABLE_CORRUPTED));
  EXPECT_EQ(1u, delay_tracker.calls().size());

  EXPECT_EQ(0, update_interceptor_->GetCount())
      << update_interceptor_->GetRequestsAsString();
  EXPECT_EQ(0, get_interceptor_count());
}

// Now actually test what happens on the next startup after the PRE test above.
IN_PROC_BROWSER_TEST_F(PolicyUpdateServiceTest, PolicyCorruptedOnStartup) {
  // Depdending on timing, the extension may have already been reinstalled
  // between SetUpInProcessBrowserTestFixture and now (usually not during local
  // testing on a developer machine, but sometimes on a heavily loaded system
  // such as the build waterfall / trybots). If the reinstall didn't already
  // happen, wait for it.

  ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
  ExtensionRegistry* registry = ExtensionRegistry::Get(profile());
  DisableReasonSet disable_reasons = prefs->GetDisableReasons(id_);
  if (disable_reasons.contains(disable_reason::DISABLE_CORRUPTED)) {
    EXPECT_EQ(update_client::ComponentState::kUpdated,
              WaitOnComponentUpdaterCompleteEvent(id_));
    disable_reasons = prefs->GetDisableReasons(id_);
  }

  EXPECT_FALSE(disable_reasons.contains(disable_reason::DISABLE_CORRUPTED));
  EXPECT_TRUE(registry->enabled_extensions().Contains(id_));

  ASSERT_EQ(1, update_interceptor_->GetCount())
      << update_interceptor_->GetRequestsAsString();
  EXPECT_EQ(1, get_interceptor_count());

  const std::string update_request =
      std::get<0>(update_interceptor_->GetRequests()[0]);
  const std::optional<base::Value::Dict> root = GetRequest(0);
  ASSERT_TRUE(root);
  const base::Value::Dict& app = GetFirstApp(root.value());
  EXPECT_EQ(id_, CHECK_DEREF(app.FindString("appid")));
  EXPECT_EQ("0.0.0.0", CHECK_DEREF(app.FindString("version")));
  EXPECT_EQ("reinstall", CHECK_DEREF(app.FindString("installsource")));
  EXPECT_EQ("policy", CHECK_DEREF(app.FindString("installedby")));
  EXPECT_FALSE(app.FindBool("enabled").value_or(true));
  const base::Value::Dict& disabled =
      CHECK_DEREF(app.FindList("disabled"))[0].GetDict();
  EXPECT_EQ(disable_reason::DISABLE_CORRUPTED, disabled.FindInt("reason"));
}
#endif  // !(defined(ADDRESS_SANITIZER) && BUILDFLAG(IS_CHROMEOS))

}  // namespace extensions