File: manifest_v2_experiment_manager.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 (712 lines) | stat: -rw-r--r-- 26,975 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
// 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 "chrome/browser/extensions/manifest_v2_experiment_manager.h"

#include "base/auto_reset.h"
#include "base/functional/callback_forward.h"
#include "base/metrics/histogram_functions.h"
#include "base/one_shot_event.h"
#include "base/strings/stringprintf.h"
#include "base/types/pass_key.h"
#include "chrome/browser/extensions/chrome_extension_system_factory.h"
#include "chrome/browser/extensions/extension_management.h"
#include "chrome/browser/extensions/mv2_experiment_stage.h"
#include "chrome/browser/extensions/profile_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_keyed_service_factory.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "extensions/browser/disable_reason.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_prefs_factory.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_registry_factory.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extensions_browser_client.h"
#include "extensions/browser/pref_names.h"
#include "extensions/browser/pref_types.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_features.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"

namespace extensions {

namespace {

// Whether to override the MV2 deprecation for testing purposes.
bool g_allow_mv2_for_testing = false;

// Returns the suffix to use for histograms related to the manifest location
// grouping.
const char* GetHistogramManifestLocation(mojom::ManifestLocation location) {
  switch (location) {
    case mojom::ManifestLocation::kComponent:
    case mojom::ManifestLocation::kExternalComponent:
      return "Component";
    case mojom::ManifestLocation::kExternalPolicy:
    case mojom::ManifestLocation::kExternalPolicyDownload:
      return "Policy";
    case mojom::ManifestLocation::kCommandLine:
    case mojom::ManifestLocation::kUnpacked:
      return "Unpacked";
    case mojom::ManifestLocation::kExternalRegistry:
    case mojom::ManifestLocation::kExternalPref:
    case mojom::ManifestLocation::kExternalPrefDownload:
      return "External";
    case mojom::ManifestLocation::kInternal:
      return "Internal";
    case mojom::ManifestLocation::kInvalidLocation:
      NOTREACHED();
  }
}

// Stores the bit for whether the user has acknowledged the MV2 deprecation
// notice for a given extension in the warning stage.
constexpr PrefMap kMV2DeprecationExtensionWarningAcknowledgedPref = {
    "mv2_deprecation_warning_ack", PrefType::kBool,
    PrefScope::kExtensionSpecific};

// Stores the bit for whether the user has acknowledged the MV2 deprecation
// notice for a given extension in the disabled stage.
constexpr PrefMap kMV2DeprecationExtensionDisabledAcknowledgedPref = {
    "mv2_deprecation_disabled_ack", PrefType::kBool,
    PrefScope::kExtensionSpecific};

// Stores a bit for whether the extension has been disabled as part of the
// MV2 deprecation.
constexpr PrefMap kMV2DeprecationDidDisablePref = {
    "mv2_deprecation_did_disable", PrefType::kBool,
    PrefScope::kExtensionSpecific};

// Stores a bit for whether the extension was re-enabled after being previously
// disabled as part of the MV2 deprecation.
// We store this separately from kMV2DeprecationDidDisablePref (as opposed to
// relying on an enum or a single bool) since there are multiple phases and
// causes for extensions to be disabled and re-enabled, and we only want to
// record that a user re-enables it if it was explicitly disabled by this phase
// of the experiment.
constexpr PrefMap kMV2DeprecationUserReEnabledPref = {
    "mv2_deprecation_user_re_enabled", PrefType::kBool,
    PrefScope::kExtensionSpecific};

class ManifestV2ExperimentManagerFactory : public ProfileKeyedServiceFactory {
 public:
  ManifestV2ExperimentManagerFactory();
  ManifestV2ExperimentManagerFactory(
      const ManifestV2ExperimentManagerFactory&) = delete;
  ManifestV2ExperimentManagerFactory& operator=(
      const ManifestV2ExperimentManagerFactory&) = delete;
  ~ManifestV2ExperimentManagerFactory() override = default;

