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

content / browser / aggregation_service / aggregation_service_key_fetcher_unittest.cc [blame]

// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/aggregation_service/aggregation_service_key_fetcher.h"

#include <memory>
#include <optional>
#include <string_view>
#include <utility>
#include <vector>

#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "base/time/clock.h"
#include "base/time/time.h"
#include "content/browser/aggregation_service/aggregation_service_storage.h"
#include "content/browser/aggregation_service/aggregation_service_test_utils.h"
#include "content/browser/aggregation_service/public_key.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"

namespace content {

namespace {

using ::testing::_;
using ::testing::DoAll;

using FetchCallback = AggregationServiceKeyFetcher::FetchCallback;
using NetworkFetchCallback =
    AggregationServiceKeyFetcher::NetworkFetcher::NetworkFetchCallback;

constexpr std::string_view kExampleUrl = "https://a.com/keys";

// NetworkFetcher that manages the public keys in memory.
class MockNetworkFetcher : public AggregationServiceKeyFetcher::NetworkFetcher {
 public:
  MOCK_METHOD(void,
              FetchPublicKeys,
              (const GURL& url, NetworkFetchCallback callback),
              (override));
};

}  // namespace

class AggregationServiceKeyFetcherTest : public testing::Test {
 public:
  AggregationServiceKeyFetcherTest()
      : task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME),
        storage_context_(task_environment_.GetMockClock()) {
    auto network_fetcher = std::make_unique<MockNetworkFetcher>();
    network_fetcher_ = network_fetcher.get();
    fetcher_ = std::make_unique<AggregationServiceKeyFetcher>(
        &storage_context_, std::move(network_fetcher));
  }

  void SetPublicKeysInStorage(const GURL& url, PublicKeyset keyset) {
    storage_context_.GetStorage()
        .AsyncCall(&AggregationServiceStorage::SetPublicKeys)
        .WithArgs(url, std::move(keyset));
  }

  void ExpectPublicKeysInStorage(const GURL& url,
                                 const std::vector<PublicKey>& expected_keys) {
    base::RunLoop run_loop;
    storage_context_.GetStorage()
        .AsyncCall(&AggregationServiceStorage::GetPublicKeys)
        .WithArgs(url)
        .Then(
            base::BindLambdaForTesting([&](std::vector<PublicKey> actual_keys) {
              EXPECT_TRUE(aggregation_service::PublicKeysEqual(expected_keys,
                                                               actual_keys));
              run_loop.Quit();
            }));
    run_loop.Run();
  }

  void ResetKeyFetcher() {
    network_fetcher_ = nullptr;
    fetcher_.reset();
  }

 protected:
  const base::Clock& clock() const { return *task_environment_.GetMockClock(); }

  base::test::TaskEnvironment task_environment_;
  TestAggregationServiceStorageContext storage_context_;
  std::unique_ptr<AggregationServiceKeyFetcher> fetcher_;
  raw_ptr<MockNetworkFetcher> network_fetcher_;
  base::MockCallback<FetchCallback> callback_;
};

TEST_F(AggregationServiceKeyFetcherTest, GetPublicKeysFromStorage_Succeed) {
  GURL url(kExampleUrl);
  PublicKey expected_key = aggregation_service::TestHpkeKey().GetPublicKey();

  SetPublicKeysInStorage(
      url, PublicKeyset(/*keys=*/{expected_key}, /*fetch_time=*/clock().Now(),
                        /*expiry_time=*/base::Time::Max()));

  EXPECT_CALL(*network_fetcher_, FetchPublicKeys(_, _)).Times(0);

  base::RunLoop run_loop;
  EXPECT_CALL(callback_,
              Run(std::optional<PublicKey>(std::move(expected_key)),
                  AggregationServiceKeyFetcher::PublicKeyFetchStatus::kOk))
      .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure()));
  fetcher_->GetPublicKey(url, callback_.Get());
  run_loop.Run();
}

TEST_F(AggregationServiceKeyFetcherTest, GetPublicKeysWithNoKeysForUrl_Failed) {
  GURL url(kExampleUrl);

  base::RunLoop run_loop;
  EXPECT_CALL(*network_fetcher_, FetchPublicKeys(url, _))
      .WillOnce(
          testing::DoAll(base::test::RunOnceClosure(run_loop.QuitClosure()),
                         base::test::RunOnceCallback<1>(std::nullopt)));
  EXPECT_CALL(callback_, Run(std::optional<PublicKey>(std::nullopt),
                             AggregationServiceKeyFetcher::
                                 PublicKeyFetchStatus::kPublicKeyFetchFailed));

  fetcher_->GetPublicKey(url, callback_.Get());
  run_loop.Run();
}

TEST_F(AggregationServiceKeyFetcherTest, FetchPublicKeysFromNetwork_Succeed) {
  GURL url(kExampleUrl);
  PublicKey expected_key = aggregation_service::TestHpkeKey().GetPublicKey();

  base::RunLoop run_loop;
  EXPECT_CALL(*network_fetcher_, FetchPublicKeys(url, _))
      .WillOnce(testing::DoAll(
          base::test::RunOnceClosure(run_loop.QuitClosure()),
          base::test::RunOnceCallback<1>(PublicKeyset(
              /*keys=*/{expected_key}, /*fetch_time=*/clock().Now(),
              /*expiry_time=*/base::Time::Max()))));
  EXPECT_CALL(callback_,
              Run(std::optional<PublicKey>(expected_key),
                  AggregationServiceKeyFetcher::PublicKeyFetchStatus::kOk));

  fetcher_->GetPublicKey(url, callback_.Get());
  run_loop.Run();

  // Verify that the fetched public keys are stored to storage.
  ExpectPublicKeysInStorage(url, /*expected_keys=*/{expected_key});
}

