File: PrivateClickMeasurementManager.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (809 lines) | stat: -rw-r--r-- 40,575 bytes parent folder | download | duplicates (6)
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
/*
 * Copyright (C) 2019 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "PrivateClickMeasurementManager.h"

#include "Logging.h"
#include "NetworkSession.h"
#include "PrivateClickMeasurementDebugInfo.h"
#include "PrivateClickMeasurementEphemeralStore.h"
#include "PrivateClickMeasurementNetworkLoader.h"
#include "PrivateClickMeasurementPersistentStore.h"
#include <JavaScriptCore/ConsoleTypes.h>
#include <WebCore/FetchOptions.h>
#include <WebCore/FormData.h>
#include <WebCore/ResourceError.h>
#include <WebCore/ResourceRequest.h>
#include <WebCore/ResourceResponse.h>
#include <pal/crypto/CryptoDigest.h>
#include <wtf/CryptographicallyRandomNumber.h>
#include <wtf/RuntimeApplicationChecks.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/StringHash.h>

namespace WebKit {
using namespace WebCore;

using SourceSite = WebCore::PCM::SourceSite;
using AttributionDestinationSite = WebCore::PCM::AttributionDestinationSite;
using AttributionTriggerData = WebCore::PCM::AttributionTriggerData;
using EphemeralNonce = WebCore::PCM::EphemeralNonce;

constexpr Seconds debugModeSecondsUntilSend { 10_s };

WTF_MAKE_TZONE_ALLOCATED_IMPL(PrivateClickMeasurementManager);

Ref<PrivateClickMeasurementManager> PrivateClickMeasurementManager::create(UniqueRef<PCM::Client>&& client, const String& storageDirectory)
{
    return adoptRef(*new PrivateClickMeasurementManager(WTFMove(client), storageDirectory));
}

PrivateClickMeasurementManager::PrivateClickMeasurementManager(UniqueRef<PCM::Client>&& client, const String& storageDirectory)
    : m_firePendingAttributionRequestsTimer(RunLoop::main(), this, &PrivateClickMeasurementManager::firePendingAttributionRequests)
    , m_storageDirectory(storageDirectory)
    , m_client(WTFMove(client))
{
    // We should send any pending attributions on session-start in case their
    // send delay has expired while the session was closed. Waiting 5 seconds accounts for the
    // delay in database startup. When running in the daemon, the xpc activity does this instead.
    if (!m_client->runningInDaemon())
        startTimer(5_s);
}

PrivateClickMeasurementManager::~PrivateClickMeasurementManager()
{
    if (m_store)
        m_store->close([] { });
}

void PrivateClickMeasurementManager::storeUnattributed(PrivateClickMeasurement&& measurement, CompletionHandler<void()>&& completionHandler)
{
    if (!featureEnabled())
        return completionHandler();

    clearExpired();

    if (m_privateClickMeasurementAppBundleIDForTesting)
        measurement.setSourceApplicationBundleIDForTesting(*m_privateClickMeasurementAppBundleIDForTesting);

    if (measurement.ephemeralSourceNonce()) {
        auto measurementCopy = measurement;
        // This is guaranteed to be close in time to the navigational click which makes it likely to be personally identifiable.
        getTokenPublicKey(WTFMove(measurementCopy), WebCore::PCM::AttributionReportEndpoint::Source, PrivateClickMeasurement::PcmDataCarried::PersonallyIdentifiable, [weakThis = WeakPtr { *this }] (PrivateClickMeasurement&& measurement, const String& publicKeyBase64URL) {
            RefPtr protectedThis = weakThis.get();
            if (!protectedThis)
                return;

            if (publicKeyBase64URL.isEmpty())
                return;

            if (protectedThis->m_fraudPreventionValuesForTesting)
                measurement.setSourceUnlinkableTokenValue(protectedThis->m_fraudPreventionValuesForTesting->unlinkableTokenForSource);
#if PLATFORM(COCOA)
            else {
                if (auto errorMessage = measurement.calculateAndUpdateSourceUnlinkableToken(publicKeyBase64URL)) {
                    RELEASE_LOG_INFO(PrivateClickMeasurement, "Got the following error in calculateAndUpdateSourceUnlinkableToken(): '%{public}s", errorMessage->utf8().data());
                    protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Error, makeString("[Private Click Measurement] "_s, *errorMessage));
                    return;
                }
            }
#endif

            protectedThis->getSignedUnlinkableTokenForSource(WTFMove(measurement));
            return;
        });
    }

    m_client->broadcastConsoleMessage(MessageLevel::Log, "[Private Click Measurement] Storing a click."_s);

    insertPrivateClickMeasurement(WTFMove(measurement), PrivateClickMeasurementAttributionType::Unattributed, WTFMove(completionHandler));
}

void PrivateClickMeasurementManager::getTokenPublicKey(PrivateClickMeasurement&& attribution, WebCore::PCM::AttributionReportEndpoint attributionReportEndpoint, PrivateClickMeasurement::PcmDataCarried pcmDataCarried, Function<void(PrivateClickMeasurement&& attribution, const String& publicKeyBase64URL)>&& callback)
{
    if (!featureEnabled())
        return;

    URL tokenPublicKeyURL;
    if (m_tokenPublicKeyURLForTesting) {
        if (attributionReportEndpoint == WebCore::PCM::AttributionReportEndpoint::Destination)
            return;
        tokenPublicKeyURL = *m_tokenPublicKeyURLForTesting;
        // FIXME(225364)
        pcmDataCarried = PrivateClickMeasurement::PcmDataCarried::NonPersonallyIdentifiable;
    } else {
        if (auto optURL = attribution.tokenPublicKeyURL())
            tokenPublicKeyURL = *optURL;
        else
            return;
    }

    if (tokenPublicKeyURL.isEmpty() || !tokenPublicKeyURL.isValid())
        return;

    if (debugModeEnabled())
        pcmDataCarried = PrivateClickMeasurement::PcmDataCarried::PersonallyIdentifiable;

    RELEASE_LOG_INFO(PrivateClickMeasurement, "About to fire a token public key request.");
    m_client->broadcastConsoleMessage(MessageLevel::Log, "[Private Click Measurement] About to fire a token public key request."_s);

    PCM::NetworkLoader::start(WTFMove(tokenPublicKeyURL), nullptr, pcmDataCarried, [weakThis = WeakPtr { *this }, attribution = WTFMove(attribution), callback = WTFMove(callback)] (auto& errorDescription, auto& jsonObject) mutable {
        WeakPtr protectedThis = weakThis.get();
        if (!protectedThis)
            return;

        if (!errorDescription.isNull()) {
            protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Error, makeString("[Private Click Measurement] Received error: '"_s, errorDescription, "' for token public key request."_s));
            return;
        }

        if (!jsonObject) {
            protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Error, makeString("[Private Click Measurement] JSON response is empty for token public key request."_s));
            return;
        }

        protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Log, makeString("[Private Click Measurement] Got JSON response for token public key request."_s));

        callback(WTFMove(attribution), jsonObject->getString("token_public_key"_s));
    });
}

void PrivateClickMeasurementManager::getTokenPublicKey(AttributionTriggerData&& attributionTriggerData, WebCore::PCM::AttributionReportEndpoint attributionReportEndpoint, PrivateClickMeasurement::PcmDataCarried pcmDataCarried, Function<void(AttributionTriggerData&& attributionTriggerData, const String& publicKeyBase64URL)>&& callback)
{
    if (!featureEnabled())
        return;

    URL tokenPublicKeyURL;
    if (m_tokenPublicKeyURLForTesting) {
        if (attributionReportEndpoint == WebCore::PCM::AttributionReportEndpoint::Source)
            return;
        tokenPublicKeyURL = *m_tokenPublicKeyURLForTesting;
        // FIXME(225364)
        pcmDataCarried = PrivateClickMeasurement::PcmDataCarried::NonPersonallyIdentifiable;
    } else {
        if (auto optURL = attributionTriggerData.tokenPublicKeyURL())
            tokenPublicKeyURL = *optURL;
        else
            return;
    }

    if (tokenPublicKeyURL.isEmpty() || !tokenPublicKeyURL.isValid())
        return;

    if (debugModeEnabled())
        pcmDataCarried = PrivateClickMeasurement::PcmDataCarried::PersonallyIdentifiable;

    RELEASE_LOG_INFO(PrivateClickMeasurement, "About to fire a token public key request.");
    m_client->broadcastConsoleMessage(MessageLevel::Log, "[Private Click Measurement] About to fire a token public key request."_s);

    PCM::NetworkLoader::start(WTFMove(tokenPublicKeyURL), nullptr, pcmDataCarried, [weakThis = WeakPtr { *this }, attributionTriggerData = WTFMove(attributionTriggerData), callback = WTFMove(callback)] (auto& errorDescription, auto& jsonObject) mutable {
        RefPtr protectedThis = weakThis.get();
        if (!protectedThis)
            return;

        if (!errorDescription.isNull()) {
            protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Error, makeString("[Private Click Measurement] Received error: '"_s, errorDescription, "' for token public key request."_s));
            return;
        }

        if (!jsonObject) {
            protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Error, makeString("[Private Click Measurement] JSON response is empty for token public key request."_s));
            return;
        }

        protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Log, makeString("[Private Click Measurement] Got JSON response for token public key request."_s));

        callback(WTFMove(attributionTriggerData), jsonObject->getString("token_public_key"_s));
    });
}

void PrivateClickMeasurementManager::configureForTokenSigning(PrivateClickMeasurement::PcmDataCarried& pcmDataCarried, URL& tokenSignatureURL, std::optional<URL> givenTokenSignatureURL)
{
    // This is guaranteed to be close in time to a page load which can identify the user, either the source or the destination.
    pcmDataCarried = PrivateClickMeasurement::PcmDataCarried::PersonallyIdentifiable;
    if (m_tokenSignatureURLForTesting) {
        tokenSignatureURL = *m_tokenSignatureURLForTesting;
        // FIXME(225364)
        if (!debugModeEnabled())
            pcmDataCarried = PrivateClickMeasurement::PcmDataCarried::NonPersonallyIdentifiable;
    } else if (givenTokenSignatureURL)
        tokenSignatureURL = *givenTokenSignatureURL;
}

std::optional<String> PrivateClickMeasurementManager::getSignatureBase64URLFromTokenSignatureResponse(const String& errorDescription, const RefPtr<JSON::Object>& jsonObject)
{
    if (!errorDescription.isNull()) {
        m_client->broadcastConsoleMessage(MessageLevel::Error, makeString("[Private Click Measurement] Received error: '"_s, errorDescription, "' for token signing request."_s));
        return std::nullopt;
    }

    if (!jsonObject) {
        m_client->broadcastConsoleMessage(MessageLevel::Error, makeString("[Private Click Measurement] JSON response is empty for token signing request."_s));
        return std::nullopt;
    }

    auto signatureBase64URL = jsonObject->getString("unlinkable_token"_s);
    if (signatureBase64URL.isEmpty()) {
        m_client->broadcastConsoleMessage(MessageLevel::Error, makeString("[Private Click Measurement] JSON response doesn't have the key 'unlinkable_token' for token signing request."_s));
        return std::nullopt;
    }

    return signatureBase64URL;
}

void PrivateClickMeasurementManager::getSignedUnlinkableTokenForSource(PrivateClickMeasurement&& measurement)
{
    if (!featureEnabled())
        return;

    PrivateClickMeasurement::PcmDataCarried pcmDataCarried;
    URL tokenSignatureURL;
    configureForTokenSigning(pcmDataCarried, tokenSignatureURL, measurement.tokenSignatureURL());

    if (tokenSignatureURL.isEmpty() || !tokenSignatureURL.isValid())
        return;

    RELEASE_LOG_INFO(PrivateClickMeasurement, "About to fire a unlinkable token signing request for the click source.");
    m_client->broadcastConsoleMessage(MessageLevel::Log, "[Private Click Measurement] About to fire a unlinkable token signing request for the click source."_s);

    PCM::NetworkLoader::start(WTFMove(tokenSignatureURL), measurement.tokenSignatureJSON(), pcmDataCarried, [weakThis = WeakPtr { *this }, measurement = WTFMove(measurement)] (auto& errorDescription, auto& jsonObject) mutable {
        WeakPtr protectedThis = weakThis.get();
        if (!protectedThis)
            return;

        auto signatureBase64URL = protectedThis->getSignatureBase64URLFromTokenSignatureResponse(errorDescription, jsonObject);
        if (!signatureBase64URL)
            return;

        if (protectedThis->m_fraudPreventionValuesForTesting) {
            WebCore::PCM::SourceSecretToken sourceSecretToken;
            sourceSecretToken.tokenBase64URL = protectedThis->m_fraudPreventionValuesForTesting->secretTokenForSource;
            sourceSecretToken.signatureBase64URL = protectedThis->m_fraudPreventionValuesForTesting->signatureForSource;
            sourceSecretToken.keyIDBase64URL = protectedThis->m_fraudPreventionValuesForTesting->keyIDForSource;
            measurement.setSourceSecretToken(WTFMove(sourceSecretToken));
#if PLATFORM(COCOA)
        } else {
            if (auto errorMessage = measurement.calculateAndUpdateSourceSecretToken(*signatureBase64URL)) {
                RELEASE_LOG_INFO(PrivateClickMeasurement, "Got the following error in calculateAndUpdateSourceSecretToken(): '%{public}s", errorMessage->utf8().data());
                protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Error, makeString("[Private Click Measurement] "_s, *errorMessage));
                return;
            }
#endif
        }

        protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Log, "[Private Click Measurement] Storing a secret token."_s);

        protectedThis->insertPrivateClickMeasurement(WTFMove(measurement), PrivateClickMeasurementAttributionType::Unattributed, [] { });
    });

}

void PrivateClickMeasurementManager::getSignedUnlinkableTokenForDestination(SourceSite&& sourceSite, AttributionDestinationSite&& destinationSite, AttributionTriggerData&& attributionTriggerData, const ApplicationBundleIdentifier& applicationBundleIdentifier)
{
    if (!featureEnabled())
        return;

    PrivateClickMeasurement::PcmDataCarried pcmDataCarried;
    URL tokenSignatureURL;
    configureForTokenSigning(pcmDataCarried, tokenSignatureURL, attributionTriggerData.tokenSignatureURL());

    if (tokenSignatureURL.isEmpty() || !tokenSignatureURL.isValid())
        return;

    RELEASE_LOG_INFO(PrivateClickMeasurement, "About to fire a unlinkable token signing request for the click destination.");
    m_client->broadcastConsoleMessage(MessageLevel::Log, "[Private Click Measurement] About to fire a unlinkable token signing request for the click destination."_s);

    PCM::NetworkLoader::start(WTFMove(tokenSignatureURL), attributionTriggerData.tokenSignatureJSON(), pcmDataCarried, [weakThis = WeakPtr { *this }, sourceSite = WTFMove(sourceSite), destinationSite = WTFMove(destinationSite), attributionTriggerData = WTFMove(attributionTriggerData), applicationBundleIdentifier = applicationBundleIdentifier.isolatedCopy()] (auto& errorDescription, auto& jsonObject) mutable {
        RefPtr protectedThis = weakThis.get();
        if (!protectedThis)
            return;

        auto signatureBase64URL = protectedThis->getSignatureBase64URLFromTokenSignatureResponse(errorDescription, jsonObject);
        if (!signatureBase64URL)
            return;

#if PLATFORM(COCOA)
            if (!attributionTriggerData.destinationUnlinkableToken) {
                RELEASE_LOG_INFO(PrivateClickMeasurement, "Destination unlinkable token is missing.");
                protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Error, "[Private Click Measurement] Destination unlinkable token is missing."_s);
                return;
            }

            auto result = PrivateClickMeasurement::calculateAndUpdateDestinationSecretToken(*signatureBase64URL, *attributionTriggerData.destinationUnlinkableToken);
            if (!result) {
                auto errorMessage = result.error().isEmpty() ? "Unknown"_s : result.error();
                RELEASE_LOG_INFO(PrivateClickMeasurement, "Got the following error in calculateAndUpdateSourceSecretToken(): '%{public}s", errorMessage.utf8().data());
                protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Error, makeString("[Private Click Measurement] "_s, errorMessage));
                return;
            }

            protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Log, "[Private Click Measurement] Storing a secret token."_s);

            attributionTriggerData.destinationSecretToken = result.value();
            protectedThis->attribute(WTFMove(sourceSite), WTFMove(destinationSite), WTFMove(attributionTriggerData), protectedThis->m_privateClickMeasurementAppBundleIDForTesting ? *protectedThis->m_privateClickMeasurementAppBundleIDForTesting : applicationBundleIdentifier);
#endif
    });
}

void PrivateClickMeasurementManager::insertPrivateClickMeasurement(PrivateClickMeasurement&& measurement, PrivateClickMeasurementAttributionType type, CompletionHandler<void()>&& completionHandler)
{
    store().insertPrivateClickMeasurement(WTFMove(measurement), type, WTFMove(completionHandler));
}

void PrivateClickMeasurementManager::migratePrivateClickMeasurementFromLegacyStorage(PrivateClickMeasurement&& measurement, PrivateClickMeasurementAttributionType type)
{
    store().insertPrivateClickMeasurement(WTFMove(measurement), type, [] { });
}

void PrivateClickMeasurementManager::setDebugModeIsEnabled(bool enabled)
{
    // This doesn't maintain global state, it just broadcasts a message when debug mode enabled changes.
    // The state is either stored in NetworkSession when not using the daemon
    // or in DaemonConnectionSet per-connection when using the daemon.

    auto message = enabled ? "[Private Click Measurement] Turned Debug Mode on."_s : "[Private Click Measurement] Turned Debug Mode off."_s;
    m_client->broadcastConsoleMessage(MessageLevel::Info, message);
}

void PrivateClickMeasurementManager::handleAttribution(AttributionTriggerData&& attributionTriggerData, const URL& requestURL, WebCore::RegistrableDomain&& redirectDomain, const URL& firstPartyURL, const ApplicationBundleIdentifier& applicationBundleIdentifier)
{
    if (!featureEnabled())
        return;

    if (!redirectDomain.matches(requestURL)) {
        m_client->broadcastConsoleMessage(MessageLevel::Warning, "[Private Click Measurement] Triggering event was not accepted because the HTTP redirect was not same-site."_s);
        return;
    }

    RegistrableDomain sourceDomain;
    if (redirectDomain.matches(firstPartyURL)) {
        if (!attributionTriggerData.sourceRegistrableDomain) {
            m_client->broadcastConsoleMessage(MessageLevel::Warning, "[Private Click Measurement] Triggering event was not accepted because it was requested in an HTTP redirect that is same-site as the first-party and no attributionSource query parameter was provided."_s);
            return;
        }
        sourceDomain = *attributionTriggerData.sourceRegistrableDomain;
    } else if (attributionTriggerData.sourceRegistrableDomain) {
        m_client->broadcastConsoleMessage(MessageLevel::Warning, "[Private Click Measurement] Triggering event was not accepted because it was requested in an HTTP redirect that is cross-site from the first-party but an attributionSource query parameter was still provided."_s);
        return;
    } else
        sourceDomain = WTFMove(redirectDomain);

    m_client->broadcastConsoleMessage(MessageLevel::Log, "[Private Click Measurement] Triggering event accepted."_s);

    // Signing of a destination token must be done unconditionally. Otherwise it becomes a way to discover that there is a pending attribution.
    if (attributionTriggerData.ephemeralDestinationNonce) {
        auto attributionTriggerDataCopy = attributionTriggerData;
        // This is guaranteed to be close in time to the triggering event which makes it likely to be personally identifiable.
        getTokenPublicKey(WTFMove(attributionTriggerDataCopy), WebCore::PCM::AttributionReportEndpoint::Destination, PrivateClickMeasurement::PcmDataCarried::PersonallyIdentifiable, [weakThis = WeakPtr { *this }, sourceSite = SourceSite { WTFMove(sourceDomain) }, destinationSite = AttributionDestinationSite { firstPartyURL }, applicationBundleIdentifier = applicationBundleIdentifier.isolatedCopy()] (AttributionTriggerData&& attributionTriggerData, const String& publicKeyBase64URL) mutable {
            WeakPtr protectedThis = weakThis.get();
            if (!protectedThis)
                return;

            if (publicKeyBase64URL.isEmpty()) {
                RELEASE_LOG_INFO(PrivateClickMeasurement, "The public key URL was empty.");
                protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Error, "[Private Click Measurement] The public key URL was empty."_s);
                return;
            }

            if (protectedThis->m_fraudPreventionValuesForTesting)
                attributionTriggerData.setDestinationUnlinkableTokenValue(protectedThis->m_fraudPreventionValuesForTesting->unlinkableTokenForDestination);
#if PLATFORM(COCOA)
            else {
                auto result = PrivateClickMeasurement::calculateAndUpdateDestinationUnlinkableToken(publicKeyBase64URL);
                if (result) {
                    attributionTriggerData.destinationUnlinkableToken = result.value();
                    protectedThis->getSignedUnlinkableTokenForDestination(WTFMove(sourceSite), WTFMove(destinationSite), WTFMove(attributionTriggerData), protectedThis->m_privateClickMeasurementAppBundleIDForTesting ? *protectedThis->m_privateClickMeasurementAppBundleIDForTesting : applicationBundleIdentifier);
                    return;
                }

                auto errorMessage = result.error().isEmpty() ? "Unknown"_s : result.error();
                RELEASE_LOG_INFO(PrivateClickMeasurement, "Got the following error in calculateAndUpdateDestinationUnlinkableToken(): '%{public}s", errorMessage.utf8().data());
                protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Error, makeString("[Private Click Measurement] "_s, errorMessage));
                return;
            }
#endif
        });
        return;
    }

    attribute(SourceSite { WTFMove(sourceDomain) }, AttributionDestinationSite { firstPartyURL }, WTFMove(attributionTriggerData), m_privateClickMeasurementAppBundleIDForTesting ? *m_privateClickMeasurementAppBundleIDForTesting : applicationBundleIdentifier);
}

void PrivateClickMeasurementManager::startTimerImmediatelyForTesting()
{
    startTimer(0_s);
}

void PrivateClickMeasurementManager::setPrivateClickMeasurementAppBundleIDForTesting(ApplicationBundleIdentifier&& appBundleID)
{
    if (appBundleID.isEmpty())
        m_privateClickMeasurementAppBundleIDForTesting = std::nullopt;
    else
        m_privateClickMeasurementAppBundleIDForTesting = WTFMove(appBundleID);
}

void PrivateClickMeasurementManager::startTimer(Seconds seconds)
{
    m_firePendingAttributionRequestsTimer.startOneShot(seconds);
}

void PrivateClickMeasurementManager::attribute(SourceSite&& sourceSite, AttributionDestinationSite&& destinationSite, AttributionTriggerData&& attributionTriggerData, const ApplicationBundleIdentifier& applicationBundleIdentifier)
{
    if (!featureEnabled())
        return;

    store().attributePrivateClickMeasurement(WTFMove(sourceSite), WTFMove(destinationSite), applicationBundleIdentifier, WTFMove(attributionTriggerData), m_isRunningTest ? WebCore::PrivateClickMeasurement::IsRunningLayoutTest::Yes : WebCore::PrivateClickMeasurement::IsRunningLayoutTest::No, [weakThis = WeakPtr { *this }] (auto attributionSecondsUntilSendData, auto debugInfo) {
        WeakPtr protectedThis = weakThis.get();
        if (!protectedThis)
            return;
        
        if (!attributionSecondsUntilSendData)
            return;

        if (UNLIKELY(protectedThis->debugModeEnabled())) {
            for (auto& message : debugInfo.messages)
                protectedThis->m_client->broadcastConsoleMessage(message.messageLevel, message.message);
        }

        if (attributionSecondsUntilSendData.value().hasValidSecondsUntilSendValues()) {
            auto minSecondsUntilSend = attributionSecondsUntilSendData.value().minSecondsUntilSend();

            ASSERT(minSecondsUntilSend);
            if (!minSecondsUntilSend)
                return;

            if (protectedThis->m_firePendingAttributionRequestsTimer.isActive() && protectedThis->m_firePendingAttributionRequestsTimer.secondsUntilFire() < *minSecondsUntilSend)
                return;

            if (UNLIKELY(protectedThis->debugModeEnabled())) {
                protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Log, makeString("[Private Click Measurement] Setting timer for firing attribution request to the debug mode timeout of "_s, debugModeSecondsUntilSend.seconds(), " seconds where the regular timeout would have been "_s, minSecondsUntilSend.value().seconds(), " seconds."_s));
                minSecondsUntilSend = debugModeSecondsUntilSend;
            } else
                protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Log, makeString("[Private Click Measurement] Setting timer for firing attribution request to the timeout of "_s, minSecondsUntilSend.value().seconds(), " seconds."_s));

            protectedThis->startTimer(*minSecondsUntilSend);
        }
    });
}

void PrivateClickMeasurementManager::fireConversionRequest(const PrivateClickMeasurement& attribution, WebCore::PCM::AttributionReportEndpoint attributionReportEndpoint)
{
    if (!featureEnabled() || !attribution.attributionTriggerData())
        return;

    if (!attribution.sourceSecretToken() && !attribution.attributionTriggerData()->destinationSecretToken) {
        fireConversionRequestImpl(attribution, attributionReportEndpoint);
        return;
    }

    auto attributionCopy = attribution;
    // This happens out of webpage context and with a long delay and is thus unlikely to be personally identifiable.
    if (attribution.sourceSecretToken()) {
        getTokenPublicKey(WTFMove(attributionCopy), attributionReportEndpoint, PrivateClickMeasurement::PcmDataCarried::NonPersonallyIdentifiable, [weakThis = WeakPtr { *this }, attributionReportEndpoint] (PrivateClickMeasurement&& attribution, const String& publicKeyBase64URL) {
            RefPtr protectedThis = weakThis.get();
            if (!protectedThis)
                return;

            auto publicKeyData = base64URLDecode(publicKeyBase64URL);
            if (!publicKeyData)
                return;

            auto crypto = PAL::CryptoDigest::create(PAL::CryptoDigest::Algorithm::SHA_256);
            crypto->addBytes(publicKeyData->span());

            auto keyID = base64URLEncodeToString(crypto->computeHash());
            if (keyID != attribution.sourceSecretToken()->keyIDBase64URL)
                return;

            if (!attribution.attributionTriggerData())
                return;

            if (attribution.attributionTriggerData()->destinationSecretToken) {
                protectedThis->getTokenPublicKey(WTFMove(attribution), attributionReportEndpoint, PrivateClickMeasurement::PcmDataCarried::NonPersonallyIdentifiable, [weakThis = WeakPtr { protectedThis.get() }, attributionReportEndpoint] (PrivateClickMeasurement&& attribution, const String& publicKeyBase64URL) {
                    RefPtr protectedThis = weakThis.get();
                    if (!protectedThis)
                        return;

                    auto publicKeyData = base64URLDecode(publicKeyBase64URL);
                    if (!publicKeyData)
                        return;

                    auto crypto = PAL::CryptoDigest::create(PAL::CryptoDigest::Algorithm::SHA_256);
                    crypto->addBytes(publicKeyData->span());

                    auto keyID = base64URLEncodeToString(crypto->computeHash());
                    if (keyID != attribution.attributionTriggerData()->destinationSecretToken->keyIDBase64URL)
                        return;

                    protectedThis->fireConversionRequestImpl(attribution, attributionReportEndpoint);
                });
                return;
            }

            protectedThis->fireConversionRequestImpl(attribution, attributionReportEndpoint);
        });
        return;
    }

    getTokenPublicKey(WTFMove(attributionCopy), attributionReportEndpoint, PrivateClickMeasurement::PcmDataCarried::NonPersonallyIdentifiable, [weakThis = WeakPtr { *this }, attributionReportEndpoint] (PrivateClickMeasurement&& attribution, const String& publicKeyBase64URL) {
        RefPtr protectedThis = weakThis.get();
        if (!protectedThis)
            return;

        auto publicKeyData = base64URLDecode(publicKeyBase64URL);
        if (!publicKeyData)
            return;

        auto crypto = PAL::CryptoDigest::create(PAL::CryptoDigest::Algorithm::SHA_256);
        crypto->addBytes(publicKeyData->span());

        auto keyID = base64URLEncodeToString(crypto->computeHash());
        if (!attribution.attributionTriggerData()->destinationSecretToken || keyID != attribution.attributionTriggerData()->destinationSecretToken->keyIDBase64URL)
            return;

        protectedThis->fireConversionRequestImpl(attribution, attributionReportEndpoint);
    });
}

void PrivateClickMeasurementManager::fireConversionRequestImpl(const PrivateClickMeasurement& attribution, WebCore::PCM::AttributionReportEndpoint attributionReportEndpoint)
{
    URL attributionURL;
    switch (attributionReportEndpoint) {
    case WebCore::PCM::AttributionReportEndpoint::Source:
        attributionURL = m_attributionReportTestConfig ? m_attributionReportTestConfig->attributionReportClickSourceURL : attribution.attributionReportClickSourceURL();
        break;
    case WebCore::PCM::AttributionReportEndpoint::Destination:
        attributionURL = m_attributionReportTestConfig ? m_attributionReportTestConfig->attributionReportClickDestinationURL : attribution.attributionReportClickDestinationURL();
    }

    if (attributionURL.isEmpty() || !attributionURL.isValid())
        return;

    auto pcmDataCarried = debugModeEnabled() ? PrivateClickMeasurement::PcmDataCarried::PersonallyIdentifiable : PrivateClickMeasurement::PcmDataCarried::NonPersonallyIdentifiable;

    RELEASE_LOG_INFO(PrivateClickMeasurement, "About to fire an attribution request.");
    m_client->broadcastConsoleMessage(MessageLevel::Log, "[Private Click Measurement] About to fire an attribution request."_s);

    PCM::NetworkLoader::start(WTFMove(attributionURL), attribution.attributionReportJSON(), pcmDataCarried, [weakThis = WeakPtr { *this }](auto& errorDescription, auto&) {
        RefPtr protectedThis = weakThis.get();
        if (!protectedThis)
            return;

        if (!errorDescription.isNull())
            protectedThis->m_client->broadcastConsoleMessage(MessageLevel::Error, makeString("[Private Click Measurement] Received error: '"_s, errorDescription, "' for ad click attribution request."_s));
    });
}

void PrivateClickMeasurementManager::clearSentAttribution(PrivateClickMeasurement&& sentConversion, WebCore::PCM::AttributionReportEndpoint attributionReportEndpoint)
{
    if (!featureEnabled())
        return;

    store().clearSentAttribution(WTFMove(sentConversion), attributionReportEndpoint);
}

Seconds PrivateClickMeasurementManager::randomlyBetweenFifteenAndThirtyMinutes() const
{
    if (m_isRunningTest)
        return 0_s;

    return debugModeEnabled() ? debugModeSecondsUntilSend : 15_min + Seconds(cryptographicallyRandomNumber<uint32_t>() % 900);
}

void PrivateClickMeasurementManager::firePendingAttributionRequests()
{
    if (!featureEnabled())
        return;

    store().allAttributedPrivateClickMeasurement([weakThis = WeakPtr { *this }] (auto&& attributions) {
        RefPtr protectedThis = weakThis.get();
        if (!protectedThis)
            return;
        auto nextTimeToFire = Seconds::infinity();
        bool hasSentAttribution = false;

        for (auto& attribution : attributions) {
            std::optional<WallTime> earliestTimeToSend = attribution.timesToSend().earliestTimeToSend();
            std::optional<WebCore::PCM::AttributionReportEndpoint> attributionReportEndpoint = attribution.timesToSend().attributionReportEndpoint();

            if (!earliestTimeToSend || !attributionReportEndpoint) {
                ASSERT_NOT_REACHED();
                continue;
            }

            auto now = WallTime::now();
            if (*earliestTimeToSend <= now || protectedThis->m_isRunningTest || protectedThis->debugModeEnabled()) {
                if (hasSentAttribution) {
                    // We've already sent an attribution this round. We should send additional overdue attributions at
                    // a random time between 15 and 30 minutes to avoid a burst of simultaneous attributions. If debug
                    // mode is enabled, this should be much shorter for easy testing.
                    protectedThis->startTimer(protectedThis->randomlyBetweenFifteenAndThirtyMinutes());
                    return;
                }

                auto laterTimeToSend = attribution.timesToSend().latestTimeToSend();
                protectedThis->fireConversionRequest(attribution, *attributionReportEndpoint);
                protectedThis->clearSentAttribution(WTFMove(attribution), *attributionReportEndpoint);
                hasSentAttribution = true;

                // Update nextTimeToFire in case the later report time for this attribution is sooner than the scheduled next time to fire.
                // Or, if debug mode is enabled, we should send the second report on a much shorter delay for easy testing.
                if (laterTimeToSend) {
                    Seconds laterTimeToSendInSecondsFromNow = (*laterTimeToSend - WallTime::now());
                    // Avoid sending expired attributions in bursts by using a random 15-30 minute interval if laterTimeToSend is expired.
                    laterTimeToSendInSecondsFromNow = laterTimeToSendInSecondsFromNow.value() < 0 ? protectedThis->randomlyBetweenFifteenAndThirtyMinutes() : laterTimeToSendInSecondsFromNow;
                    nextTimeToFire = protectedThis->debugModeEnabled() ? debugModeSecondsUntilSend : std::min(nextTimeToFire, laterTimeToSendInSecondsFromNow);
                }
                continue;
            }

            auto seconds = *earliestTimeToSend - now;
            nextTimeToFire = std::min(nextTimeToFire, seconds);

            // Attributions are sorted by earliestTimeToSend, so the first time we hit this there can be no further attributions
            // due for reporting, and nextTimeToFire is the minimum earliestTimeToSend value for any pending attribution.
            break;
        }

        if (nextTimeToFire < Seconds::infinity())
            protectedThis->startTimer(nextTimeToFire);
    });
}

void PrivateClickMeasurementManager::clear(CompletionHandler<void()>&& completionHandler)
{
    m_firePendingAttributionRequestsTimer.stop();
    m_privateClickMeasurementAppBundleIDForTesting = std::nullopt;

    if (!featureEnabled())
        return completionHandler();

    store().clearPrivateClickMeasurement(WTFMove(completionHandler));
}

void PrivateClickMeasurementManager::clearForRegistrableDomain(RegistrableDomain&& domain, CompletionHandler<void()>&& completionHandler)
{
    if (!featureEnabled())
        return completionHandler();

    store().clearPrivateClickMeasurementForRegistrableDomain(WTFMove(domain), WTFMove(completionHandler));
}

void PrivateClickMeasurementManager::clearExpired()
{
    if (!featureEnabled())
        return;

    store().clearExpiredPrivateClickMeasurement();
}

void PrivateClickMeasurementManager::toStringForTesting(CompletionHandler<void(String)>&& completionHandler) const
{
    if (!featureEnabled())
        return completionHandler("\nNo stored Private Click Measurement data.\n"_s);

    store().privateClickMeasurementToStringForTesting(WTFMove(completionHandler));
}

void PrivateClickMeasurementManager::setTokenPublicKeyURLForTesting(URL&& testURL)
{
    if (testURL.isEmpty())
        return;
    m_tokenPublicKeyURLForTesting = WTFMove(testURL);
}

void PrivateClickMeasurementManager::setTokenSignatureURLForTesting(URL&& testURL)
{
    if (testURL.isEmpty())
        m_tokenSignatureURLForTesting = { };
    else
        m_tokenSignatureURLForTesting = WTFMove(testURL);
}

void PrivateClickMeasurementManager::setAttributionReportURLsForTesting(URL&& sourceURL, URL&& destinationURL)
{
    if (sourceURL.isEmpty() || destinationURL.isEmpty())
        m_attributionReportTestConfig = std::nullopt;
    else
        m_attributionReportTestConfig = AttributionReportTestConfig { WTFMove(sourceURL), WTFMove(destinationURL) };
}

void PrivateClickMeasurementManager::markAllUnattributedAsExpiredForTesting()
{
    if (!featureEnabled())
        return;

    store().markAllUnattributedPrivateClickMeasurementAsExpiredForTesting();
}

void PrivateClickMeasurementManager::setPCMFraudPreventionValuesForTesting(String&& unlinkableToken, String&& secretToken, String&& signature, String&& keyID)
{
    if (unlinkableToken.isEmpty() || secretToken.isEmpty() || signature.isEmpty() || keyID.isEmpty())
        return;
    m_fraudPreventionValuesForTesting = TestingFraudPreventionValues { WTFMove(unlinkableToken), WTFMove(secretToken), WTFMove(signature), WTFMove(keyID), emptyString(), emptyString(), emptyString(), emptyString() };
}

bool PrivateClickMeasurementManager::featureEnabled() const
{
    return m_client->featureEnabled();
}

bool PrivateClickMeasurementManager::debugModeEnabled() const
{
    return m_client->debugModeEnabled();
}

void PrivateClickMeasurementManager::markAttributedPrivateClickMeasurementsAsExpiredForTesting(CompletionHandler<void()>&& completionHandler)
{
    if (!featureEnabled())
        return completionHandler();

    store().markAttributedPrivateClickMeasurementsAsExpiredForTesting(WTFMove(completionHandler));
}

void PrivateClickMeasurementManager::initializeStore() const
{
    if (m_store)
        return;

    if (m_client->usesEphemeralDataStore()) {
        ASSERT(m_storageDirectory.isEmpty());
        m_store = PCM::EphemeralStore::create();
    } else
        m_store = PCM::PersistentStore::create(m_storageDirectory);
}

PCM::Store& PrivateClickMeasurementManager::store()
{
    initializeStore();
    return *m_store;
}

const PCM::Store& PrivateClickMeasurementManager::store() const
{
    initializeStore();
    return *m_store;
}

void PrivateClickMeasurementManager::destroyStoreForTesting(CompletionHandler<void()>&& completionHandler)
{
    if (!m_store)
        return completionHandler();
    m_store->close([weakThis = WeakPtr { *this }, completionHandler = WTFMove(completionHandler)] () mutable {
        if (weakThis)
            weakThis->m_store = nullptr;
        return completionHandler();
    });
}

void PrivateClickMeasurementManager::allowTLSCertificateChainForLocalPCMTesting(const WebCore::CertificateInfo& certificateInfo)
{
    PCM::NetworkLoader::allowTLSCertificateChainForLocalPCMTesting(certificateInfo);
}

} // namespace WebKit