File: reporting_endpoint_manager_unittest.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (680 lines) | stat: -rw-r--r-- 25,527 bytes parent folder | download
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
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/reporting/reporting_endpoint_manager.h"

#include <string>

#include "base/strings/stringprintf.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/time/time.h"
#include "base/unguessable_token.h"
#include "net/base/backoff_entry.h"
#include "net/base/isolation_info.h"
#include "net/base/network_anonymization_key.h"
#include "net/base/schemeful_site.h"
#include "net/reporting/reporting_cache.h"
#include "net/reporting/reporting_endpoint.h"
#include "net/reporting/reporting_policy.h"
#include "net/reporting/reporting_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/gurl.h"
#include "url/origin.h"

namespace net {
namespace {

class TestReportingCache : public ReportingCache {
 public:
  class PersistentReportingStore;

  // Tests using this class only use one origin/group.
  TestReportingCache(const url::Origin& expected_origin,
                     const std::string& expected_group)
      : expected_origin_(expected_origin), expected_group_(expected_group) {}

  TestReportingCache(const TestReportingCache&) = delete;
  TestReportingCache& operator=(const TestReportingCache&) = delete;

  ~TestReportingCache() override = default;

  void SetEndpoint(const ReportingEndpoint& reporting_endpoint) {
    reporting_endpoints_[reporting_endpoint.group_key.network_anonymization_key]
        .push_back(reporting_endpoint);
  }

  // ReportingCache implementation:

  std::vector<ReportingEndpoint> GetCandidateEndpointsForDelivery(
      const ReportingEndpointGroupKey& group_key) override {
    EXPECT_EQ(expected_origin_, group_key.origin);
    EXPECT_EQ(expected_group_, group_key.group_name);
    return reporting_endpoints_[group_key.network_anonymization_key];
  }

