-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
attribution_src_loader.cc
603 lines (496 loc) · 21.8 KB
/
attribution_src_loader.cc
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/frame/attribution_src_loader.h"
#include <utility>
#include "base/bind.h"
#include "base/check.h"
#include "base/check_op.h"
#include "base/memory/scoped_refptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/http/structured_headers.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/navigation/impression.h"
#include "third_party/blink/public/common/tokens/tokens.h"
#include "third_party/blink/public/mojom/conversions/attribution_data_host.mojom-blink.h"
#include "third_party/blink/public/mojom/conversions/conversions.mojom-blink.h"
#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/mojom/permissions_policy/permissions_policy_feature.mojom-blink.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/attribution_response_parsing.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/inspector/identifiers_factory.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/heap/self_keep_alive.h"
#include "third_party/blink/renderer/platform/loader/attribution_header_constants.h"
#include "third_party/blink/renderer/platform/loader/cors/cors.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_context.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_utils.h"
#include "third_party/blink/renderer/platform/loader/fetch/raw_resource.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_error.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
#include "third_party/blink/renderer/platform/network/encoded_form_data.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
namespace {
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class AttributionSrcRequestStatus {
kRequested = 0,
kReceived = 1,
kFailed = 2,
kMaxValue = kFailed,
};
void RecordAttributionSrcRequestStatus(AttributionSrcRequestStatus status) {
base::UmaHistogramEnumeration("Conversions.AttributionSrcRequestStatus",
status);
}
void LogAuditIssue(ExecutionContext* execution_context,
AttributionReportingIssueType issue_type,
HTMLElement* element,
absl::optional<uint64_t> request_id,
const String& invalid_parameter) {
String id_string;
if (request_id)
id_string = IdentifiersFactory::SubresourceRequestId(*request_id);
AuditsIssue::ReportAttributionIssue(execution_context, issue_type, element,
id_string, invalid_parameter);
}
} // namespace
bool CanRegisterAttributionInContext(LocalFrame* frame,
HTMLElement* element,
absl::optional<uint64_t> request_id,
bool log_issues) {
DCHECK(frame);
LocalDOMWindow* window = frame->DomWindow();
DCHECK(window);
if (!RuntimeEnabledFeatures::AttributionReportingEnabled(window))
return false;
const bool feature_policy_enabled = window->IsFeatureEnabled(
mojom::blink::PermissionsPolicyFeature::kAttributionReporting);
if (!feature_policy_enabled) {
if (log_issues) {
LogAuditIssue(window,
AttributionReportingIssueType::kPermissionPolicyDisabled,
element, request_id, /*invalid_parameter=*/String());
}
return false;
}
if (!window->IsSecureContext()) {
if (log_issues) {
LogAuditIssue(
window, AttributionReportingIssueType::kInsecureContext, element,
request_id, /*invalid_parameter=*/
window->GetSecurityContext().GetSecurityOrigin()->ToString());
}
return false;
}
return true;
}
class AttributionSrcLoader::ResourceClient
: public GarbageCollected<AttributionSrcLoader::ResourceClient>,
public RawResourceClient {
public:
// `associated_with_navigation` indicates whether the attribution data
// produced by this client will need to be associated with a navigation.
ResourceClient(AttributionSrcLoader* loader,
SrcType type,
bool associated_with_navigation)
: loader_(loader), type_(type) {
DCHECK(loader_);
DCHECK(loader_->local_frame_);
DCHECK(loader_->local_frame_->IsAttached());
mojo::AssociatedRemote<mojom::blink::ConversionHost> conversion_host;
loader_->local_frame_->GetRemoteNavigationAssociatedInterfaces()
->GetInterface(&conversion_host);
if (associated_with_navigation) {
// Create a new token which will be used to identify `data_host_` in the
// browser process.
attribution_src_token_ = AttributionSrcToken();
conversion_host->RegisterNavigationDataHost(
data_host_.BindNewPipeAndPassReceiver(), *attribution_src_token_);
} else {
// Send the data host normally.
conversion_host->RegisterDataHost(
data_host_.BindNewPipeAndPassReceiver());
}
}
~ResourceClient() override = default;
ResourceClient(const ResourceClient&) = delete;
ResourceClient(ResourceClient&&) = delete;
ResourceClient& operator=(const ResourceClient&) = delete;
ResourceClient& operator=(ResourceClient&&) = delete;
void Trace(Visitor* visitor) const override {
visitor->Trace(loader_);
RawResourceClient::Trace(visitor);
}
const absl::optional<AttributionSrcToken>& attribution_src_token() const {
return attribution_src_token_;
}
// Public, may be called if a response was received prior to the client being
// added to the resource.
void HandleResponseHeaders(const ResourceResponse& response,
uint64_t request_id);
private:
[[nodiscard]] bool CheckReportingOrigin(
const SecurityOrigin& reporting_origin,
uint64_t request_id);
void HandleSourceRegistration(
const AtomicString& json,
scoped_refptr<const SecurityOrigin> reporting_origin,
uint64_t request_id);
void HandleTriggerRegistration(
const AtomicString& json,
scoped_refptr<const SecurityOrigin> reporting_origin,
uint64_t request_id);
// RawResourceClient:
String DebugName() const override;
void ResponseReceived(Resource* resource,
const ResourceResponse& response) override;
bool RedirectReceived(Resource* resource,
const ResourceRequest& request,
const ResourceResponse& response) override;
void NotifyFinished(Resource* resource) override;
const Member<AttributionSrcLoader> loader_;
// Type of events this request can register. In some cases, this will not be
// assigned until the first event is received. A single attributionsrc
// request can only register one type of event across redirects.
SrcType type_;
// Token used to identify an attributionsrc request in the browser process.
// Only generated for attributionsrc requests that are associated with a
// navigation.
absl::optional<AttributionSrcToken> attribution_src_token_;
// Remote used for registering responses with the browser-process.
mojo::Remote<mojom::blink::AttributionDataHost> data_host_;
SelfKeepAlive<ResourceClient> keep_alive_{this};
};
AttributionSrcLoader::AttributionSrcLoader(LocalFrame* frame)
: local_frame_(frame) {
DCHECK(local_frame_);
}
AttributionSrcLoader::~AttributionSrcLoader() = default;
void AttributionSrcLoader::Trace(Visitor* visitor) const {
visitor->Trace(local_frame_);
}
void AttributionSrcLoader::Register(const KURL& src_url, HTMLElement* element) {
CreateAndSendRequest(src_url, element, SrcType::kUndetermined,
/*associated_with_navigation=*/false);
}
absl::optional<Impression> AttributionSrcLoader::RegisterNavigation(
const KURL& src_url,
HTMLElement* element) {
// TODO(apaseltiner): Add tests to ensure that this method can't be used to
// register triggers.
ResourceClient* client =
CreateAndSendRequest(src_url, element, SrcType::kSource,
/*associated_with_navigation=*/true);
if (!client)
return absl::nullopt;
DCHECK(client->attribution_src_token());
return blink::Impression{.attribution_src_token =
*client->attribution_src_token()};
}
AttributionSrcLoader::ResourceClient*
AttributionSrcLoader::CreateAndSendRequest(const KURL& src_url,
HTMLElement* element,
SrcType src_type,
bool associated_with_navigation) {
// Detached frames cannot/should not register new attributionsrcs.
if (!local_frame_->IsAttached())
return nullptr;
LocalDOMWindow* window = local_frame_->DomWindow();
if (num_resource_clients_ >= kMaxConcurrentRequests) {
LogAuditIssue(
window, AttributionReportingIssueType::kTooManyConcurrentRequests,
element, /*request_id=*/absl::nullopt,
/*invalid_parameter=*/AtomicString::Number(kMaxConcurrentRequests));
return nullptr;
}
if (!src_url.ProtocolIsInHTTPFamily())
return nullptr;
if (!UrlCanRegisterAttribution(src_url, element,
/*request_id=*/absl::nullopt)) {
return nullptr;
}
Document* document = window->document();
if (document->IsPrerendering()) {
document->AddPostPrerenderingActivationStep(
WTF::Bind(base::IgnoreResult(&AttributionSrcLoader::DoRegistration),
WrapPersistentIfNeeded(this), src_url, src_type,
associated_with_navigation));
return nullptr;
}
return DoRegistration(src_url, src_type, associated_with_navigation);
}
AttributionSrcLoader::ResourceClient* AttributionSrcLoader::DoRegistration(
const KURL& src_url,
SrcType src_type,
bool associated_with_navigation) {
if (!local_frame_->IsAttached())
return nullptr;
// TODO(apaseltiner): Respect the referrerpolicy attribute of the
// originating <a> or <img> tag, if present.
ResourceRequest request(src_url);
request.SetHttpMethod(http_names::kGET);
request.SetKeepalive(true);
request.SetRequestContext(mojom::blink::RequestContextType::ATTRIBUTION_SRC);
const char* eligible = [src_type,
associated_with_navigation]() -> const char* {
switch (src_type) {
case SrcType::kSource:
return associated_with_navigation ? kAttributionEligibleNavigationSource
: kAttributionEligibleEventSource;
case SrcType::kTrigger:
NOTREACHED();
return nullptr;
case SrcType::kUndetermined:
DCHECK(!associated_with_navigation);
return kAttributionEligibleEventSourceAndTrigger;
}
}();
request.SetHttpHeaderField(http_names::kAttributionReportingEligible,
eligible);
FetchParameters params(std::move(request),
local_frame_->DomWindow()->GetCurrentWorld());
params.MutableOptions().initiator_info.name =
fetch_initiator_type_names::kAttributionsrc;
auto* client = MakeGarbageCollected<ResourceClient>(
this, src_type, associated_with_navigation);
++num_resource_clients_;
RawResource::Fetch(params, local_frame_->DomWindow()->Fetcher(), client);
RecordAttributionSrcRequestStatus(AttributionSrcRequestStatus::kRequested);
return client;
}
bool AttributionSrcLoader::UrlCanRegisterAttribution(
const KURL& url,
HTMLElement* element,
absl::optional<uint64_t> request_id) {
LocalDOMWindow* window = local_frame_->DomWindow();
DCHECK(window);
if (!CanRegisterAttributionInContext(local_frame_, element, request_id))
return false;
scoped_refptr<const SecurityOrigin> reporting_origin =
SecurityOrigin::Create(url);
if (!reporting_origin->IsPotentiallyTrustworthy()) {
LogAuditIssue(window,
AttributionReportingIssueType::kUntrustworthyReportingOrigin,
element, request_id,
/*invalid_parameter=*/reporting_origin->ToString());
return false;
}
UseCounter::Count(window, mojom::blink::WebFeature::kConversionAPIAll);
// Only record the ads APIs counter if enabled in that manner.
if (RuntimeEnabledFeatures::PrivacySandboxAdsAPIsEnabled(window)) {
UseCounter::Count(window, mojom::blink::WebFeature::kPrivacySandboxAdsAPIs);
}
return true;
}
bool AttributionSrcLoader::MaybeRegisterAttributionHeaders(
const ResourceRequest& request,
const ResourceResponse& response,
const Resource* resource) {
DCHECK(resource);
if (response.IsNull()) {
return false;
}
// Attributionsrc requests will be serviced by the
// `AttributionSrcLoader::ResourceClient`.
if (request.GetRequestContext() ==
mojom::blink::RequestContextType::ATTRIBUTION_SRC) {
return false;
}
// Only handle requests which are attempting to invoke the API.
if (!response.HttpHeaderFields().Contains(
http_names::kAttributionReportingRegisterSource) &&
!response.HttpHeaderFields().Contains(
http_names::kAttributionReportingRegisterTrigger)) {
return false;
}
const uint64_t request_id = request.InspectorId();
if (!UrlCanRegisterAttribution(response.CurrentRequestUrl(),
/*element=*/nullptr, request_id)) {
return false;
}
SrcType src_type = SrcType::kUndetermined;
// Determine eligibility for this registration by considering first request
// for a resource (even if `response` is for a redirect). This indicates
// whether the redirect chain was configured for eligibility.
// https://github.com/WICG/attribution-reporting-api/blob/main/EVENT.md#registering-attribution-sources
const AtomicString& header_value =
resource->GetResourceRequest().HttpHeaderField(
http_names::kAttributionReportingEligible);
if (header_value.IsNull()) {
// All subresources are eligible to register triggers if they do *not*
// specify the header.
src_type = SrcType::kTrigger;
} else {
absl::optional<net::structured_headers::Dictionary> dict =
net::structured_headers::ParseDictionary(
StringUTF8Adaptor(header_value).AsStringPiece());
if (!dict) {
LogAuditIssue(local_frame_->DomWindow(),
AttributionReportingIssueType::kInvalidEligibleHeader,
/*element=*/nullptr, request_id,
/*invalid_parameter=*/header_value);
return false;
}
const bool allows_event_source =
dict->contains(kAttributionEligibleEventSource);
const bool allows_navigation_source =
dict->contains(kAttributionEligibleNavigationSource);
const bool allows_trigger = dict->contains(kAttributionEligibleTrigger);
// TODO(johnidel): Consider logging a devtools issue here for early exits.
if (allows_navigation_source) {
return false;
} else if (allows_event_source && allows_trigger) {
// We use an undetermined SrcType which indicates either a source or
// trigger may be registered.
src_type = SrcType::kUndetermined;
} else if (allows_event_source) {
src_type = SrcType::kSource;
} else if (allows_trigger) {
src_type = SrcType::kTrigger;
} else {
return false;
}
}
// TODO(johnidel): We should consider updating the eligibility header based on
// previously registered requests in the chain.
// Create a client to mimic processing of attributionsrc requests. Note we do
// not share `AttributionDataHosts` for redirects chains.
// TODO(johnidel): Consider refactoring this such that we can share clients
// for redirect chain, or not create the client at all.
auto* client = MakeGarbageCollected<ResourceClient>(
this, src_type, /*associated_with_navigation=*/false);
client->HandleResponseHeaders(response, resource->InspectorId());
return true;
}
void AttributionSrcLoader::RegisterTrigger(
mojom::blink::AttributionTriggerDataPtr trigger_data) const {
mojo::AssociatedRemote<mojom::blink::ConversionHost> conversion_host;
local_frame_->GetRemoteNavigationAssociatedInterfaces()->GetInterface(
&conversion_host);
mojo::Remote<mojom::blink::AttributionDataHost> data_host;
conversion_host->RegisterDataHost(data_host.BindNewPipeAndPassReceiver());
data_host->TriggerDataAvailable(std::move(trigger_data));
}
String AttributionSrcLoader::ResourceClient::DebugName() const {
return "AttributionSrcLoader::ResourceClient";
}
void AttributionSrcLoader::ResourceClient::ResponseReceived(
Resource* resource,
const ResourceResponse& response) {
HandleResponseHeaders(response, resource->InspectorId());
}
bool AttributionSrcLoader::ResourceClient::RedirectReceived(
Resource* resource,
const ResourceRequest& request,
const ResourceResponse& response) {
HandleResponseHeaders(response, request.InspectorId());
return true;
}
void AttributionSrcLoader::ResourceClient::NotifyFinished(Resource* resource) {
ClearResource();
DCHECK_GT(loader_->num_resource_clients_, 0u);
--loader_->num_resource_clients_;
if (resource->ErrorOccurred()) {
RecordAttributionSrcRequestStatus(AttributionSrcRequestStatus::kFailed);
} else {
RecordAttributionSrcRequestStatus(AttributionSrcRequestStatus::kReceived);
}
// Eagerly reset the data host so that the receiver is closed and any buffered
// triggers are flushed as soon as possible. See crbug.com/1336797 for
// details.
data_host_.reset();
keep_alive_.Clear();
}
void AttributionSrcLoader::ResourceClient::HandleResponseHeaders(
const ResourceResponse& response,
uint64_t request_id) {
scoped_refptr<const SecurityOrigin> reporting_origin =
SecurityOrigin::Create(response.CurrentRequestUrl());
const auto& headers = response.HttpHeaderFields();
// TODO(apaseltiner): Report a DevTools issue when `type_` and `headers` do
// not correspond correctly.
// TODO(johnidel): Consider surfacing an error when source and trigger headers
// are present together.
if (type_ == SrcType::kUndetermined || type_ == SrcType::kSource) {
const AtomicString& json =
headers.Get(http_names::kAttributionReportingRegisterSource);
if (!json.IsNull()) {
type_ = SrcType::kSource;
HandleSourceRegistration(json, std::move(reporting_origin), request_id);
return;
}
}
if (type_ == SrcType::kUndetermined || type_ == SrcType::kTrigger) {
const AtomicString& json =
headers.Get(http_names::kAttributionReportingRegisterTrigger);
if (!json.IsNull()) {
type_ = SrcType::kTrigger;
HandleTriggerRegistration(json, std::move(reporting_origin), request_id);
}
}
}
bool AttributionSrcLoader::ResourceClient::CheckReportingOrigin(
const SecurityOrigin& reporting_origin,
uint64_t request_id) {
if (reporting_origin.IsPotentiallyTrustworthy())
return true;
LogAuditIssue(loader_->local_frame_->DomWindow(),
AttributionReportingIssueType::kUntrustworthyReportingOrigin,
/*element=*/nullptr, request_id,
/*invalid_parameter=*/reporting_origin.ToString());
return false;
}
void AttributionSrcLoader::ResourceClient::HandleSourceRegistration(
const AtomicString& json,
scoped_refptr<const SecurityOrigin> reporting_origin,
uint64_t request_id) {
DCHECK_EQ(type_, SrcType::kSource);
if (!CheckReportingOrigin(*reporting_origin, request_id))
return;
auto source_data = mojom::blink::AttributionSourceData::New();
source_data->reporting_origin = std::move(reporting_origin);
if (!attribution_response_parsing::ParseSourceRegistrationHeader(
json, *source_data)) {
LogAuditIssue(loader_->local_frame_->DomWindow(),
AttributionReportingIssueType::kInvalidRegisterSourceHeader,
/*element=*/nullptr, request_id,
/*invalid_parameter=*/json);
return;
}
data_host_->SourceDataAvailable(std::move(source_data));
}
void AttributionSrcLoader::ResourceClient::HandleTriggerRegistration(
const AtomicString& json,
scoped_refptr<const SecurityOrigin> reporting_origin,
uint64_t request_id) {
DCHECK_EQ(type_, SrcType::kTrigger);
if (!CheckReportingOrigin(*reporting_origin, request_id))
return;
auto trigger_data = mojom::blink::AttributionTriggerData::New();
trigger_data->reporting_origin = std::move(reporting_origin);
if (!attribution_response_parsing::ParseTriggerRegistrationHeader(
json, *trigger_data)) {
LogAuditIssue(loader_->local_frame_->DomWindow(),
AttributionReportingIssueType::kInvalidRegisterTriggerHeader,
/*element=*/nullptr, request_id,
/*invalid_parameter=*/json);
return;
}
data_host_->TriggerDataAvailable(std::move(trigger_data));
}
} // namespace blink