aw_feature_list_creator.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "android_webview/browser/aw_feature_list_creator.h"
  5. #include <memory>
  6. #include <set>
  7. #include <string>
  8. #include <utility>
  9. #include <vector>
  10. #include "android_webview/browser/aw_browser_context.h"
  11. #include "android_webview/browser/aw_browser_process.h"
  12. #include "android_webview/browser/aw_feature_entries.h"
  13. #include "android_webview/browser/aw_metrics_service_client_delegate.h"
  14. #include "android_webview/browser/metrics/aw_metrics_service_client.h"
  15. #include "android_webview/browser/tracing/aw_tracing_delegate.h"
  16. #include "android_webview/browser/variations/variations_seed_loader.h"
  17. #include "android_webview/common/aw_switches.h"
  18. #include "android_webview/proto/aw_variations_seed.pb.h"
  19. #include "base/bind.h"
  20. #include "base/callback_helpers.h"
  21. #include "base/command_line.h"
  22. #include "base/feature_list.h"
  23. #include "base/files/file_path.h"
  24. #include "base/metrics/field_trial.h"
  25. #include "base/path_service.h"
  26. #include "base/strings/string_split.h"
  27. #include "base/time/time.h"
  28. #include "base/trace_event/trace_event.h"
  29. #include "components/autofill/core/common/autofill_prefs.h"
  30. #include "components/embedder_support/android/metrics/android_metrics_service_client.h"
  31. #include "components/embedder_support/origin_trials/origin_trial_prefs.h"
  32. #include "components/metrics/metrics_pref_names.h"
  33. #include "components/metrics/persistent_histograms.h"
  34. #include "components/policy/core/browser/configuration_policy_pref_store.h"
  35. #include "components/pref_registry/pref_registry_syncable.h"
  36. #include "components/prefs/in_memory_pref_store.h"
  37. #include "components/prefs/json_pref_store.h"
  38. #include "components/prefs/pref_registry_simple.h"
  39. #include "components/prefs/pref_service.h"
  40. #include "components/prefs/pref_service_factory.h"
  41. #include "components/prefs/segregated_pref_store.h"
  42. #include "components/tracing/common/pref_names.h"
  43. #include "components/variations/entropy_provider.h"
  44. #include "components/variations/pref_names.h"
  45. #include "components/variations/service/safe_seed_manager.h"
  46. #include "components/variations/service/variations_service.h"
  47. #include "components/variations/variations_switches.h"
  48. #include "content/public/common/content_switch_dependent_feature_overrides.h"
  49. #include "net/base/features.h"
  50. #include "net/nqe/pref_names.h"
  51. namespace android_webview {
  52. namespace {
  53. bool g_signature_verification_enabled = true;
  54. // These prefs go in the JsonPrefStore, and will persist across runs. Other
  55. // prefs go in the InMemoryPrefStore, and will be lost when the process ends.
  56. const char* const kPersistentPrefsAllowlist[] = {
  57. // Randomly-generated GUID which pseudonymously identifies uploaded metrics.
  58. metrics::prefs::kMetricsClientID,
  59. // Random seed value for variation's entropy providers. Used to assign
  60. // experiment groups.
  61. metrics::prefs::kMetricsLowEntropySource,
  62. // File metrics metadata.
  63. metrics::prefs::kMetricsFileMetricsMetadata,
  64. // Logged directly in the ChromeUserMetricsExtension proto.
  65. metrics::prefs::kInstallDate,
  66. metrics::prefs::kMetricsReportingEnabledTimestamp,
  67. metrics::prefs::kMetricsSessionID,
  68. // Logged in system_profile.stability fields.
  69. metrics::prefs::kStabilityFileMetricsUnsentFilesCount,
  70. metrics::prefs::kStabilityFileMetricsUnsentSamplesCount,
  71. metrics::prefs::kStabilityLaunchCount,
  72. metrics::prefs::kStabilityPageLoadCount,
  73. metrics::prefs::kStabilityRendererLaunchCount,
  74. // Unsent logs.
  75. metrics::prefs::kMetricsInitialLogs,
  76. metrics::prefs::kMetricsOngoingLogs,
  77. // Unsent logs metadata.
  78. metrics::prefs::kMetricsInitialLogsMetadata,
  79. metrics::prefs::kMetricsOngoingLogsMetadata,
  80. net::nqe::kNetworkQualities,
  81. // Current and past country codes, to filter variations studies by country.
  82. variations::prefs::kVariationsCountry,
  83. variations::prefs::kVariationsPermanentConsistencyCountry,
  84. // Last variations seed fetch date/time, used for histograms and to
  85. // determine if the seed is expired.
  86. variations::prefs::kVariationsLastFetchTime,
  87. variations::prefs::kVariationsSeedDate,
  88. // A dictionary that caches 'AppPackageNameLoggingRule' object which decides
  89. // whether the app package name should be recorded in UMA or not.
  90. prefs::kMetricsAppPackageNameLoggingRule,
  91. // The last time the apps package name allowlist was queried from the
  92. // component update service, regardless if it was successful or not.
  93. prefs::kAppPackageNameLoggingRuleLastUpdateTime,
  94. // The state of the previous background tracing session.
  95. tracing::kBackgroundTracingSessionState,
  96. };
  97. void HandleReadError(PersistentPrefStore::PrefReadError error) {}
  98. base::FilePath GetPrefStorePath() {
  99. base::FilePath path;
  100. base::PathService::Get(base::DIR_ANDROID_APP_DATA, &path);
  101. path = path.Append(FILE_PATH_LITERAL("pref_store"));
  102. return path;
  103. }
  104. // Adds WebView-specific switch-dependent feature overrides on top of the ones
  105. // from the content layer.
  106. std::vector<base::FeatureList::FeatureOverrideInfo>
  107. GetSwitchDependentFeatureOverrides(const base::CommandLine& command_line) {
  108. std::vector<base::FeatureList::FeatureOverrideInfo> feature_overrides =
  109. content::GetSwitchDependentFeatureOverrides(command_line);
  110. return feature_overrides;
  111. }
  112. } // namespace
  113. AwFeatureListCreator::AwFeatureListCreator()
  114. : aw_field_trials_(std::make_unique<AwFieldTrials>()) {}
  115. AwFeatureListCreator::~AwFeatureListCreator() {}
  116. void AwFeatureListCreator::CreateFeatureListAndFieldTrials() {
  117. TRACE_EVENT0("startup",
  118. "AwFeatureListCreator::CreateFeatureListAndFieldTrials");
  119. CreateLocalState();
  120. AwMetricsServiceClient::SetInstance(std::make_unique<AwMetricsServiceClient>(
  121. std::make_unique<AwMetricsServiceClientDelegate>()));
  122. AwMetricsServiceClient::GetInstance()->Initialize(local_state_.get());
  123. SetUpFieldTrials();
  124. }
  125. void AwFeatureListCreator::CreateLocalState() {
  126. browser_policy_connector_ = std::make_unique<AwBrowserPolicyConnector>();
  127. local_state_ = CreatePrefService();
  128. }
  129. void AwFeatureListCreator::DisableSignatureVerificationForTesting() {
  130. g_signature_verification_enabled = false;
  131. }
  132. std::unique_ptr<PrefService> AwFeatureListCreator::CreatePrefService() {
  133. auto pref_registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>();
  134. AwMetricsServiceClient::RegisterMetricsPrefs(pref_registry.get());
  135. variations::VariationsService::RegisterPrefs(pref_registry.get());
  136. embedder_support::OriginTrialPrefs::RegisterPrefs(pref_registry.get());
  137. AwBrowserProcess::RegisterNetworkContextLocalStatePrefs(pref_registry.get());
  138. AwBrowserProcess::RegisterEnterpriseAuthenticationAppLinkPolicyPref(
  139. pref_registry.get());
  140. AwTracingDelegate::RegisterPrefs(pref_registry.get());
  141. PrefServiceFactory pref_service_factory;
  142. std::set<std::string> persistent_prefs;
  143. for (const char* const pref_name : kPersistentPrefsAllowlist)
  144. persistent_prefs.insert(pref_name);
  145. persistent_prefs.insert(std::string(metrics::prefs::kMetricsLastSeenPrefix) +
  146. kBrowserMetricsName);
  147. persistent_prefs.insert(std::string(metrics::prefs::kMetricsLastSeenPrefix) +
  148. metrics::kCrashpadHistogramAllocatorName);
  149. // SegregatedPrefStore may be validated with a MAC (message authentication
  150. // code). On Android, the store is protected by app sandboxing, so validation
  151. // is unnnecessary. Thus validation_delegate is null.
  152. pref_service_factory.set_user_prefs(base::MakeRefCounted<SegregatedPrefStore>(
  153. base::MakeRefCounted<InMemoryPrefStore>(),
  154. base::MakeRefCounted<JsonPrefStore>(GetPrefStorePath()),
  155. std::move(persistent_prefs)));
  156. pref_service_factory.set_managed_prefs(
  157. base::MakeRefCounted<policy::ConfigurationPolicyPrefStore>(
  158. browser_policy_connector_.get(),
  159. browser_policy_connector_->GetPolicyService(),
  160. browser_policy_connector_->GetHandlerList(),
  161. policy::POLICY_LEVEL_MANDATORY));
  162. pref_service_factory.set_read_error_callback(
  163. base::BindRepeating(&HandleReadError));
  164. return pref_service_factory.Create(pref_registry);
  165. }
  166. void AwFeatureListCreator::SetUpFieldTrials() {
  167. // The FieldTrialList should have been instantiated in
  168. // AndroidMetricsServiceClient::Initialize().
  169. DCHECK(base::FieldTrialList::GetInstance());
  170. // Convert the AwVariationsSeed proto to a SeedResponse object.
  171. std::unique_ptr<AwVariationsSeed> seed_proto = TakeSeed();
  172. std::unique_ptr<variations::SeedResponse> seed;
  173. base::Time seed_date; // Initializes to null time.
  174. if (seed_proto) {
  175. seed = std::make_unique<variations::SeedResponse>();
  176. seed->data = seed_proto->seed_data();
  177. seed->signature = seed_proto->signature();
  178. seed->country = seed_proto->country();
  179. seed->date = seed_proto->date();
  180. seed->is_gzip_compressed = seed_proto->is_gzip_compressed();
  181. // We set the seed fetch time to when the service downloaded the seed rather
  182. // than base::Time::Now() because we want to compute seed freshness based on
  183. // the initial download time, which happened in the service at some earlier
  184. // point.
  185. seed_date = base::Time::FromJavaTime(seed->date);
  186. }
  187. client_ = std::make_unique<AwVariationsServiceClient>();
  188. auto seed_store = std::make_unique<variations::VariationsSeedStore>(
  189. local_state_.get(), /*initial_seed=*/std::move(seed),
  190. /*signature_verification_enabled=*/g_signature_verification_enabled,
  191. /*use_first_run_prefs=*/false);
  192. if (!seed_date.is_null())
  193. seed_store->RecordLastFetchTime(seed_date);
  194. variations::UIStringOverrider ui_string_overrider;
  195. variations_field_trial_creator_ =
  196. std::make_unique<variations::VariationsFieldTrialCreator>(
  197. client_.get(), std::move(seed_store), ui_string_overrider);
  198. variations_field_trial_creator_->OverrideVariationsPlatform(
  199. variations::Study::PLATFORM_ANDROID_WEBVIEW);
  200. // Safe Mode is a feature which reverts to a previous variations seed if the
  201. // current one is suspected to be causing crashes, or preventing new seeds
  202. // from being downloaded. It's not implemented for WebView because 1) it's
  203. // difficult for WebView to implement Safe Mode's crash detection, and 2)
  204. // downloading and disseminating seeds is handled by the WebView service,
  205. // which itself doesn't support variations; therefore a bad seed shouldn't be
  206. // able to break seed downloads. See https://crbug.com/801771 for more info.
  207. variations::SafeSeedManager ignored_safe_seed_manager(local_state_.get());
  208. auto feature_list = std::make_unique<base::FeatureList>();
  209. std::vector<std::string> variation_ids =
  210. aw_feature_entries::RegisterEnabledFeatureEntries(feature_list.get());
  211. auto* metrics_client = AwMetricsServiceClient::GetInstance();
  212. const base::CommandLine* command_line =
  213. base::CommandLine::ForCurrentProcess();
  214. // Populate FieldTrialList. Since |low_entropy_provider| is null, it will fall
  215. // back to the provider we previously gave to FieldTrialList, which is a low
  216. // entropy provider. The X-Client-Data header is not reported on WebView, so
  217. // we pass an empty object as the |low_entropy_source_value|.
  218. variations_field_trial_creator_->SetUpFieldTrials(
  219. variation_ids,
  220. command_line->GetSwitchValueASCII(
  221. variations::switches::kForceVariationIds),
  222. GetSwitchDependentFeatureOverrides(*command_line),
  223. /*low_entropy_provider=*/nullptr, std::move(feature_list),
  224. metrics_client->metrics_state_manager(), aw_field_trials_.get(),
  225. &ignored_safe_seed_manager, /*low_entropy_source_value=*/absl::nullopt);
  226. }
  227. } // namespace android_webview