  ManifestV2ExperimentManager* GetForBrowserContext(
      content::BrowserContext* context);

 private:
  // BrowserContextKeyedServiceFactory:
  std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext(
      content::BrowserContext* context) const override;
  bool ServiceIsCreatedWithBrowserContext() const override;
};

ManifestV2ExperimentManagerFactory::ManifestV2ExperimentManagerFactory()
    : ProfileKeyedServiceFactory(
          "ManifestV2ExperimentManager",
          ProfileSelections::Builder()
              .WithRegular(ProfileSelection::kRedirectedToOriginal)
              .WithGuest(ProfileSelection::kRedirectedToOriginal)
              .WithAshInternals(ProfileSelection::kNone)
              .Build()) {
  DependsOn(ExtensionManagementFactory::GetInstance());
  DependsOn(ExtensionPrefsFactory::GetInstance());
  DependsOn(ChromeExtensionSystemFactory::GetInstance());
  DependsOn(ExtensionRegistryFactory::GetInstance());
}

ManifestV2ExperimentManager*
ManifestV2ExperimentManagerFactory::GetForBrowserContext(
    content::BrowserContext* browser_context) {
  return static_cast<ManifestV2ExperimentManager*>(
      GetServiceForBrowserContext(browser_context, /*create=*/true));
}

std::unique_ptr<KeyedService>
ManifestV2ExperimentManagerFactory::BuildServiceInstanceForBrowserContext(
    content::BrowserContext* context) const {
  return std::make_unique<ManifestV2ExperimentManager>(context);
}

bool ManifestV2ExperimentManagerFactory::ServiceIsCreatedWithBrowserContext()
    const {
  return true;
}

// Determines the current stage of the MV2 deprecation experiments.
MV2ExperimentStage CalculateCurrentExperimentStage() {
  // Return the "highest" stage that is currently active for the user.
  if (base::FeatureList::IsEnabled(
          extensions_features::kExtensionManifestV2Unsupported)) {
    return MV2ExperimentStage::kUnsupported;
  }

  if (base::FeatureList::IsEnabled(
          extensions_features::kExtensionManifestV2Disabled)) {
    return MV2ExperimentStage::kDisableWithReEnable;
  }

  if (base::FeatureList::IsEnabled(
          extensions_features::kExtensionManifestV2DeprecationWarning)) {
    return MV2ExperimentStage::kWarning;
  }

  return MV2ExperimentStage::kNone;
}

// Returns the pref that stores whether the user has acknowledged the MV2
// deprecation notice for a given extension in `experiment_stage`.
PrefMap GetExtensionAcknowledgedPrefFor(MV2ExperimentStage experiment_stage) {
  switch (experiment_stage) {
    case MV2ExperimentStage::kNone:
      // There is no notice for this stage, thus it cannot be acknowledged.
      NOTREACHED();
    case MV2ExperimentStage::kWarning:
      return kMV2DeprecationExtensionWarningAcknowledgedPref;
    case MV2ExperimentStage::kDisableWithReEnable:
      return kMV2DeprecationExtensionDisabledAcknowledgedPref;
    case MV2ExperimentStage::kUnsupported:
      NOTREACHED();
  }
}

// Returns the pref that stores whether the user has acknowledged the MV2
// deprecation global notice in `experiment_stage`.
PrefMap GetGlobalNoticeAcknowledgedPrefFor(
    MV2ExperimentStage experiment_stage) {
  switch (experiment_stage) {
    case MV2ExperimentStage::kNone:
      // There is no notice for this stage, thus it cannot be acknowledged.
      NOTREACHED();
    case MV2ExperimentStage::kWarning:
      return kMV2DeprecationWarningAcknowledgedGloballyPref;
    case MV2ExperimentStage::kDisableWithReEnable:
      return kMV2DeprecationDisabledAcknowledgedGloballyPref;
    case MV2ExperimentStage::kUnsupported:
      return kMV2DeprecationUnsupportedAcknowledgedGloballyPref;
  }
}

// Returns true if legacy extensions should be disabled, looking at both
// experiment stage and global state.
bool ShouldDisableLegacyExtensions(MV2ExperimentStage stage) {
  if (g_allow_mv2_for_testing) {
    // We allow legacy MV2 extensions for testing purposes.
    return false;
  }

  switch (stage) {
    case MV2ExperimentStage::kNone:
    case MV2ExperimentStage::kWarning:
      return false;
    case MV2ExperimentStage::kDisableWithReEnable:
    case MV2ExperimentStage::kUnsupported:
      return true;
  }
}

// Returns true if the given `stage` is one in which extension enablement should
// potentially be blocked.
bool ShouldBlockLegacyExtensionEnableForStage(MV2ExperimentStage stage) {
  // The times in which we block extension enablement are a strict subset of
  // those when we disable legacy extensions.
  if (!ShouldDisableLegacyExtensions(stage)) {
    return false;
  }

  // We only block extension enablement in the `kUnsupported` phase.
  // (We use a switch just to ensure compile errors if we ever add a new phase.)
  switch (stage) {
    case MV2ExperimentStage::kNone:
    case MV2ExperimentStage::kWarning:
    case MV2ExperimentStage::kDisableWithReEnable:
      return false;
    case MV2ExperimentStage::kUnsupported:
      return true;
  }
}

// Returns true if unpacked extensions should be blocked in the given experiment
// `stage`. This is true only for cases where MV2 extensions are fully
// unsupported.
bool ShouldBlockUnpackedExtensions(MV2ExperimentStage stage) {
  if (!ShouldBlockLegacyExtensionEnableForStage(stage)) {
    return false;
  }

  // If the developer has flipped the explicit flag to allow legacy MV2
  // extensions, we allow the unpacked extension to be loaded.
  if (base::FeatureList::IsEnabled(
          extensions_features::kAllowLegacyMV2Extensions)) {
    return false;
  }

  return true;
}

// Returns true if the user is allowed to re-enable disabled extensions in the
// given experiment `stage`.
bool UserCanReEnableExtensionsForStage(MV2ExperimentStage stage) {
  switch (stage) {
    case MV2ExperimentStage::kNone:
    case MV2ExperimentStage::kWarning:
    case MV2ExperimentStage::kDisableWithReEnable:
      return true;
    case MV2ExperimentStage::kUnsupported:
      return false;
  }
}

}  // namespace

ManifestV2ExperimentManager::ManifestV2ExperimentManager(
    content::BrowserContext* browser_context)
    : experiment_stage_(CalculateCurrentExperimentStage()),
      // Note: passing `ExtensionManagement` is safe and guaranteed to outlive
      // the `impact_checker_` because this class is a KeyedService that depends
      // on `ExtensionManagement`.
      impact_checker_(
          experiment_stage_,
          ExtensionManagementFactory::GetForBrowserContext(browser_context)),
      browser_context_(browser_context) {
  registry_observation_.Observe(ExtensionRegistry::Get(browser_context));

  ExtensionSystem::Get(browser_context)
      ->ready()
      .Post(FROM_HERE,
            base::BindOnce(&ManifestV2ExperimentManager::OnExtensionSystemReady,
                           weak_factory_.GetWeakPtr()));

  // Listen to management policy changes. `Unretained` is safe since the
  // `pref_change_registrar` is owned by this class.
  pref_change_registrar_.Init(
      Profile::FromBrowserContext(browser_context_)->GetPrefs());
  pref_change_registrar_.Add(
      pref_names::kManifestV2Availability,
      base::BindRepeating(
          &ManifestV2ExperimentManager::OnManagementPolicyChanged,
          base::Unretained(this)));
}

ManifestV2ExperimentManager::~ManifestV2ExperimentManager() = default;

// static
ManifestV2ExperimentManager* ManifestV2ExperimentManager::Get(
    content::BrowserContext* browser_context) {
  return static_cast<ManifestV2ExperimentManagerFactory*>(GetFactory())
      ->GetForBrowserContext(browser_context);
}

// static
BrowserContextKeyedServiceFactory* ManifestV2ExperimentManager::GetFactory() {
  static base::NoDestructor<ManifestV2ExperimentManagerFactory> g_factory;
  return g_factory.get();
}

MV2ExperimentStage ManifestV2ExperimentManager::GetCurrentExperimentStage() {
  return experiment_stage_;
}

bool ManifestV2ExperimentManager::IsExtensionAffected(
    const Extension& extension) {
  return impact_checker_.IsExtensionAffected(extension);
}

bool ManifestV2ExperimentManager::ShouldBlockExtensionInstallation(
    const ExtensionId& extension_id,
    int manifest_version,
    Manifest::Type manifest_type,
    mojom::ManifestLocation manifest_location,
    const HashedExtensionId& hashed_id) {
  // Only block extension installation during phases in which legacy extensions
  // are automatically disabled.
  if (!ShouldDisableLegacyExtensions(experiment_stage_)) {
    return false;
  }

  // Unpacked extensions are special-cased (since developers need to be able to
  // continue supporting them). Check if unpacked extensions are blocked, either
  // by the experiment phase or by enterprise policy.
  ExtensionManagement* extension_management =
      ExtensionManagementFactory::GetForBrowserContext(browser_context_);
  if (Manifest::IsUnpackedLocation(manifest_location) &&
      !ShouldBlockUnpackedExtensions(experiment_stage_) &&
      extension_management->IsAllowedManifestVersion(
          manifest_version, extension_id, manifest_type)) {
    return false;
  }

  // Otherwise, if the extension is affected by the deprecation, it should be
  // blocked.
  return impact_checker_.IsExtensionAffected(extension_id, manifest_version,
                                             manifest_type, manifest_location,
                                             hashed_id);
}

bool ManifestV2ExperimentManager::ShouldBlockExtensionEnable(
    const Extension& extension) {
  if (!ShouldBlockLegacyExtensionEnableForStage(experiment_stage_)) {
    return false;
  }

  // Block unpacked extension enablement only if unpacked extensions are blocked
  // in this stage.
  if (Manifest::IsUnpackedLocation(extension.location()) &&
      !ShouldBlockUnpackedExtensions(experiment_stage_)) {
    return false;
  }

  return impact_checker_.IsExtensionAffected(
      extension.id(), extension.manifest_version(), extension.GetType(),
      extension.location(), extension.hashed_id());
}

bool ManifestV2ExperimentManager::DidUserAcknowledgeNotice(
    const ExtensionId& extension_id) {
  // There is no notice for kNone stage, thus it cannot be acknowledged.
  // The notice cannot be acknowledged in kUnsupported stage.
  if (experiment_stage_ == MV2ExperimentStage::kNone ||
      experiment_stage_ == MV2ExperimentStage::kUnsupported) {
    return false;
  }

  bool acknowledged = false;
  PrefMap pref = GetExtensionAcknowledgedPrefFor(experiment_stage_);
  return extension_prefs()->ReadPrefAsBoolean(extension_id, pref,
                                              &acknowledged) &&
         acknowledged;
}

void ManifestV2ExperimentManager::MarkNoticeAsAcknowledged(
    const ExtensionId& extension_id) {
  // There is no notice for kNone stage, thus it cannot be acknowledged. The
  // notice cannot be acknowledged in kUnsupported stage.
  if (experiment_stage_ == MV2ExperimentStage::kNone ||
      experiment_stage_ == MV2ExperimentStage::kUnsupported) {
    return;
  }

  PrefMap pref = GetExtensionAcknowledgedPrefFor(experiment_stage_);
  extension_prefs()->SetBooleanPref(extension_id, pref, true);
}

bool ManifestV2ExperimentManager::DidUserAcknowledgeNoticeGlobally() {
  // There is no notice for kNone stage, thus it cannot be acknowledged.
  if (experiment_stage_ == MV2ExperimentStage::kNone) {
    return false;
  }

  PrefMap pref = GetGlobalNoticeAcknowledgedPrefFor(experiment_stage_);
  return extension_prefs()->GetPrefAsBoolean(pref);
}

void ManifestV2ExperimentManager::MarkNoticeAsAcknowledgedGlobally() {
  // There is no notice for kNone stage, thus it cannot be acknowledged.
  if (experiment_stage_ == MV2ExperimentStage::kNone) {
    return;
  }

  PrefMap pref = GetGlobalNoticeAcknowledgedPrefFor(experiment_stage_);
  extension_prefs()->SetBooleanPref(pref, true);
}

ExtensionPrefs* ManifestV2ExperimentManager::extension_prefs() {
  if (!extension_prefs_) {
    extension_prefs_ = ExtensionPrefs::Get(browser_context_);
  }
  return extension_prefs_;
}

void ManifestV2ExperimentManager::OnExtensionSystemReady() {
  CheckDisabledExtensions();
  DisableAffectedExtensions();

  EmitMetricsForProfileReady();

  is_manager_ready_ = true;
  on_manager_ready_callback_list_.Notify();
}

base::CallbackListSubscription
ManifestV2ExperimentManager::RegisterOnManagerReadyCallback(
    base::RepeatingClosure callback) {
  CHECK(!is_manager_ready_);
  return on_manager_ready_callback_list_.Add(std::move(callback));
}

void ManifestV2ExperimentManager::SetHasTriggeredDisabledDialog(
    bool has_triggered) {
  has_triggered_disabled_dialog_ = has_triggered;
}

void ManifestV2ExperimentManager::DisableAffectedExtensions() {
  if (!ShouldDisableLegacyExtensions(experiment_stage_)) {
    return;
  }

  ExtensionRegistry* extension_registry =
      ExtensionRegistry::Get(browser_context_);
  std::set<scoped_refptr<const Extension>> extensions_to_disable;

  // Whether the user is allowed to re-enable disabled extensions in the given
  // experiment phase.
  bool user_reenable_allowed =
      UserCanReEnableExtensionsForStage(experiment_stage_);
  // Whether unpacked extensions are exempt from being disabled.
  // Note that this is distinct from `ShouldBlockUnpackedExtensions()`, since
  // unpacked extensions are only blocked in "unsupported" phase, but they may
  // be *disabled* in other phases.
  bool unpacked_extensions_are_exempt = base::FeatureList::IsEnabled(
      extensions_features::kAllowLegacyMV2Extensions);
  for (const auto& extension : extension_registry->enabled_extensions()) {
    if (!impact_checker_.IsExtensionAffected(*extension)) {
      continue;
    }

    if (user_reenable_allowed && DidUserReEnableExtension(extension->id())) {
      // The user explicitly chose to re-enable the extension after it was
      // disabled, and that's allowed in this experiment stage. Allow it to
      // remain enabled.
      continue;
    }

    if (Manifest::IsUnpackedLocation(extension->location()) &&
        unpacked_extensions_are_exempt) {
      continue;
    }

    extensions_to_disable.insert(extension);
  }

  auto* registrar = ExtensionRegistrar::Get(browser_context_);
  for (const auto& extension : extensions_to_disable) {
    registrar->DisableExtension(
        extension->id(),
        {disable_reason::DISABLE_UNSUPPORTED_MANIFEST_VERSION});
    extension_prefs()->SetBooleanPref(extension->id(),
                                      kMV2DeprecationDidDisablePref, true);
  }
}

void ManifestV2ExperimentManager::CheckDisabledExtensions() {
  ExtensionRegistry* extension_registry =
      ExtensionRegistry::Get(browser_context_);
  ExtensionSet disabled_extensions;
  // Loop through all disabled extensions. For each, check if they should be
  // re-enabled (e.g. because they've updated to MV3 or a change in policy
  // settings).
  // Use a copy of the set to avoid changing the set while iterating.
  disabled_extensions.InsertAll(extension_registry->disabled_extensions());
  for (const auto& extension : disabled_extensions) {
    MaybeReEnableExtension(*extension);
  }
}

void ManifestV2ExperimentManager::MaybeReEnableExtension(
    const Extension& extension) {
  if (!extension_prefs()->HasDisableReason(
          extension.id(),
          disable_reason::DISABLE_UNSUPPORTED_MANIFEST_VERSION)) {
    // We only care about extensions that were disabled for this reason.
    return;
  }

  // Check if the extension is still affected *and* whether the environment is
  // still one in which extensions should be disabled. It's possible the user
  // moved from a later experiment stage to an earlier one or set a feature
  // flag, in which case extensions should be re-enabled.
  if (impact_checker_.IsExtensionAffected(extension) &&
      ShouldDisableLegacyExtensions(experiment_stage_)) {
    return;
  }

  // Remove the bit that the extension was disabled by the MV2 deprecation,
  // since it no longer is. This also ensures we don't count it as user-
  // re-enabled, if it gets re-enabled below.
  extension_prefs()->SetBooleanPref(extension.id(),
                                    kMV2DeprecationDidDisablePref, false);
  // Remove the disable reason (possibly re-enabling the extension).
  ExtensionRegistrar::Get(browser_context_)
      ->RemoveDisableReasonAndMaybeEnable(
          extension.id(), disable_reason::DISABLE_UNSUPPORTED_MANIFEST_VERSION);
}

bool ManifestV2ExperimentManager::DidUserReEnableExtension(
    const ExtensionId& extension_id) {
  bool acknowledged = false;
  return extension_prefs()->ReadPrefAsBoolean(
             extension_id, kMV2DeprecationUserReEnabledPref, &acknowledged) &&
         acknowledged;
}

void ManifestV2ExperimentManager::EmitMetricsForProfileReady() {
  if (!ShouldDisableLegacyExtensions(experiment_stage_)) {
    // Don't bother reporting MV2-specific metrics if the user isn't in an
    // environment in which extensions could be disabled.
    return;
  }

  if (!profile_util::ProfileCanUseNonComponentExtensions(
          Profile::FromBrowserContext(browser_context_))) {
    // Don't report metrics if the user can't install extensions in this
    // profile.
    return;
  }

  ExtensionRegistry* extension_registry =
      ExtensionRegistry::Get(browser_context_);

  auto emit_state_for_mv2_extension = [this](const Extension& extension,
                                             bool is_enabled) {
    if (extension.manifest_version() != 2) {
      return;
    }

    if (extension.GetType() != Manifest::TYPE_EXTENSION &&
        extension.GetType() != Manifest::TYPE_LOGIN_SCREEN_EXTENSION) {
      return;
    }

    if (Manifest::IsComponentLocation(extension.location())) {
      return;
    }

    bool user_reenabled = DidUserReEnableExtension(extension.id());
    MV2ExtensionState extension_state = MV2ExtensionState::kUnaffected;
    if (!impact_checker_.IsExtensionAffected(extension)) {
      extension_state = MV2ExtensionState::kUnaffected;
    } else if (is_enabled && user_reenabled) {
      extension_state = MV2ExtensionState::kUserReEnabled;
    } else if (extension_prefs()->HasDisableReason(
                   extension.id(),
                   disable_reason::DISABLE_UNSUPPORTED_MANIFEST_VERSION)) {
      CHECK(!is_enabled);
      CHECK(experiment_stage_ == MV2ExperimentStage::kUnsupported ||
            experiment_stage_ == MV2ExperimentStage::kDisableWithReEnable);
      extension_state = experiment_stage_ == MV2ExperimentStage::kUnsupported
                            ? MV2ExtensionState::kHardDisabled
                            : MV2ExtensionState::kSoftDisabled;
    } else {
      extension_state = MV2ExtensionState::kOther;
    }

    std::string histogram_name =
        base::StringPrintf("Extensions.MV2Deprecation.MV2ExtensionState.%s",
                           GetHistogramManifestLocation(extension.location()));

    base::UmaHistogramEnumeration(histogram_name, extension_state);
  };

  for (const auto& extension : extension_registry->enabled_extensions()) {
    emit_state_for_mv2_extension(*extension, /*is_enabled=*/true);
  }
  for (const auto& extension : extension_registry->disabled_extensions()) {
    emit_state_for_mv2_extension(*extension, /*is_enabled=*/false);
  }
}

void ManifestV2ExperimentManager::RecordUkmForExtension(
    const GURL& extension_url,
    ExtensionMV2DeprecationAction action) {
  if (experiment_stage_ != MV2ExperimentStage::kDisableWithReEnable) {
    // The UKM is only emitted for the "disable with re-enable" phase. We do
    // not need UKM for the "hard disable" phase (as the only action available
    // to the user is to remove or find alternatives).
    return;
  }

  ukm::builders::Extensions_MV2ExtensionHandledInSoftDisable(
      ukm::UkmRecorder::GetSourceIdForExtensionUrl(
          base::PassKey<ManifestV2ExperimentManager>(), extension_url))
      .SetAction(static_cast<int64_t>(action))
      .Record(ukm::UkmRecorder::Get());
}

void ManifestV2ExperimentManager::OnExtensionLoaded(
    content::BrowserContext* browser_context,
    const Extension* extension) {
  bool was_extension_disabled_by_mv2_deprecation = false;
  extension_prefs()->ReadPrefAsBoolean(
      extension->id(), kMV2DeprecationDidDisablePref,
      &was_extension_disabled_by_mv2_deprecation);
  if (!was_extension_disabled_by_mv2_deprecation) {
    return;
  }

  extension_prefs()->SetBooleanPref(extension->id(),
                                    kMV2DeprecationUserReEnabledPref, true);
  RecordUkmForExtension(extension->url(),
                        ExtensionMV2DeprecationAction::kReEnabled);
}

void ManifestV2ExperimentManager::OnExtensionInstalled(
    content::BrowserContext* browser_context,
    const Extension* extension,
    bool is_update) {
  if (!is_update) {
    // We would only ever re-enable a disabled extension if it was already
    // installed. No need to look at new installs.
    return;
  }

  MaybeReEnableExtension(*extension);
}

void ManifestV2ExperimentManager::OnExtensionUninstalled(
    content::BrowserContext* browser_context,
    const Extension* extension,
    UninstallReason uninstall_reason) {
  // We only care about user uninstallations...
  if (uninstall_reason != UNINSTALL_REASON_USER_INITIATED) {
    return;
  }
  // ... of extensions that were disabled by the MV2 deprecation.
  bool was_extension_disabled_by_mv2_deprecation = false;
  extension_prefs()->ReadPrefAsBoolean(
      extension->id(), kMV2DeprecationDidDisablePref,
      &was_extension_disabled_by_mv2_deprecation);
  if (!was_extension_disabled_by_mv2_deprecation) {
    return;
  }

  RecordUkmForExtension(extension->url(),
                        ExtensionMV2DeprecationAction::kRemoved);
}

void ManifestV2ExperimentManager::OnManagementPolicyChanged() {
  // The management policy has changed. Go through all disabled extensions to
  // check if any should be re-enabled, and go through all enabled extensions
  // to see if any should be disabled (if the experiment is active).
  CheckDisabledExtensions();
  DisableAffectedExtensions();
}

bool ManifestV2ExperimentManager::DidUserReEnableExtensionForTesting(
    const ExtensionId& extension_id) {
  return DidUserReEnableExtension(extension_id);
}

void ManifestV2ExperimentManager::DisableAffectedExtensionsForTesting() {
  DisableAffectedExtensions();
}

void ManifestV2ExperimentManager::EmitMetricsForProfileReadyForTesting() {
  EmitMetricsForProfileReady();
}

base::AutoReset<bool> ManifestV2ExperimentManager::AllowMV2ExtensionsForTesting(
    base::PassKey<ScopedTestMV2Enabler> pass_key) {
  return base::AutoReset<bool>(&g_allow_mv2_for_testing, true);
}

}  // namespace extensions