local_state_utils.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2022 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 "components/local_state/local_state_utils.h"
  5. #include <string>
  6. #include <vector>
  7. #include "base/json/json_string_value_serializer.h"
  8. #include "base/strings/string_util.h"
  9. #include "base/values.h"
  10. #include "build/build_config.h"
  11. #include "build/chromeos_buildflags.h"
  12. #include "components/prefs/pref_service.h"
  13. #if BUILDFLAG(IS_CHROMEOS_ASH)
  14. #define ENABLE_FILTERING true
  15. #else
  16. #define ENABLE_FILTERING false
  17. #endif // BUILDFLAG(IS_CHROMEOS_ASH)
  18. namespace {
  19. // Returns true if |pref_name| starts with one of the |valid_prefixes|.
  20. bool HasValidPrefix(const std::string& pref_name,
  21. const std::vector<std::string> valid_prefixes) {
  22. for (const std::string& prefix : valid_prefixes) {
  23. if (base::StartsWith(pref_name, prefix, base::CompareCase::SENSITIVE))
  24. return true;
  25. }
  26. return false;
  27. }
  28. } // namespace
  29. namespace internal {
  30. void FilterPrefs(const std::vector<std::string>& valid_prefixes,
  31. base::Value& prefs) {
  32. std::vector<std::string> prefs_to_remove;
  33. for (auto it : prefs.DictItems()) {
  34. if (!HasValidPrefix(it.first, valid_prefixes))
  35. prefs_to_remove.push_back(it.first);
  36. }
  37. for (const std::string& pref_to_remove : prefs_to_remove) {
  38. bool successfully_removed = prefs.RemovePath(pref_to_remove);
  39. DCHECK(successfully_removed);
  40. }
  41. }
  42. } // namespace internal
  43. bool GetPrefsAsJson(PrefService* pref_service, std::string* json_string) {
  44. base::Value local_state_values =
  45. pref_service->GetPreferenceValues(PrefService::EXCLUDE_DEFAULTS);
  46. if (ENABLE_FILTERING) {
  47. // Filter out the prefs to only include variations and UMA related fields,
  48. // which don't contain PII.
  49. std::vector<std::string> allowlisted_prefixes = {"variations",
  50. "user_experience_metrics"};
  51. internal::FilterPrefs(allowlisted_prefixes, local_state_values);
  52. }
  53. JSONStringValueSerializer serializer(json_string);
  54. serializer.set_pretty_print(true);
  55. return serializer.Serialize(local_state_values);
  56. }