File: parsing_utils.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 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 (331 lines) | stat: -rw-r--r-- 10,381 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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// Copyright 2022 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/attribution_reporting/parsing_utils.h"

#include <stddef.h>
#include <stdint.h>

#include <algorithm>
#include <cmath>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "base/check.h"
#include "base/containers/flat_set.h"
#include "base/containers/flat_tree.h"
#include "base/containers/to_vector.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/abseil_string_number_conversions.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#include "base/types/expected.h"
#include "base/types/expected_macros.h"
#include "base/values.h"
#include "components/aggregation_service/parsing_utils.h"
#include "components/attribution_reporting/aggregatable_utils.h"
#include "components/attribution_reporting/constants.h"
#include "components/attribution_reporting/suitable_origin.h"
#include "third_party/abseil-cpp/absl/numeric/int128.h"
#include "url/origin.h"

namespace attribution_reporting {

namespace {

constexpr char kDebugKey[] = "debug_key";
constexpr char kDebugReporting[] = "debug_reporting";

template <typename T>
base::expected<std::optional<T>, ParseError> ParseIntegerFromString(
    const base::Value::Dict& dict,
    std::string_view key,
    bool (*parse)(std::string_view, T*)) {
  const base::Value* value = dict.Find(key);
  if (!value) {
    return std::nullopt;
  }

  T parsed_val;
  if (const std::string* str = value->GetIfString();
      !str || !parse(*str, &parsed_val)) {
    return base::unexpected(ParseError());
  }
  return parsed_val;
}

}  // namespace

base::expected<absl::uint128, ParseError> ParseAggregationKeyPiece(
    const base::Value& value) {
  const std::string* str = value.GetIfString();
  if (!str) {
    return base::unexpected(ParseError());
  }

  absl::uint128 key_piece;

  if (!base::StartsWith(*str, "0x", base::CompareCase::INSENSITIVE_ASCII) ||
      !base::HexStringToUInt128(*str, &key_piece)) {
    return base::unexpected(ParseError());
  }

  return key_piece;
}

std::string HexEncodeAggregationKey(absl::uint128 value) {
  std::ostringstream out;
  out << "0x";
  out.setf(out.hex, out.basefield);
  out << value;
  return std::move(out).str();
}

base::expected<std::optional<uint64_t>, ParseError> ParseUint64(
    const base::Value::Dict& dict,
    std::string_view key) {
  return ParseIntegerFromString<uint64_t>(dict, key, &base::StringToUint64);
}

base::expected<std::optional<int64_t>, ParseError> ParseInt64(
    const base::Value::Dict& dict,
    std::string_view key) {
  return ParseIntegerFromString<int64_t>(dict, key, &base::StringToInt64);
}

base::expected<int64_t, ParseError> ParsePriority(
    const base::Value::Dict& dict) {
  return ParseInt64(dict, kPriority).transform(&ValueOrZero<int64_t>);
}

std::optional<uint64_t> ParseDebugKey(const base::Value::Dict& dict) {
  return ParseUint64(dict, kDebugKey).value_or(std::nullopt);
}

base::expected<std::optional<uint64_t>, ParseError> ParseDeduplicationKey(
    const base::Value::Dict& dict) {
  return ParseUint64(dict, kDeduplicationKey);
}

bool ParseDebugReporting(const base::Value::Dict& dict) {
  return dict.FindBool(kDebugReporting).value_or(false);
}

bool HasFractionalPart(double v) {
  double int_part;
  return std::modf(v, &int_part) != 0;
}

template <typename T>
base::expected<T, ParseError> ParseIntFromIntOrDouble(
    const base::Value& value) {
  // JSON serialization does not distinguish between integer and non-integer
  // numbers, but `base::Value` does. To be maximally compatible, we permit
  // `double` in addition to `int` as long as the `double`'s fractional part is
  // 0.

  if (std::optional<int> int_value = value.GetIfInt()) {
    if (!base::IsValueInRangeForNumericType<T>(*int_value)) {
      return base::unexpected(ParseError());
    }
    return static_cast<T>(*int_value);
  } else if (std::optional<double> double_value = value.GetIfDouble()) {
    if (HasFractionalPart(*double_value) ||
        !base::IsValueInRangeForNumericType<T>(*double_value)) {
      return base::unexpected(ParseError());
    }
    return static_cast<T>(*double_value);
  } else {
    return base::unexpected(ParseError());
  }
}

base::expected<base::TimeDelta, ParseError> ParseLegacyDuration(
    const base::Value& value,
    const base::TimeDelta clamp_min,
    const base::TimeDelta clamp_max) {
  // Note: The full range of uint64 seconds cannot be represented in the
  // resulting `base::TimeDelta`, but this is fine because `base::Seconds()`
  // properly clamps out-of-bound values and because the Attribution
  // Reporting API itself clamps values to 30 days:
  // https://wicg.github.io/attribution-reporting-api/#valid-source-expiry-range

  base::TimeDelta duration;

  if (const std::string* str = value.GetIfString()) {
    uint64_t seconds;
    if (!base::StringToUint64(*str, &seconds)) {
      return base::unexpected(ParseError());
    }
    duration = base::Seconds(seconds);
  } else {
    ASSIGN_OR_RETURN(duration, ParseDuration(value));
  }

  if (duration.is_negative()) {
    return base::unexpected(ParseError());
  }

  return std::clamp(duration, clamp_min, clamp_max);
}

base::expected<base::TimeDelta, ParseError> ParseDuration(
    const base::Value& value) {
  if (std::optional<int> int_value = value.GetIfInt()) {
    return base::Seconds(*int_value);
  } else if (std::optional<double> double_value = value.GetIfDouble()) {
    if (HasFractionalPart(*double_value)) {
      return base::unexpected(ParseError());
    }
    return base::Seconds(*double_value);
  } else {
    return base::unexpected(ParseError());
  }
}

base::expected<std::optional<SuitableOrigin>, ParseError>
ParseAggregationCoordinator(const base::Value::Dict& dict) {
  const base::Value* value = dict.Find(kAggregationCoordinatorOrigin);

  // The default value is used for backward compatibility prior to this
  // attribute being added, but ideally this would invalidate the registration
  // if other aggregatable fields were present.
  if (!value) {
    return std::nullopt;
  }

  const std::string* str = value->GetIfString();
  if (!str) {
    return base::unexpected(ParseError());
  }

  std::optional<url::Origin> aggregation_coordinator =
      aggregation_service::ParseAggregationCoordinator(*str);
  if (!aggregation_coordinator.has_value()) {
    return base::unexpected(ParseError());
  }
  auto aggregation_coordinator_origin =
      SuitableOrigin::Create(*std::move(aggregation_coordinator));
  CHECK(aggregation_coordinator_origin.has_value());
  return *std::move(aggregation_coordinator_origin);
}

base::expected<int, ParseError> ParseAggregatableValue(const base::Value& v) {
  ASSIGN_OR_RETURN(int value, ParseInt(v));
  if (!IsAggregatableValueInRange(value)) {
    return base::unexpected(ParseError());
  }
  return value;
}

void SerializeUint64(base::Value::Dict& dict,
                     std::string_view key,
                     uint64_t value) {
  dict.Set(key, base::NumberToString(value));
}

void SerializeInt64(base::Value::Dict& dict,
                    std::string_view key,
                    int64_t value) {
  dict.Set(key, base::NumberToString(value));
}

void SerializePriority(base::Value::Dict& dict, int64_t priority) {
  SerializeInt64(dict, kPriority, priority);
}

void SerializeDebugKey(base::Value::Dict& dict,
                       std::optional<uint64_t> debug_key) {
  if (debug_key) {
    SerializeUint64(dict, kDebugKey, *debug_key);
  }
}

void SerializeDebugReporting(base::Value::Dict& dict, bool debug_reporting) {
  dict.Set(kDebugReporting, debug_reporting);
}

void SerializeDeduplicationKey(base::Value::Dict& dict,
                               std::optional<uint64_t> dedup_key) {
  if (dedup_key) {
    SerializeUint64(dict, kDeduplicationKey, *dedup_key);
  }
}

void SerializeTimeDeltaInSeconds(base::Value::Dict& dict,
                                 std::string_view key,
                                 base::TimeDelta value) {
  int64_t seconds = value.InSeconds();
  if (base::IsValueInRangeForNumericType<int>(seconds)) {
    dict.Set(key, static_cast<int>(seconds));
  } else {
    SerializeInt64(dict, key, seconds);
  }
}

base::expected<int, ParseError> ParseInt(const base::Value& value) {
  return ParseIntFromIntOrDouble<int>(value);
}

base::expected<uint32_t, ParseError> ParseUint32(const base::Value& value) {
  // Assumes that all `uint32_t` can be represented either by `int` or `double`,
  // and that when represented internally by `base::Value` as an `int`, can be
  // precisely represented by `double`.
  //
  // TODO(apaseltiner): Consider test coverage for all `uint32_t` values, or
  // some kind of fuzzer.
  return ParseIntFromIntOrDouble<uint32_t>(value);
}

base::expected<uint32_t, ParseError> ParsePositiveUint32(
    const base::Value& value) {
  ASSIGN_OR_RETURN(uint32_t int_value, ParseUint32(value));
  if (int_value == 0) {
    return base::unexpected(ParseError());
  }
  return int_value;
}

base::Value Uint32ToJson(uint32_t value) {
  // All `uint32_t` can be represented exactly by `double`.
  return base::IsValueInRangeForNumericType<int>(value)
             ? base::Value(static_cast<int>(value))
             : base::Value(static_cast<double>(value));
}

base::expected<base::flat_set<std::string>, StringSetError> ExtractStringSet(
    base::Value::List list,
    const size_t max_string_size,
    const size_t max_set_size) {
  for (const base::Value& item : list) {
    const std::string* string = item.GetIfString();
    if (!string) {
      return base::unexpected(StringSetError::kWrongType);
    }

    if (string->size() > max_string_size) {
      return base::unexpected(StringSetError::kStringTooLong);
    }
  }

  std::ranges::sort(list);
  auto repeated = std::ranges::unique(list);
  list.erase(repeated.begin(), repeated.end());

  if (list.size() > max_set_size) {
    return base::unexpected(StringSetError::kSetTooLong);
  }

  return base::flat_set<std::string>(
      base::sorted_unique, base::ToVector(list, [](base::Value& item) {
        return std::move(item).TakeString();
      }));
}

}  // namespace attribution_reporting