  // Everything below is NOTREACHED.
  void AddReport(const absl::optional<base::UnguessableToken>& reporting_source,
                 const NetworkAnonymizationKey& network_anonymization_key,
                 const GURL& url,
                 const std::string& user_agent,
                 const std::string& group_name,
                 const std::string& type,
                 base::Value::Dict body,
                 int depth,
                 base::TimeTicks queued,
                 int attempts) override {
    NOTREACHED();
  }
  void GetReports(
      std::vector<const ReportingReport*>* reports_out) const override {
    NOTREACHED();
  }
  base::Value GetReportsAsValue() const override {
    NOTREACHED();
    return base::Value();
  }
  std::vector<const ReportingReport*> GetReportsToDeliver() override {
    NOTREACHED();
    return {};
  }
  std::vector<const ReportingReport*> GetReportsToDeliverForSource(
      const base::UnguessableToken& reporting_source) override {
    NOTREACHED();
    return {};
  }
  void ClearReportsPending(
      const std::vector<const ReportingReport*>& reports) override {
    NOTREACHED();
  }
  void IncrementReportsAttempts(
      const std::vector<const ReportingReport*>& reports) override {
    NOTREACHED();
  }
  base::flat_map<url::Origin, std::vector<ReportingEndpoint>>
  GetV1ReportingEndpointsByOrigin() const override {
    NOTREACHED();
    return base::flat_map<url::Origin, std::vector<ReportingEndpoint>>();
  }
  void IncrementEndpointDeliveries(const ReportingEndpointGroupKey& group_key,
                                   const GURL& url,
                                   int reports_delivered,
                                   bool successful) override {
    NOTREACHED();
  }
  void SetExpiredSource(
      const base::UnguessableToken& reporting_source) override {
    NOTREACHED();
  }
  const base::flat_set<base::UnguessableToken>& GetExpiredSources()
      const override {
    NOTREACHED();
    return expired_sources_;
  }
  void RemoveReports(
      const std::vector<const ReportingReport*>& reports) override {
    NOTREACHED();
  }
  void RemoveReports(const std::vector<const ReportingReport*>& reports,
                     bool delivery_success) override {
    NOTREACHED();
  }
  void RemoveAllReports() override { NOTREACHED(); }
  size_t GetFullReportCountForTesting() const override {
    NOTREACHED();
    return 0;
  }
  size_t GetReportCountWithStatusForTesting(
      ReportingReport::Status status) const override {
    NOTREACHED();
    return 0;
  }
  bool IsReportPendingForTesting(const ReportingReport* report) const override {
    NOTREACHED();
    return false;
  }
  bool IsReportDoomedForTesting(const ReportingReport* report) const override {
    NOTREACHED();
    return false;
  }
  void OnParsedHeader(
      const NetworkAnonymizationKey& network_anonymization_key,
      const url::Origin& origin,
      std::vector<ReportingEndpointGroup> parsed_header) override {
    NOTREACHED();
  }
  void OnParsedReportingEndpointsHeader(
      const base::UnguessableToken& reporting_source,
      const IsolationInfo& isolation_info,
      std::vector<ReportingEndpoint> endpoints) override {
    NOTREACHED();
  }
  std::set<url::Origin> GetAllOrigins() const override {
    NOTREACHED();
    return std::set<url::Origin>();
  }
  void RemoveClient(const NetworkAnonymizationKey& network_anonymization_key,
                    const url::Origin& origin) override {
    NOTREACHED();
  }
  void RemoveClientsForOrigin(const url::Origin& origin) override {
    NOTREACHED();
  }
  void RemoveAllClients() override { NOTREACHED(); }
  void RemoveEndpointGroup(
      const ReportingEndpointGroupKey& group_key) override {
    NOTREACHED();
  }
  void RemoveEndpointsForUrl(const GURL& url) override { NOTREACHED(); }
  void RemoveSourceAndEndpoints(
      const base::UnguessableToken& reporting_source) override {
    NOTREACHED();
  }
  void AddClientsLoadedFromStore(
      std::vector<ReportingEndpoint> loaded_endpoints,
      std::vector<CachedReportingEndpointGroup> loaded_endpoint_groups)
      override {
    NOTREACHED();
  }
  base::Value GetClientsAsValue() const override {
    NOTREACHED();
    return base::Value();
  }
  size_t GetEndpointCount() const override {
    NOTREACHED();
    return 0;
  }
  void Flush() override { NOTREACHED(); }
  ReportingEndpoint GetV1EndpointForTesting(
      const base::UnguessableToken& reporting_source,
      const std::string& endpoint_name) const override {
    NOTREACHED();
    return ReportingEndpoint();
  }
  ReportingEndpoint GetEndpointForTesting(
      const ReportingEndpointGroupKey& group_key,
      const GURL& url) const override {
    NOTREACHED();
    return ReportingEndpoint();
  }
  bool EndpointGroupExistsForTesting(const ReportingEndpointGroupKey& group_key,
                                     OriginSubdomains include_subdomains,
                                     base::Time expires) const override {
    NOTREACHED();
    return false;
  }
  bool ClientExistsForTesting(
      const NetworkAnonymizationKey& network_anonymization_key,
      const url::Origin& origin) const override {
    NOTREACHED();
    return false;
  }
  size_t GetEndpointGroupCountForTesting() const override {
    NOTREACHED();
    return 0;
  }
  size_t GetClientCountForTesting() const override {
    NOTREACHED();
    return 0;
  }
  size_t GetReportingSourceCountForTesting() const override {
    NOTREACHED();
    return 0;
  }
  void SetEndpointForTesting(const ReportingEndpointGroupKey& group_key,
                             const GURL& url,
                             OriginSubdomains include_subdomains,
                             base::Time expires,
                             int priority,
                             int weight) override {
    NOTREACHED();
  }
  void SetV1EndpointForTesting(const ReportingEndpointGroupKey& group_key,
                               const base::UnguessableToken& reporting_source,
                               const IsolationInfo& isolation_info,
                               const GURL& url) override {
    NOTREACHED();
  }
  IsolationInfo GetIsolationInfoForEndpoint(
      const ReportingEndpoint& endpoint) const override {
    NOTREACHED();
    return IsolationInfo();
  }

