forked from googleapis/google-cloud-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoauth2_compute_engine_credentials_test.cc
More file actions
634 lines (572 loc) · 26.2 KB
/
oauth2_compute_engine_credentials_test.cc
File metadata and controls
634 lines (572 loc) · 26.2 KB
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
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/internal/oauth2_compute_engine_credentials.h"
#include "google/cloud/internal/backoff_policy.h"
#include "google/cloud/internal/compute_engine_util.h"
#include "google/cloud/internal/make_status.h"
#include "google/cloud/internal/retry_policy_impl.h"
#include "google/cloud/testing_util/mock_http_payload.h"
#include "google/cloud/testing_util/mock_rest_client.h"
#include "google/cloud/testing_util/mock_rest_response.h"
#include "google/cloud/testing_util/status_matchers.h"
#include "google/cloud/universe_domain_options.h"
#include "absl/strings/str_cat.h"
#include <gmock/gmock.h>
#include <chrono>
namespace google {
namespace cloud {
namespace oauth2_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {
using ::google::cloud::rest_internal::HttpStatusCode;
using ::google::cloud::rest_internal::RestContext;
using ::google::cloud::rest_internal::RestRequest;
using ::google::cloud::rest_internal::RestResponse;
using ::google::cloud::testing_util::IsOk;
using ::google::cloud::testing_util::IsOkAndHolds;
using ::google::cloud::testing_util::MakeMockHttpPayloadSuccess;
using ::google::cloud::testing_util::MockRestClient;
using ::google::cloud::testing_util::MockRestResponse;
using ::google::cloud::testing_util::StatusIs;
using ::testing::_;
using ::testing::AllOf;
using ::testing::ByMove;
using ::testing::Contains;
using ::testing::HasSubstr;
using ::testing::Not;
using ::testing::Pair;
using ::testing::Property;
using ::testing::Return;
using ::testing::UnorderedElementsAre;
using ::testing::UnorderedElementsAreArray;
using ::testing::VariantWith;
using MockHttpClientFactory =
::testing::MockFunction<std::unique_ptr<rest_internal::RestClient>(
Options const&)>;
auto expect_service_config = [](std::string const& account) {
auto const expected_path = absl::StrCat(
internal::GceMetadataScheme(), "://", internal::GceMetadataHostname(),
"/computeMetadata/v1/instance/service-accounts/", account, "/");
return AllOf(
Property(&RestRequest::path, expected_path),
Property(&RestRequest::headers,
Contains(Pair("metadata-flavor", Contains("Google")))),
Property(&RestRequest::parameters, Contains(Pair("recursive", "true"))));
};
auto expect_token = [](std::string const& account) {
auto const expected_path = absl::StrCat(
internal::GceMetadataScheme(), "://", internal::GceMetadataHostname(),
"/computeMetadata/v1/instance/service-accounts/", account, "/token");
return AllOf(Property(&RestRequest::path, expected_path),
Property(&RestRequest::headers,
Contains(Pair("metadata-flavor", Contains("Google")))),
Property(&RestRequest::parameters,
Not(Contains(Pair("recursive", "true")))));
};
/// @test Verify that we can create and refresh ComputeEngineCredentials.
TEST(ComputeEngineCredentialsTest,
RefreshingSendsCorrectRequestBodyAndParsesResponse) {
auto const alias = std::string{"default"};
auto const email = std::string{"foo@bar.baz"};
auto const svc_acct_info_resp = std::string{R"""({
"email": ")""" + email + R"""(",
"scopes": ["scope1","scope2"]
})"""};
auto const token_info_resp = std::string{R"""({
"access_token": "mysupersecrettoken",
"expires_in": 3600,
"token_type": "tokentype"
})"""};
auto mock_metadata_client = [&]() {
auto response = std::make_unique<MockRestResponse>();
EXPECT_CALL(*response, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kOk));
EXPECT_CALL(std::move(*response), ExtractPayload)
.WillOnce(
Return(ByMove(MakeMockHttpPayloadSuccess(svc_acct_info_resp))));
auto mock = std::make_unique<MockRestClient>();
EXPECT_CALL(*mock, Get(_, expect_service_config(alias)))
.WillOnce(
Return(ByMove(std::unique_ptr<RestResponse>(std::move(response)))));
return mock;
}();
auto mock_token_client = [&]() {
auto response = std::make_unique<MockRestResponse>();
EXPECT_CALL(*response, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kOk));
EXPECT_CALL(std::move(*response), ExtractPayload)
.WillOnce(Return(ByMove(MakeMockHttpPayloadSuccess(token_info_resp))));
auto mock = std::make_unique<MockRestClient>();
EXPECT_CALL(*mock, Get(_, expect_token(email)))
.WillOnce(
Return(ByMove(std::unique_ptr<RestResponse>(std::move(response)))));
return mock;
}();
MockHttpClientFactory mock_http_client_factory;
EXPECT_CALL(mock_http_client_factory, Call)
.WillOnce(Return(ByMove(std::move(mock_metadata_client))))
.WillOnce(Return(ByMove(std::move(mock_token_client))));
ComputeEngineCredentials credentials(
alias, Options{}, mock_http_client_factory.AsStdFunction());
// Calls Refresh to obtain the access token for our authorization header.
auto const now = std::chrono::system_clock::now();
auto const expected_token =
AccessToken{"mysupersecrettoken", now + std::chrono::seconds(3600)};
EXPECT_EQ(expected_token, credentials.GetToken(now).value());
// Make sure we obtain the scopes and email from the metadata server.
EXPECT_EQ(email, credentials.service_account_email());
EXPECT_THAT(credentials.scopes(), UnorderedElementsAre("scope1", "scope2"));
}
/// @test Parsing a refresh response with missing fields results in failure.
TEST(ComputeEngineCredentialsTest,
ParseComputeEngineRefreshResponseMissingFields) {
std::string token_info_resp = R"""({})""";
// Does not have access_token.
std::string token_info_resp2 = R"""({
"expires_in": 3600,
"token_type": "tokentype"
)""";
auto mock_response1 = std::make_unique<MockRestResponse>();
EXPECT_CALL(*mock_response1, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kBadRequest));
EXPECT_CALL(std::move(*mock_response1), ExtractPayload)
.WillOnce(Return(ByMove(MakeMockHttpPayloadSuccess(token_info_resp))));
auto mock_response2 = std::make_unique<MockRestResponse>();
EXPECT_CALL(*mock_response2, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kBadRequest));
EXPECT_CALL(std::move(*mock_response2), ExtractPayload)
.WillOnce(Return(ByMove(MakeMockHttpPayloadSuccess(token_info_resp2))));
auto status = ParseComputeEngineRefreshResponse(
*mock_response1, std::chrono::system_clock::from_time_t(1000));
EXPECT_THAT(status,
StatusIs(StatusCode::kInvalidArgument,
HasSubstr("Could not find all required fields")));
status = ParseComputeEngineRefreshResponse(
*mock_response2, std::chrono::system_clock::from_time_t(1000));
EXPECT_THAT(status,
StatusIs(StatusCode::kInvalidArgument,
HasSubstr("Could not find all required fields")));
}
/// @test Parsing a refresh response yields an access token.
TEST(ComputeEngineCredentialsTest, ParseComputeEngineRefreshResponse) {
auto const token_info_resp = std::string{R"""({
"access_token": "mysupersecrettoken",
"expires_in": 3600,
"token_type": "tokentype"})"""};
auto mock_http_payload = MakeMockHttpPayloadSuccess(token_info_resp);
auto mock_response = std::make_unique<MockRestResponse>();
EXPECT_CALL(*mock_response, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kBadRequest));
EXPECT_CALL(std::move(*mock_response), ExtractPayload)
.WillOnce(Return(ByMove(std::move(mock_http_payload))));
auto const now = std::chrono::system_clock::now();
auto const expires_in = std::chrono::seconds(3600);
auto status = ParseComputeEngineRefreshResponse(*mock_response, now);
EXPECT_STATUS_OK(status);
auto token = *status;
EXPECT_EQ(token.expiration, now + expires_in);
EXPECT_EQ(token.token, "mysupersecrettoken");
}
/// @test Parsing a metadata server response yields a ServiceAccountMetadata.
TEST(ComputeEngineCredentialsTest, ParseMetadataServerResponse) {
struct TestCase {
std::string payload;
ServiceAccountMetadata expected;
} cases[] = {
{R"js({"email": "foo@bar.baz", "scopes": ["scope1", "scope2"], "universe_domain": "test-ud.net"})js",
ServiceAccountMetadata{
{"scope1", "scope2"}, "foo@bar.baz", "test-ud.net"}},
{R"js({"email": "foo@bar.baz", "scopes": "scope1\nscope2\n"})js",
ServiceAccountMetadata{
{"scope1", "scope2"}, "foo@bar.baz", "googleapis.com"}},
// Ignore invalid formats
{R"js({"email": ["1", "2"], "scopes": ["scope1", "scope2"], "universe_domain": true})js",
ServiceAccountMetadata{{"scope1", "scope2"}, "", {}}},
{R"js({"email": "foo@bar", "scopes": {"foo": "bar"}, "universe_domain": 42})js",
ServiceAccountMetadata{{}, "foo@bar", {}}},
// Ignore missing fields
{R"js({"scopes": ["scope1", "scope2"]})js",
ServiceAccountMetadata{{"scope1", "scope2"}, "", "googleapis.com"}},
{R"js({"email": "foo@bar.baz"})js",
ServiceAccountMetadata{{}, "foo@bar.baz", "googleapis.com"}},
{R"js({})js", ServiceAccountMetadata{{}, "", "googleapis.com"}},
};
for (auto const& test : cases) {
SCOPED_TRACE("testing with " + test.payload);
auto mock_response = std::make_unique<MockRestResponse>();
EXPECT_CALL(*mock_response, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kOk));
EXPECT_CALL(std::move(*mock_response), ExtractPayload)
.WillOnce(Return(ByMove(MakeMockHttpPayloadSuccess(test.payload))));
auto status = ParseMetadataServerResponse(*mock_response);
ASSERT_STATUS_OK(status);
auto metadata = *status;
EXPECT_EQ(metadata.email, test.expected.email);
EXPECT_THAT(metadata.scopes,
UnorderedElementsAreArray(test.expected.scopes));
EXPECT_EQ(metadata.universe_domain, test.expected.universe_domain);
}
}
/// @test Mock a failed refresh response during RetrieveServiceAccountInfo.
TEST(ComputeEngineCredentialsTest, FailedRetrieveServiceAccountInfo) {
auto const alias = std::string{"default"};
auto const email = std::string{"foo@bar.baz"};
auto const token_info_resp = std::string{R"""({
"access_token": "mysupersecrettoken",
"expires_in": 3600,
"token_type": "tokentype"})"""};
auto mock_metadata_client_get_error = [&]() {
auto mock = std::make_unique<MockRestClient>();
EXPECT_CALL(*mock, Get(_, expect_service_config(alias))).WillOnce([]() {
return Status{StatusCode::kAborted, "Fake Curl error"};
});
return mock;
}();
auto mock_metadata_client_response_error = [&]() {
auto mock = std::make_unique<MockRestClient>();
EXPECT_CALL(*mock, Get(_, expect_service_config(alias))).WillOnce([] {
auto response = std::make_unique<MockRestResponse>();
EXPECT_CALL(*response, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kBadRequest));
return std::unique_ptr<RestResponse>(std::move(response));
});
return mock;
}();
MockHttpClientFactory mock_http_client_factory;
EXPECT_CALL(mock_http_client_factory, Call)
.WillOnce(Return(ByMove(std::move(mock_metadata_client_get_error))))
.WillOnce(Return(ByMove(std::move(mock_metadata_client_response_error))));
ComputeEngineCredentials credentials(
alias, Options{}, mock_http_client_factory.AsStdFunction());
// Response 1
auto actual = credentials.AccountEmail();
EXPECT_EQ(actual, alias);
// Response 2
actual = credentials.AccountEmail();
EXPECT_EQ(actual, alias);
}
/// @test Mock a failed refresh response.
TEST(ComputeEngineCredentialsTest, FailedRefresh) {
auto const alias = std::string{"default"};
auto const email = std::string{"foo@bar.baz"};
auto const svc_acct_info_resp = std::string{R"""({
"email": "foo@bar.baz",
"scopes": ["scope1","scope2"]
})"""};
// Note this response is missing a field.
auto const token_info_resp = std::string{R"""({
"expires_in": 3600,
"token_type": "tokentype"
})"""};
// Fail the first call to RetrieveServiceAccountInfo immediately.
auto metadata_aborted = [&]() {
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expect_service_config(alias)))
.WillOnce([&](RestContext&, RestRequest const&) {
return Status{StatusCode::kAborted, "Fake Curl error / info", {}};
});
return client;
}();
// Then fail the token request immediately.
auto token_aborted = [&]() {
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expect_token(alias)))
.WillOnce([&](RestContext&, RestRequest const&) {
return Status{StatusCode::kAborted, "Fake Curl error / token", {}};
});
return client;
}();
// Since the service config request failed, it will be attempted again. This
// time have it succeed.
auto metadata_success = [&]() {
auto response = std::make_unique<MockRestResponse>();
EXPECT_CALL(*response, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kOk));
EXPECT_CALL(std::move(*response), ExtractPayload).WillOnce([&]() {
return MakeMockHttpPayloadSuccess(svc_acct_info_resp);
});
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expect_service_config(alias)))
.WillOnce(
Return(ByMove(std::unique_ptr<RestResponse>(std::move(response)))));
return client;
}();
// Make the token request fail. Now with a bad HTTP error code.
auto token_bad_http = [&]() {
auto response = std::make_unique<MockRestResponse>();
EXPECT_CALL(*response, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kBadRequest));
EXPECT_CALL(std::move(*response), ExtractPayload).WillOnce([&] {
return MakeMockHttpPayloadSuccess(std::string{});
});
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expect_token(email)))
.WillOnce(
Return(ByMove(std::unique_ptr<RestResponse>(std::move(response)))));
return client;
}();
// And fail again, now with an incomplete response.
auto token_incomplete = [&]() {
auto response = std::make_unique<MockRestResponse>();
EXPECT_CALL(*response, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kOk));
EXPECT_CALL(std::move(*response), ExtractPayload).WillOnce([&] {
return MakeMockHttpPayloadSuccess(token_info_resp);
});
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expect_token(email)))
.WillOnce(
Return(ByMove(std::unique_ptr<RestResponse>(std::move(response)))));
return client;
}();
MockHttpClientFactory client_factory;
EXPECT_CALL(client_factory, Call)
.WillOnce(Return(ByMove(std::move(metadata_aborted))))
.WillOnce(Return(ByMove(std::move(token_aborted))))
.WillOnce(Return(ByMove(std::move(metadata_success))))
.WillOnce(Return(ByMove(std::move(token_bad_http))))
.WillOnce(Return(ByMove(std::move(token_incomplete))));
ComputeEngineCredentials credentials(alias, Options{},
client_factory.AsStdFunction());
auto const now = std::chrono::system_clock::now();
auto status = credentials.GetToken(now);
EXPECT_THAT(status, StatusIs(StatusCode::kAborted,
HasSubstr("Fake Curl error / token")));
status = credentials.GetToken(now);
EXPECT_THAT(status, Not(IsOk()));
status = credentials.GetToken(now);
EXPECT_THAT(status,
StatusIs(Not(StatusCode::kOk),
HasSubstr("Could not find all required fields")));
}
MATCHER_P(RequestServiceAccountEmailIs, email, "has service account email") {
return email == arg.service_account_email;
}
/// @test Verify that we can force a refresh of the service account email.
TEST(ComputeEngineCredentialsTest, AccountEmail) {
auto const alias = std::string{"default"};
auto const email = std::string{"foo@bar.baz"};
auto const svc_acct_info_resp = std::string{R"""({
"email": ")""" + email + R"""(",
"scopes": ["scope1","scope2"]
})"""};
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expect_service_config(alias)))
.WillOnce([&](RestContext&, RestRequest const&) {
auto response = std::make_unique<MockRestResponse>();
EXPECT_CALL(*response, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kOk));
EXPECT_CALL(std::move(*response), ExtractPayload).WillOnce([&] {
return MakeMockHttpPayloadSuccess(svc_acct_info_resp);
});
return std::unique_ptr<RestResponse>(std::move(response));
});
MockHttpClientFactory client_factory;
EXPECT_CALL(client_factory, Call).WillOnce(Return(ByMove(std::move(client))));
ComputeEngineCredentials credentials(alias, Options{},
client_factory.AsStdFunction());
EXPECT_EQ(credentials.service_account_email(), alias);
auto refreshed_email = credentials.AccountEmail();
EXPECT_EQ(email, refreshed_email);
EXPECT_EQ(credentials.service_account_email(), refreshed_email);
// TODO(#16079): Remove conditional and else clause when GA.
#ifdef GOOGLE_CLOUD_CPP_TESTING_ENABLE_RAB
EXPECT_THAT(credentials.AllowedLocationsRequest(),
VariantWith<ServiceAccountAllowedLocationsRequest>(
RequestServiceAccountEmailIs(email)));
#else
EXPECT_THAT(credentials.AllowedLocationsRequest(),
VariantWith<std::monostate>(std::monostate()));
#endif
}
auto expected_universe_domain_request = []() {
auto const expected_path = absl::StrCat(
internal::GceMetadataScheme(), "://", internal::GceMetadataHostname(),
"/computeMetadata/v1/universe/universe-domain");
return AllOf(
Property(&RestRequest::path, expected_path),
Property(&RestRequest::headers,
Contains(Pair("metadata-flavor", Contains("Google")))),
Property(&RestRequest::parameters, Contains(Pair("recursive", "true"))));
};
TEST(ComputeEngineCredentialsTest, UniverseDomainSuccess) {
auto const universe_domain_resp = std::string{R"""(my-ud.net)"""};
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expected_universe_domain_request()))
.WillOnce([&](RestContext&, RestRequest const&) {
return internal::UnavailableError("Transient Error");
})
.WillOnce([&](RestContext&, RestRequest const&) {
auto response = std::make_unique<MockRestResponse>();
EXPECT_CALL(*response, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kOk));
EXPECT_CALL(std::move(*response), ExtractPayload).WillOnce([&] {
return MakeMockHttpPayloadSuccess(universe_domain_resp);
});
return std::unique_ptr<RestResponse>(std::move(response));
});
MockHttpClientFactory client_factory;
EXPECT_CALL(client_factory, Call).WillOnce(Return(ByMove(std::move(client))));
ComputeEngineCredentials credentials(Options{},
client_factory.AsStdFunction());
EXPECT_THAT(credentials.universe_domain(), IsOkAndHolds("my-ud.net"));
}
TEST(ComputeEngineCredentialsTest, UniverseDomainPermanentFailure) {
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expected_universe_domain_request()))
.WillOnce([&](RestContext&, RestRequest const&) {
return internal::UnavailableError("Transient Error");
})
.WillOnce([&](RestContext&, RestRequest const&) {
return internal::NotFoundError("Permanent Error");
});
MockHttpClientFactory client_factory;
EXPECT_CALL(client_factory, Call).WillOnce(Return(ByMove(std::move(client))));
ComputeEngineCredentials credentials(Options{},
client_factory.AsStdFunction());
EXPECT_THAT(credentials.universe_domain(), StatusIs(StatusCode::kNotFound));
}
TEST(ComputeEngineCredentialsTest, UniverseDomainMDSResourceNotFound) {
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expected_universe_domain_request()))
.WillOnce([&](RestContext&, RestRequest const&) {
return internal::UnavailableError("Transient Error");
})
.WillOnce([&](RestContext&, RestRequest const&) {
auto response = std::make_unique<MockRestResponse>();
EXPECT_CALL(*response, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kNotFound));
return std::unique_ptr<RestResponse>(std::move(response));
});
MockHttpClientFactory client_factory;
EXPECT_CALL(client_factory, Call).WillOnce(Return(ByMove(std::move(client))));
ComputeEngineCredentials credentials(Options{},
client_factory.AsStdFunction());
EXPECT_THAT(credentials.universe_domain(), IsOkAndHolds("googleapis.com"));
}
struct TestUniverseDomainRetryTraits {
static bool IsPermanentFailure(Status const& status) {
return !status.ok() && status.code() != StatusCode::kUnavailable;
}
};
class TestUniverseDomainRetryPolicy
: public internal::UniverseDomainRetryPolicy {
public:
~TestUniverseDomainRetryPolicy() override = default;
explicit TestUniverseDomainRetryPolicy(int maximum_failures)
: impl_(maximum_failures) {}
TestUniverseDomainRetryPolicy(TestUniverseDomainRetryPolicy&& rhs) noexcept
: TestUniverseDomainRetryPolicy(rhs.maximum_failures()) {}
TestUniverseDomainRetryPolicy(
TestUniverseDomainRetryPolicy const& rhs) noexcept
: TestUniverseDomainRetryPolicy(rhs.maximum_failures()) {}
bool OnFailure(Status const& status) override {
return impl_.OnFailure(status);
}
bool IsExhausted() const override { return impl_.IsExhausted(); }
bool IsPermanentFailure(Status const& status) const override {
return impl_.IsPermanentFailure(status);
}
int maximum_failures() const { return impl_.maximum_failures(); }
std::unique_ptr<internal::UniverseDomainRetryPolicy> clone() const override {
return std::make_unique<TestUniverseDomainRetryPolicy>(maximum_failures());
}
private:
internal::LimitedErrorCountRetryPolicy<TestUniverseDomainRetryTraits> impl_;
};
TEST(ComputeEngineCredentialsTest,
UniverseDomainCredentialsOptionsCustomRetryPolicy) {
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expected_universe_domain_request()))
.Times(3)
.WillRepeatedly([&](RestContext&, RestRequest const&) {
return internal::UnavailableError("Transient Error");
});
auto credentials_options =
Options{}.set<internal::UniverseDomainRetryPolicyOption>(
std::make_unique<TestUniverseDomainRetryPolicy>(2)->clone());
MockHttpClientFactory client_factory;
EXPECT_CALL(client_factory, Call).WillOnce(Return(ByMove(std::move(client))));
ComputeEngineCredentials credentials(credentials_options,
client_factory.AsStdFunction());
EXPECT_THAT(credentials.universe_domain(),
StatusIs(StatusCode::kUnavailable));
}
TEST(ComputeEngineCredentialsTest, UniverseDomainCallOptionsCustomRetryPolicy) {
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expected_universe_domain_request()))
.Times(4)
.WillRepeatedly([&](RestContext&, RestRequest const&) {
return internal::UnavailableError("Transient Error");
});
auto call_options = Options{}.set<internal::UniverseDomainRetryPolicyOption>(
std::make_unique<TestUniverseDomainRetryPolicy>(3)->clone());
auto credentials_options =
Options{}.set<internal::UniverseDomainRetryPolicyOption>(
std::make_unique<TestUniverseDomainRetryPolicy>(2)->clone());
MockHttpClientFactory client_factory;
EXPECT_CALL(client_factory, Call).WillOnce(Return(ByMove(std::move(client))));
ComputeEngineCredentials credentials(credentials_options,
client_factory.AsStdFunction());
EXPECT_THAT(credentials.universe_domain(call_options),
StatusIs(StatusCode::kUnavailable));
}
TEST(ComputeEngineCredentialsTest, ProjectIdSuccess) {
auto expected_request = []() {
auto const expected_path = absl::StrCat(
internal::GceMetadataScheme(), "://", internal::GceMetadataHostname(),
"/computeMetadata/v1/project/project-id");
return AllOf(
Property(&RestRequest::path, expected_path),
Property(&RestRequest::headers,
Contains(Pair("metadata-flavor", Contains("Google")))));
};
auto const expected = std::string{"test-only-project-id"};
MockHttpClientFactory client_factory;
EXPECT_CALL(client_factory, Call)
.WillOnce([&] {
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expected_request())).WillOnce([] {
return internal::UnavailableError("Transient Error");
});
return client;
})
.WillOnce([&] {
auto client = std::make_unique<MockRestClient>();
EXPECT_CALL(*client, Get(_, expected_request())).WillOnce([&] {
auto response = std::make_unique<MockRestResponse>();
EXPECT_CALL(*response, StatusCode)
.WillRepeatedly(Return(HttpStatusCode::kOk));
EXPECT_CALL(std::move(*response), ExtractPayload).WillOnce([&] {
return MakeMockHttpPayloadSuccess(expected);
});
return std::unique_ptr<RestResponse>(std::move(response));
});
return client;
});
ComputeEngineCredentials credentials(Options{},
client_factory.AsStdFunction());
// The first attempt fails, no retry policies for project id, so the error
// should be returned to the caller.
EXPECT_THAT(credentials.project_id(), StatusIs(StatusCode::kUnavailable));
// The error is not cached, a second request may succeed.
EXPECT_THAT(credentials.project_id(), IsOkAndHolds(expected));
// Verify the value is cached and further lookups do not create requests.
EXPECT_THAT(credentials.project_id(), IsOkAndHolds(expected));
}
} // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace oauth2_internal
} // namespace cloud
} // namespace google