• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "components/metrics/metrics_state_manager.h"
6 
7 #include <cstddef>
8 #include <cstdint>
9 #include <limits>
10 #include <memory>
11 #include <random>
12 #include <string>
13 #include <tuple>
14 #include <utility>
15 
16 #include "base/base_switches.h"
17 #include "base/check.h"
18 #include "base/command_line.h"
19 #include "base/debug/leak_annotations.h"
20 #include "base/functional/callback_helpers.h"
21 #include "base/memory/raw_ptr.h"
22 #include "base/memory/raw_ref.h"
23 #include "base/metrics/histogram_functions.h"
24 #include "base/metrics/histogram_macros.h"
25 #include "base/numerics/safe_conversions.h"
26 #include "base/rand_util.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/stringprintf.h"
29 #include "base/threading/thread_restrictions.h"
30 #include "base/time/time.h"
31 #include "base/uuid.h"
32 #include "build/branding_buildflags.h"
33 #include "build/build_config.h"
34 #include "components/metrics/cloned_install_detector.h"
35 #include "components/metrics/enabled_state_provider.h"
36 #include "components/metrics/entropy_state.h"
37 #include "components/metrics/metrics_data_validation.h"
38 #include "components/metrics/metrics_log.h"
39 #include "components/metrics/metrics_pref_names.h"
40 #include "components/metrics/metrics_provider.h"
41 #include "components/metrics/metrics_switches.h"
42 #include "components/prefs/pref_registry_simple.h"
43 #include "components/prefs/pref_service.h"
44 #include "components/variations/entropy_provider.h"
45 #include "components/variations/field_trial_config/field_trial_util.h"
46 #include "components/variations/pref_names.h"
47 #include "components/variations/variations_switches.h"
48 #include "third_party/metrics_proto/chrome_user_metrics_extension.pb.h"
49 #include "third_party/metrics_proto/system_profile.pb.h"
50 
51 namespace metrics {
52 namespace {
53 
ReadEnabledDate(PrefService * local_state)54 int64_t ReadEnabledDate(PrefService* local_state) {
55   return local_state->GetInt64(prefs::kMetricsReportingEnabledTimestamp);
56 }
57 
ReadInstallDate(PrefService * local_state)58 int64_t ReadInstallDate(PrefService* local_state) {
59   return local_state->GetInt64(prefs::kInstallDate);
60 }
61 
ReadClientId(PrefService * local_state)62 std::string ReadClientId(PrefService* local_state) {
63   return local_state->GetString(prefs::kMetricsClientID);
64 }
65 
66 // Round a timestamp measured in seconds since epoch to one with a granularity
67 // of an hour. This can be used before uploaded potentially sensitive
68 // timestamps.
RoundSecondsToHour(int64_t time_in_seconds)69 int64_t RoundSecondsToHour(int64_t time_in_seconds) {
70   return 3600 * (time_in_seconds / 3600);
71 }
72 
73 // Records the cloned install histogram.
LogClonedInstall()74 void LogClonedInstall() {
75   // Equivalent to UMA_HISTOGRAM_BOOLEAN with the stability flag set.
76   UMA_STABILITY_HISTOGRAM_ENUMERATION("UMA.IsClonedInstall", 1, 2);
77 }
78 
79 // No-op function used to create a MetricsStateManager.
NoOpLoadClientInfoBackup()80 std::unique_ptr<metrics::ClientInfo> NoOpLoadClientInfoBackup() {
81   return nullptr;
82 }
83 
84 // Exits the browser with a helpful error message if an invalid,
85 // field-trial-related command-line flag was specified.
ExitWithMessage(const std::string & message)86 void ExitWithMessage(const std::string& message) {
87   puts(message.c_str());
88   exit(1);
89 }
90 
91 // Returns a log normal distribution based on the feature params of
92 // |kNonUniformityValidationFeature|.
GetLogNormalDist()93 std::lognormal_distribution<double> GetLogNormalDist() {
94   double mean = kLogNormalMean.Get();
95   double delta = kLogNormalDelta.Get();
96   double std_dev = kLogNormalStdDev.Get();
97   return std::lognormal_distribution<double>(mean + std::log(1.0 + delta),
98                                              std_dev);
99 }
100 
101 // Used to draw a data point from a log normal distribution.
102 struct LogNormalMetricState {
LogNormalMetricStatemetrics::__anonc1ad9ddf0111::LogNormalMetricState103   LogNormalMetricState()
104       : dist(GetLogNormalDist()), gen(std::mt19937(base::RandUint64())) {}
105 
106   // Records the artificial non-uniformity histogram for data validation.
LogArtificialNonUniformitymetrics::__anonc1ad9ddf0111::LogNormalMetricState107   void LogArtificialNonUniformity() {
108     double rand = dist(gen);
109     // We pick 10k as the upper bound for this histogram so as to avoid losing
110     // precision. See comments for |kLogNormalMean|.
111     base::UmaHistogramCounts10000("UMA.DataValidation.LogNormal",
112                                   base::saturated_cast<int>(rand));
113   }
114 
115   // A log normal distribution generator generated by the `GetLogNormalDist()`
116   // function.
117   std::lognormal_distribution<double> dist;
118   // The pseudo-random generator used to generate a data point from |dist|.
119   std::mt19937 gen;
120 };
121 
122 class MetricsStateMetricsProvider : public MetricsProvider {
123  public:
MetricsStateMetricsProvider(PrefService * local_state,bool metrics_ids_were_reset,std::string previous_client_id,std::string initial_client_id,ClonedInstallDetector const & cloned_install_detector)124   MetricsStateMetricsProvider(
125       PrefService* local_state,
126       bool metrics_ids_were_reset,
127       std::string previous_client_id,
128       std::string initial_client_id,
129       ClonedInstallDetector const& cloned_install_detector)
130       : local_state_(local_state),
131         metrics_ids_were_reset_(metrics_ids_were_reset),
132         previous_client_id_(std::move(previous_client_id)),
133         initial_client_id_(std::move(initial_client_id)),
134         cloned_install_detector_(cloned_install_detector) {}
135 
136   MetricsStateMetricsProvider(const MetricsStateMetricsProvider&) = delete;
137   MetricsStateMetricsProvider& operator=(const MetricsStateMetricsProvider&) =
138       delete;
139 
140   // MetricsProvider:
ProvideSystemProfileMetrics(SystemProfileProto * system_profile)141   void ProvideSystemProfileMetrics(
142       SystemProfileProto* system_profile) override {
143     system_profile->set_uma_enabled_date(
144         RoundSecondsToHour(ReadEnabledDate(local_state_)));
145     system_profile->set_install_date(
146         RoundSecondsToHour(ReadInstallDate(local_state_)));
147 
148     // Client id in the log shouldn't be different than the |local_state_| one
149     // except when the client disabled UMA before we populate this field to the
150     // log. If that's the case, the client id in the |local_state_| should be
151     // empty and we should set |client_id_was_used_for_trial_assignment| to
152     // false.
153     std::string client_id = ReadClientId(local_state_);
154     system_profile->set_client_id_was_used_for_trial_assignment(
155         !client_id.empty() && client_id == initial_client_id_);
156 
157     ClonedInstallInfo cloned =
158         ClonedInstallDetector::ReadClonedInstallInfo(local_state_);
159     if (cloned.reset_count == 0)
160       return;
161     auto* cloned_install_info = system_profile->mutable_cloned_install_info();
162     if (metrics_ids_were_reset_) {
163       // Only report the cloned from client_id in the resetting session.
164       if (!previous_client_id_.empty()) {
165         cloned_install_info->set_cloned_from_client_id(
166             MetricsLog::Hash(previous_client_id_));
167       }
168     }
169     cloned_install_info->set_last_timestamp(
170         RoundSecondsToHour(cloned.last_reset_timestamp));
171     cloned_install_info->set_first_timestamp(
172         RoundSecondsToHour(cloned.first_reset_timestamp));
173     cloned_install_info->set_count(cloned.reset_count);
174   }
175 
ProvidePreviousSessionData(ChromeUserMetricsExtension * uma_proto)176   void ProvidePreviousSessionData(
177       ChromeUserMetricsExtension* uma_proto) override {
178     if (metrics_ids_were_reset_) {
179       LogClonedInstall();
180       if (!previous_client_id_.empty()) {
181         // NOTE: If you are adding anything here, consider also changing
182         // FileMetricsProvider::ProvideIndependentMetricsOnTaskRunner().
183 
184         // If we know the previous client id, overwrite the client id for the
185         // previous session log so the log contains the client id at the time
186         // of the previous session. This allows better attribution of crashes
187         // to earlier behavior. If the previous client id is unknown, leave
188         // the current client id.
189         uma_proto->set_client_id(MetricsLog::Hash(previous_client_id_));
190       }
191     }
192   }
193 
ProvideCurrentSessionData(ChromeUserMetricsExtension * uma_proto)194   void ProvideCurrentSessionData(
195       ChromeUserMetricsExtension* uma_proto) override {
196     if (cloned_install_detector_->ClonedInstallDetectedInCurrentSession()) {
197       LogClonedInstall();
198     }
199     log_normal_metric_state_.LogArtificialNonUniformity();
200   }
201 
202   // Set a random seed for the random number generator.
SetRandomSeedForTesting(int64_t seed)203   void SetRandomSeedForTesting(int64_t seed) {
204     log_normal_metric_state_.gen = std::mt19937(seed);
205   }
206 
207  private:
208   const raw_ptr<PrefService> local_state_;
209   const bool metrics_ids_were_reset_;
210   // |previous_client_id_| is set only (if known) when
211   // |metrics_ids_were_reset_|
212   const std::string previous_client_id_;
213   // The client id that was used to randomize field trials. An empty string if
214   // the low entropy source was used to do randomization.
215   const std::string initial_client_id_;
216   const raw_ref<const ClonedInstallDetector> cloned_install_detector_;
217   LogNormalMetricState log_normal_metric_state_;
218 };
219 
ShouldEnableBenchmarking(bool force_benchmarking_mode)220 bool ShouldEnableBenchmarking(bool force_benchmarking_mode) {
221   // TODO(crbug/1251680): See whether it's possible to consolidate the switches.
222   return force_benchmarking_mode ||
223          base::CommandLine::ForCurrentProcess()->HasSwitch(
224              variations::switches::kEnableBenchmarking);
225 }
226 
227 }  // namespace
228 
229 // static
230 bool MetricsStateManager::instance_exists_ = false;
231 
232 // static
233 bool MetricsStateManager::enable_provisional_client_id_for_testing_ = false;
234 
MetricsStateManager(PrefService * local_state,EnabledStateProvider * enabled_state_provider,const std::wstring & backup_registry_key,const base::FilePath & user_data_dir,EntropyParams entropy_params,StartupVisibility startup_visibility,StoreClientInfoCallback store_client_info,LoadClientInfoCallback retrieve_client_info,base::StringPiece external_client_id)235 MetricsStateManager::MetricsStateManager(
236     PrefService* local_state,
237     EnabledStateProvider* enabled_state_provider,
238     const std::wstring& backup_registry_key,
239     const base::FilePath& user_data_dir,
240     EntropyParams entropy_params,
241     StartupVisibility startup_visibility,
242     StoreClientInfoCallback store_client_info,
243     LoadClientInfoCallback retrieve_client_info,
244     base::StringPiece external_client_id)
245     : local_state_(local_state),
246       enabled_state_provider_(enabled_state_provider),
247       entropy_params_(entropy_params),
248       store_client_info_(std::move(store_client_info)),
249       load_client_info_(std::move(retrieve_client_info)),
250       clean_exit_beacon_(backup_registry_key, user_data_dir, local_state),
251       external_client_id_(external_client_id),
252       entropy_state_(local_state),
253       entropy_source_returned_(ENTROPY_SOURCE_NONE),
254       metrics_ids_were_reset_(false),
255       startup_visibility_(startup_visibility) {
256   DCHECK(!store_client_info_.is_null());
257   DCHECK(!load_client_info_.is_null());
258   ResetMetricsIDsIfNecessary();
259 
260   [[maybe_unused]] bool is_first_run = false;
261   int64_t install_date = local_state_->GetInt64(prefs::kInstallDate);
262 
263   // Set the install date if this is our first run.
264   if (install_date == 0) {
265     local_state_->SetInt64(prefs::kInstallDate, base::Time::Now().ToTimeT());
266     is_first_run = true;
267   }
268 
269   if (enabled_state_provider_->IsConsentGiven()) {
270     ForceClientIdCreation();
271   } else {
272 #if BUILDFLAG(IS_ANDROID)
273     // If on start up we determine that the client has not given their consent
274     // to report their metrics, the new sampling trial should be used to
275     // determine whether the client is sampled in or out (if the user ever
276     // enables metrics reporting). This covers users that are going through
277     // the first run, as well as users that have metrics reporting disabled.
278     //
279     // See crbug/1306481 and the comment above |kUsePostFREFixSamplingTrial| in
280     // components/metrics/metrics_pref_names.cc for more details.
281     local_state_->SetBoolean(metrics::prefs::kUsePostFREFixSamplingTrial, true);
282 #endif  // BUILDFLAG(IS_ANDROID)
283   }
284 
285   // Generate and store a provisional client ID if necessary. This ID will be
286   // used for field trial randomization on first run (and possibly in future
287   // runs if the user closes Chrome during the FRE) and will be promoted to
288   // become the client ID if UMA is enabled during this session, via the logic
289   // in ForceClientIdCreation(). If UMA is disabled (refused), we discard it.
290   //
291   // Note: This means that if a provisional client ID is used for this session,
292   // and the user disables (refuses) UMA, then starting from the next run, the
293   // field trial randomization (group assignment) will be different.
294   if (ShouldGenerateProvisionalClientId(is_first_run)) {
295     local_state_->SetString(prefs::kMetricsProvisionalClientID,
296                             base::Uuid::GenerateRandomV4().AsLowercaseString());
297   }
298 
299   // The |initial_client_id_| should only be set if UMA is enabled or there's a
300   // provisional client id.
301   initial_client_id_ =
302       (client_id_.empty()
303            ? local_state_->GetString(prefs::kMetricsProvisionalClientID)
304            : client_id_);
305   DCHECK(!instance_exists_);
306   instance_exists_ = true;
307 }
308 
~MetricsStateManager()309 MetricsStateManager::~MetricsStateManager() {
310   DCHECK(instance_exists_);
311   instance_exists_ = false;
312 }
313 
GetProvider()314 std::unique_ptr<MetricsProvider> MetricsStateManager::GetProvider() {
315   return std::make_unique<MetricsStateMetricsProvider>(
316       local_state_, metrics_ids_were_reset_, previous_client_id_,
317       initial_client_id_, cloned_install_detector_);
318 }
319 
320 std::unique_ptr<MetricsProvider>
GetProviderAndSetRandomSeedForTesting(int64_t seed)321 MetricsStateManager::GetProviderAndSetRandomSeedForTesting(int64_t seed) {
322   auto provider = std::make_unique<MetricsStateMetricsProvider>(
323       local_state_, metrics_ids_were_reset_, previous_client_id_,
324       initial_client_id_, cloned_install_detector_);
325   provider->SetRandomSeedForTesting(seed);  // IN-TEST
326   return provider;
327 }
328 
IsMetricsReportingEnabled()329 bool MetricsStateManager::IsMetricsReportingEnabled() {
330   return enabled_state_provider_->IsReportingEnabled();
331 }
332 
IsExtendedSafeModeSupported() const333 bool MetricsStateManager::IsExtendedSafeModeSupported() const {
334   return clean_exit_beacon_.IsExtendedSafeModeSupported();
335 }
336 
GetLowEntropySource()337 int MetricsStateManager::GetLowEntropySource() {
338   return entropy_state_.GetLowEntropySource();
339 }
340 
GetOldLowEntropySource()341 int MetricsStateManager::GetOldLowEntropySource() {
342   return entropy_state_.GetOldLowEntropySource();
343 }
344 
GetPseudoLowEntropySource()345 int MetricsStateManager::GetPseudoLowEntropySource() {
346   return entropy_state_.GetPseudoLowEntropySource();
347 }
348 
InstantiateFieldTrialList()349 void MetricsStateManager::InstantiateFieldTrialList() {
350   // Instantiate the FieldTrialList to support field trials. If an instance
351   // already exists, this is likely a test scenario with a ScopedFeatureList, so
352   // use the existing instance so that any overrides are still applied.
353   if (!base::FieldTrialList::GetInstance()) {
354     // This is intentionally leaked since it needs to live for the duration of
355     // the browser process and there's no benefit in cleaning it up at exit.
356     base::FieldTrialList* leaked_field_trial_list = new base::FieldTrialList();
357     ANNOTATE_LEAKING_OBJECT_PTR(leaked_field_trial_list);
358     std::ignore = leaked_field_trial_list;
359   }
360 
361   // When benchmarking is enabled, field trials' default groups are chosen, so
362   // see whether benchmarking needs to be enabled here, before any field trials
363   // are created.
364   // TODO(crbug/1257204): Some FieldTrial-setup-related code is here and some is
365   // in VariationsFieldTrialCreator::SetUpFieldTrials(). It's not ideal that
366   // it's in two places.
367   if (ShouldEnableBenchmarking(entropy_params_.force_benchmarking_mode))
368     base::FieldTrial::EnableBenchmarking();
369 
370   const base::CommandLine* command_line =
371       base::CommandLine::ForCurrentProcess();
372   if (command_line->HasSwitch(variations::switches::kForceFieldTrialParams)) {
373     bool result =
374         variations::AssociateParamsFromString(command_line->GetSwitchValueASCII(
375             variations::switches::kForceFieldTrialParams));
376     if (!result) {
377       // Some field trial params implement things like csv or json with a
378       // particular param. If some control characters are not %-encoded, it can
379       // lead to confusing error messages, so add a hint here.
380       ExitWithMessage(base::StringPrintf(
381           "Invalid --%s list specified. Make sure you %%-"
382           "encode the following characters in param values: %%:/.,",
383           variations::switches::kForceFieldTrialParams));
384     }
385   }
386 
387   // Ensure any field trials specified on the command line are initialized.
388   if (command_line->HasSwitch(::switches::kForceFieldTrials)) {
389     // Create field trials without activating them, so that this behaves in a
390     // consistent manner with field trials created from the server.
391     bool result = base::FieldTrialList::CreateTrialsFromString(
392         command_line->GetSwitchValueASCII(::switches::kForceFieldTrials));
393     if (!result) {
394       ExitWithMessage(base::StringPrintf("Invalid --%s list specified.",
395                                          ::switches::kForceFieldTrials));
396     }
397   }
398 
399   // Initializing the CleanExitBeacon is done after FieldTrialList instantiation
400   // to allow experimentation on the CleanExitBeacon.
401   clean_exit_beacon_.Initialize();
402 }
403 
LogHasSessionShutdownCleanly(bool has_session_shutdown_cleanly,bool is_extended_safe_mode)404 void MetricsStateManager::LogHasSessionShutdownCleanly(
405     bool has_session_shutdown_cleanly,
406     bool is_extended_safe_mode) {
407   clean_exit_beacon_.WriteBeaconValue(has_session_shutdown_cleanly,
408                                       is_extended_safe_mode);
409 }
410 
ForceClientIdCreation()411 void MetricsStateManager::ForceClientIdCreation() {
412   // TODO(asvitkine): Ideally, all tests would actually set up consent properly,
413   // so the command-line checks wouldn't be needed here.
414   // Currently, kForceEnableMetricsReporting is used by Java UkmTest and
415   // kMetricsRecordingOnly is used by Chromedriver tests.
416   DCHECK(enabled_state_provider_->IsConsentGiven() ||
417          IsMetricsReportingForceEnabled() || IsMetricsRecordingOnlyEnabled());
418   if (!external_client_id_.empty()) {
419     client_id_ = external_client_id_;
420     base::UmaHistogramEnumeration("UMA.ClientIdSource",
421                                   ClientIdSource::kClientIdFromExternal);
422     local_state_->SetString(prefs::kMetricsClientID, client_id_);
423     return;
424   }
425 #if BUILDFLAG(IS_CHROMEOS_ASH)
426   std::string previous_client_id = client_id_;
427 #endif  // BUILDFLAG(IS_CHROMEOS_ASH)
428   {
429     std::string client_id_from_prefs = ReadClientId(local_state_);
430     // If client id in prefs matches the cached copy, return early.
431     if (!client_id_from_prefs.empty() && client_id_from_prefs == client_id_) {
432       base::UmaHistogramEnumeration("UMA.ClientIdSource",
433                                     ClientIdSource::kClientIdMatches);
434       return;
435     }
436     client_id_.swap(client_id_from_prefs);
437   }
438 
439   if (!client_id_.empty()) {
440     base::UmaHistogramEnumeration("UMA.ClientIdSource",
441                                   ClientIdSource::kClientIdFromLocalState);
442     return;
443   }
444 
445   const std::unique_ptr<ClientInfo> client_info_backup = LoadClientInfo();
446   if (client_info_backup) {
447     client_id_ = client_info_backup->client_id;
448 
449     const base::Time now = base::Time::Now();
450 
451     // Save the recovered client id and also try to reinstantiate the backup
452     // values for the dates corresponding with that client id in order to avoid
453     // weird scenarios where we could report an old client id with a recent
454     // install date.
455     local_state_->SetString(prefs::kMetricsClientID, client_id_);
456     local_state_->SetInt64(prefs::kInstallDate,
457                            client_info_backup->installation_date != 0
458                                ? client_info_backup->installation_date
459                                : now.ToTimeT());
460     local_state_->SetInt64(prefs::kMetricsReportingEnabledTimestamp,
461                            client_info_backup->reporting_enabled_date != 0
462                                ? client_info_backup->reporting_enabled_date
463                                : now.ToTimeT());
464 
465     base::TimeDelta recovered_installation_age;
466     if (client_info_backup->installation_date != 0) {
467       recovered_installation_age =
468           now - base::Time::FromTimeT(client_info_backup->installation_date);
469     }
470     base::UmaHistogramEnumeration("UMA.ClientIdSource",
471                                   ClientIdSource::kClientIdBackupRecovered);
472     base::UmaHistogramCounts10000("UMA.ClientIdBackupRecoveredWithAge",
473                                   recovered_installation_age.InHours());
474 
475     // Flush the backup back to persistent storage in case we re-generated
476     // missing data above.
477     BackUpCurrentClientInfo();
478     return;
479   }
480 
481   // If we're here, there was no client ID yet (either in prefs or backup),
482   // so generate a new one. If there's a provisional client id (e.g. UMA
483   // was enabled as part of first run), promote that to the client id,
484   // otherwise (e.g. UMA enabled in a future session), generate a new one.
485   std::string provisional_client_id =
486       local_state_->GetString(prefs::kMetricsProvisionalClientID);
487   if (provisional_client_id.empty()) {
488     client_id_ = base::Uuid::GenerateRandomV4().AsLowercaseString();
489     base::UmaHistogramEnumeration("UMA.ClientIdSource",
490                                   ClientIdSource::kClientIdNew);
491   } else {
492     client_id_ = provisional_client_id;
493     local_state_->ClearPref(prefs::kMetricsProvisionalClientID);
494     base::UmaHistogramEnumeration("UMA.ClientIdSource",
495                                   ClientIdSource::kClientIdFromProvisionalId);
496   }
497   local_state_->SetString(prefs::kMetricsClientID, client_id_);
498 
499   // Record the timestamp of when the user opted in to UMA.
500   local_state_->SetInt64(prefs::kMetricsReportingEnabledTimestamp,
501                          base::Time::Now().ToTimeT());
502 
503   BackUpCurrentClientInfo();
504 }
505 
SetExternalClientId(const std::string & id)506 void MetricsStateManager::SetExternalClientId(const std::string& id) {
507   external_client_id_ = id;
508 }
509 
CheckForClonedInstall()510 void MetricsStateManager::CheckForClonedInstall() {
511   cloned_install_detector_.CheckForClonedInstall(local_state_);
512 }
513 
ShouldResetClientIdsOnClonedInstall()514 bool MetricsStateManager::ShouldResetClientIdsOnClonedInstall() {
515   return cloned_install_detector_.ShouldResetClientIds(local_state_);
516 }
517 
518 base::CallbackListSubscription
AddOnClonedInstallDetectedCallback(base::OnceClosure callback)519 MetricsStateManager::AddOnClonedInstallDetectedCallback(
520     base::OnceClosure callback) {
521   return cloned_install_detector_.AddOnClonedInstallDetectedCallback(
522       std::move(callback));
523 }
524 
525 std::unique_ptr<const variations::EntropyProviders>
CreateEntropyProviders()526 MetricsStateManager::CreateEntropyProviders() {
527   return std::make_unique<variations::EntropyProviders>(
528       GetHighEntropySource(),
529       variations::ValueInRange{
530           .value = base::checked_cast<uint32_t>(GetLowEntropySource()),
531           .range = EntropyState::kMaxLowEntropySize},
532       ShouldEnableBenchmarking(entropy_params_.force_benchmarking_mode));
533 }
534 
535 // static
Create(PrefService * local_state,EnabledStateProvider * enabled_state_provider,const std::wstring & backup_registry_key,const base::FilePath & user_data_dir,StartupVisibility startup_visibility,EntropyParams entropy_params,StoreClientInfoCallback store_client_info,LoadClientInfoCallback retrieve_client_info,base::StringPiece external_client_id)536 std::unique_ptr<MetricsStateManager> MetricsStateManager::Create(
537     PrefService* local_state,
538     EnabledStateProvider* enabled_state_provider,
539     const std::wstring& backup_registry_key,
540     const base::FilePath& user_data_dir,
541     StartupVisibility startup_visibility,
542     EntropyParams entropy_params,
543     StoreClientInfoCallback store_client_info,
544     LoadClientInfoCallback retrieve_client_info,
545     base::StringPiece external_client_id) {
546   std::unique_ptr<MetricsStateManager> result;
547   // Note: |instance_exists_| is updated in the constructor and destructor.
548   if (!instance_exists_) {
549     result.reset(new MetricsStateManager(
550         local_state, enabled_state_provider, backup_registry_key, user_data_dir,
551         entropy_params, startup_visibility,
552         store_client_info.is_null() ? base::DoNothing()
553                                     : std::move(store_client_info),
554         retrieve_client_info.is_null()
555             ? base::BindRepeating(&NoOpLoadClientInfoBackup)
556             : std::move(retrieve_client_info),
557         external_client_id));
558   }
559   return result;
560 }
561 
562 // static
RegisterPrefs(PrefRegistrySimple * registry)563 void MetricsStateManager::RegisterPrefs(PrefRegistrySimple* registry) {
564   registry->RegisterStringPref(prefs::kMetricsProvisionalClientID,
565                                std::string());
566   registry->RegisterStringPref(prefs::kMetricsClientID, std::string());
567   registry->RegisterInt64Pref(prefs::kMetricsReportingEnabledTimestamp, 0);
568   registry->RegisterInt64Pref(prefs::kInstallDate, 0);
569 #if BUILDFLAG(IS_ANDROID)
570   registry->RegisterBooleanPref(prefs::kUsePostFREFixSamplingTrial, false);
571 #endif  // BUILDFLAG(IS_ANDROID)
572 
573   EntropyState::RegisterPrefs(registry);
574   ClonedInstallDetector::RegisterPrefs(registry);
575 }
576 
BackUpCurrentClientInfo()577 void MetricsStateManager::BackUpCurrentClientInfo() {
578   ClientInfo client_info;
579   client_info.client_id = client_id_;
580   client_info.installation_date = ReadInstallDate(local_state_);
581   client_info.reporting_enabled_date = ReadEnabledDate(local_state_);
582   store_client_info_.Run(client_info);
583 }
584 
LoadClientInfo()585 std::unique_ptr<ClientInfo> MetricsStateManager::LoadClientInfo() {
586   // If a cloned install was detected, loading ClientInfo from backup will be
587   // a race condition with clearing the backup. Skip all backup reads for this
588   // session.
589   if (metrics_ids_were_reset_)
590     return nullptr;
591 
592   std::unique_ptr<ClientInfo> client_info = load_client_info_.Run();
593 
594   // The GUID retrieved should be valid unless retrieval failed.
595   // If not, return nullptr. This will result in a new GUID being generated by
596   // the calling function ForceClientIdCreation().
597   if (client_info &&
598       !base::Uuid::ParseCaseInsensitive(client_info->client_id).is_valid()) {
599     return nullptr;
600   }
601 
602   return client_info;
603 }
604 
GetHighEntropySource()605 std::string MetricsStateManager::GetHighEntropySource() {
606   // If high entropy randomization is not supported in this context (e.g. in
607   // webview), or if UMA is not enabled (so there is no client id), then high
608   // entropy randomization is disabled.
609   if (entropy_params_.default_entropy_provider_type ==
610           EntropyProviderType::kLow ||
611       initial_client_id_.empty()) {
612     UpdateEntropySourceReturnedValue(ENTROPY_SOURCE_LOW);
613     return "";
614   }
615   UpdateEntropySourceReturnedValue(ENTROPY_SOURCE_HIGH);
616   return entropy_state_.GetHighEntropySource(initial_client_id_);
617 }
618 
UpdateEntropySourceReturnedValue(EntropySourceType type)619 void MetricsStateManager::UpdateEntropySourceReturnedValue(
620     EntropySourceType type) {
621   if (entropy_source_returned_ != ENTROPY_SOURCE_NONE)
622     return;
623 
624   entropy_source_returned_ = type;
625   base::UmaHistogramEnumeration("UMA.EntropySourceType", type,
626                                 ENTROPY_SOURCE_ENUM_SIZE);
627 }
628 
ResetMetricsIDsIfNecessary()629 void MetricsStateManager::ResetMetricsIDsIfNecessary() {
630   if (!ShouldResetClientIdsOnClonedInstall())
631     return;
632   metrics_ids_were_reset_ = true;
633   previous_client_id_ = ReadClientId(local_state_);
634 
635   base::UmaHistogramBoolean("UMA.MetricsIDsReset", true);
636 
637   DCHECK(client_id_.empty());
638 
639   local_state_->ClearPref(prefs::kMetricsClientID);
640   local_state_->ClearPref(prefs::kMetricsLogRecordId);
641   EntropyState::ClearPrefs(local_state_);
642 
643   ClonedInstallDetector::RecordClonedInstallInfo(local_state_);
644 
645   // Also clear the backed up client info. This is asynchronus; any reads
646   // shortly after may retrieve the old ClientInfo from the backup.
647   store_client_info_.Run(ClientInfo());
648 }
649 
ShouldGenerateProvisionalClientId(bool is_first_run)650 bool MetricsStateManager::ShouldGenerateProvisionalClientId(bool is_first_run) {
651 #if BUILDFLAG(IS_WIN)
652   // We do not want to generate a provisional client ID on Windows because
653   // there's no UMA checkbox on first run. Instead it comes from the install
654   // page. So if UMA is not enabled at this point, it's unlikely it will be
655   // enabled in the same session since that requires the user to manually do
656   // that via settings page after they unchecked it on the download page.
657   //
658   // Note: Windows first run is covered by browser tests
659   // FirstRunMasterPrefsVariationsSeedTest.PRE_SecondRun and
660   // FirstRunMasterPrefsVariationsSeedTest.SecondRun. If the platform ifdef
661   // for this logic changes, the tests should be updated as well.
662   return false;
663 #else
664   // We should only generate a provisional client ID on the first run. If for
665   // some reason there is already a client ID, we do not generate one either.
666   // This can happen if metrics reporting is managed by a policy.
667   if (!is_first_run || !client_id_.empty())
668     return false;
669 
670   // Return false if |kMetricsReportingEnabled| is managed by a policy. For
671   // example, if metrics reporting is disabled by a policy, then
672   // |kMetricsReportingEnabled| will always be set to false, so there is no
673   // reason to generate a provisional client ID. If metrics reporting is enabled
674   // by a policy, then the default value of |kMetricsReportingEnabled| will be
675   // true, and so a client ID will have already been generated (we would have
676   // returned false already because of the previous check).
677   if (local_state_->IsManagedPreference(prefs::kMetricsReportingEnabled))
678     return false;
679 
680   // If this is a non-Google-Chrome-branded build, we do not want to generate a
681   // provisional client ID because metrics reporting is not enabled on those
682   // builds. This would be problematic because we store the provisional client
683   // ID in the Local State, and clear it when either 1) we enable UMA (the
684   // provisional client ID becomes the client ID), or 2) we disable UMA. Since
685   // in non-Google-Chrome-branded builds we never actually go through the code
686   // paths to either enable or disable UMA, the pref storing the provisional
687   // client ID would never be cleared. However, for test consistency between
688   // the different builds, we do not return false here if
689   // |enable_provisional_client_id_for_testing_| is set to true.
690   if (!BUILDFLAG(GOOGLE_CHROME_BRANDING) &&
691       !enable_provisional_client_id_for_testing_) {
692     return false;
693   }
694 
695   return true;
696 #endif  // BUILDFLAG(IS_WIN)
697 }
698 
699 }  // namespace metrics
700