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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
|
// Copyright 2023 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/privacy_sandbox/privacy_sandbox_attestations/privacy_sandbox_attestations.h"
#include <ios>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "base/check.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/scoped_refptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/no_destructor.h"
#include "base/strings/string_split.h"
#include "base/strings/string_view_util.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "base/timer/elapsed_timer.h"
#include "base/trace_event/memory_usage_estimator.h"
#include "base/types/expected.h"
#include "build/buildflag.h"
#include "components/privacy_sandbox/privacy_sandbox_attestations/privacy_sandbox_attestations_histograms.h"
#include "components/privacy_sandbox/privacy_sandbox_attestations/privacy_sandbox_attestations_parser.h"
#include "components/privacy_sandbox/privacy_sandbox_features.h"
#include "components/startup_metric_utils/browser/startup_metric_utils.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/schemeful_site.h"
#include "url/gurl.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/apk_assets.h"
#include "base/containers/span.h"
#include "base/files/memory_mapped_file.h"
#include "components/privacy_sandbox/privacy_sandbox_attestations/preload/android_apk_assets.h"
#endif // BUILDFLAG(IS_ANDROID)
namespace privacy_sandbox {
namespace {
// Global PrivacySandboxAttestations instance for testing.
PrivacySandboxAttestations* g_test_instance = nullptr;
// Helper function that checks if enrollment overrides are set from the
// chrome://flags entry.
bool IsOverriddenByFlags(const net::SchemefulSite& site) {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (!command_line.HasSwitch(
privacy_sandbox::kPrivacySandboxEnrollmentOverrides)) {
return false;
}
std::string origins_str = command_line.GetSwitchValueASCII(
privacy_sandbox::kPrivacySandboxEnrollmentOverrides);
std::vector<std::string> overrides_list = base::SplitString(
origins_str, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
for (std::string override_str : overrides_list) {
if (override_str.empty()) {
continue;
}
GURL override_url(override_str);
if (!override_url.is_valid()) {
continue;
}
if (site.IsSameSiteWith(override_url)) {
return true;
}
}
return false;
}
void RecordParsingStatusHistogram(ParsingStatus status) {
base::UmaHistogramEnumeration(kAttestationsFileParsingStatusUMA, status);
}
// Parse the attestations map from the proto string.
base::expected<PrivacySandboxAttestationsMap, ParsingStatus>
ParseAttestationsMap(const std::string& proto_str) {
base::ElapsedTimer parsing_timer;
std::optional<PrivacySandboxAttestationsMap> attestations_map =
ParseAttestationsFromString(proto_str);
if (!attestations_map.has_value()) {
// The parsing failed.
return base::unexpected(ParsingStatus::kCannotParseFile);
}
// For an attestations file with 10,000 entries, the average parsing time is
// around 240 milliseconds as per local testing on a n2-standard-128 with 128
// vCPUs and 512 GB memory. The estimated dynamic memory usage is around 880
// KB.
base::UmaHistogramTimes(kAttestationsFileParsingTimeUMA,
parsing_timer.Elapsed());
// Count up to 10000 KB with a minimum of 1 KB.
base::UmaHistogramCounts10000(
kAttestationsMapMemoryUsageUMA,
base::trace_event::EstimateMemoryUsage(attestations_map.value()) / 1024);
return base::ok(std::move(attestations_map.value()));
}
// Trigger the opening and parsing of the attestations file. Returns the
// parsed `attestations_map_` or the failure status. This function should only
// be invoked with `kEnforcePrivacySandboxAttestations` enabled.
// `installed_file_path` is the path to the attestations list file.
base::expected<PrivacySandboxAttestationsMap, ParsingStatus>
LoadAttestationsInternal(base::FilePath installed_file_path) {
// This function should only be called when the feature is enabled.
CHECK(base::FeatureList::IsEnabled(
privacy_sandbox::kEnforcePrivacySandboxAttestations));
std::string proto_str;
// When reading the file, the `base::FilePath` directory should be used to
// make sure it works across platforms. If using the converted directory
// returned by `base::FilePath::AsUTF8Unsafe()`, it fails on Windows when the
// directory contains combining characters.
if (!base::ReadFileToString(installed_file_path, &proto_str)) {
return base::unexpected(ParsingStatus::kFileNotExist);
}
return ParseAttestationsMap(proto_str);
}
#if BUILDFLAG(IS_ANDROID)
void RecordLoadAPKAssetStatusHistogram(LoadAPKAssetStatus status) {
base::UmaHistogramEnumeration(kAttestationsLoadAPKAssetStatusUMA, status);
}
// Read the attestations list from APK assets and parse the content to the
// attestations map.
base::expected<PrivacySandboxAttestationsMap, ParsingStatus>
LoadAttestationsFromAPKAsset() {
base::MemoryMappedFile::Region region =
base::MemoryMappedFile::Region::kWholeFile;
// Open the attestation list from APK assets.
int open_list_status = base::android::OpenApkAsset(
std::string(kAttestationsListAssetPath), ®ion);
// The attestations APK assets are unconditionally packaged. It is safe to
// assume that assets exist since they live in the same .apk file as the
// program itself. In case of unexpected failure, the error is recorded to the
// histogram.
if (open_list_status == -1) {
// TODO(crbug.com/408992354): Replace this histogram recording to a CHECK if
// there is few failures observed.
RecordLoadAPKAssetStatusHistogram(LoadAPKAssetStatus::kCannotOpenList);
return base::unexpected(ParsingStatus::kFileNotExist);
}
// Create a memory mapped file of privacy-sandbox-attestations.dat.
base::File list_file(open_list_status);
base::MemoryMappedFile list_memory_mapped_file;
bool mapped =
list_memory_mapped_file.Initialize(std::move(list_file), region);
if (!mapped) {
// TODO(crbug.com/408992354): Replace this histogram recording to a CHECK if
// there is few failures observed.
RecordLoadAPKAssetStatusHistogram(LoadAPKAssetStatus::kCannotMemoryMapList);
return base::unexpected(ParsingStatus::kFileNotExist);
}
const std::string proto_str(
base::as_string_view(base::as_chars(list_memory_mapped_file.bytes())));
base::expected<PrivacySandboxAttestationsMap, ParsingStatus>
attestations_map = ParseAttestationsMap(proto_str);
RecordLoadAPKAssetStatusHistogram(attestations_map.has_value()
? LoadAPKAssetStatus::kSuccess
: LoadAPKAssetStatus::kCannotParseList);
return attestations_map;
}
#endif // BUILDFLAG(IS_ANDROID)
} // namespace
// static
PrivacySandboxAttestations* PrivacySandboxAttestations::GetInstance() {
if (g_test_instance) {
return g_test_instance;
}
static base::NoDestructor<PrivacySandboxAttestations> instance;
return instance.get();
}
// static
void PrivacySandboxAttestations::SetInstanceForTesting(
PrivacySandboxAttestations* test_instance) {
g_test_instance = test_instance;
}
// static
std::unique_ptr<PrivacySandboxAttestations>
PrivacySandboxAttestations::CreateForTesting() {
std::unique_ptr<PrivacySandboxAttestations> test_instance(
new PrivacySandboxAttestations());
return test_instance;
}
PrivacySandboxAttestations::~PrivacySandboxAttestations() = default;
PrivacySandboxSettingsImpl::Status PrivacySandboxAttestations::IsSiteAttested(
const net::SchemefulSite& site,
PrivacySandboxAttestationsGatedAPI invoking_api,
std::optional<AttestationsDefaultBehavior> attestations_default_behavior)
const {
PrivacySandboxSettingsImpl::Status status =
IsSiteAttestedInternal(site, invoking_api);
base::UmaHistogramEnumeration(kAttestationStatusUMA, status);
// Record the time when the first Privacy Sandbox API attestation check takes
// place.
startup_metric_utils::GetBrowser().RecordPrivacySandboxAttestationFirstCheck(
base::TimeTicks::Now());
// If the attestations map is absent and feature
// `kDefaultAllowPrivacySandboxAttestations` is on, default allow.
switch (status) {
case PrivacySandboxSettingsImpl::Status::kAttestationsFileNotPresent:
case PrivacySandboxSettingsImpl::Status::
kAttestationsDownloadedNotYetLoaded:
case PrivacySandboxSettingsImpl::Status::kAttestationsFileCorrupt:
case PrivacySandboxSettingsImpl::Status::kAttestationsFileNotYetChecked:
if (attestations_default_behavior.has_value()) {
switch (*attestations_default_behavior) {
case AttestationsDefaultBehavior::kAllow:
return PrivacySandboxSettingsImpl::Status::kAllowed;
case AttestationsDefaultBehavior::kDeny:
return status;
}
} else {
return base::FeatureList::IsEnabled(
kDefaultAllowPrivacySandboxAttestations)
? PrivacySandboxSettingsImpl::Status::kAllowed
: status;
}
default: {
// Record whether the attestation map is parsed from the pre-installed or
// downloaded file.
base::UmaHistogramEnumeration(kAttestationsFileSource,
is_pre_installed()
? FileSource::kPreInstalled
: FileSource::kDownloaded);
return status;
}
}
}
PrivacySandboxSettingsImpl::Status
PrivacySandboxAttestations::IsSiteAttestedInternal(
const net::SchemefulSite& site,
PrivacySandboxAttestationsGatedAPI invoking_api) const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// If attestations aren't enabled, pass the check trivially.
if (!base::FeatureList::IsEnabled(
privacy_sandbox::kEnforcePrivacySandboxAttestations)) {
return PrivacySandboxSettingsImpl::Status::kAllowed;
}
// Test has marked all Privacy Sandbox APIs as attested for any given site.
if (is_all_apis_attested_for_testing_) {
return PrivacySandboxSettingsImpl::Status::kAllowed;
}
// Pass the check if the site is in the list of devtools overrides.
if (IsOverridden(site)) {
return PrivacySandboxSettingsImpl::Status::kAllowed;
}
// When the attestations map is not present, return the reason.
if (!attestations_map_.has_value()) {
// Break down by type of failure.
// If parsing hasn't started, there are two possible cases:
// 1. `kAttestationsFileNotPresent`: The component installer has already
// checked and found the attestations file did not exist on disk.
// 2. `kAttestationsFileNotYetChecked`: The component installer has not
// checked the attestations file yet. The file may or may not exist on disk.
if (attestations_parse_progress_ == Progress::kNotStarted) {
return attestations_file_checked() ? PrivacySandboxSettingsImpl::Status::
kAttestationsFileNotPresent
: PrivacySandboxSettingsImpl::Status::
kAttestationsFileNotYetChecked;
}
// If parsing is in progress, the attestation file has been downloaded but
// isn't ready for use yet.
if (attestations_parse_progress_ == Progress::kStarted) {
return PrivacySandboxSettingsImpl::Status::
kAttestationsDownloadedNotYetLoaded;
}
// If parsing is finished but there is still no attestations map, the
// attestation file must have been corrupt.
if (attestations_parse_progress_ == Progress::kFinished) {
return PrivacySandboxSettingsImpl::Status::kAttestationsFileCorrupt;
}
}
// If `site` isn't enrolled at all, fail the check.
auto it = attestations_map_->find(site);
if (it == attestations_map_->end()) {
return PrivacySandboxSettingsImpl::Status::kAttestationFailed;
}
// If `site` is attested for `invoking_api`, pass the check.
if (it->second.Has(invoking_api)) {
return PrivacySandboxSettingsImpl::Status::kAllowed;
}
// Otherwise, fail.
return PrivacySandboxSettingsImpl::Status::kAttestationFailed;
}
void PrivacySandboxAttestations::LoadAttestations(
base::Version version,
base::FilePath installed_file_path,
bool is_pre_installed) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// `LoadAttestations` is invoked by `ComponentReady`, which is always run on
// the UI thread.
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// This function should only be called when the feature is enabled.
CHECK(base::FeatureList::IsEnabled(
privacy_sandbox::kEnforcePrivacySandboxAttestations));
CHECK(version.IsValid());
// File version and attestations map should either both exist, or neither of
// them exist.
CHECK(file_version_.IsValid() == attestations_map_.has_value());
if (file_version_.IsValid() && file_version_.CompareTo(version) >= 0) {
// No need to parse if the incoming version is not newer than the existing
// one.
RecordParsingStatusHistogram(ParsingStatus::kNotNewerVersion);
RunLoadAttestationsDoneCallbackForTesting(); // IN-TEST
return;
}
// Mark the progress as started before posting the parsing task to the
// sequenced task runner.
attestations_parse_progress_ = Progress::kStarted;
if (RunLoadAttestationsParsingStartedCallbackForTesting()) { // IN-TEST
// If necessary for testing, indefinitely pause parsing once the progress
// is marked as started.
return;
}
// Post the parsing task to the sequenced task runner. Upon receiving the
// parsed attestations map, store it to `attestations_map_` in callback
// `OnAttestationsLoaded` on UI thread. `base::Unretained(this)` is fine in
// the reply callback because this is a singleton that will never be
// destroyed.
task_runner_->PostTaskAndReplyWithResult(
FROM_HERE,
base::BindOnce(&LoadAttestationsInternal, std::move(installed_file_path)),
base::BindOnce(&PrivacySandboxAttestations::OnAttestationsParsed,
base::Unretained(this), version, is_pre_installed));
}
void PrivacySandboxAttestations::AddOverride(const net::SchemefulSite& site) {
overridden_sites_.push_back(site);
}
bool PrivacySandboxAttestations::IsOverridden(
const net::SchemefulSite& site) const {
return IsOverriddenByFlags(site) || base::Contains(overridden_sites_, site);
}
void PrivacySandboxAttestations::SetAllPrivacySandboxAttestedForTesting(
bool all_attested) {
is_all_apis_attested_for_testing_ = all_attested;
}
void PrivacySandboxAttestations::SetAttestationsForTesting(
std::optional<PrivacySandboxAttestationsMap> attestations_map) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
attestations_map_ = std::move(attestations_map);
}
base::Version PrivacySandboxAttestations::GetVersionForTesting() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return file_version_;
}
void PrivacySandboxAttestations::SetLoadAttestationsDoneCallbackForTesting(
base::OnceClosure callback) {
load_attestations_done_callback_ = std::move(callback);
}
void PrivacySandboxAttestations::
SetLoadAttestationsParsingStartedCallbackForTesting(
base::OnceClosure callback) {
load_attestations_parsing_started_callback_ = std::move(callback);
}
void PrivacySandboxAttestations::SetComponentRegistrationCallbackForTesting(
base::OnceClosure callback) {
component_registration_callback_ = std::move(callback);
}
PrivacySandboxAttestations::PrivacySandboxAttestations()
: task_runner_(base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE})) {}
void PrivacySandboxAttestations::RunLoadAttestationsDoneCallbackForTesting() {
if (!load_attestations_done_callback_.is_null()) {
std::move(load_attestations_done_callback_).Run();
}
}
bool PrivacySandboxAttestations::
RunLoadAttestationsParsingStartedCallbackForTesting() {
if (!load_attestations_parsing_started_callback_.is_null()) {
std::move(load_attestations_parsing_started_callback_).Run();
return true;
}
return false;
}
void PrivacySandboxAttestations::RunComponentRegistrationCallbackForTesting() {
if (component_registration_callback_) {
std::move(component_registration_callback_).Run();
}
}
void PrivacySandboxAttestations::OnAttestationsParsed(
base::Version version,
bool is_pre_installed,
base::expected<PrivacySandboxAttestationsMap, ParsingStatus>
attestations_map) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Queries on Privacy Sandbox APIs attestation status will happen on the UI
// thread. The final assignment of the attestations map and its version is
// done on the UI thread to avoid race condition.
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
RecordParsingStatusHistogram(attestations_map.has_value()
? ParsingStatus::kSuccess
: attestations_map.error());
if (attestations_map.has_value() &&
(!file_version_.IsValid() || file_version_.CompareTo(version) < 0)) {
// Parsing succeeded and the attestations file has newer version.
file_version_ = std::move(version);
attestations_map_ = std::move(attestations_map.value());
}
SetIsPreInstalled(is_pre_installed);
attestations_parse_progress_ = Progress::kFinished;
// Do not remove. There is an internal test that depends on the loggings.
VLOG(1) << "Parsed Privacy Sandbox Attestation list version: "
<< file_version_;
VLOG(1) << "Number of attestation entries: "
<< (attestations_map_ ? attestations_map_->size() : 0);
RunLoadAttestationsDoneCallbackForTesting(); // IN-TEST
}
void PrivacySandboxAttestations::OnAttestationsFileCheckComplete() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
attestations_file_checked_ = true;
RunComponentRegistrationCallbackForTesting(); // IN-TEST
// On Android, if the parsing has not yet started at the end of component
// registration, this implies there is no attestations list available. The
// pre-installed attestations component in APK assets will be read to populate
// the in-memory attestations map.
// TODO(crbug.com/406020732): Consider also loading the attestations component
// from APK assets if the parsing has finished with error.
#if BUILDFLAG(IS_ANDROID)
if (attestations_parse_progress_ == Progress::kNotStarted &&
base::FeatureList::IsEnabled(
privacy_sandbox::kPrivacySandboxAttestationsLoadFromAPKAsset)) {
attestations_parse_progress_ = Progress::kStarted;
task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&LoadAttestationsFromAPKAsset),
base::BindOnce(&PrivacySandboxAttestations::OnAttestationsParsed,
base::Unretained(this),
base::Version(kAttestationsListAssetVersion),
/*is_pre_installed=*/true));
}
#endif // BUILDFLAG(IS_ANDROID)
}
} // namespace privacy_sandbox
|