| 1 |
// |
| 2 |
// Copyright 2020 gRPC authors. |
| 3 |
// |
| 4 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
// you may not use this file except in compliance with the License. |
| 6 |
// You may obtain a copy of the License at |
| 7 |
// |
| 8 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
// |
| 10 |
// Unless required by applicable law or agreed to in writing, software |
| 11 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
// See the License for the specific language governing permissions and |
| 14 |
// limitations under the License. |
| 15 |
// |
| 16 |
|
| 17 |
#include <grpc/support/port_platform.h> |
| 18 |
|
| 19 |
#include "src/core/lib/security/credentials/external/external_account_credentials.h" |
| 20 |
|
| 21 |
#include <stdint.h> |
| 22 |
#include <string.h> |
| 23 |
|
| 24 |
#include <algorithm> |
| 25 |
#include <map> |
| 26 |
#include <memory> |
| 27 |
#include <utility> |
| 28 |
|
| 29 |
#include "absl/status/status.h" |
| 30 |
#include "absl/status/statusor.h" |
| 31 |
#include "absl/strings/match.h" |
| 32 |
#include "absl/strings/str_cat.h" |
| 33 |
#include "absl/strings/str_format.h" |
| 34 |
#include "absl/strings/str_join.h" |
| 35 |
#include "absl/strings/str_split.h" |
| 36 |
#include "absl/strings/strip.h" |
| 37 |
#include "absl/time/clock.h" |
| 38 |
#include "absl/time/time.h" |
| 39 |
|
| 40 |
#include <grpc/grpc.h> |
| 41 |
#include <grpc/grpc_security.h> |
| 42 |
#include <grpc/support/alloc.h> |
| 43 |
#include <grpc/support/log.h> |
| 44 |
#include <grpc/support/string_util.h> |
| 45 |
|
| 46 |
#include "src/core/lib/gprpp/status_helper.h" |
| 47 |
#include "src/core/lib/http/httpcli_ssl_credentials.h" |
| 48 |
#include "src/core/lib/http/parser.h" |
| 49 |
#include "src/core/lib/security/credentials/credentials.h" |
| 50 |
#include "src/core/lib/security/credentials/external/aws_external_account_credentials.h" |
| 51 |
#include "src/core/lib/security/credentials/external/file_external_account_credentials.h" |
| 52 |
#include "src/core/lib/security/credentials/external/url_external_account_credentials.h" |
| 53 |
#include "src/core/lib/security/util/json_util.h" |
| 54 |
#include "src/core/lib/slice/b64.h" |
| 55 |
#include "src/core/lib/uri/uri_parser.h" |
| 56 |
|
| 57 |
#define EXTERNAL_ACCOUNT_CREDENTIALS_GRANT_TYPE \ |
| 58 |
"urn:ietf:params:oauth:grant-type:token-exchange" |
| 59 |
#define EXTERNAL_ACCOUNT_CREDENTIALS_REQUESTED_TOKEN_TYPE \ |
| 60 |
"urn:ietf:params:oauth:token-type:access_token" |
| 61 |
#define GOOGLE_CLOUD_PLATFORM_DEFAULT_SCOPE \ |
| 62 |
"https://www.googleapis.com/auth/cloud-platform" |
| 63 |
|
| 64 |
namespace grpc_core { |
| 65 |
|
| 66 |
namespace { |
| 67 |
|
| 68 |
std::string UrlEncode(const absl::string_view& s) { |
| 69 |
const char* hex = "0123456789ABCDEF"; |
| 70 |
std::string result; |
| 71 |
result.reserve(s.length()); |
| 72 |
for (auto c : s) { |
| 73 |
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || |
| 74 |
(c >= 'a' && c <= 'z') || c == '-' || c == '_' || c == '!' || |
| 75 |
c == '\'' || c == '(' || c == ')' || c == '*' || c == '~' || c == '.') { |
| 76 |
result.push_back(c); |
| 77 |
} else { |
| 78 |
result.push_back('%'); |
| 79 |
result.push_back(hex[static_cast<unsigned char>(c) >> 4]); |
| 80 |
result.push_back(hex[static_cast<unsigned char>(c) & 15]); |
| 81 |
} |
| 82 |
} |
| 83 |
return result; |
| 84 |
} |
| 85 |
|
| 86 |
// Expression to match: |
| 87 |
// //iam.googleapis.com/locations/[^/]+/workforcePools/[^/]+/providers/.+ |
| 88 |
bool MatchWorkforcePoolAudience(absl::string_view audience) { |
| 89 |
// Match "//iam.googleapis.com/locations/" |
| 90 |
if (!absl::ConsumePrefix(&audience, "//iam.googleapis.com")) return false; |
| 91 |
if (!absl::ConsumePrefix(&audience, "/locations/")) return false; |
| 92 |
// Match "[^/]+/workforcePools/" |
| 93 |
std::pair<absl::string_view, absl::string_view> workforce_pools_split_result = |
| 94 |
absl::StrSplit(audience, absl::MaxSplits("/workforcePools/", 1)); |
| 95 |
if (absl::StrContains(workforce_pools_split_result.first, '/')) return false; |
| 96 |
// Match "[^/]+/providers/.+" |
| 97 |
std::pair<absl::string_view, absl::string_view> providers_split_result = |
| 98 |
absl::StrSplit(workforce_pools_split_result.second, |
| 99 |
absl::MaxSplits("/providers/", 1)); |
| 100 |
return !absl::StrContains(providers_split_result.first, '/'); |
| 101 |
} |
| 102 |
|
| 103 |
} // namespace |
| 104 |
|
| 105 |
RefCountedPtr<ExternalAccountCredentials> ExternalAccountCredentials::Create( |
| 106 |
const Json& json, std::vector<std::string> scopes, |
| 107 |
grpc_error_handle* error) { |
| 108 |
GPR_ASSERT(error->ok()); |
| 109 |
Options options; |
| 110 |
options.type = GRPC_AUTH_JSON_TYPE_INVALID; |
| 111 |
if (json.type() != Json::Type::OBJECT) { |
| 112 |
*error = |
| 113 |
GRPC_ERROR_CREATE("Invalid json to construct credentials options."); |
| 114 |
return nullptr; |
| 115 |
} |
| 116 |
auto it = json.object_value().find("type"); |
| 117 |
if (it == json.object_value().end()) { |
| 118 |
*error = GRPC_ERROR_CREATE("type field not present."); |
| 119 |
return nullptr; |
| 120 |
} |
| 121 |
if (it->second.type() != Json::Type::STRING) { |
| 122 |
*error = GRPC_ERROR_CREATE("type field must be a string."); |
| 123 |
return nullptr; |
| 124 |
} |
| 125 |
if (it->second.string_value() != GRPC_AUTH_JSON_TYPE_EXTERNAL_ACCOUNT) { |
| 126 |
*error = GRPC_ERROR_CREATE("Invalid credentials json type."); |
| 127 |
return nullptr; |
| 128 |
} |
| 129 |
options.type = GRPC_AUTH_JSON_TYPE_EXTERNAL_ACCOUNT; |
| 130 |
it = json.object_value().find("audience"); |
| 131 |
if (it == json.object_value().end()) { |
| 132 |
*error = GRPC_ERROR_CREATE("audience field not present."); |
| 133 |
return nullptr; |
| 134 |
} |
| 135 |
if (it->second.type() != Json::Type::STRING) { |
| 136 |
*error = GRPC_ERROR_CREATE("audience field must be a string."); |
| 137 |
return nullptr; |
| 138 |
} |
| 139 |
options.audience = it->second.string_value(); |
| 140 |
it = json.object_value().find("subject_token_type"); |
| 141 |
if (it == json.object_value().end()) { |
| 142 |
*error = GRPC_ERROR_CREATE("subject_token_type field not present."); |
| 143 |
return nullptr; |
| 144 |
} |
| 145 |
if (it->second.type() != Json::Type::STRING) { |
| 146 |
*error = GRPC_ERROR_CREATE("subject_token_type field must be a string."); |
| 147 |
return nullptr; |
| 148 |
} |
| 149 |
options.subject_token_type = it->second.string_value(); |
| 150 |
it = json.object_value().find("service_account_impersonation_url"); |
| 151 |
if (it != json.object_value().end()) { |
| 152 |
options.service_account_impersonation_url = it->second.string_value(); |
| 153 |
} |
| 154 |
it = json.object_value().find("token_url"); |
| 155 |
if (it == json.object_value().end()) { |
| 156 |
*error = GRPC_ERROR_CREATE("token_url field not present."); |
| 157 |
return nullptr; |
| 158 |
} |
| 159 |
if (it->second.type() != Json::Type::STRING) { |
| 160 |
*error = GRPC_ERROR_CREATE("token_url field must be a string."); |
| 161 |
return nullptr; |
| 162 |
} |
| 163 |
options.token_url = it->second.string_value(); |
| 164 |
it = json.object_value().find("token_info_url"); |
| 165 |
if (it != json.object_value().end()) { |
| 166 |
options.token_info_url = it->second.string_value(); |
| 167 |
} |
| 168 |
it = json.object_value().find("credential_source"); |
| 169 |
if (it == json.object_value().end()) { |
| 170 |
*error = GRPC_ERROR_CREATE("credential_source field not present."); |
| 171 |
return nullptr; |
| 172 |
} |
| 173 |
options.credential_source = it->second; |
| 174 |
it = json.object_value().find("quota_project_id"); |
| 175 |
if (it != json.object_value().end()) { |
| 176 |
options.quota_project_id = it->second.string_value(); |
| 177 |
} |
| 178 |
it = json.object_value().find("client_id"); |
| 179 |
if (it != json.object_value().end()) { |
| 180 |
options.client_id = it->second.string_value(); |
| 181 |
} |
| 182 |
it = json.object_value().find("client_secret"); |
| 183 |
if (it != json.object_value().end()) { |
| 184 |
options.client_secret = it->second.string_value(); |
| 185 |
} |
| 186 |
it = json.object_value().find("workforce_pool_user_project"); |
| 187 |
if (it != json.object_value().end()) { |
| 188 |
if (MatchWorkforcePoolAudience(options.audience)) { |
| 189 |
options.workforce_pool_user_project = it->second.string_value(); |
| 190 |
} else { |
| 191 |
*error = GRPC_ERROR_CREATE( |
| 192 |
"workforce_pool_user_project should not be set for non-workforce " |
| 193 |
"pool credentials"); |
| 194 |
return nullptr; |
| 195 |
} |
| 196 |
} |
| 197 |
RefCountedPtr<ExternalAccountCredentials> creds; |
| 198 |
if (options.credential_source.object_value().find("environment_id") != |
| 199 |
options.credential_source.object_value().end()) { |
| 200 |
creds = MakeRefCounted<AwsExternalAccountCredentials>( |
| 201 |
std::move(options), std::move(scopes), error); |
| 202 |
} else if (options.credential_source.object_value().find("file") != |
| 203 |
options.credential_source.object_value().end()) { |
| 204 |
creds = MakeRefCounted<FileExternalAccountCredentials>( |
| 205 |
std::move(options), std::move(scopes), error); |
| 206 |
} else if (options.credential_source.object_value().find("url") != |
| 207 |
options.credential_source.object_value().end()) { |
| 208 |
creds = MakeRefCounted<UrlExternalAccountCredentials>( |
| 209 |
std::move(options), std::move(scopes), error); |
| 210 |
} else { |
| 211 |
*error = GRPC_ERROR_CREATE( |
| 212 |
"Invalid options credential source to create " |
| 213 |
"ExternalAccountCredentials."); |
| 214 |
} |
| 215 |
if (error->ok()) { |
| 216 |
return creds; |
| 217 |
} else { |
| 218 |
return nullptr; |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
ExternalAccountCredentials::ExternalAccountCredentials( |
| 223 |
Options options, std::vector<std::string> scopes) |
| 224 |
: options_(std::move(options)) { |
| 225 |
if (scopes.empty()) { |
| 226 |
scopes.push_back(GOOGLE_CLOUD_PLATFORM_DEFAULT_SCOPE); |
| 227 |
} |
| 228 |
scopes_ = std::move(scopes); |
| 229 |
} |
| 230 |
|
| 231 |
ExternalAccountCredentials::~ExternalAccountCredentials() {} |
| 232 |
|
| 233 |
std::string ExternalAccountCredentials::debug_string() { |
| 234 |
return absl::StrFormat("ExternalAccountCredentials{Audience:%s,%s}", |
| 235 |
options_.audience, |
| 236 |
grpc_oauth2_token_fetcher_credentials::debug_string()); |
| 237 |
} |
| 238 |
|
| 239 |
// The token fetching flow: |
| 240 |
// 1. Retrieve subject token - Subclass's RetrieveSubjectToken() gets called |
| 241 |
// and the subject token is received in OnRetrieveSubjectTokenInternal(). |
| 242 |
// 2. Exchange token - ExchangeToken() gets called with the |
| 243 |
// subject token from #1. Receive the response in OnExchangeTokenInternal(). |
| 244 |
// 3. (Optional) Impersonate service account - ImpersenateServiceAccount() gets |
| 245 |
// called with the access token of the response from #2. Get an impersonated |
| 246 |
// access token in OnImpersenateServiceAccountInternal(). |
| 247 |
// 4. Finish token fetch - Return back the response that contains an access |
| 248 |
// token in FinishTokenFetch(). |
| 249 |
// TODO(chuanr): Avoid starting the remaining requests if the channel gets shut |
| 250 |
// down. |
| 251 |
void ExternalAccountCredentials::fetch_oauth2( |
| 252 |
grpc_credentials_metadata_request* metadata_req, |
| 253 |
grpc_polling_entity* pollent, grpc_iomgr_cb_func response_cb, |
| 254 |
Timestamp deadline) { |
| 255 |
GPR_ASSERT(ctx_ == nullptr); |
| 256 |
ctx_ = new HTTPRequestContext(pollent, deadline); |
| 257 |
metadata_req_ = metadata_req; |
| 258 |
response_cb_ = response_cb; |
| 259 |
auto cb = [this](std::string token, grpc_error_handle error) { |
| 260 |
OnRetrieveSubjectTokenInternal(token, error); |
| 261 |
}; |
| 262 |
RetrieveSubjectToken(ctx_, options_, cb); |
| 263 |
} |
| 264 |
|
| 265 |
void ExternalAccountCredentials::OnRetrieveSubjectTokenInternal( |
| 266 |
absl::string_view subject_token, grpc_error_handle error) { |
| 267 |
if (!error.ok()) { |
| 268 |
FinishTokenFetch(error); |
| 269 |
} else { |
| 270 |
ExchangeToken(subject_token); |
| 271 |
} |
| 272 |
} |
| 273 |
|
| 274 |
void ExternalAccountCredentials::ExchangeToken( |
| 275 |
absl::string_view subject_token) { |
| 276 |
absl::StatusOr<URI> uri = URI::Parse(options_.token_url); |
| 277 |
if (!uri.ok()) { |
| 278 |
FinishTokenFetch(GRPC_ERROR_CREATE( |
| 279 |
absl::StrFormat("Invalid token url: %s. Error: %s", options_.token_url, |
| 280 |
uri.status().ToString()))); |
| 281 |
return; |
| 282 |
} |
| 283 |
grpc_http_request request; |
| 284 |
memset(&request, 0, sizeof(grpc_http_request)); |
| 285 |
grpc_http_header* headers = nullptr; |
| 286 |
if (!options_.client_id.empty() && !options_.client_secret.empty()) { |
| 287 |
request.hdr_count = 2; |
| 288 |
headers = static_cast<grpc_http_header*>( |
| 289 |
gpr_malloc(sizeof(grpc_http_header) * request.hdr_count)); |
| 290 |
headers[0].key = gpr_strdup("Content-Type"); |
| 291 |
headers[0].value = gpr_strdup("application/x-www-form-urlencoded"); |
| 292 |
std::string raw_cred = |
| 293 |
absl::StrFormat("%s:%s", options_.client_id, options_.client_secret); |
| 294 |
char* encoded_cred = |
| 295 |
grpc_base64_encode(raw_cred.c_str(), raw_cred.length(), 0, 0); |
| 296 |
std::string str = absl::StrFormat("Basic %s", std::string(encoded_cred)); |
| 297 |
headers[1].key = gpr_strdup("Authorization"); |
| 298 |
headers[1].value = gpr_strdup(str.c_str()); |
| 299 |
gpr_free(encoded_cred); |
| 300 |
} else { |
| 301 |
request.hdr_count = 1; |
| 302 |
headers = static_cast<grpc_http_header*>( |
| 303 |
gpr_malloc(sizeof(grpc_http_header) * request.hdr_count)); |
| 304 |
headers[0].key = gpr_strdup("Content-Type"); |
| 305 |
headers[0].value = gpr_strdup("application/x-www-form-urlencoded"); |
| 306 |
} |
| 307 |
request.hdrs = headers; |
| 308 |
std::vector<std::string> body_parts; |
| 309 |
body_parts.push_back( |
| 310 |
absl::StrFormat("audience=%s", UrlEncode(options_.audience).c_str())); |
| 311 |
body_parts.push_back(absl::StrFormat( |
| 312 |
"grant_type=%s", |
| 313 |
UrlEncode(EXTERNAL_ACCOUNT_CREDENTIALS_GRANT_TYPE).c_str())); |
| 314 |
body_parts.push_back(absl::StrFormat( |
| 315 |
"requested_token_type=%s", |
| 316 |
UrlEncode(EXTERNAL_ACCOUNT_CREDENTIALS_REQUESTED_TOKEN_TYPE).c_str())); |
| 317 |
body_parts.push_back(absl::StrFormat( |
| 318 |
"subject_token_type=%s", UrlEncode(options_.subject_token_type).c_str())); |
| 319 |
body_parts.push_back( |
| 320 |
absl::StrFormat("subject_token=%s", UrlEncode(subject_token).c_str())); |
| 321 |
std::string scope = GOOGLE_CLOUD_PLATFORM_DEFAULT_SCOPE; |
| 322 |
if (options_.service_account_impersonation_url.empty()) { |
| 323 |
scope = absl::StrJoin(scopes_, " "); |
| 324 |
} |
| 325 |
body_parts.push_back(absl::StrFormat("scope=%s", UrlEncode(scope).c_str())); |
| 326 |
Json::Object addtional_options_json_object; |
| 327 |
if (options_.client_id.empty() && options_.client_secret.empty()) { |
| 328 |
addtional_options_json_object["userProject"] = |
| 329 |
options_.workforce_pool_user_project; |
| 330 |
} |
| 331 |
Json addtional_options_json(std::move(addtional_options_json_object)); |
| 332 |
body_parts.push_back(absl::StrFormat( |
| 333 |
"options=%s", UrlEncode(addtional_options_json.Dump()).c_str())); |
| 334 |
std::string body = absl::StrJoin(body_parts, "&"); |
| 335 |
request.body = const_cast<char*>(body.c_str()); |
| 336 |
request.body_length = body.size(); |
| 337 |
grpc_http_response_destroy(&ctx_->response); |
| 338 |
ctx_->response = {}; |
| 339 |
GRPC_CLOSURE_INIT(&ctx_->closure, OnExchangeToken, this, nullptr); |
| 340 |
GPR_ASSERT(http_request_ == nullptr); |
| 341 |
RefCountedPtr<grpc_channel_credentials> http_request_creds; |
| 342 |
if (uri->scheme() == "http") { |
| 343 |
http_request_creds = RefCountedPtr<grpc_channel_credentials>( |
| 344 |
grpc_insecure_credentials_create()); |
| 345 |
} else { |
| 346 |
http_request_creds = CreateHttpRequestSSLCredentials(); |
| 347 |
} |
| 348 |
http_request_ = |
| 349 |
HttpRequest::Post(std::move(*uri), nullptr /* channel args */, |
| 350 |
ctx_->pollent, &request, ctx_->deadline, &ctx_->closure, |
| 351 |
&ctx_->response, std::move(http_request_creds)); |
| 352 |
http_request_->Start(); |
| 353 |
request.body = nullptr; |
| 354 |
grpc_http_request_destroy(&request); |
| 355 |
} |
| 356 |
|
| 357 |
void ExternalAccountCredentials::OnExchangeToken(void* arg, |
| 358 |
grpc_error_handle error) { |
| 359 |
ExternalAccountCredentials* self = |
| 360 |
static_cast<ExternalAccountCredentials*>(arg); |
| 361 |
self->OnExchangeTokenInternal(error); |
| 362 |
} |
| 363 |
|
| 364 |
void ExternalAccountCredentials::OnExchangeTokenInternal( |
| 365 |
grpc_error_handle error) { |
| 366 |
http_request_.reset(); |
| 367 |
if (!error.ok()) { |
| 368 |
FinishTokenFetch(error); |
| 369 |
} else { |
| 370 |
if (options_.service_account_impersonation_url.empty()) { |
| 371 |
metadata_req_->response = ctx_->response; |
| 372 |
metadata_req_->response.body = gpr_strdup( |
| 373 |
std::string(ctx_->response.body, ctx_->response.body_length).c_str()); |
| 374 |
metadata_req_->response.hdrs = static_cast<grpc_http_header*>( |
| 375 |
gpr_malloc(sizeof(grpc_http_header) * ctx_->response.hdr_count)); |
| 376 |
for (size_t i = 0; i < ctx_->response.hdr_count; i++) { |
| 377 |
metadata_req_->response.hdrs[i].key = |
| 378 |
gpr_strdup(ctx_->response.hdrs[i].key); |
| 379 |
metadata_req_->response.hdrs[i].value = |
| 380 |
gpr_strdup(ctx_->response.hdrs[i].value); |
| 381 |
} |
| 382 |
FinishTokenFetch(absl::OkStatus()); |
| 383 |
} else { |
| 384 |
ImpersenateServiceAccount(); |
| 385 |
} |
| 386 |
} |
| 387 |
} |
| 388 |
|
| 389 |
void ExternalAccountCredentials::ImpersenateServiceAccount() { |
| 390 |
absl::string_view response_body(ctx_->response.body, |
| 391 |
ctx_->response.body_length); |
| 392 |
auto json = Json::Parse(response_body); |
| 393 |
if (!json.ok()) { |
| 394 |
FinishTokenFetch(GRPC_ERROR_CREATE(absl::StrCat( |
| 395 |
"Invalid token exchange response: ", json.status().ToString()))); |
| 396 |
return; |
| 397 |
} |
| 398 |
if (json->type() != Json::Type::OBJECT) { |
| 399 |
FinishTokenFetch(GRPC_ERROR_CREATE( |
| 400 |
"Invalid token exchange response: JSON type is not object")); |
| 401 |
return; |
| 402 |
} |
| 403 |
auto it = json->object_value().find("access_token"); |
| 404 |
if (it == json->object_value().end() || |
| 405 |
it->second.type() != Json::Type::STRING) { |
| 406 |
FinishTokenFetch(GRPC_ERROR_CREATE(absl::StrFormat( |
| 407 |
"Missing or invalid access_token in %s.", response_body))); |
| 408 |
return; |
| 409 |
} |
| 410 |
std::string access_token = it->second.string_value(); |
| 411 |
absl::StatusOr<URI> uri = |
| 412 |
URI::Parse(options_.service_account_impersonation_url); |
| 413 |
if (!uri.ok()) { |
| 414 |
FinishTokenFetch(GRPC_ERROR_CREATE(absl::StrFormat( |
| 415 |
"Invalid service account impersonation url: %s. Error: %s", |
| 416 |
options_.service_account_impersonation_url, uri.status().ToString()))); |
| 417 |
return; |
| 418 |
} |
| 419 |
grpc_http_request request; |
| 420 |
memset(&request, 0, sizeof(grpc_http_request)); |
| 421 |
request.hdr_count = 2; |
| 422 |
grpc_http_header* headers = static_cast<grpc_http_header*>( |
| 423 |
gpr_malloc(sizeof(grpc_http_header) * request.hdr_count)); |
| 424 |
headers[0].key = gpr_strdup("Content-Type"); |
| 425 |
headers[0].value = gpr_strdup("application/x-www-form-urlencoded"); |
| 426 |
std::string str = absl::StrFormat("Bearer %s", access_token); |
| 427 |
headers[1].key = gpr_strdup("Authorization"); |
| 428 |
headers[1].value = gpr_strdup(str.c_str()); |
| 429 |
request.hdrs = headers; |
| 430 |
std::string scope = absl::StrJoin(scopes_, " "); |
| 431 |
std::string body = absl::StrFormat("scope=%s", scope); |
| 432 |
request.body = const_cast<char*>(body.c_str()); |
| 433 |
request.body_length = body.size(); |
| 434 |
grpc_http_response_destroy(&ctx_->response); |
| 435 |
ctx_->response = {}; |
| 436 |
GRPC_CLOSURE_INIT(&ctx_->closure, OnImpersenateServiceAccount, this, nullptr); |
| 437 |
// TODO(ctiller): Use the callers resource quota. |
| 438 |
GPR_ASSERT(http_request_ == nullptr); |
| 439 |
RefCountedPtr<grpc_channel_credentials> http_request_creds; |
| 440 |
if (uri->scheme() == "http") { |
| 441 |
http_request_creds = RefCountedPtr<grpc_channel_credentials>( |
| 442 |
grpc_insecure_credentials_create()); |
| 443 |
} else { |
| 444 |
http_request_creds = CreateHttpRequestSSLCredentials(); |
| 445 |
} |
| 446 |
http_request_ = HttpRequest::Post( |
| 447 |
std::move(*uri), nullptr, ctx_->pollent, &request, ctx_->deadline, |
| 448 |
&ctx_->closure, &ctx_->response, std::move(http_request_creds)); |
| 449 |
http_request_->Start(); |
| 450 |
request.body = nullptr; |
| 451 |
grpc_http_request_destroy(&request); |
| 452 |
} |
| 453 |
|
| 454 |
void ExternalAccountCredentials::OnImpersenateServiceAccount( |
| 455 |
void* arg, grpc_error_handle error) { |
| 456 |
ExternalAccountCredentials* self = |
| 457 |
static_cast<ExternalAccountCredentials*>(arg); |
| 458 |
self->OnImpersenateServiceAccountInternal(error); |
| 459 |
} |
| 460 |
|
| 461 |
void ExternalAccountCredentials::OnImpersenateServiceAccountInternal( |
| 462 |
grpc_error_handle error) { |
| 463 |
http_request_.reset(); |
| 464 |
if (!error.ok()) { |
| 465 |
FinishTokenFetch(error); |
| 466 |
return; |
| 467 |
} |
| 468 |
absl::string_view response_body(ctx_->response.body, |
| 469 |
ctx_->response.body_length); |
| 470 |
auto json = Json::Parse(response_body); |
| 471 |
if (!json.ok()) { |
| 472 |
FinishTokenFetch(GRPC_ERROR_CREATE( |
| 473 |
absl::StrCat("Invalid service account impersonation response: ", |
| 474 |
json.status().ToString()))); |
| 475 |
return; |
| 476 |
} |
| 477 |
if (json->type() != Json::Type::OBJECT) { |
| 478 |
FinishTokenFetch( |
| 479 |
GRPC_ERROR_CREATE("Invalid service account impersonation response: " |
| 480 |
"JSON type is not object")); |
| 481 |
return; |
| 482 |
} |
| 483 |
auto it = json->object_value().find("accessToken"); |
| 484 |
if (it == json->object_value().end() || |
| 485 |
it->second.type() != Json::Type::STRING) { |
| 486 |
FinishTokenFetch(GRPC_ERROR_CREATE(absl::StrFormat( |
| 487 |
"Missing or invalid accessToken in %s.", response_body))); |
| 488 |
return; |
| 489 |
} |
| 490 |
std::string access_token = it->second.string_value(); |
| 491 |
it = json->object_value().find("expireTime"); |
| 492 |
if (it == json->object_value().end() || |
| 493 |
it->second.type() != Json::Type::STRING) { |
| 494 |
FinishTokenFetch(GRPC_ERROR_CREATE(absl::StrFormat( |
| 495 |
"Missing or invalid expireTime in %s.", response_body))); |
| 496 |
return; |
| 497 |
} |
| 498 |
std::string expire_time = it->second.string_value(); |
| 499 |
absl::Time t; |
| 500 |
if (!absl::ParseTime(absl::RFC3339_full, expire_time, &t, nullptr)) { |
| 501 |
FinishTokenFetch(GRPC_ERROR_CREATE( |
| 502 |
"Invalid expire time of service account impersonation response.")); |
| 503 |
return; |
| 504 |
} |
| 505 |
int64_t expire_in = (t - absl::Now()) / absl::Seconds(1); |
| 506 |
std::string body = absl::StrFormat( |
| 507 |
"{\"access_token\":\"%s\",\"expires_in\":%d,\"token_type\":\"Bearer\"}", |
| 508 |
access_token, expire_in); |
| 509 |
metadata_req_->response = ctx_->response; |
| 510 |
metadata_req_->response.body = gpr_strdup(body.c_str()); |
| 511 |
metadata_req_->response.body_length = body.length(); |
| 512 |
metadata_req_->response.hdrs = static_cast<grpc_http_header*>( |
| 513 |
gpr_malloc(sizeof(grpc_http_header) * ctx_->response.hdr_count)); |
| 514 |
for (size_t i = 0; i < ctx_->response.hdr_count; i++) { |
| 515 |
metadata_req_->response.hdrs[i].key = |
| 516 |
gpr_strdup(ctx_->response.hdrs[i].key); |
| 517 |
metadata_req_->response.hdrs[i].value = |
| 518 |
gpr_strdup(ctx_->response.hdrs[i].value); |
| 519 |
} |
| 520 |
FinishTokenFetch(absl::OkStatus()); |
| 521 |
} |
| 522 |
|
| 523 |
void ExternalAccountCredentials::FinishTokenFetch(grpc_error_handle error) { |
| 524 |
GRPC_LOG_IF_ERROR("Fetch external account credentials access token", error); |
| 525 |
// Move object state into local variables. |
| 526 |
auto* cb = response_cb_; |
| 527 |
response_cb_ = nullptr; |
| 528 |
auto* metadata_req = metadata_req_; |
| 529 |
metadata_req_ = nullptr; |
| 530 |
auto* ctx = ctx_; |
| 531 |
ctx_ = nullptr; |
| 532 |
// Invoke the callback. |
| 533 |
cb(metadata_req, error); |
| 534 |
// Delete context. |
| 535 |
delete ctx; |
| 536 |
} |
| 537 |
|
| 538 |
} // namespace grpc_core |
| 539 |
|
| 540 |
grpc_call_credentials* grpc_external_account_credentials_create( |
| 541 |
const char* json_string, const char* scopes_string) { |
| 542 |
auto json = grpc_core::Json::Parse(json_string); |
| 543 |
if (!json.ok()) { |
| 544 |
gpr_log(GPR_ERROR, |
| 545 |
"External account credentials creation failed. Error: %s.", |
| 546 |
json.status().ToString().c_str()); |
| 547 |
return nullptr; |
| 548 |
} |
| 549 |
std::vector<std::string> scopes = absl::StrSplit(scopes_string, ','); |
| 550 |
grpc_error_handle error; |
| 551 |
auto creds = grpc_core::ExternalAccountCredentials::Create( |
| 552 |
*json, std::move(scopes), &error) |
| 553 |
.release(); |
| 554 |
if (!error.ok()) { |
| 555 |
gpr_log(GPR_ERROR, |
| 556 |
"External account credentials creation failed. Error: %s.", |
| 557 |
grpc_core::StatusToString(error).c_str()); |
| 558 |
return nullptr; |
| 559 |
} |
| 560 |
return creds; |
| 561 |
} |