File: ip_protection_config_http_unittest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; 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 (261 lines) | stat: -rw-r--r-- 10,765 bytes parent folder | download | duplicates (3)
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
// Copyright 2023 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/ip_protection/common/ip_protection_config_http.h"

#include <map>
#include <memory>
#include <string>
#include <utility>

#include "base/memory/scoped_refptr.h"
#include "base/strings/strcat.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/test/test_future.h"
#include "net/base/features.h"
#include "net/base/net_errors.h"
#include "net/http/http_status_code.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/url_loader_completion_status.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace ip_protection {
namespace {

const char kProtobufContentType[] = "application/x-protobuf";

class IpProtectionConfigHttpTest : public testing::Test {
 protected:
  void SetUp() override {
    http_fetcher_ = std::make_unique<IpProtectionConfigHttp>(
        base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
            &test_url_loader_factory_));
    token_server_get_initial_data_url_ = GURL(base::StrCat(
        {net::features::kIpPrivacyTokenServer.Get(),
         net::features::kIpPrivacyTokenServerGetInitialDataPath.Get()}));
    ASSERT_TRUE(token_server_get_initial_data_url_.is_valid());
    token_server_get_tokens_url_ = GURL(base::StrCat(
        {net::features::kIpPrivacyTokenServer.Get(),
         net::features::kIpPrivacyTokenServerGetTokensPath.Get()}));
    ASSERT_TRUE(token_server_get_tokens_url_.is_valid());
    token_server_get_proxy_config_url_ = GURL(base::StrCat(
        {net::features::kIpPrivacyTokenServer.Get(),
         net::features::kIpPrivacyTokenServerGetProxyConfigPath.Get()}));
    ASSERT_TRUE(token_server_get_proxy_config_url_.is_valid());
  }

  base::test::TaskEnvironment task_environment_;
  network::TestURLLoaderFactory test_url_loader_factory_;
  std::unique_ptr<IpProtectionConfigHttp> http_fetcher_;
  GURL token_server_get_initial_data_url_;
  GURL token_server_get_tokens_url_;
  GURL token_server_get_proxy_config_url_;
};

TEST_F(IpProtectionConfigHttpTest, DoRequestSendsCorrectRequestInitialData) {
  auto request_type = quiche::BlindSignMessageRequestType::kGetInitialData;
  std::string authorization_header = "token";
  std::string body = "body";

  // Set up the response to return from the mock.
  test_url_loader_factory_.SetInterceptor(
      base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
        ASSERT_TRUE(request.url.is_valid());
        ASSERT_EQ(request.url, token_server_get_initial_data_url_);

        ASSERT_THAT(
            request.headers.GetHeader(net::HttpRequestHeaders::kAuthorization),
            testing::Optional(base::StrCat({"Bearer ", authorization_header})));
        EXPECT_FALSE(
            request.headers.HasHeader("Ip-Protection-Debug-Experiment-Arm"));
        ASSERT_THAT(request.headers.GetHeader(net::HttpRequestHeaders::kAccept),
                    testing::Optional(std::string(kProtobufContentType)));

        std::string response_str = "Response body";
        auto head = network::mojom::URLResponseHead::New();
        test_url_loader_factory_.AddResponse(
            request.url, std::move(head), response_str,
            network::URLLoaderCompletionStatus(net::OK));
      }));

  base::test::TestFuture<absl::StatusOr<quiche::BlindSignMessageResponse>>
      result_future;
  // Note: We use a lambda expression and `TestFuture::SetValue()` instead of
  // `TestFuture::GetCallback()` to avoid having to convert the
  // `base::OnceCallback` to a `quiche::SignedTokenCallback` (an
  // `absl::AnyInvocable` behind the scenes).
  auto callback =
      [&result_future](
          absl::StatusOr<quiche::BlindSignMessageResponse> response) {
        result_future.SetValue(std::move(response));
      };

  http_fetcher_->DoRequest(request_type, authorization_header, body,
                           std::move(callback));

  absl::StatusOr<quiche::BlindSignMessageResponse> result = result_future.Get();

  ASSERT_TRUE(result.ok());
  EXPECT_EQ("Response body", result->body());
}

