File: url_checker_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (285 lines) | stat: -rw-r--r-- 9,223 bytes parent folder | download | duplicates (5)
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
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/safe_search_api/url_checker.h"

#include <stddef.h>

#include <algorithm>
#include <array>
#include <iterator>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/task_environment.h"
#include "components/safe_search_api/fake_url_checker_client.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"

using testing::_;

namespace safe_search_api {

namespace {

constexpr size_t kCacheSize = 2;

auto kURLs = std::to_array<const char*>({
    "http://www.randomsite1.com",
    "http://www.randomsite2.com",
    "http://www.randomsite3.com",
    "http://www.randomsite4.com",
    "http://www.randomsite5.com",
    "http://www.randomsite6.com",
    "http://www.randomsite7.com",
    "http://www.randomsite8.com",
    "http://www.randomsite9.com",
});

ClientClassification ToAPIClassification(Classification classification,
                                         bool uncertain) {
  if (uncertain) {
    return ClientClassification::kUnknown;
  }
  switch (classification) {
    case Classification::SAFE:
      return ClientClassification::kAllowed;
    case Classification::UNSAFE:
      return ClientClassification::kRestricted;
  }
}

auto Recorded(const std::map<CacheAccessStatus, int>& expected) {
  std::vector<base::Bucket> buckets_array;
  std::ranges::transform(
      expected, std::back_inserter(buckets_array),
      [](auto& entry) { return base::Bucket(entry.first, entry.second); });
  return base::BucketsInclude(buckets_array);
}

// A matcher which checks that the provided |ClassificationDetails| has the
// expected |reason| value.
MATCHER_P(ReasonEq, reason, "") {
  return arg.reason == reason;
}

}  // namespace

class SafeSearchURLCheckerTest : public testing::Test {
 public:
  SafeSearchURLCheckerTest() {
    std::unique_ptr<FakeURLCheckerClient> fake_client =
        std::make_unique<FakeURLCheckerClient>();
    fake_client_ = fake_client.get();
    checker_ = std::make_unique<URLChecker>(std::move(fake_client), kCacheSize);
  }

  MOCK_METHOD3(OnCheckDone,
               void(const GURL& url,
                    Classification classification,
                    ClassificationDetails details));

 protected:
  GURL GetNewURL() {
    CHECK(next_url_ < std::size(kURLs));
    return GURL(kURLs[next_url_++]);
  }

  // Returns true if the result was returned synchronously (cache hit).
  bool CheckURL(const GURL& url) {
    bool cached = checker_->CheckURL(
        url, base::BindOnce(&SafeSearchURLCheckerTest::OnCheckDone,
                            base::Unretained(this)));
    return cached;
  }

  bool SendResponse(const GURL& url,
                    Classification classification,
                    bool uncertain) {
    bool result = CheckURL(url);
    fake_client_->RunCallback(ToAPIClassification(classification, uncertain));
    return result;
  }

  std::vector<base::Bucket> CacheHitMetric() {
    return histogram_tester_.GetAllSamples("Net.SafeSearch.CacheHit");
  }

  size_t next_url_{0};
  raw_ptr<FakeURLCheckerClient, DanglingUntriaged> fake_client_;
  std::unique_ptr<URLChecker> checker_;
  base::test::SingleThreadTaskEnvironment task_environment_;