 private:
  const url::Origin expected_origin_;
  const std::string expected_group_;

  std::map<NetworkAnonymizationKey, std::vector<ReportingEndpoint>>
      reporting_endpoints_;
  base::flat_set<base::UnguessableToken> expired_sources_;
};

class ReportingEndpointManagerTest : public testing::Test {
 public:
  ReportingEndpointManagerTest() : cache_(kOrigin, kGroup) {
    policy_.endpoint_backoff_policy.num_errors_to_ignore = 0;
    policy_.endpoint_backoff_policy.initial_delay_ms = 60000;
    policy_.endpoint_backoff_policy.multiply_factor = 2.0;
    policy_.endpoint_backoff_policy.jitter_factor = 0.0;
    policy_.endpoint_backoff_policy.maximum_backoff_ms = -1;
    policy_.endpoint_backoff_policy.entry_lifetime_ms = 0;
    policy_.endpoint_backoff_policy.always_use_initial_delay = false;

    clock_.SetNowTicks(base::TimeTicks());

    endpoint_manager_ = ReportingEndpointManager::Create(
        &policy_, &clock_, &delegate_, &cache_, TestReportingRandIntCallback());
  }

 protected:
  void SetEndpoint(
      const GURL& endpoint,
      int priority = ReportingEndpoint::EndpointInfo::kDefaultPriority,
      int weight = ReportingEndpoint::EndpointInfo::kDefaultWeight,
      const NetworkAnonymizationKey& network_anonymization_key =
          NetworkAnonymizationKey()) {
    ReportingEndpointGroupKey group_key(kGroupKey);
    group_key.network_anonymization_key = network_anonymization_key;
    cache_.SetEndpoint(ReportingEndpoint(
        group_key,
        ReportingEndpoint::EndpointInfo{endpoint, priority, weight}));
  }

  const NetworkAnonymizationKey kNik;
  const url::Origin kOrigin = url::Origin::Create(GURL("https://origin/"));
  const SchemefulSite kSite = SchemefulSite(kOrigin);
  const std::string kGroup = "group";
  const ReportingEndpointGroupKey kGroupKey =
      ReportingEndpointGroupKey(kNik, kOrigin, kGroup);
  const GURL kEndpoint = GURL("https://endpoint/");