TEST_F(IpProtectionConfigHttpTest,
       DoRequestSendsCorrectRequestAuthAndSignAndExperimentArm) {
  std::map<std::string, std::string> parameters;
  parameters["IpPrivacyDebugExperimentArm"] = "42";
  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitAndEnableFeatureWithParameters(
      net::features::kEnableIpProtectionProxy, std::move(parameters));

  auto request_type = quiche::BlindSignMessageRequestType::kAuthAndSign;
  std::string authorization_header = "token";
  std::string body = "body";

  // Set up the response to return from the mock.
  test_url_loader_factory_.SetInterceptor(
      base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
        ASSERT_TRUE(request.url.is_valid());
        ASSERT_EQ(request.url, token_server_get_tokens_url_);

        ASSERT_THAT(
            request.headers.GetHeader(net::HttpRequestHeaders::kAuthorization),
            testing::Optional(base::StrCat({"Bearer ", authorization_header})));
        ASSERT_THAT(
            request.headers.GetHeader("Ip-Protection-Debug-Experiment-Arm"),
            testing::Optional(std::string("42")));
        ASSERT_THAT(request.headers.GetHeader(net::HttpRequestHeaders::kAccept),
                    testing::Optional(std::string(kProtobufContentType)));

        std::string response_str = "Response body";
        auto head = network::mojom::URLResponseHead::New();
        test_url_loader_factory_.AddResponse(
            request.url, std::move(head), response_str,
            network::URLLoaderCompletionStatus(net::OK));
      }));

  base::test::TestFuture<absl::StatusOr<quiche::BlindSignMessageResponse>>
      result_future;
  // Note: We use a lambda expression and `TestFuture::SetValue()` instead of
  // `TestFuture::GetCallback()` to avoid having to convert the
  // `base::OnceCallback` to a `quiche::SignedTokenCallback` (an
  // `absl::AnyInvocable` behind the scenes).
  auto callback =
      [&result_future](
          absl::StatusOr<quiche::BlindSignMessageResponse> response) {
        result_future.SetValue(std::move(response));
      };

  http_fetcher_->DoRequest(request_type, authorization_header, body,
                           std::move(callback));

  absl::StatusOr<quiche::BlindSignMessageResponse> result = result_future.Get();

  ASSERT_TRUE(result.ok());
  EXPECT_EQ("Response body", result->body());
}

TEST_F(IpProtectionConfigHttpTest,
       DoRequestFailsToConnectReturnsFailureStatus) {
  auto request_type = quiche::BlindSignMessageRequestType::kAuthAndSign;
  std::string authorization_header = "token";
  std::string body = "body";

  // Mock no response from Authentication Server (such as a network error).
  std::string response_body;
  auto head = network::mojom::URLResponseHead::New();
  test_url_loader_factory_.AddResponse(
      token_server_get_tokens_url_, std::move(head), response_body,
      network::URLLoaderCompletionStatus(net::ERR_FAILED));

  base::test::TestFuture<absl::StatusOr<quiche::BlindSignMessageResponse>>
      result_future;
  auto callback =
      [&result_future](
          absl::StatusOr<quiche::BlindSignMessageResponse> response) {
        result_future.SetValue(std::move(response));
      };

  http_fetcher_->DoRequest(request_type, authorization_header, body,
                           std::move(callback));

  absl::StatusOr<quiche::BlindSignMessageResponse> result = result_future.Get();

  EXPECT_EQ("Failed Request to Authentication Server",
            result.status().message());
  EXPECT_EQ(absl::StatusCode::kInternal, result.status().code());
}

TEST_F(IpProtectionConfigHttpTest,
       DoRequestInvalidFinchParametersFailsGracefully) {
  std::map<std::string, std::string> parameters;
  parameters["IpPrivacyTokenServer"] = "<(^_^)>";
  parameters["IpPrivacyTokenServerGetInitialDataPath"] = "(>_<)";
  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitAndEnableFeatureWithParameters(
      net::features::kEnableIpProtectionProxy, std::move(parameters));

  // Create a new IpProtectionConfigHttp for this test so that the new
  // FeatureParams get used.
  std::unique_ptr<IpProtectionConfigHttp> http_fetcher =
      std::make_unique<IpProtectionConfigHttp>(
          test_url_loader_factory_.GetSafeWeakWrapper());

  auto request_type = quiche::BlindSignMessageRequestType::kGetInitialData;
  std::string authorization_header = "token";
  std::string body = "body";

  base::test::TestFuture<absl::StatusOr<quiche::BlindSignMessageResponse>>
      result_future;
  auto callback =
      [&result_future](
          absl::StatusOr<quiche::BlindSignMessageResponse> response) {
        result_future.SetValue(std::move(response));
      };

  http_fetcher->DoRequest(request_type, authorization_header, body,
                          std::move(callback));

  absl::StatusOr<quiche::BlindSignMessageResponse> result = result_future.Get();

  EXPECT_EQ("Invalid IP Protection Token URL", result.status().message());
  EXPECT_EQ(absl::StatusCode::kInternal, result.status().code());
}

TEST_F(IpProtectionConfigHttpTest, DoRequestHttpFailureStatus) {
  auto request_type = quiche::BlindSignMessageRequestType::kAuthAndSign;
  std::string authorization_header = "token";
  std::string body = "body";

  // Mock a non-200 HTTP response from Authentication Server.
  std::string response_body;
  auto head = network::mojom::URLResponseHead::New();
  test_url_loader_factory_.AddResponse(token_server_get_tokens_url_.spec(),
                                       response_body, net::HTTP_BAD_REQUEST);

  base::test::TestFuture<absl::StatusOr<quiche::BlindSignMessageResponse>>
      result_future;
  auto callback =
      [&result_future](
          absl::StatusOr<quiche::BlindSignMessageResponse> response) {
        result_future.SetValue(std::move(response));
      };

  http_fetcher_->DoRequest(request_type, authorization_header, body,
                           std::move(callback));

  absl::StatusOr<quiche::BlindSignMessageResponse> result = result_future.Get();

  EXPECT_TRUE(result.ok());
  EXPECT_EQ(quiche::BlindSignMessageResponse::HttpCodeToStatusCode(
                net::HTTP_BAD_REQUEST),
            result.value().status_code());
}

}  // namespace
}  // namespace ip_protection