• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 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 #ifndef COMPONENTS_METRICS_STRUCTURED_KEY_DATA_H_
6 #define COMPONENTS_METRICS_STRUCTURED_KEY_DATA_H_
7 
8 #include <string>
9 
10 #include "base/files/file_path.h"
11 #include "base/memory/scoped_refptr.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/sequence_checker.h"
14 #include "base/task/sequenced_task_runner.h"
15 #include "components/metrics/structured/persistent_proto.h"
16 #include "components/metrics/structured/storage.pb.h"
17 #include "third_party/abseil-cpp/absl/types/optional.h"
18 
19 namespace metrics::structured {
20 
21 class KeyDataTest;
22 
23 // KeyData is the central class for managing keys and generating hashes for
24 // structured metrics.
25 //
26 // The class maintains one key and its rotation data for every project defined
27 // in /tools/metrics/structured.xml. This can be used to generate:
28 //  - an ID for the project with KeyData::Id.
29 //  - a hash of a given value for an event with KeyData::HmacMetric.
30 //
31 // KeyData performs key rotation. Every project is associated with a rotation
32 // period, which is 90 days unless specified in structured.xml. Keys are rotated
33 // with a resolution of one day. They are guaranteed not to be used for
34 // HmacMetric or UserProjectId for longer than their rotation period, except in
35 // cases of local clock changes.
36 //
37 // When first created, every project's key rotation date is selected uniformly
38 // so that there is an even distribution of rotations across users. This means
39 // that, for most users, the first rotation period will be shorter than the
40 // standard full rotation period for that project.
41 //
42 // Key storage is backed by a PersistentProto, stored at the path given to the
43 // constructor.
44 class KeyData {
45  public:
46   KeyData(const base::FilePath& path,
47           const base::TimeDelta& save_delay,
48           base::OnceCallback<void()> on_initialized);
49   ~KeyData();
50 
51   KeyData(const KeyData&) = delete;
52   KeyData& operator=(const KeyData&) = delete;
53 
54   // Returns a digest of |value| for |metric| in the context of
55   // |project_name_hash|. Terminology: a metric is a (name, value) pair, and an
56   // event is a bundle of metrics. Each event is associated with a project.
57   //
58   //  - |project_name_hash| is the uint64 name hash of a project.
59   //  - |metric_name_hash| is the uint64 name hash of a metric.
60   //  - |value| is the string value to hash.
61   //
62   // The result is the HMAC digest of the |value| salted with |metric|, using
63   // the key for |project_name_hash|. That is:
64   //
65   //   HMAC_SHA256(key(project_name_hash), concat(value, hex(event),
66   //   hex(metric)))
67   //
68   // Returns 0u in case of an error.
69   uint64_t HmacMetric(uint64_t project_name_hash,
70                       uint64_t metric_name_hash,
71                       const std::string& value,
72                       int key_rotation_period);
73 
74   // Returns an ID for this (user, |project_name_hash|) pair.
75   // |project_name_hash| is the name of a project, represented by the first 8
76   // bytes of the MD5 hash of its name defined in structured.xml.
77   //
78   // The derived ID is the first 8 bytes of SHA256(key(project_name_hash)).
79   // Returns 0u in case of an error.
80   //
81   // This ID is intended as the only ID for the events of a particular
82   // structured metrics project. However, events are uploaded from the device
83   // alongside the UMA client ID, which is only removed after the event reaches
84   // the server. This means events are associated with the client ID when
85   // uploaded from the device. See the class comment of
86   // StructuredMetricsProvider for more details.
87   //
88   // Default |key_rotation_period| is 90 days.
89   uint64_t Id(uint64_t project_name_hash, int key_rotation_period);
90 
91   // Returns when the key for |project_name_hash| was last rotated, in days
92   // since epoch. Returns nullopt if the key doesn't exist.
93   absl::optional<int> LastKeyRotation(uint64_t project_name_hash);
94 
95   // Clears all key data from memory and from disk. If this is called before the
96   // underlying proto has been read from disk, the purge will be performed once
97   // the read is complete.
98   void Purge();
99 
100   // Returns whether this KeyData instance has finished reading from disk and is
101   // ready to be used. If false, both Id and HmacMetric will return 0u.
is_initialized()102   bool is_initialized() { return is_initialized_; }
103 
104  private:
105   friend class KeyDataTest;
106 
107   void WriteNowForTest();
108 
109   void OnRead(ReadStatus status);
110 
111   void OnWrite(WriteStatus status);
112 
113   // Ensure that a valid key exists for |project|, and return it. Either returns
114   // a string of size |kKeySize| or absl::nullopt, which indicates an error. If
115   // a key doesn't exist OR if the key needs to be rotated, then a new key with
116   // |key_rotation_period| will be created.
117   absl::optional<std::string> ValidateAndGetKey(uint64_t project_name_hash,
118                                                 int key_rotation_period);
119 
120   // Regenerate |key|, also updating the |last_key_rotation| and
121   // |key_rotation_period|. This triggers a save.
122   void UpdateKey(KeyProto* key, int last_key_rotation, int key_rotation_period);
123 
124   // Storage for keys.
125   std::unique_ptr<PersistentProto<KeyDataProto>> proto_;
126 
127   // Whether this instance has finished reading from disk.
128   bool is_initialized_ = false;
129 
130   base::OnceCallback<void()> on_initialized_;
131 
132   SEQUENCE_CHECKER(sequence_checker_);
133 
134   scoped_refptr<base::SequencedTaskRunner> task_runner_;
135   base::WeakPtrFactory<KeyData> weak_factory_{this};
136 };
137 
138 }  // namespace metrics::structured
139 
140 #endif  // COMPONENTS_METRICS_STRUCTURED_KEY_DATA_H_
141