 private:
  base::HistogramTester histogram_tester_;
};

TEST_F(SafeSearchURLCheckerTest, Simple) {
  {
    GURL url(GetNewURL());
    EXPECT_CALL(
        *this,
        OnCheckDone(
            url, Classification::SAFE,
            ReasonEq(ClassificationDetails::Reason::kFreshServerResponse)));
    ASSERT_FALSE(SendResponse(url, Classification::SAFE, /*uncertain=*/false));
  }
  {
    GURL url(GetNewURL());
    EXPECT_CALL(
        *this,
        OnCheckDone(
            url, Classification::UNSAFE,
            ReasonEq(ClassificationDetails::Reason::kFreshServerResponse)));
    ASSERT_FALSE(
        SendResponse(url, Classification::UNSAFE, /*uncertain=*/false));
  }
  {
    GURL url(GetNewURL());
    EXPECT_CALL(
        *this, OnCheckDone(
                   url, Classification::SAFE,
                   ReasonEq(ClassificationDetails::Reason::kFailedUseDefault)));
    ASSERT_FALSE(SendResponse(url, Classification::SAFE, /*uncertain=*/true));
  }

  EXPECT_THAT(CacheHitMetric(), Recorded({{CacheAccessStatus::kHit, 0},
                                          {CacheAccessStatus::kNotFound, 3}}));
}

TEST_F(SafeSearchURLCheckerTest, Cache) {
  // One more URL than fit in the cache.
  ASSERT_EQ(2u, kCacheSize);
  GURL url1(GetNewURL());
  GURL url2(GetNewURL());
  GURL url3(GetNewURL());

  // Populate the cache.
  EXPECT_CALL(
      *this,
      OnCheckDone(
          url1, Classification::SAFE,
          ReasonEq(ClassificationDetails::Reason::kFreshServerResponse)));
  ASSERT_FALSE(SendResponse(url1, Classification::SAFE, /*uncertain=*/false));
  EXPECT_CALL(
      *this,
      OnCheckDone(
          url2, Classification::SAFE,
          ReasonEq(ClassificationDetails::Reason::kFreshServerResponse)));
  ASSERT_FALSE(SendResponse(url2, Classification::SAFE, /*uncertain=*/false));

  // Now we should get results synchronously, without a request to the api.
  EXPECT_CALL(
      *this,
      OnCheckDone(url2, Classification::SAFE,
                  ReasonEq(ClassificationDetails::Reason::kCachedResponse)));
  ASSERT_TRUE(CheckURL(url2));
  EXPECT_CALL(
      *this,
      OnCheckDone(url1, Classification::SAFE,
                  ReasonEq(ClassificationDetails::Reason::kCachedResponse)));
  ASSERT_TRUE(CheckURL(url1));

  // Now |url2| is the LRU and should be evicted on the next check.
  EXPECT_CALL(
      *this,
      OnCheckDone(
          url3, Classification::SAFE,
          ReasonEq(ClassificationDetails::Reason::kFreshServerResponse)));
  ASSERT_FALSE(SendResponse(url3, Classification::SAFE, /*uncertain=*/false));

  EXPECT_CALL(
      *this,
      OnCheckDone(
          url2, Classification::SAFE,
          ReasonEq(ClassificationDetails::Reason::kFreshServerResponse)));
  ASSERT_FALSE(SendResponse(url2, Classification::SAFE, /*uncertain=*/false));

  EXPECT_THAT(CacheHitMetric(), Recorded({{CacheAccessStatus::kHit, 2},
                                          {CacheAccessStatus::kNotFound, 4}}));
}

TEST_F(SafeSearchURLCheckerTest, CoalesceRequestsToSameURL) {
  GURL url(GetNewURL());
  // Start two checks for the same URL.
  ASSERT_FALSE(CheckURL(url));
  ASSERT_FALSE(CheckURL(url));
  // A single response should answer both of those checks
  EXPECT_CALL(
      *this, OnCheckDone(
                 url, Classification::SAFE,
                 ReasonEq(ClassificationDetails::Reason::kFreshServerResponse)))
      .Times(2);
  fake_client_->RunCallback(ToAPIClassification(Classification::SAFE, false));

  EXPECT_THAT(CacheHitMetric(), Recorded({{CacheAccessStatus::kHit, 0},
                                          {CacheAccessStatus::kNotFound, 2}}));
}

TEST_F(SafeSearchURLCheckerTest, CacheTimeout) {
  GURL url(GetNewURL());

  checker_->SetCacheTimeoutForTesting(base::Seconds(0));

  EXPECT_CALL(
      *this,
      OnCheckDone(
          url, Classification::SAFE,
          ReasonEq(ClassificationDetails::Reason::kFreshServerResponse)));
  ASSERT_FALSE(SendResponse(url, Classification::SAFE, /*uncertain=*/false));

  // Since the cache timeout is zero, the cache entry should be invalidated
  // immediately.
  EXPECT_CALL(
      *this,
      OnCheckDone(
          url, Classification::UNSAFE,
          ReasonEq(ClassificationDetails::Reason::kFreshServerResponse)));
  ASSERT_FALSE(SendResponse(url, Classification::UNSAFE, /*uncertain=*/false));

  EXPECT_THAT(CacheHitMetric(), Recorded({{CacheAccessStatus::kHit, 0},
                                          {CacheAccessStatus::kNotFound, 1},
                                          {CacheAccessStatus::kOutdated, 1}}));
}

TEST_F(SafeSearchURLCheckerTest, DoNotCacheUncertainClassifications) {
  GURL url(GetNewURL());

  ASSERT_FALSE(SendResponse(
      url, Classification::SAFE,
      /*uncertain=*/true));     // First check was asynchronous (uncached).
  EXPECT_FALSE(CheckURL(url));  // And so was the second one.

  EXPECT_THAT(CacheHitMetric(), Recorded({{CacheAccessStatus::kHit, 0},
                                          {CacheAccessStatus::kNotFound, 2}}));
}

TEST_F(SafeSearchURLCheckerTest, DestroyURLCheckerBeforeCallback) {
  GURL url(GetNewURL());
  EXPECT_CALL(*this, OnCheckDone(_, _, _)).Times(0);

  // Start a URL check.
  ASSERT_FALSE(CheckURL(url));
  fake_client_->RunCallbackAsync(
      ToAPIClassification(Classification::SAFE, /*uncertain=*/false));

  // Reset the URLChecker before the callback occurs.
  checker_.reset();

  // The callback should now be invalid.
  task_environment_.RunUntilIdle();

  EXPECT_THAT(CacheHitMetric(), Recorded({{CacheAccessStatus::kHit, 0},
                                          {CacheAccessStatus::kNotFound, 1}}));
}

}  // namespace safe_search_api