-
Notifications
You must be signed in to change notification settings - Fork 444
Expand file tree
/
Copy pathgrpc_credential_types.cc
More file actions
331 lines (298 loc) · 13.8 KB
/
grpc_credential_types.cc
File metadata and controls
331 lines (298 loc) · 13.8 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
// Copyright 2021 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/iam/credentials/v1/iam_credentials_client.h"
#include "google/cloud/spanner/admin/instance_admin_client.h"
#include "google/cloud/common_options.h"
#include "google/cloud/credentials.h"
#include "google/cloud/grpc_options.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/log.h"
#include "google/cloud/project.h"
#include "google/cloud/testing_util/example_driver.h"
#include "absl/strings/match.h"
#include "absl/strings/str_split.h"
#include "absl/time/time.h" // NOLINT(modernize-deprecated-headers)
#include <curl/curl.h>
#include <hello_world_grpc/hello_world.grpc.pb.h>
#include <chrono>
#include <stdexcept>
#include <thread>
namespace {
auto constexpr kTokenValidationPeriod = std::chrono::seconds(30);
extern "C" size_t CurlOnWriteData(char* ptr, size_t size, size_t nmemb,
void* userdata) {
auto* buffer = reinterpret_cast<std::string*>(userdata);
buffer->append(ptr, size * nmemb);
return size * nmemb;
}
struct CurlPtrCleanup {
void operator()(CURL* arg) const { return curl_easy_cleanup(arg); }
};
struct CurlSListFreeAll {
void operator()(curl_slist* arg) const { return curl_slist_free_all(arg); }
};
google::cloud::StatusOr<std::string> HttpGet(std::string const& url,
std::string const& token) {
static auto const kCurlInit = [] {
return curl_global_init(CURL_GLOBAL_ALL);
}();
(void)kCurlInit;
auto const authorization = "Authorization: Bearer " + token;
using Headers = std::unique_ptr<curl_slist, CurlSListFreeAll>;
auto const headers =
Headers{curl_slist_append(nullptr, authorization.c_str())};
using CurlHandle = std::unique_ptr<CURL, CurlPtrCleanup>;
auto curl = CurlHandle(curl_easy_init());
if (!curl) throw std::runtime_error("Failed to create CurlHandle");
std::string buffer;
curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, headers.get());
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, &CurlOnWriteData);
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
CURLcode code = curl_easy_perform(curl.get());
if (code != CURLE_OK) throw std::runtime_error(curl_easy_strerror(code));
long status; // NOLINT(google-runtime-int)
code = curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &status);
if (code != CURLE_OK) throw std::runtime_error(curl_easy_strerror(code));
// Handle common errors as Status, this is not exhaustive.
using ::google::cloud::Status;
using ::google::cloud::StatusCode;
if (status == 400) return Status(StatusCode::kInvalidArgument, buffer);
if (status == 401) return Status(StatusCode::kUnauthenticated, buffer);
if (status == 403) return Status(StatusCode::kPermissionDenied, buffer);
if (status >= 500) return Status(StatusCode::kInternal, buffer);
if (status < 200 || status >= 300) {
std::ostringstream os;
os << "HTTP error [" << status << "]: " << buffer;
return Status(StatusCode::kUnknown, buffer);
}
return buffer;
}
google::iam::credentials::v1::GenerateAccessTokenResponse UseAccessToken(
google::cloud::iam_credentials_v1::IAMCredentialsClient client,
std::vector<std::string> const& argv) {
namespace iam = ::google::cloud::iam_credentials_v1;
return [](iam::IAMCredentialsClient client,
std::string const& service_account, std::string const& project_id) {
google::protobuf::Duration duration;
duration.set_seconds(
std::chrono::seconds(2 * kTokenValidationPeriod).count());
auto token = client.GenerateAccessToken(
"projects/-/serviceAccounts/" + service_account, /*delegates=*/{},
/*scope=*/{"https://www.googleapis.com/auth/cloud-platform"}, duration);
if (!token) throw std::move(token).status();
auto const expiration = absl::ToChronoTime(
absl::FromUnixSeconds(token->expire_time().seconds()));
std::cout << "Fetched token starting with "
<< token->access_token().substr(0, 8)
<< ", which will expire around " << absl::FromChrono(expiration)
<< std::endl;
auto credentials = google::cloud::MakeAccessTokenCredentials(
token->access_token(), expiration);
google::cloud::spanner_admin::InstanceAdminClient admin(
google::cloud::spanner_admin::MakeInstanceAdminConnection(
google::cloud::Options{}
.set<google::cloud::UnifiedCredentialsOption>(credentials)));
for (auto config : admin.ListInstanceConfigs(
google::cloud::Project(project_id).FullName())) {
if (!config) throw std::move(config).status();
std::cout << "InstanceConfig: " << config->name() << "\n";
}
return *std::move(token);
}(std::move(client), argv.at(0), argv.at(1));
}
void UseAccessTokenUntilExpired(
google::cloud::iam_credentials_v1::IAMCredentialsClient client,
std::vector<std::string> const& argv) {
auto token = UseAccessToken(std::move(client), argv);
auto const& project_id = argv.at(1);
auto const expiration =
absl::ToChronoTime(absl::FromUnixSeconds(token.expire_time().seconds()));
auto const deadline = expiration + 4 * kTokenValidationPeriod;
std::cout << "Running until " << absl::FromChrono(deadline)
<< ". This is past the access token expiration time ("
<< absl::FromChrono(expiration) << ")" << std::endl;
auto iteration = [=](bool expired) {
auto credentials = google::cloud::MakeAccessTokenCredentials(
token.access_token(), expiration);
google::cloud::spanner_admin::InstanceAdminClient admin(
google::cloud::spanner_admin::MakeInstanceAdminConnection(
google::cloud::Options{}
.set<google::cloud::UnifiedCredentialsOption>(credentials)));
for (auto config : admin.ListInstanceConfigs(
google::cloud::Project(project_id).FullName())) {
// kUnauthenticated receives special treatment, it is the error received
// when the token expires.
if (config.status().code() ==
google::cloud::StatusCode::kUnauthenticated) {
std::cout << "error [" << config.status() << "]";
if (!expired) {
std::cout << ": unexpected, but could be a race condition."
<< " Trying again\n";
return true;
}
std::cout << ": this is expected as the token is expired\n";
return false;
}
if (!config) throw std::move(config).status();
std::cout << "success (" << config->name() << ")\n";
return true;
}
return false;
};
for (auto now = std::chrono::system_clock::now(); now < deadline;
now = std::chrono::system_clock::now()) {
auto const expired = (now > expiration);
std::cout << absl::FromChrono(now) << ": running iteration with "
<< (expired ? "an expired" : "a valid") << " token ";
if (!iteration(expired)) break;
std::this_thread::sleep_for(kTokenValidationPeriod);
}
}
void UseIdTokenHttp(
google::cloud::iam_credentials_v1::IAMCredentialsClient client,
std::vector<std::string> const& argv) {
namespace iam = ::google::cloud::iam_credentials_v1;
[](iam::IAMCredentialsClient client, std::string const& service_account,
std::string const& hello_world_url) {
auto token = client.GenerateIdToken(
"projects/-/serviceAccounts/" + service_account, /*delegates=*/{},
/*audience=*/{hello_world_url},
/*include_email=*/true);
if (!token) throw std::move(token).status();
auto backoff = std::chrono::milliseconds(250);
for (int i = 0; i != 3; ++i) {
auto text = HttpGet(hello_world_url, token->token());
if (text.ok()) {
std::cout << "Server says: " << *text << "\n";
return;
}
std::this_thread::sleep_for(backoff);
backoff *= 2;
}
throw std::runtime_error("Could not contact server after 3 attempts");
}(std::move(client), argv.at(0), argv.at(1));
}
void UseIdTokenGrpc(
google::cloud::iam_credentials_v1::IAMCredentialsClient client,
std::vector<std::string> const& argv) {
namespace iam = ::google::cloud::iam_credentials_v1;
[](iam::IAMCredentialsClient client, std::string const& service_account,
std::string const& url) {
auto token = client.GenerateIdToken(
"projects/-/serviceAccounts/" + service_account, /*delegates=*/{},
/*audience=*/{url},
/*include_email=*/true);
if (!token) throw std::move(token).status();
auto const prefix = std::string{"https://"};
if (!absl::StartsWith(url, prefix)) {
throw std::runtime_error("Invalid URL" + url);
}
auto endpoint = url.substr(prefix.length()) + ":443";
auto credentials = grpc::CompositeChannelCredentials(
grpc::SslCredentials(grpc::SslCredentialsOptions{}),
grpc::AccessTokenCredentials(token->token()));
auto channel = grpc::CreateChannel(endpoint, credentials);
auto stub = google::cloud::examples::Greet::NewStub(channel);
auto request = google::cloud::examples::HelloRequest{};
auto backoff = std::chrono::milliseconds(250);
for (int i = 0; i != 3; ++i) {
grpc::ClientContext context;
google::cloud::examples::HelloResponse response;
auto status = stub->Hello(&context, request, &response);
if (status.ok()) {
std::cout << "Servers says: " << response.greeting() << "\n";
return;
}
std::cout << "Server returned error=" << status.error_code()
<< ", message=" << status.error_message() << "\n";
std::this_thread::sleep_for(backoff);
backoff *= 2;
}
throw std::runtime_error("Could not contact server after 3 attempts");
}(std::move(client), argv.at(0), argv.at(1));
}
void AutoRun(std::vector<std::string> const& argv) {
namespace examples = ::google::cloud::testing_util;
namespace iam = ::google::cloud::iam_credentials_v1;
using ::google::cloud::internal::GetEnv;
if (!argv.empty()) throw examples::Usage{"auto"};
examples::CheckEnvironmentVariablesAreSet({
"GOOGLE_CLOUD_PROJECT",
"GOOGLE_CLOUD_CPP_IAM_TEST_SERVICE_ACCOUNT",
"GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_SERVICE_ACCOUNT",
"GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_HTTP_URL",
"GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_GRPC_URL",
});
auto project_id = GetEnv("GOOGLE_CLOUD_PROJECT").value();
auto const test_iam_service_account =
GetEnv("GOOGLE_CLOUD_CPP_IAM_TEST_SERVICE_ACCOUNT").value_or("");
auto const hello_world_service_account =
GetEnv("GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_SERVICE_ACCOUNT").value_or("");
auto const hello_world_http_url =
GetEnv("GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_HTTP_URL").value_or("");
auto const hello_world_grpc_url =
GetEnv("GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_GRPC_URL").value_or("");
auto client = iam::IAMCredentialsClient(iam::MakeIAMCredentialsConnection(
google::cloud::Options{}.set<google::cloud::GrpcTracingOptionsOption>(
// There are some credentials returned by RPCs. On an error
// these are printed. This truncates them, making the output
// safe, and yet useful for debugging.
google::cloud::TracingOptions{}.SetOptions(
"truncate_string_field_longer_than=32"))));
std::cout << "\nRunning UseAccessToken() example" << std::endl;
UseAccessToken(client, {test_iam_service_account, project_id});
std::cout << "\nRunning UseAccessTokenUntilExpired() example" << std::endl;
UseAccessTokenUntilExpired(client, {test_iam_service_account, project_id});
std::cout << "\nRunning UseIdTokenHttp() example" << std::endl;
UseIdTokenHttp(client, {hello_world_service_account, hello_world_http_url});
std::cout << "\nRunning UseIdTokenGrpc() example" << std::endl;
UseIdTokenGrpc(client, {hello_world_service_account, hello_world_grpc_url});
}
} // namespace
int main(int argc, char* argv[]) { // NOLINT(bugprone-exception-escape)
using ::google::cloud::testing_util::Example;
namespace iam = ::google::cloud::iam_credentials_v1;
using ClientCommand = std::function<void(iam::IAMCredentialsClient,
std::vector<std::string> argv)>;
auto make_entry = [](std::string name,
std::vector<std::string> const& arg_names,
ClientCommand const& command) {
auto adapter = [=](std::vector<std::string> argv) {
if ((argv.size() == 1 && argv[0] == "--help") ||
argv.size() != arg_names.size()) {
std::string usage = name;
for (auto const& a : arg_names) usage += " <" + a + ">";
throw google::cloud::testing_util::Usage{std::move(usage)};
}
auto client =
iam::IAMCredentialsClient(iam::MakeIAMCredentialsConnection());
command(client, std::move(argv));
};
return google::cloud::testing_util::Commands::value_type(std::move(name),
adapter);
};
Example example({
make_entry("use-access-token", {"service-account", "project-id"},
UseAccessToken),
make_entry("use-access-token-until-expired",
{"service-account", "project-id"}, UseAccessTokenUntilExpired),
make_entry("use-id-token-http",
{"service-account", "hello-world-http-url"}, UseIdTokenHttp),
make_entry("use-id-token-grpc",
{"service-account", "hello-world-http-url"}, UseIdTokenGrpc),
{"auto", AutoRun},
});
return example.Run(argc, argv);
}