summaryrefslogtreecommitdiffstats
path: root/dom/reporting/ReportingHeader.cpp
blob: 66a7c93e1e63f7eca8b2b320ee563ecf549f4749 (plain)
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/dom/ReportingHeader.h"

#include "js/Array.h"  // JS::GetArrayLength, JS::IsArrayObject
#include "js/JSON.h"
#include "js/PropertyAndElement.h"  // JS_GetElement
#include "mozilla/dom/ReportingBinding.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/SimpleGlobalObject.h"
#include "mozilla/ipc/BackgroundUtils.h"
#include "mozilla/OriginAttributes.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPtr.h"
#include "nsCOMPtr.h"
#include "nsContentUtils.h"
#include "nsIEffectiveTLDService.h"
#include "nsIHttpChannel.h"
#include "nsIHttpProtocolHandler.h"
#include "nsIObserverService.h"
#include "nsIPrincipal.h"
#include "nsIRandomGenerator.h"
#include "nsIScriptError.h"
#include "nsNetUtil.h"
#include "nsXULAppAPI.h"

#define REPORTING_PURGE_ALL "reporting:purge-all"
#define REPORTING_PURGE_HOST "reporting:purge-host"

namespace mozilla::dom {

namespace {

StaticRefPtr<ReportingHeader> gReporting;

}  // namespace

/* static */
void ReportingHeader::Initialize() {
  MOZ_ASSERT(!gReporting);
  MOZ_ASSERT(NS_IsMainThread());

  if (!XRE_IsParentProcess()) {
    return;
  }

  RefPtr<ReportingHeader> service = new ReportingHeader();

  nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
  if (NS_WARN_IF(!obs)) {
    return;
  }

  obs->AddObserver(service, NS_HTTP_ON_EXAMINE_RESPONSE_TOPIC, false);
  obs->AddObserver(service, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
  obs->AddObserver(service, "clear-origin-attributes-data", false);
  obs->AddObserver(service, REPORTING_PURGE_HOST, false);
  obs->AddObserver(service, REPORTING_PURGE_ALL, false);

  gReporting = service;
}

/* static */
void ReportingHeader::Shutdown() {
  MOZ_ASSERT(NS_IsMainThread());

  if (!gReporting) {
    return;
  }

  RefPtr<ReportingHeader> service = gReporting;
  gReporting = nullptr;

  if (service->mCleanupTimer) {
    service->mCleanupTimer->Cancel();
    service->mCleanupTimer = nullptr;
  }

  nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
  if (NS_WARN_IF(!obs)) {
    return;
  }

  obs->RemoveObserver(service, NS_HTTP_ON_EXAMINE_RESPONSE_TOPIC);
  obs->RemoveObserver(service, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
  obs->RemoveObserver(service, "clear-origin-attributes-data");
  obs->RemoveObserver(service, REPORTING_PURGE_HOST);
  obs->RemoveObserver(service, REPORTING_PURGE_ALL);
}

ReportingHeader::ReportingHeader() = default;
ReportingHeader::~ReportingHeader() = default;

NS_IMETHODIMP
ReportingHeader::Observe(nsISupports* aSubject, const char* aTopic,
                         const char16_t* aData) {
  if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
    Shutdown();
    return NS_OK;
  }

  // Pref disabled.
  if (!StaticPrefs::dom_reporting_header_enabled()) {
    return NS_OK;
  }

  if (!strcmp(aTopic, NS_HTTP_ON_EXAMINE_RESPONSE_TOPIC)) {
    nsCOMPtr<nsIHttpChannel> channel = do_QueryInterface(aSubject);
    if (NS_WARN_IF(!channel)) {
      return NS_OK;
    }

    ReportingFromChannel(channel);
    return NS_OK;
  }

  if (!strcmp(aTopic, REPORTING_PURGE_HOST)) {
    RemoveOriginsFromHost(nsDependentString(aData));
    return NS_OK;
  }

  if (!strcmp(aTopic, "clear-origin-attributes-data")) {
    OriginAttributesPattern pattern;
    if (!pattern.Init(nsDependentString(aData))) {
      NS_ERROR("Cannot parse origin attributes pattern");
      return NS_ERROR_FAILURE;
    }

    RemoveOriginsFromOriginAttributesPattern(pattern);
    return NS_OK;
  }

  if (!strcmp(aTopic, REPORTING_PURGE_ALL)) {
    RemoveOrigins();
    return NS_OK;
  }

  return NS_ERROR_FAILURE;
}

void ReportingHeader::ReportingFromChannel(nsIHttpChannel* aChannel) {
  MOZ_ASSERT(aChannel);

  if (!StaticPrefs::dom_reporting_header_enabled()) {
    return;
  }

  // We want to use the final URI to check if Report-To should be allowed or
  // not.
  nsCOMPtr<nsIURI> uri;
  nsresult rv = aChannel->GetURI(getter_AddRefs(uri));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  if (!IsSecureURI(uri)) {
    return;
  }

  if (NS_UsePrivateBrowsing(aChannel)) {
    return;
  }

  nsAutoCString headerValue;
  rv = aChannel->GetResponseHeader("Report-To"_ns, headerValue);
  if (NS_FAILED(rv)) {
    return;
  }

  nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
  if (NS_WARN_IF(!ssm)) {
    return;
  }

  nsCOMPtr<nsIPrincipal> principal;
  rv = ssm->GetChannelURIPrincipal(aChannel, getter_AddRefs(principal));
  if (NS_WARN_IF(NS_FAILED(rv)) || !principal) {
    return;
  }

  nsAutoCString origin;
  rv = principal->GetOrigin(origin);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  UniquePtr<Client> client = ParseHeader(aChannel, uri, headerValue);
  if (!client) {
    return;
  }

  // Here we override the previous data.
  mOrigins.InsertOrUpdate(origin, std::move(client));

  MaybeCreateCleanupTimer();
}

/* static */ UniquePtr<ReportingHeader::Client> ReportingHeader::ParseHeader(
    nsIHttpChannel* aChannel, nsIURI* aURI, const nsACString& aHeaderValue) {
  MOZ_ASSERT(aURI);
  // aChannel can be null in gtest

  AutoJSAPI jsapi;

  JSObject* cleanGlobal =
      SimpleGlobalObject::Create(SimpleGlobalObject::GlobalType::BindingDetail);
  if (NS_WARN_IF(!cleanGlobal)) {
    return nullptr;
  }

  if (NS_WARN_IF(!jsapi.Init(cleanGlobal))) {
    return nullptr;
  }

  // WebIDL dictionary parses single items. Let's create a object to parse the
  // header.
  nsAutoString json;
  json.AppendASCII("{ \"items\": [");
  json.Append(NS_ConvertUTF8toUTF16(aHeaderValue));
  json.AppendASCII("]}");

  JSContext* cx = jsapi.cx();
  JS::Rooted<JS::Value> jsonValue(cx);
  bool ok = JS_ParseJSON(cx, json.BeginReading(), json.Length(), &jsonValue);
  if (!ok) {
    LogToConsoleInvalidJSON(aChannel, aURI);
    return nullptr;
  }

  dom::ReportingHeaderValue data;
  if (!data.Init(cx, jsonValue)) {
    LogToConsoleInvalidJSON(aChannel, aURI);
    return nullptr;
  }

  if (!data.mItems.WasPassed() || data.mItems.Value().IsEmpty()) {
    return nullptr;
  }

  UniquePtr<Client> client = MakeUnique<Client>();

  for (const dom::ReportingItem& item : data.mItems.Value()) {
    nsAutoString groupName;

    if (item.mGroup.isUndefined()) {
      groupName.AssignLiteral("default");
    } else if (!item.mGroup.isString()) {
      LogToConsoleInvalidNameItem(aChannel, aURI);
      continue;
    } else {
      JS::Rooted<JSString*> groupStr(cx, item.mGroup.toString());
      MOZ_ASSERT(groupStr);

      nsAutoJSString string;
      if (NS_WARN_IF(!string.init(cx, groupStr))) {
        continue;
      }

      groupName = string;
    }

    if (!item.mMax_age.isNumber() || !item.mEndpoints.isObject()) {
      LogToConsoleIncompleteItem(aChannel, aURI, groupName);
      continue;
    }

    JS::Rooted<JSObject*> endpoints(cx, &item.mEndpoints.toObject());
    MOZ_ASSERT(endpoints);

    bool isArray = false;
    if (!JS::IsArrayObject(cx, endpoints, &isArray) || !isArray) {
      LogToConsoleIncompleteItem(aChannel, aURI, groupName);
      continue;
    }

    uint32_t endpointsLength;
    if (!JS::GetArrayLength(cx, endpoints, &endpointsLength) ||
        endpointsLength == 0) {
      LogToConsoleIncompleteItem(aChannel, aURI, groupName);
      continue;
    }

    const auto [begin, end] = client->mGroups.NonObservingRange();
    if (std::any_of(begin, end, [&groupName](const Group& group) {
          return group.mName == groupName;
        })) {
      LogToConsoleDuplicateGroup(aChannel, aURI, groupName);
      continue;
    }

    Group* group = client->mGroups.AppendElement();
    group->mName = groupName;
    group->mIncludeSubdomains = item.mInclude_subdomains;
    group->mTTL = item.mMax_age.toNumber();
    group->mCreationTime = TimeStamp::Now();

    for (uint32_t i = 0; i < endpointsLength; ++i) {
      JS::Rooted<JS::Value> element(cx);
      if (!JS_GetElement(cx, endpoints, i, &element)) {
        return nullptr;
      }

      RootedDictionary<ReportingEndpoint> endpoint(cx);
      if (!endpoint.Init(cx, element)) {
        LogToConsoleIncompleteEndpoint(aChannel, aURI, groupName);
        continue;
      }

      if (!endpoint.mUrl.isString() ||
          (!endpoint.mPriority.isUndefined() &&
           (!endpoint.mPriority.isNumber() ||
            endpoint.mPriority.toNumber() < 0)) ||
          (!endpoint.mWeight.isUndefined() &&
           (!endpoint.mWeight.isNumber() || endpoint.mWeight.toNumber() < 0))) {
        LogToConsoleIncompleteEndpoint(aChannel, aURI, groupName);
        continue;
      }

      JS::Rooted<JSString*> endpointUrl(cx, endpoint.mUrl.toString());
      MOZ_ASSERT(endpointUrl);

      nsAutoJSString endpointString;
      if (NS_WARN_IF(!endpointString.init(cx, endpointUrl))) {
        continue;
      }

      nsCOMPtr<nsIURI> uri;
      nsresult rv = NS_NewURI(getter_AddRefs(uri), endpointString);
      if (NS_FAILED(rv)) {
        LogToConsoleInvalidURLEndpoint(aChannel, aURI, groupName,
                                       endpointString);
        continue;
      }

      Endpoint* ep = group->mEndpoints.AppendElement();
      ep->mUrl = uri;
      ep->mPriority =
          endpoint.mPriority.isUndefined() ? 1 : endpoint.mPriority.toNumber();
      ep->mWeight =
          endpoint.mWeight.isUndefined() ? 1 : endpoint.mWeight.toNumber();
    }
  }

  if (client->mGroups.IsEmpty()) {
    return nullptr;
  }

  return client;
}

bool ReportingHeader::IsSecureURI(nsIURI* aURI) const {
  MOZ_ASSERT(aURI);

  bool prioriAuthenticated = false;
  if (NS_WARN_IF(NS_FAILED(NS_URIChainHasFlags(
          aURI, nsIProtocolHandler::URI_IS_POTENTIALLY_TRUSTWORTHY,
          &prioriAuthenticated)))) {
    return false;
  }

  return prioriAuthenticated;
}

/* static */
void ReportingHeader::LogToConsoleInvalidJSON(nsIHttpChannel* aChannel,
                                              nsIURI* aURI) {
  nsTArray<nsString> params;
  LogToConsoleInternal(aChannel, aURI, "ReportingHeaderInvalidJSON", params);
}

/* static */
void ReportingHeader::LogToConsoleDuplicateGroup(nsIHttpChannel* aChannel,
                                                 nsIURI* aURI,
                                                 const nsAString& aName) {
  nsTArray<nsString> params;
  params.AppendElement(aName);

  LogToConsoleInternal(aChannel, aURI, "ReportingHeaderDuplicateGroup", params);
}

/* static */
void ReportingHeader::LogToConsoleInvalidNameItem(nsIHttpChannel* aChannel,
                                                  nsIURI* aURI) {
  nsTArray<nsString> params;
  LogToConsoleInternal(aChannel, aURI, "ReportingHeaderInvalidNameItem",
                       params);
}

/* static */
void ReportingHeader::LogToConsoleIncompleteItem(nsIHttpChannel* aChannel,
                                                 nsIURI* aURI,
                                                 const nsAString& aName) {
  nsTArray<nsString> params;
  params.AppendElement(aName);

  LogToConsoleInternal(aChannel, aURI, "ReportingHeaderInvalidItem", params);
}

/* static */
void ReportingHeader::LogToConsoleIncompleteEndpoint(nsIHttpChannel* aChannel,
                                                     nsIURI* aURI,
                                                     const nsAString& aName) {
  nsTArray<nsString> params;
  params.AppendElement(aName);

  LogToConsoleInternal(aChannel, aURI, "ReportingHeaderInvalidEndpoint",
                       params);
}

/* static */
void ReportingHeader::LogToConsoleInvalidURLEndpoint(nsIHttpChannel* aChannel,
                                                     nsIURI* aURI,
                                                     const nsAString& aName,
                                                     const nsAString& aURL) {
  nsTArray<nsString> params;
  params.AppendElement(aURL);
  params.AppendElement(aName);

  LogToConsoleInternal(aChannel, aURI, "ReportingHeaderInvalidURLEndpoint",
                       params);
}

/* static */
void ReportingHeader::LogToConsoleInternal(nsIHttpChannel* aChannel,
                                           nsIURI* aURI, const char* aMsg,
                                           const nsTArray<nsString>& aParams) {
  MOZ_ASSERT(aURI);

  if (!aChannel) {
    // We are in a gtest.
    return;
  }

  uint64_t windowID = 0;

  nsresult rv = aChannel->GetTopLevelContentWindowId(&windowID);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  if (!windowID) {
    nsCOMPtr<nsILoadGroup> loadGroup;
    nsresult rv = aChannel->GetLoadGroup(getter_AddRefs(loadGroup));
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return;
    }

    if (loadGroup) {
      windowID = nsContentUtils::GetInnerWindowID(loadGroup);
    }
  }

  nsAutoString localizedMsg;
  rv = nsContentUtils::FormatLocalizedString(
      nsContentUtils::eSECURITY_PROPERTIES, aMsg, aParams, localizedMsg);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  rv = nsContentUtils::ReportToConsoleByWindowID(
      localizedMsg, nsIScriptError::infoFlag, "Reporting"_ns, windowID, aURI);
  Unused << NS_WARN_IF(NS_FAILED(rv));
}

/* static */
void ReportingHeader::GetEndpointForReport(
    const nsAString& aGroupName,
    const mozilla::ipc::PrincipalInfo& aPrincipalInfo,
    nsACString& aEndpointURI) {
  auto principalOrErr = PrincipalInfoToPrincipal(aPrincipalInfo);
  if (NS_WARN_IF(principalOrErr.isErr())) {
    return;
  }

  nsCOMPtr<nsIPrincipal> principal = principalOrErr.unwrap();
  GetEndpointForReport(aGroupName, principal, aEndpointURI);
}

/* static */
void ReportingHeader::GetEndpointForReport(const nsAString& aGroupName,
                                           nsIPrincipal* aPrincipal,
                                           nsACString& aEndpointURI) {
  MOZ_ASSERT(aEndpointURI.IsEmpty());

  if (!gReporting) {
    return;
  }

  nsAutoCString origin;
  nsresult rv = aPrincipal->GetOrigin(origin);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  Client* client = gReporting->mOrigins.Get(origin);
  if (!client) {
    return;
  }

  const auto [begin, end] = client->mGroups.NonObservingRange();
  const auto foundIt = std::find_if(
      begin, end,
      [&aGroupName](const Group& group) { return group.mName == aGroupName; });
  if (foundIt != end) {
    GetEndpointForReportInternal(*foundIt, aEndpointURI);
  }

  // XXX More explicitly report an error if not found?
}

/* static */
void ReportingHeader::GetEndpointForReportInternal(
    const ReportingHeader::Group& aGroup, nsACString& aEndpointURI) {
  TimeDuration diff = TimeStamp::Now() - aGroup.mCreationTime;
  if (diff.ToSeconds() > aGroup.mTTL) {
    // Expired.
    return;
  }

  if (aGroup.mEndpoints.IsEmpty()) {
    return;
  }

  int64_t minPriority = -1;
  uint32_t totalWeight = 0;

  for (const Endpoint& endpoint : aGroup.mEndpoints.NonObservingRange()) {
    if (minPriority == -1 || minPriority > endpoint.mPriority) {
      minPriority = endpoint.mPriority;
      totalWeight = endpoint.mWeight;
    } else if (minPriority == endpoint.mPriority) {
      totalWeight += endpoint.mWeight;
    }
  }

  nsCOMPtr<nsIRandomGenerator> randomGenerator =
      do_GetService("@mozilla.org/security/random-generator;1");
  if (NS_WARN_IF(!randomGenerator)) {
    return;
  }

  uint32_t randomNumber = 0;

  uint8_t* buffer;
  nsresult rv =
      randomGenerator->GenerateRandomBytes(sizeof(randomNumber), &buffer);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  memcpy(&randomNumber, buffer, sizeof(randomNumber));
  free(buffer);

  totalWeight = randomNumber % totalWeight;

  const auto [begin, end] = aGroup.mEndpoints.NonObservingRange();
  const auto foundIt = std::find_if(
      begin, end, [minPriority, totalWeight](const Endpoint& endpoint) {
        return minPriority == endpoint.mPriority &&
               totalWeight < endpoint.mWeight;
      });
  if (foundIt != end) {
    Unused << NS_WARN_IF(NS_FAILED(foundIt->mUrl->GetSpec(aEndpointURI)));
  }
  // XXX More explicitly report an error if not found?
}

/* static */
void ReportingHeader::RemoveEndpoint(
    const nsAString& aGroupName, const nsACString& aEndpointURL,
    const mozilla::ipc::PrincipalInfo& aPrincipalInfo) {
  if (!gReporting) {
    return;
  }

  nsCOMPtr<nsIURI> uri;
  nsresult rv = NS_NewURI(getter_AddRefs(uri), aEndpointURL);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  auto principalOrErr = PrincipalInfoToPrincipal(aPrincipalInfo);
  if (NS_WARN_IF(principalOrErr.isErr())) {
    return;
  }

  nsAutoCString origin;
  rv = principalOrErr.unwrap()->GetOrigin(origin);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  Client* client = gReporting->mOrigins.Get(origin);
  if (!client) {
    return;
  }

  // Scope for the group iterator.
  {
    nsTObserverArray<Group>::BackwardIterator iter(client->mGroups);
    while (iter.HasMore()) {
      const Group& group = iter.GetNext();
      if (group.mName != aGroupName) {
        continue;
      }

      // Scope for the endpoint iterator.
      {
        nsTObserverArray<Endpoint>::BackwardIterator endpointIter(
            group.mEndpoints);
        while (endpointIter.HasMore()) {
          const Endpoint& endpoint = endpointIter.GetNext();

          bool equal = false;
          rv = endpoint.mUrl->Equals(uri, &equal);
          if (NS_WARN_IF(NS_FAILED(rv))) {
            continue;
          }

          if (equal) {
            endpointIter.Remove();
            break;
          }
        }
      }

      if (group.mEndpoints.IsEmpty()) {
        iter.Remove();
      }

      break;
    }
  }

  if (client->mGroups.IsEmpty()) {
    gReporting->mOrigins.Remove(origin);
    gReporting->MaybeCancelCleanupTimer();
  }
}

void ReportingHeader::RemoveOriginsFromHost(const nsAString& aHost) {
  nsCOMPtr<nsIEffectiveTLDService> tldService =
      do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
  if (NS_WARN_IF(!tldService)) {
    return;
  }

  NS_ConvertUTF16toUTF8 host(aHost);

  for (auto iter = mOrigins.Iter(); !iter.Done(); iter.Next()) {
    bool hasRootDomain = false;
    nsresult rv = tldService->HasRootDomain(iter.Key(), host, &hasRootDomain);
    if (NS_WARN_IF(NS_FAILED(rv)) || !hasRootDomain) {
      continue;
    }

    iter.Remove();
  }

  MaybeCancelCleanupTimer();
}

void ReportingHeader::RemoveOriginsFromOriginAttributesPattern(
    const OriginAttributesPattern& aPattern) {
  for (auto iter = mOrigins.Iter(); !iter.Done(); iter.Next()) {
    nsAutoCString suffix;
    OriginAttributes attr;
    if (NS_WARN_IF(!attr.PopulateFromOrigin(iter.Key(), suffix))) {
      continue;
    }

    if (aPattern.Matches(attr)) {
      iter.Remove();
    }
  }

  MaybeCancelCleanupTimer();
}

void ReportingHeader::RemoveOrigins() {
  mOrigins.Clear();
  MaybeCancelCleanupTimer();
}

void ReportingHeader::RemoveOriginsForTTL() {
  TimeStamp now = TimeStamp::Now();

  for (auto iter = mOrigins.Iter(); !iter.Done(); iter.Next()) {
    Client* client = iter.UserData();

    // Scope of the iterator.
    {
      nsTObserverArray<Group>::BackwardIterator groupIter(client->mGroups);
      while (groupIter.HasMore()) {
        const Group& group = groupIter.GetNext();
        TimeDuration diff = now - group.mCreationTime;
        if (diff.ToSeconds() > group.mTTL) {
          groupIter.Remove();
          return;
        }
      }
    }

    if (client->mGroups.IsEmpty()) {
      iter.Remove();
    }
  }
}

/* static */
bool ReportingHeader::HasReportingHeaderForOrigin(const nsACString& aOrigin) {
  if (!gReporting) {
    return false;
  }

  return gReporting->mOrigins.Contains(aOrigin);
}

NS_IMETHODIMP
ReportingHeader::Notify(nsITimer* aTimer) {
  mCleanupTimer = nullptr;

  RemoveOriginsForTTL();
  MaybeCreateCleanupTimer();

  return NS_OK;
}

NS_IMETHODIMP
ReportingHeader::GetName(nsACString& aName) {
  aName.AssignLiteral("ReportingHeader");
  return NS_OK;
}

void ReportingHeader::MaybeCreateCleanupTimer() {
  if (mCleanupTimer) {
    return;
  }

  if (mOrigins.Count() == 0) {
    return;
  }

  uint32_t timeout = StaticPrefs::dom_reporting_cleanup_timeout() * 1000;
  nsresult rv =
      NS_NewTimerWithCallback(getter_AddRefs(mCleanupTimer), this, timeout,
                              nsITimer::TYPE_ONE_SHOT_LOW_PRIORITY);
  Unused << NS_WARN_IF(NS_FAILED(rv));
}

void ReportingHeader::MaybeCancelCleanupTimer() {
  if (!mCleanupTimer) {
    return;
  }

  if (mOrigins.Count() != 0) {
    return;
  }

  mCleanupTimer->Cancel();
  mCleanupTimer = nullptr;
}

NS_INTERFACE_MAP_BEGIN(ReportingHeader)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIObserver)
  NS_INTERFACE_MAP_ENTRY(nsIObserver)
  NS_INTERFACE_MAP_ENTRY(nsITimerCallback)
  NS_INTERFACE_MAP_ENTRY(nsINamed)
NS_INTERFACE_MAP_END

NS_IMPL_ADDREF(ReportingHeader)
NS_IMPL_RELEASE(ReportingHeader)

}  // namespace mozilla::dom