  ReportingPolicy policy_;
  base::SimpleTestTickClock clock_;
  TestReportingDelegate delegate_;
  TestReportingCache cache_;
  std::unique_ptr<ReportingEndpointManager> endpoint_manager_;
};

TEST_F(ReportingEndpointManagerTest, NoEndpoint) {
  ReportingEndpoint endpoint =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  EXPECT_FALSE(endpoint);
}

TEST_F(ReportingEndpointManagerTest, Endpoint) {
  SetEndpoint(kEndpoint);

  ReportingEndpoint endpoint =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  ASSERT_TRUE(endpoint);
  EXPECT_EQ(kEndpoint, endpoint.info.url);
}

TEST_F(ReportingEndpointManagerTest, BackedOffEndpoint) {
  ASSERT_EQ(2.0, policy_.endpoint_backoff_policy.multiply_factor);

  base::TimeDelta initial_delay =
      base::Milliseconds(policy_.endpoint_backoff_policy.initial_delay_ms);

  SetEndpoint(kEndpoint);

  endpoint_manager_->InformOfEndpointRequest(NetworkAnonymizationKey(),
                                             kEndpoint, false);

  // After one failure, endpoint is in exponential backoff.
  ReportingEndpoint endpoint =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  EXPECT_FALSE(endpoint);

  // After initial delay, endpoint is usable again.
  clock_.Advance(initial_delay);

  ReportingEndpoint endpoint2 =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  ASSERT_TRUE(endpoint2);
  EXPECT_EQ(kEndpoint, endpoint2.info.url);

  endpoint_manager_->InformOfEndpointRequest(NetworkAnonymizationKey(),
                                             kEndpoint, false);

  // After a second failure, endpoint is backed off again.
  ReportingEndpoint endpoint3 =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  EXPECT_FALSE(endpoint3);

  clock_.Advance(initial_delay);

  // Next backoff is longer -- 2x the first -- so endpoint isn't usable yet.
  ReportingEndpoint endpoint4 =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  EXPECT_FALSE(endpoint4);

  clock_.Advance(initial_delay);

  // After 2x the initial delay, the endpoint is usable again.
  ReportingEndpoint endpoint5 =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  ASSERT_TRUE(endpoint5);
  EXPECT_EQ(kEndpoint, endpoint5.info.url);

  endpoint_manager_->InformOfEndpointRequest(NetworkAnonymizationKey(),
                                             kEndpoint, true);
  endpoint_manager_->InformOfEndpointRequest(NetworkAnonymizationKey(),
                                             kEndpoint, true);

  // Two more successful requests should reset the backoff to the initial delay
  // again.
  endpoint_manager_->InformOfEndpointRequest(NetworkAnonymizationKey(),
                                             kEndpoint, false);

  ReportingEndpoint endpoint6 =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  EXPECT_FALSE(endpoint6);

  clock_.Advance(initial_delay);

  ReportingEndpoint endpoint7 =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  EXPECT_TRUE(endpoint7);
}

// Make sure that multiple endpoints will all be returned at some point, to
// avoid accidentally or intentionally implementing any priority ordering.
TEST_F(ReportingEndpointManagerTest, RandomEndpoint) {
  static const GURL kEndpoint1("https://endpoint1/");
  static const GURL kEndpoint2("https://endpoint2/");
  static const int kMaxAttempts = 20;

  SetEndpoint(kEndpoint1);
  SetEndpoint(kEndpoint2);

  bool endpoint1_seen = false;
  bool endpoint2_seen = false;

  for (int i = 0; i < kMaxAttempts; ++i) {
    ReportingEndpoint endpoint =
        endpoint_manager_->FindEndpointForDelivery(kGroupKey);
    ASSERT_TRUE(endpoint);
    ASSERT_TRUE(endpoint.info.url == kEndpoint1 ||
                endpoint.info.url == kEndpoint2);

    if (endpoint.info.url == kEndpoint1)
      endpoint1_seen = true;
    else if (endpoint.info.url == kEndpoint2)
      endpoint2_seen = true;

    if (endpoint1_seen && endpoint2_seen)
      break;
  }

  EXPECT_TRUE(endpoint1_seen);
  EXPECT_TRUE(endpoint2_seen);
}

TEST_F(ReportingEndpointManagerTest, Priority) {
  static const GURL kPrimaryEndpoint("https://endpoint1/");
  static const GURL kBackupEndpoint("https://endpoint2/");

  SetEndpoint(kPrimaryEndpoint, 10 /* priority */,
              ReportingEndpoint::EndpointInfo::kDefaultWeight);
  SetEndpoint(kBackupEndpoint, 20 /* priority */,
              ReportingEndpoint::EndpointInfo::kDefaultWeight);

  ReportingEndpoint endpoint =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  ASSERT_TRUE(endpoint);
  EXPECT_EQ(kPrimaryEndpoint, endpoint.info.url);

  // The backoff policy we set up in the constructor means that a single failed
  // upload will take the primary endpoint out of contention.  This should cause
  // us to choose the backend endpoint.
  endpoint_manager_->InformOfEndpointRequest(NetworkAnonymizationKey(),
                                             kPrimaryEndpoint, false);
  ReportingEndpoint endpoint2 =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  ASSERT_TRUE(endpoint2);
  EXPECT_EQ(kBackupEndpoint, endpoint2.info.url);

  // Advance the current time far enough to clear out the primary endpoint's
  // backoff clock.  This should bring the primary endpoint back into play.
  clock_.Advance(base::Minutes(2));
  ReportingEndpoint endpoint3 =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  ASSERT_TRUE(endpoint3);
  EXPECT_EQ(kPrimaryEndpoint, endpoint3.info.url);
}

// Note: This test depends on the deterministic mock RandIntCallback set up in
// TestReportingContext, which returns consecutive integers starting at 0
// (modulo the requested range, plus the requested minimum).
TEST_F(ReportingEndpointManagerTest, Weight) {
  static const GURL kEndpoint1("https://endpoint1/");
  static const GURL kEndpoint2("https://endpoint2/");

  static const int kEndpoint1Weight = 5;
  static const int kEndpoint2Weight = 2;
  static const int kTotalEndpointWeight = kEndpoint1Weight + kEndpoint2Weight;

  SetEndpoint(kEndpoint1, ReportingEndpoint::EndpointInfo::kDefaultPriority,
              kEndpoint1Weight);
  SetEndpoint(kEndpoint2, ReportingEndpoint::EndpointInfo::kDefaultPriority,
              kEndpoint2Weight);

  int endpoint1_count = 0;
  int endpoint2_count = 0;

  for (int i = 0; i < kTotalEndpointWeight; ++i) {
    ReportingEndpoint endpoint =
        endpoint_manager_->FindEndpointForDelivery(kGroupKey);
    ASSERT_TRUE(endpoint);
    ASSERT_TRUE(endpoint.info.url == kEndpoint1 ||
                endpoint.info.url == kEndpoint2);

    if (endpoint.info.url == kEndpoint1)
      ++endpoint1_count;
    else if (endpoint.info.url == kEndpoint2)
      ++endpoint2_count;
  }

  EXPECT_EQ(kEndpoint1Weight, endpoint1_count);
  EXPECT_EQ(kEndpoint2Weight, endpoint2_count);
}

TEST_F(ReportingEndpointManagerTest, ZeroWeights) {
  static const GURL kEndpoint1("https://endpoint1/");
  static const GURL kEndpoint2("https://endpoint2/");

  SetEndpoint(kEndpoint1, ReportingEndpoint::EndpointInfo::kDefaultPriority,
              0 /* weight */);
  SetEndpoint(kEndpoint2, ReportingEndpoint::EndpointInfo::kDefaultPriority,
              0 /* weight */);

  int endpoint1_count = 0;
  int endpoint2_count = 0;

  for (int i = 0; i < 10; ++i) {
    ReportingEndpoint endpoint =
        endpoint_manager_->FindEndpointForDelivery(kGroupKey);
    ASSERT_TRUE(endpoint);
    ASSERT_TRUE(endpoint.info.url == kEndpoint1 ||
                endpoint.info.url == kEndpoint2);

    if (endpoint.info.url == kEndpoint1)
      ++endpoint1_count;
    else if (endpoint.info.url == kEndpoint2)
      ++endpoint2_count;
  }

  EXPECT_EQ(5, endpoint1_count);
  EXPECT_EQ(5, endpoint2_count);
}

// Check that ReportingEndpointManager distinguishes NetworkAnonymizationKeys.
TEST_F(ReportingEndpointManagerTest, NetworkAnonymizationKey) {
  const SchemefulSite kSite2(GURL("https://origin2/"));

  const auto kNetworkAnonymizationKey1 =
      NetworkAnonymizationKey::CreateSameSite(kSite);
  const auto kNetworkAnonymizationKey2 =
      NetworkAnonymizationKey::CreateSameSite(kSite2);
  const ReportingEndpointGroupKey kGroupKey1(kNetworkAnonymizationKey1, kOrigin,
                                             kGroup);
  const ReportingEndpointGroupKey kGroupKey2(kNetworkAnonymizationKey2, kOrigin,
                                             kGroup);

  // An Endpoint set for kNetworkAnonymizationKey1 should not affect
  // kNetworkAnonymizationKey2.
  SetEndpoint(kEndpoint, ReportingEndpoint::EndpointInfo::kDefaultPriority,
              0 /* weight */, kNetworkAnonymizationKey1);
  ReportingEndpoint endpoint =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey1);
  ASSERT_TRUE(endpoint);
  EXPECT_EQ(kEndpoint, endpoint.info.url);
  EXPECT_FALSE(endpoint_manager_->FindEndpointForDelivery(kGroupKey2));
  EXPECT_FALSE(endpoint_manager_->FindEndpointForDelivery(kGroupKey));