TEST_F(AggregationServiceKeyFetcherTest,
       FetchPublicKeysFromNetworkNoStore_NotStored) {
  GURL url(kExampleUrl);
  PublicKey expected_key = aggregation_service::TestHpkeKey().GetPublicKey();

  base::RunLoop run_loop;
  EXPECT_CALL(*network_fetcher_, FetchPublicKeys(url, _))
      .WillOnce(
          testing::DoAll(base::test::RunOnceClosure(run_loop.QuitClosure()),
                         base::test::RunOnceCallback<1>(
                             PublicKeyset(/*keys=*/{expected_key},
                                          /*fetch_time=*/clock().Now(),
                                          /*expiry_time=*/base::Time()))));
  EXPECT_CALL(callback_,
              Run(std::optional<PublicKey>(std::move(expected_key)),
                  AggregationServiceKeyFetcher::PublicKeyFetchStatus::kOk));

  fetcher_->GetPublicKey(url, callback_.Get());
  run_loop.Run();

  // Verify that the fetched public keys are not stored to storage.
  ExpectPublicKeysInStorage(url, /*expected_keys=*/{});
}

TEST_F(AggregationServiceKeyFetcherTest,
       FetchPublicKeysFromNetworkError_StorageCleared) {
  GURL url(kExampleUrl);
  base::Time now = clock().Now();

  PublicKey key = aggregation_service::TestHpkeKey().GetPublicKey();
  SetPublicKeysInStorage(url,
                         PublicKeyset(/*keys=*/{key}, /*fetch_time=*/now,
                                      /*expiry_time=*/now + base::Days(1)));

  task_environment_.FastForwardBy(base::Days(2));

  base::RunLoop run_loop;
  EXPECT_CALL(*network_fetcher_, FetchPublicKeys(url, _))
      .WillOnce(
          testing::DoAll(base::test::RunOnceClosure(run_loop.QuitClosure()),
                         base::test::RunOnceCallback<1>(std::nullopt)));
  EXPECT_CALL(callback_, Run(std::optional<PublicKey>(std::nullopt),
                             AggregationServiceKeyFetcher::
                                 PublicKeyFetchStatus::kPublicKeyFetchFailed));

  fetcher_->GetPublicKey(url, callback_.Get());
  run_loop.Run();

  // Verify that the public keys in storage are cleared.
  ExpectPublicKeysInStorage(url, /*expected_keys=*/{});
}

TEST_F(AggregationServiceKeyFetcherTest,
       SimultaneousFetches_NoDuplicateNetworkRequest) {
  GURL url(kExampleUrl);
  PublicKey expected_key = aggregation_service::TestHpkeKey().GetPublicKey();

  base::RunLoop run_loop;
  EXPECT_CALL(*network_fetcher_, FetchPublicKeys(url, _))
      .WillOnce(
          testing::DoAll(base::test::RunOnceClosure(run_loop.QuitClosure()),
                         base::test::RunOnceCallback<1>(
                             PublicKeyset(/*keys=*/{expected_key},
                                          /*fetch_time=*/clock().Now(),
                                          /*expiry_time=*/base::Time::Max()))));
  EXPECT_CALL(callback_,
              Run(std::optional<PublicKey>(std::move(expected_key)),
                  AggregationServiceKeyFetcher::PublicKeyFetchStatus::kOk))
      .Times(10);

  for (int i = 0; i < 10; ++i) {
    fetcher_->GetPublicKey(url, callback_.Get());
  }
  run_loop.Run();
}

TEST_F(AggregationServiceKeyFetcherTest,
       SimultaneousFetchesInvalidKeysFromNetwork_NoDuplicateNetworkRequest) {
  GURL url(kExampleUrl);

  base::RunLoop run_loop;
  EXPECT_CALL(*network_fetcher_, FetchPublicKeys(url, _))
      .WillOnce(
          testing::DoAll(base::test::RunOnceClosure(run_loop.QuitClosure()),
                         base::test::RunOnceCallback<1>(std::nullopt)));
  EXPECT_CALL(callback_, Run(std::optional<PublicKey>(std::nullopt),
                             AggregationServiceKeyFetcher::
                                 PublicKeyFetchStatus::kPublicKeyFetchFailed))
      .Times(10);

  for (int i = 0; i < 10; ++i) {
    fetcher_->GetPublicKey(url, callback_.Get());
  }
  run_loop.Run();
}

TEST_F(AggregationServiceKeyFetcherTest,
       KeyFetcherDeleted_PendingRequestsNotRun) {
  GURL url(kExampleUrl);

  base::RunLoop run_loop;
  EXPECT_CALL(*network_fetcher_, FetchPublicKeys(url, _))
      .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure()));
  EXPECT_CALL(callback_, Run(_, _)).Times(0);

  fetcher_->GetPublicKey(url, callback_.Get());
  run_loop.Run();

  ResetKeyFetcher();
}

}  // namespace content