File: key_data.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (155 lines) | stat: -rw-r--r-- 5,386 bytes parent folder | download | duplicates (5)
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
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/metrics/structured/lib/key_data.h"

#include <memory>
#include <utility>

#include "base/check.h"
#include "base/logging.h"
#include "base/notreached.h"
#include "base/numerics/byte_conversions.h"
#include "base/rand_util.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
#include "base/unguessable_token.h"
#include "components/metrics/structured/lib/histogram_util.h"
#include "components/metrics/structured/lib/key_util.h"
#include "crypto/hash.h"
#include "crypto/hmac.h"

namespace metrics::structured {
namespace {

std::string HashToHex(const uint64_t hash) {
  return base::HexEncode(&hash, sizeof(uint64_t));
}

int NowInDays() {
  return (base::Time::Now() - base::Time::UnixEpoch()).InDays();
}

}  // namespace

KeyData::KeyData(std::unique_ptr<StorageDelegate> storage_delegate)
    : storage_delegate_(std::move(storage_delegate)) {
  CHECK(storage_delegate_);
}
KeyData::~KeyData() = default;

uint64_t KeyData::Id(const uint64_t project_name_hash,
                     base::TimeDelta key_rotation_period) {
  if (!storage_delegate_->IsReady()) {
    return 0u;
  }

  // Retrieve the key for |project_name_hash|.
  EnsureKeyUpdated(project_name_hash, key_rotation_period);
  const std::optional<std::string_view> key = GetKeyBytes(project_name_hash);
  CHECK(key);

  // Compute and return the hash.
  auto hash = crypto::hash::Sha256(*key);
  return base::U64FromNativeEndian(base::span<uint8_t>(hash).first<8>());
}

uint64_t KeyData::HmacMetric(const uint64_t project_name_hash,
                             const uint64_t metric_name_hash,
                             const std::string& value,
                             base::TimeDelta key_rotation_period) {
  if (!storage_delegate_->IsReady()) {
    return 0u;
  }

  // Retrieve the key for |project_name_hash|.
  EnsureKeyUpdated(project_name_hash, key_rotation_period);
  const std::optional<std::string_view> key = GetKeyBytes(project_name_hash);
  CHECK(key);

  // Compute and return the digest.
  const std::string salted_value =
      base::StrCat({HashToHex(metric_name_hash), value});
  auto hmac = crypto::hmac::SignSha256(base::as_byte_span(*key),
                                       base::as_byte_span(salted_value));
  return base::U64FromNativeEndian(base::span<uint8_t>(hmac).first<8>());
}

std::optional<base::TimeDelta> KeyData::LastKeyRotation(
    const uint64_t project_name_hash) const {
  const KeyProto* key = storage_delegate_->GetKey(project_name_hash);
  if (!key) {
    return std::nullopt;
  }
  return base::Days(key->last_rotation());
}

std::optional<int> KeyData::GetKeyAgeInWeeks(uint64_t project_name_hash) const {
  std::optional<base::TimeDelta> last_rotation =
      LastKeyRotation(project_name_hash);
  if (!last_rotation.has_value()) {
    return std::nullopt;
  }
  const int now = NowInDays();
  const int days_since_rotation = now - last_rotation->InDays();
  return days_since_rotation / 7;
}

void KeyData::Purge() {
  storage_delegate_->Purge();
}

void KeyData::EnsureKeyUpdated(const uint64_t project_name_hash,
                               base::TimeDelta key_rotation_period) {
  CHECK(storage_delegate_->IsReady());

  const int now = NowInDays();
  const int key_rotation_period_days = key_rotation_period.InDays();
  const KeyProto* key = storage_delegate_->GetKey(project_name_hash);

  // Generate or rotate key.
  if (!key || key->last_rotation() == 0) {
    LogKeyValidation(KeyValidationState::kCreated);
    // If the key does not exist, generate a new one. Set the last rotation to a
    // uniformly selected day between today and |key_rotation_period| days
    // ago, to uniformly distribute users amongst rotation cohorts.
    const int rotation_seed = base::RandInt(0, key_rotation_period_days - 1);
    storage_delegate_->UpsertKey(project_name_hash,
                                 base::Days(now - rotation_seed),
                                 key_rotation_period);
  } else if (now - key->last_rotation() > key_rotation_period_days) {
    LogKeyValidation(KeyValidationState::kRotated);
    // If the key is outdated, generate a new one. Update the last rotation
    // such that the user stays in the same cohort.
    //
    // Note that if the max key rotation period has changed, the new rotation
    // period will be used to calculate whether the key should be rotated or
    // not.
    const int new_last_rotation =
        now - (now - key->last_rotation()) % key_rotation_period_days;
    storage_delegate_->UpsertKey(
        project_name_hash, base::Days(new_last_rotation), key_rotation_period);
  } else {
    LogKeyValidation(KeyValidationState::kValid);
  }
}

const std::optional<std::string_view> KeyData::GetKeyBytes(
    const uint64_t project_name_hash) const {
  // Re-fetch the key after keys are rotated.
  const KeyProto* key = storage_delegate_->GetKey(project_name_hash);
  if (!key) {
    return std::nullopt;
  }

  // Return the key unless it's the wrong size, in which case return nullopt.
  const std::string_view key_string = key->key();
  if (key_string.size() != kKeySize) {
    return std::nullopt;
  }
  return key_string;
}

}  // namespace metrics::structured