  // Set the same Endpoint for kNetworkAnonymizationKey2, so both should be
  // reporting to the same URL.
  SetEndpoint(kEndpoint, ReportingEndpoint::EndpointInfo::kDefaultPriority,
              0 /* weight */, kNetworkAnonymizationKey2);
  endpoint = endpoint_manager_->FindEndpointForDelivery(kGroupKey1);
  ASSERT_TRUE(endpoint);
  EXPECT_EQ(kEndpoint, endpoint.info.url);
  endpoint = endpoint_manager_->FindEndpointForDelivery(kGroupKey2);
  ASSERT_TRUE(endpoint);
  EXPECT_EQ(kEndpoint, endpoint.info.url);
  EXPECT_FALSE(endpoint_manager_->FindEndpointForDelivery(kGroupKey));

  // An error reporting to that URL in the context of kNetworkAnonymizationKey1
  // should only affect the Endpoint retrieved in the context of
  // kNetworkAnonymizationKey1.
  endpoint_manager_->InformOfEndpointRequest(kNetworkAnonymizationKey1,
                                             kEndpoint, false);
  EXPECT_FALSE(endpoint_manager_->FindEndpointForDelivery(kGroupKey1));
  endpoint = endpoint_manager_->FindEndpointForDelivery(kGroupKey2);
  ASSERT_TRUE(endpoint);
  EXPECT_EQ(kEndpoint, endpoint.info.url);
  EXPECT_FALSE(endpoint_manager_->FindEndpointForDelivery(kGroupKey));
}

TEST_F(ReportingEndpointManagerTest,
       NetworkAnonymizationKeyWithMultipleEndpoints) {
  const SchemefulSite kSite2(GURL("https://origin2/"));

  const auto kNetworkAnonymizationKey1 =
      NetworkAnonymizationKey::CreateSameSite(kSite);
  const auto kNetworkAnonymizationKey2 =
      NetworkAnonymizationKey::CreateSameSite(kSite2);
  const ReportingEndpointGroupKey kGroupKey1(kNetworkAnonymizationKey1, kOrigin,
                                             kGroup);
  const ReportingEndpointGroupKey kGroupKey2(kNetworkAnonymizationKey2, kOrigin,
                                             kGroup);

  const GURL kEndpoint1("https://endpoint1/");
  const GURL kEndpoint2("https://endpoint2/");
  const GURL kEndpoint3("https://endpoint3/");
  const int kMaxAttempts = 20;

  // Add two Endpoints for kNetworkAnonymizationKey1, and a different one for
  // kNetworkAnonymizationKey2.
  SetEndpoint(kEndpoint1, ReportingEndpoint::EndpointInfo::kDefaultPriority,
              ReportingEndpoint::EndpointInfo::kDefaultWeight,
              kNetworkAnonymizationKey1);
  SetEndpoint(kEndpoint2, ReportingEndpoint::EndpointInfo::kDefaultPriority,
              ReportingEndpoint::EndpointInfo::kDefaultWeight,
              kNetworkAnonymizationKey1);
  SetEndpoint(kEndpoint3, ReportingEndpoint::EndpointInfo::kDefaultPriority,
              ReportingEndpoint::EndpointInfo::kDefaultWeight,
              kNetworkAnonymizationKey2);

  bool endpoint1_seen = false;
  bool endpoint2_seen = false;

  // Make sure that calling FindEndpointForDelivery() with
  // kNetworkAnonymizationKey1 can return both of its endpoints, but not
  // kNetworkAnonymizationKey2's endpoint.
  for (int i = 0; i < kMaxAttempts; ++i) {
    ReportingEndpoint endpoint =
        endpoint_manager_->FindEndpointForDelivery(kGroupKey1);
    ASSERT_TRUE(endpoint);
    ASSERT_TRUE(endpoint.info.url == kEndpoint1 ||
                endpoint.info.url == kEndpoint2);

    if (endpoint.info.url == kEndpoint1) {
      endpoint1_seen = true;
    } else if (endpoint.info.url == kEndpoint2) {
      endpoint2_seen = true;
    }
  }

  EXPECT_TRUE(endpoint1_seen);
  EXPECT_TRUE(endpoint2_seen);

  ReportingEndpoint endpoint =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey2);
  ASSERT_TRUE(endpoint);
  EXPECT_EQ(kEndpoint3, endpoint.info.url);
}

