summaryrefslogtreecommitdiffstats
path: root/toolkit/components/telemetry/tests/gtest/TestOrigins.cpp
blob: b52391e8693cb0ff280327959ee939b2c2045d78 (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
/* vim:set ts=2 sw=2 sts=2 et: */
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

#include "core/TelemetryOrigin.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "mozilla/ContentBlockingLog.h"
#include "mozilla/Preferences.h"
#include "mozilla/Services.h"
#include "mozilla/Telemetry.h"
#include "mozilla/Unused.h"
#include "nsIObserverService.h"
#include "TelemetryFixture.h"
#include "TelemetryTestHelpers.h"

using namespace mozilla;
using namespace TelemetryTestHelpers;
using mozilla::Telemetry::OriginMetricID;
using ::testing::_;
using ::testing::AtLeast;
using ::testing::StrEq;

constexpr auto kTelemetryTest1Metric = "telemetry.test_test1"_ns;

constexpr auto kDoubleclickOrigin = "doubleclick.net"_ns;
constexpr auto kDoubleclickOriginHash =
    "uXNT1PzjAVau8b402OMAIGDejKbiXfQX5iXvPASfO/s="_ns;
constexpr auto kFacebookOrigin = "fb.com"_ns;
constexpr auto kUnknownOrigin1 =
    "this origin isn't known to Origin Telemetry"_ns;
constexpr auto kUnknownOrigin2 = "neither is this one"_ns;

// Properly prepare the prio prefs
// (Sourced from PrioEncoder.cpp from when it was being prototyped)
constexpr auto prioKeyA =
    "35AC1C7576C7C6EDD7FED6BCFC337B34D48CB4EE45C86BEEFB40BD8875707733"_ns;
constexpr auto prioKeyB =
    "26E6674E65425B823F1F1D5F96E3BB3EF9E406EC7FBA7DEF8B08A35DD135AF50"_ns;

// Test that we can properly record origin stuff using the C++ API.
TEST_F(TelemetryTestFixture, RecordOrigin) {
  AutoJSContextWithGlobal cx(mCleanGlobal);
  JSContext* aCx = cx.GetJSContext();

  Unused << mTelemetry->ClearOrigins();

  Telemetry::RecordOrigin(OriginMetricID::TelemetryTest_Test1,
                          mozilla::ContentBlockingLog::kDummyOriginHash);

  JS::RootedValue originSnapshot(aCx);
  GetOriginSnapshot(aCx, &originSnapshot);

  ASSERT_FALSE(originSnapshot.isNullOrUndefined())
  << "Origin snapshot must not be null/undefined.";

  JS::RootedValue origins(aCx);
  JS::RootedObject snapshotObj(aCx, &originSnapshot.toObject());
  ASSERT_TRUE(
      JS_GetProperty(aCx, snapshotObj, kTelemetryTest1Metric.get(), &origins))
  << "telemetry.test_test1 must be in the snapshot.";

  JS::RootedObject originsObj(aCx, &origins.toObject());
  JS::RootedValue count(aCx);
  ASSERT_TRUE(JS_GetProperty(
      aCx, originsObj, mozilla::ContentBlockingLog::kDummyOriginHash.get(),
      &count));
  ASSERT_TRUE(count.isInt32() && count.toInt32() == 1)
  << "Must have recorded the origin exactly once.";

  // Now test that the snapshot didn't clear things out.
  GetOriginSnapshot(aCx, &originSnapshot);
  ASSERT_FALSE(originSnapshot.isNullOrUndefined());
  JS::RootedObject unemptySnapshotObj(aCx, &originSnapshot.toObject());
  JS::Rooted<JS::IdVector> ids(aCx, JS::IdVector(aCx));
  ASSERT_TRUE(JS_Enumerate(aCx, unemptySnapshotObj, &ids));
  ASSERT_GE(ids.length(), (unsigned)0) << "Returned object must not be empty.";
}

TEST_F(TelemetryTestFixture, RecordOriginTwiceAndClear) {
  AutoJSContextWithGlobal cx(mCleanGlobal);
  JSContext* aCx = cx.GetJSContext();

  Unused << mTelemetry->ClearOrigins();

  Telemetry::RecordOrigin(OriginMetricID::TelemetryTest_Test1,
                          kDoubleclickOrigin);
  Telemetry::RecordOrigin(OriginMetricID::TelemetryTest_Test1,
                          kDoubleclickOrigin);

  JS::RootedValue originSnapshot(aCx);
  GetOriginSnapshot(aCx, &originSnapshot, true /* aClear */);

  ASSERT_FALSE(originSnapshot.isNullOrUndefined())
  << "Origin snapshot must not be null/undefined.";

  JS::RootedValue origins(aCx);
  JS::RootedObject snapshotObj(aCx, &originSnapshot.toObject());
  ASSERT_TRUE(
      JS_GetProperty(aCx, snapshotObj, kTelemetryTest1Metric.get(), &origins))
  << "telemetry.test_test1 must be in the snapshot.";

  JS::RootedObject originsObj(aCx, &origins.toObject());
  JS::RootedValue count(aCx);
  ASSERT_TRUE(
      JS_GetProperty(aCx, originsObj, kDoubleclickOrigin.get(), &count));
  ASSERT_TRUE(count.isInt32() && count.toInt32() == 2)
  << "Must have recorded the origin exactly twice.";

  // Now check that snapshotting with clear actually cleared it.
  GetOriginSnapshot(aCx, &originSnapshot);
  ASSERT_FALSE(originSnapshot.isNullOrUndefined());
  JS::RootedObject emptySnapshotObj(aCx, &originSnapshot.toObject());
  JS::Rooted<JS::IdVector> ids(aCx, JS::IdVector(aCx));
  ASSERT_TRUE(JS_Enumerate(aCx, emptySnapshotObj, &ids));
  ASSERT_EQ(ids.length(), (unsigned)0) << "Returned object must be empty.";
}

TEST_F(TelemetryTestFixture, RecordOriginTwiceMixed) {
  AutoJSContextWithGlobal cx(mCleanGlobal);
  JSContext* aCx = cx.GetJSContext();

  Unused << mTelemetry->ClearOrigins();

  Telemetry::RecordOrigin(OriginMetricID::TelemetryTest_Test1,
                          kDoubleclickOrigin);
  Telemetry::RecordOrigin(OriginMetricID::TelemetryTest_Test1,
                          kDoubleclickOriginHash);

  Preferences::SetCString("prio.publicKeyA", prioKeyA);
  Preferences::SetCString("prio.publicKeyB", prioKeyB);

  nsTArray<Tuple<nsCString, nsCString>> encodedStrings;
  GetEncodedOriginStrings(aCx, kTelemetryTest1Metric + "-%u"_ns,
                          encodedStrings);
  ASSERT_EQ(2 * TelemetryOrigin::SizeOfPrioDatasPerMetric(),
            encodedStrings.Length());

  JS::RootedValue originSnapshot(aCx);
  GetOriginSnapshot(aCx, &originSnapshot, true /* aClear */);

  ASSERT_FALSE(originSnapshot.isNullOrUndefined())
  << "Origin snapshot must not be null/undefined.";

  JS::RootedValue origins(aCx);
  JS::RootedObject snapshotObj(aCx, &originSnapshot.toObject());
  ASSERT_TRUE(
      JS_GetProperty(aCx, snapshotObj, kTelemetryTest1Metric.get(), &origins))
  << "telemetry.test_test1 must be in the snapshot.";

  JS::RootedObject originsObj(aCx, &origins.toObject());
  JS::RootedValue count(aCx);
  ASSERT_TRUE(
      JS_GetProperty(aCx, originsObj, kDoubleclickOrigin.get(), &count));
  ASSERT_TRUE(count.isInt32() && count.toInt32() == 2)
  << "Must have recorded the origin exactly twice.";
}

TEST_F(TelemetryTestFixture, RecordUnknownOrigin) {
  AutoJSContextWithGlobal cx(mCleanGlobal);
  JSContext* aCx = cx.GetJSContext();

  Unused << mTelemetry->ClearOrigins();

  Telemetry::RecordOrigin(OriginMetricID::TelemetryTest_Test1, kUnknownOrigin1);

  JS::RootedValue originSnapshot(aCx);
  GetOriginSnapshot(aCx, &originSnapshot);

  ASSERT_FALSE(originSnapshot.isNullOrUndefined())
  << "Origin snapshot must not be null/undefined.";

  JS::RootedValue origins(aCx);
  JS::RootedObject snapshotObj(aCx, &originSnapshot.toObject());
  ASSERT_TRUE(
      JS_GetProperty(aCx, snapshotObj, kTelemetryTest1Metric.get(), &origins))
  << "telemetry.test_test1 must be in the snapshot.";

  JS::RootedObject originsObj(aCx, &origins.toObject());
  JS::RootedValue count(aCx);
  ASSERT_TRUE(JS_GetProperty(aCx, originsObj, "__UNKNOWN__", &count));
  ASSERT_TRUE(count.isInt32() && count.toInt32() == 1)
  << "Must have recorded the unknown origin exactly once.";

  // Record a second, different unknown origin and ensure only one is stored.
  Telemetry::RecordOrigin(OriginMetricID::TelemetryTest_Test1, kUnknownOrigin2);

  GetOriginSnapshot(aCx, &originSnapshot);

  ASSERT_FALSE(originSnapshot.isNullOrUndefined())
  << "Origin snapshot must not be null/undefined.";

  JS::RootedObject snapshotObj2(aCx, &originSnapshot.toObject());
  ASSERT_TRUE(
      JS_GetProperty(aCx, snapshotObj2, kTelemetryTest1Metric.get(), &origins))
  << "telemetry.test_test1 must be in the snapshot.";

  JS::RootedObject originsObj2(aCx, &origins.toObject());
  JS::RootedValue count2(aCx);
  ASSERT_TRUE(JS_GetProperty(aCx, originsObj2, "__UNKNOWN__", &count2));
  ASSERT_TRUE(count2.isInt32() && count2.toInt32() == 1)
  << "Must have recorded the unknown origin exactly once.";
}

TEST_F(TelemetryTestFixture, EncodedSnapshot) {
  AutoJSContextWithGlobal cx(mCleanGlobal);
  JSContext* aCx = cx.GetJSContext();

  Unused << mTelemetry->ClearOrigins();

  Telemetry::RecordOrigin(OriginMetricID::TelemetryTest_Test1,
                          kDoubleclickOrigin);
  Telemetry::RecordOrigin(OriginMetricID::TelemetryTest_Test1, kUnknownOrigin1);

  Preferences::SetCString("prio.publicKeyA", prioKeyA);
  Preferences::SetCString("prio.publicKeyB", prioKeyB);

  nsTArray<Tuple<nsCString, nsCString>> firstStrings;
  GetEncodedOriginStrings(aCx, kTelemetryTest1Metric + "-%u"_ns, firstStrings);

  // Now snapshot a second time and ensure the encoded payloads change.
  nsTArray<Tuple<nsCString, nsCString>> secondStrings;
  GetEncodedOriginStrings(aCx, kTelemetryTest1Metric + "-%u"_ns, secondStrings);

  const auto sizeOfPrioDatasPerMetric =
      TelemetryOrigin::SizeOfPrioDatasPerMetric();
  ASSERT_EQ(sizeOfPrioDatasPerMetric, firstStrings.Length());
  ASSERT_EQ(sizeOfPrioDatasPerMetric, secondStrings.Length());

  for (size_t i = 0; i < sizeOfPrioDatasPerMetric; ++i) {
    auto& aStr = Get<0>(firstStrings[i]);
    auto& bStr = Get<1>(firstStrings[i]);
    auto& secondAStr = Get<0>(secondStrings[i]);
    auto& secondBStr = Get<1>(secondStrings[i]);

    ASSERT_TRUE(aStr != secondAStr)
    << "aStr (" << aStr.get() << ") must not equal secondAStr ("
    << secondAStr.get() << ")";
    ASSERT_TRUE(bStr != secondBStr)
    << "bStr (" << bStr.get() << ") must not equal secondBStr ("
    << secondBStr.get() << ")";
  }
}

class MockObserver final : public nsIObserver {
 public:
  NS_DECL_ISUPPORTS

  MOCK_METHOD1(Mobserve, void(const char* aTopic));
  NS_IMETHOD Observe(nsISupports* aSubject, const char* aTopic,
                     const char16_t* aData) override {
    Mobserve(aTopic);
    return NS_OK;
  };

  MockObserver() = default;

 private:
  ~MockObserver() = default;
};

NS_IMPL_ISUPPORTS(MockObserver, nsIObserver);

TEST_F(TelemetryTestFixture, OriginTelemetryNotifiesTopic) {
  Unused << mTelemetry->ClearOrigins();

  const char* kTopic = "origin-telemetry-storage-limit-reached";

  MockObserver* mo = new MockObserver();
  nsCOMPtr<nsIObserver> nsMo(mo);
  EXPECT_CALL(*mo, Mobserve(StrEq(kTopic))).Times(1);

  nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
  ASSERT_TRUE(os);
  os->AddObserver(nsMo, kTopic, false);

  const size_t size = ceil(10.0 / TelemetryOrigin::SizeOfPrioDatasPerMetric());
  for (size_t i = 0; i < size; ++i) {
    if (i < size - 1) {
      // Let's ensure we only notify the once.
      Telemetry::RecordOrigin(OriginMetricID::TelemetryTest_Test1,
                              kFacebookOrigin);
    }
    Telemetry::RecordOrigin(OriginMetricID::TelemetryTest_Test1,
                            kDoubleclickOrigin);
  }

  os->RemoveObserver(nsMo, kTopic);
}