TEST_F(ReportingEndpointManagerTest, CacheEviction) {
  // Add |kMaxEndpointBackoffCacheSize| endpoints.
  for (int i = 0; i < ReportingEndpointManager::kMaxEndpointBackoffCacheSize;
       ++i) {
    SetEndpoint(GURL(base::StringPrintf("https://endpoint%i/", i)));
  }

  // Mark each endpoint as bad, one-at-a-time. Use FindEndpointForDelivery() to
  // pick which one to mark as bad, both to exercise the code walking through
  // all endpoints, and as a consistency check.
  std::set<GURL> seen_endpoints;
  for (int i = 0; i < ReportingEndpointManager::kMaxEndpointBackoffCacheSize;
       ++i) {
    ReportingEndpoint endpoint =
        endpoint_manager_->FindEndpointForDelivery(kGroupKey);
    EXPECT_TRUE(endpoint);
    EXPECT_FALSE(seen_endpoints.count(endpoint.info.url));
    seen_endpoints.insert(endpoint.info.url);
    endpoint_manager_->InformOfEndpointRequest(NetworkAnonymizationKey(),
                                               endpoint.info.url, false);
  }
  // All endpoints should now be marked as bad.
  EXPECT_FALSE(endpoint_manager_->FindEndpointForDelivery(kGroupKey));

  // Add another endpoint with a different NetworkAnonymizationKey;
  const auto kDifferentNetworkAnonymizationKey =
      NetworkAnonymizationKey::CreateSameSite(kSite);
  const ReportingEndpointGroupKey kDifferentGroupKey(
      kDifferentNetworkAnonymizationKey, kOrigin, kGroup);
  SetEndpoint(kEndpoint, ReportingEndpoint::EndpointInfo::kDefaultPriority,
              ReportingEndpoint::EndpointInfo::kDefaultWeight,
              kDifferentNetworkAnonymizationKey);
  // All endpoints associated with the empty NetworkAnonymizationKey should
  // still be marked as bad.
  EXPECT_FALSE(endpoint_manager_->FindEndpointForDelivery(kGroupKey));

  // Make the endpoint added for the kDifferentNetworkAnonymizationKey as bad.
  endpoint_manager_->InformOfEndpointRequest(kDifferentNetworkAnonymizationKey,
                                             kEndpoint, false);
  // The only endpoint for kDifferentNetworkAnonymizationKey should still be
  // marked as bad.
  EXPECT_FALSE(endpoint_manager_->FindEndpointForDelivery(kDifferentGroupKey));
  // One of the endpoints for the empty NetworkAnonymizationKey should no longer
  // be marked as bad, due to eviction.
  ReportingEndpoint endpoint =
      endpoint_manager_->FindEndpointForDelivery(kGroupKey);
  EXPECT_TRUE(endpoint);

  // Reporting a success for the (only) good endpoint for the empty
  // NetworkAnonymizationKey should evict the entry for
  // kNetworkAnonymizationKey, since the most recent FindEndpointForDelivery()
  // call visited all of the empty NetworkAnonymizationKey's cached bad entries.
  endpoint_manager_->InformOfEndpointRequest(NetworkAnonymizationKey(),
                                             endpoint.info.url, true);

  EXPECT_TRUE(endpoint_manager_->FindEndpointForDelivery(kDifferentGroupKey));
}

}  // namespace
}  // namespace net