Debian Codegraph @

src/core/lib/security/credentials/oauth2/oauth2_credentials.cc

raw
1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h"
22
23 #include <stdlib.h>
24 #include <string.h>
25
26 #include <algorithm>
27 #include <atomic>
28 #include <map>
29 #include <memory>
30 #include <vector>
31
32 #include "absl/status/status.h"
33 #include "absl/strings/str_cat.h"
34 #include "absl/strings/str_format.h"
35 #include "absl/strings/str_join.h"
36 #include "absl/strings/string_view.h"
37
38 #include <grpc/grpc.h>
39 #include <grpc/grpc_security.h>
40 #include <grpc/impl/codegen/gpr_slice.h>
41 #include <grpc/slice.h>
42 #include <grpc/support/alloc.h>
43 #include <grpc/support/log.h>
44 #include <grpc/support/string_util.h>
45 #include <grpc/support/time.h>
46
47 #include "src/core/lib/debug/trace.h"
48 #include "src/core/lib/gprpp/memory.h"
49 #include "src/core/lib/gprpp/ref_counted_ptr.h"
50 #include "src/core/lib/gprpp/status_helper.h"
51 #include "src/core/lib/http/httpcli_ssl_credentials.h"
52 #include "src/core/lib/iomgr/error.h"
53 #include "src/core/lib/iomgr/load_file.h"
54 #include "src/core/lib/iomgr/pollset_set.h"
55 #include "src/core/lib/json/json.h"
56 #include "src/core/lib/promise/context.h"
57 #include "src/core/lib/promise/poll.h"
58 #include "src/core/lib/promise/promise.h"
59 #include "src/core/lib/security/util/json_util.h"
60 #include "src/core/lib/surface/api_trace.h"
61 #include "src/core/lib/transport/error_utils.h"
62 #include "src/core/lib/transport/metadata_batch.h"
63 #include "src/core/lib/uri/uri_parser.h"
64
65 using grpc_core::Json;
66
67 //
68 // Auth Refresh Token.
69 //
70
71 int grpc_auth_refresh_token_is_valid(
72 const grpc_auth_refresh_token* refresh_token) {
73 return (refresh_token != nullptr) &&
74 strcmp(refresh_token->type, GRPC_AUTH_JSON_TYPE_INVALID) != 0;
75 }
76
77 grpc_auth_refresh_token grpc_auth_refresh_token_create_from_json(
78 const Json& json) {
79 grpc_auth_refresh_token result;
80 const char* prop_value;
81 int success = 0;
82 grpc_error_handle error;
83
84 memset(&result, 0, sizeof(grpc_auth_refresh_token));
85 result.type = GRPC_AUTH_JSON_TYPE_INVALID;
86 if (json.type() != Json::Type::OBJECT) {
87 gpr_log(GPR_ERROR, "Invalid json.");
88 goto end;
89 }
90
91 prop_value = grpc_json_get_string_property(json, "type", &error);
92 GRPC_LOG_IF_ERROR("Parsing refresh token", error);
93 if (prop_value == nullptr ||
94 strcmp(prop_value, GRPC_AUTH_JSON_TYPE_AUTHORIZED_USER) != 0) {
95 goto end;
96 }
97 result.type = GRPC_AUTH_JSON_TYPE_AUTHORIZED_USER;
98
99 if (!grpc_copy_json_string_property(json, "client_secret",
100 &result.client_secret) ||
101 !grpc_copy_json_string_property(json, "client_id", &result.client_id) ||
102 !grpc_copy_json_string_property(json, "refresh_token",
103 &result.refresh_token)) {
104 goto end;
105 }
106 success = 1;
107
108 end:
109 if (!success) grpc_auth_refresh_token_destruct(&result);
110 return result;
111 }
112
113 grpc_auth_refresh_token grpc_auth_refresh_token_create_from_string(
114 const char* json_string) {
115 Json json;
116 auto json_or = Json::Parse(json_string);
117 if (!json_or.ok()) {
118 gpr_log(GPR_ERROR, "JSON parsing failed: %s",
119 json_or.status().ToString().c_str());
120 } else {
121 json = std::move(*json_or);
122 }
123 return grpc_auth_refresh_token_create_from_json(json);
124 }
125
126 void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token* refresh_token) {
127 if (refresh_token == nullptr) return;
128 refresh_token->type = GRPC_AUTH_JSON_TYPE_INVALID;
129 if (refresh_token->client_id != nullptr) {
130 gpr_free(refresh_token->client_id);
131 refresh_token->client_id = nullptr;
132 }
133 if (refresh_token->client_secret != nullptr) {
134 gpr_free(refresh_token->client_secret);
135 refresh_token->client_secret = nullptr;
136 }
137 if (refresh_token->refresh_token != nullptr) {
138 gpr_free(refresh_token->refresh_token);
139 refresh_token->refresh_token = nullptr;
140 }
141 }
142
143 //
144 // Oauth2 Token Fetcher credentials.
145 //
146
147 grpc_oauth2_token_fetcher_credentials::
148 ~grpc_oauth2_token_fetcher_credentials() {
149 gpr_mu_destroy(&mu_);
150 grpc_pollset_set_destroy(grpc_polling_entity_pollset_set(&pollent_));
151 }
152
153 grpc_credentials_status
154 grpc_oauth2_token_fetcher_credentials_parse_server_response(
155 const grpc_http_response* response,
156 absl::optional<grpc_core::Slice>* token_value,
157 grpc_core::Duration* token_lifetime) {
158 char* null_terminated_body = nullptr;
159 grpc_credentials_status status = GRPC_CREDENTIALS_OK;
160
161 if (response == nullptr) {
162 gpr_log(GPR_ERROR, "Received NULL response.");
163 status = GRPC_CREDENTIALS_ERROR;
164 goto end;
165 }
166
167 if (response->body_length > 0) {
168 null_terminated_body =
169 static_cast<char*>(gpr_malloc(response->body_length + 1));
170 null_terminated_body[response->body_length] = '\0';
171 memcpy(null_terminated_body, response->body, response->body_length);
172 }
173
174 if (response->status != 200) {
175 gpr_log(GPR_ERROR, "Call to http server ended with error %d [%s].",
176 response->status,
177 null_terminated_body != nullptr ? null_terminated_body : "");
178 status = GRPC_CREDENTIALS_ERROR;
179 goto end;
180 } else {
181 const char* access_token = nullptr;
182 const char* token_type = nullptr;
183 const char* expires_in = nullptr;
184 Json::Object::const_iterator it;
185 auto json = Json::Parse(
186 null_terminated_body != nullptr ? null_terminated_body : "");
187 if (!json.ok()) {
188 gpr_log(GPR_ERROR, "Could not parse JSON from %s: %s",
189 null_terminated_body, json.status().ToString().c_str());
190 status = GRPC_CREDENTIALS_ERROR;
191 goto end;
192 }
193 if (json->type() != Json::Type::OBJECT) {
194 gpr_log(GPR_ERROR, "Response should be a JSON object");
195 status = GRPC_CREDENTIALS_ERROR;
196 goto end;
197 }
198 it = json->object_value().find("access_token");
199 if (it == json->object_value().end() ||
200 it->second.type() != Json::Type::STRING) {
201 gpr_log(GPR_ERROR, "Missing or invalid access_token in JSON.");
202 status = GRPC_CREDENTIALS_ERROR;
203 goto end;
204 }
205 access_token = it->second.string_value().c_str();
206 it = json->object_value().find("token_type");
207 if (it == json->object_value().end() ||
208 it->second.type() != Json::Type::STRING) {
209 gpr_log(GPR_ERROR, "Missing or invalid token_type in JSON.");
210 status = GRPC_CREDENTIALS_ERROR;
211 goto end;
212 }
213 token_type = it->second.string_value().c_str();
214 it = json->object_value().find("expires_in");
215 if (it == json->object_value().end() ||
216 it->second.type() != Json::Type::NUMBER) {
217 gpr_log(GPR_ERROR, "Missing or invalid expires_in in JSON.");
218 status = GRPC_CREDENTIALS_ERROR;
219 goto end;
220 }
221 expires_in = it->second.string_value().c_str();
222 *token_lifetime =
223 grpc_core::Duration::Seconds(strtol(expires_in, nullptr, 10));
224 *token_value = grpc_core::Slice::FromCopiedString(
225 absl::StrCat(token_type, " ", access_token));
226 status = GRPC_CREDENTIALS_OK;
227 }
228
229 end:
230 if (status != GRPC_CREDENTIALS_OK) *token_value = absl::nullopt;
231 gpr_free(null_terminated_body);
232 return status;
233 }
234
235 static void on_oauth2_token_fetcher_http_response(void* user_data,
236 grpc_error_handle error) {
237 GRPC_LOG_IF_ERROR("oauth_fetch", error);
238 grpc_credentials_metadata_request* r =
239 static_cast<grpc_credentials_metadata_request*>(user_data);
240 grpc_oauth2_token_fetcher_credentials* c =
241 reinterpret_cast<grpc_oauth2_token_fetcher_credentials*>(r->creds.get());
242 c->on_http_response(r, error);
243 }
244
245 void grpc_oauth2_token_fetcher_credentials::on_http_response(
246 grpc_credentials_metadata_request* r, grpc_error_handle error) {
247 absl::optional<grpc_core::Slice> access_token_value;
248 grpc_core::Duration token_lifetime;
249 grpc_credentials_status status =
250 error.ok() ? grpc_oauth2_token_fetcher_credentials_parse_server_response(
251 &r->response, &access_token_value, &token_lifetime)
252 : GRPC_CREDENTIALS_ERROR;
253 // Update cache and grab list of pending requests.
254 gpr_mu_lock(&mu_);
255 token_fetch_pending_ = false;
256 if (access_token_value.has_value()) {
257 access_token_value_ = access_token_value->Ref();
258 } else {
259 access_token_value_ = absl::nullopt;
260 }
261 token_expiration_ = status == GRPC_CREDENTIALS_OK
262 ? gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
263 token_lifetime.as_timespec())
264 : gpr_inf_past(GPR_CLOCK_MONOTONIC);
265 grpc_oauth2_pending_get_request_metadata* pending_request = pending_requests_;
266 pending_requests_ = nullptr;
267 gpr_mu_unlock(&mu_);
268 // Invoke callbacks for all pending requests.
269 while (pending_request != nullptr) {
270 if (status == GRPC_CREDENTIALS_OK) {
271 pending_request->md->Append(
272 GRPC_AUTHORIZATION_METADATA_KEY, access_token_value->Ref(),
273 [](absl::string_view, const grpc_core::Slice&) { abort(); });
274 pending_request->result = std::move(pending_request->md);
275 } else {
276 auto err = GRPC_ERROR_CREATE_REFERENCING(
277 "Error occurred when fetching oauth2 token.", &error, 1);
278 pending_request->result = grpc_error_to_absl_status(err);
279 }
280 pending_request->done.store(true, std::memory_order_release);
281 pending_request->waker.Wakeup();
282 grpc_polling_entity_del_from_pollset_set(
283 pending_request->pollent, grpc_polling_entity_pollset_set(&pollent_));
284 grpc_oauth2_pending_get_request_metadata* prev = pending_request;
285 pending_request = pending_request->next;
286 prev->Unref();
287 }
288 delete r;
289 }
290
291 grpc_core::ArenaPromise<absl::StatusOr<grpc_core::ClientMetadataHandle>>
292 grpc_oauth2_token_fetcher_credentials::GetRequestMetadata(
293 grpc_core::ClientMetadataHandle initial_metadata,
294 const grpc_call_credentials::GetRequestMetadataArgs*) {
295 // Check if we can use the cached token.
296 absl::optional<grpc_core::Slice> cached_access_token_value;
297 gpr_mu_lock(&mu_);
298 if (access_token_value_.has_value() &&
299 gpr_time_cmp(
300 gpr_time_sub(token_expiration_, gpr_now(GPR_CLOCK_MONOTONIC)),
301 gpr_time_from_seconds(GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS,
302 GPR_TIMESPAN)) > 0) {
303 cached_access_token_value = access_token_value_->Ref();
304 }
305 if (cached_access_token_value.has_value()) {
306 gpr_mu_unlock(&mu_);
307 initial_metadata->Append(
308 GRPC_AUTHORIZATION_METADATA_KEY, std::move(*cached_access_token_value),
309 [](absl::string_view, const grpc_core::Slice&) { abort(); });
310 return grpc_core::Immediate(std::move(initial_metadata));
311 }
312 // Couldn't get the token from the cache.
313 // Add request to pending_requests_ and start a new fetch if needed.
314 grpc_core::Duration refresh_threshold =
315 grpc_core::Duration::Seconds(GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS);
316 auto pending_request =
317 grpc_core::MakeRefCounted<grpc_oauth2_pending_get_request_metadata>();
318 pending_request->pollent = grpc_core::GetContext<grpc_polling_entity>();
319 pending_request->waker = grpc_core::Activity::current()->MakeNonOwningWaker();
320 grpc_polling_entity_add_to_pollset_set(
321 pending_request->pollent, grpc_polling_entity_pollset_set(&pollent_));
322 pending_request->next = pending_requests_;
323 pending_request->md = std::move(initial_metadata);
324 pending_requests_ = pending_request->Ref().release();
325 bool start_fetch = false;
326 if (!token_fetch_pending_) {
327 token_fetch_pending_ = true;
328 start_fetch = true;
329 }
330 gpr_mu_unlock(&mu_);
331 if (start_fetch) {
332 fetch_oauth2(new grpc_credentials_metadata_request(Ref()), &pollent_,
333 on_oauth2_token_fetcher_http_response,
334 grpc_core::Timestamp::Now() + refresh_threshold);
335 }
336 return
337 [pending_request]()
338 -> grpc_core::Poll<absl::StatusOr<grpc_core::ClientMetadataHandle>> {
339 if (!pending_request->done.load(std::memory_order_acquire)) {
340 return grpc_core::Pending{};
341 }
342 return std::move(pending_request->result);
343 };
344 }
345
346 grpc_oauth2_token_fetcher_credentials::grpc_oauth2_token_fetcher_credentials()
347 : token_expiration_(gpr_inf_past(GPR_CLOCK_MONOTONIC)),
348 pollent_(grpc_polling_entity_create_from_pollset_set(
349 grpc_pollset_set_create())) {
350 gpr_mu_init(&mu_);
351 }
352
353 std::string grpc_oauth2_token_fetcher_credentials::debug_string() {
354 return "OAuth2TokenFetcherCredentials";
355 }
356
357 grpc_core::UniqueTypeName grpc_oauth2_token_fetcher_credentials::type() const {
358 static grpc_core::UniqueTypeName::Factory kFactory("Oauth2");
359 return kFactory.Create();
360 }
361
362 //
363 // Google Compute Engine credentials.
364 //
365
366 namespace {
367
368 class grpc_compute_engine_token_fetcher_credentials
369 : public grpc_oauth2_token_fetcher_credentials {
370 public:
371 grpc_compute_engine_token_fetcher_credentials() = default;
372 ~grpc_compute_engine_token_fetcher_credentials() override = default;
373
374 protected:
375 void fetch_oauth2(grpc_credentials_metadata_request* metadata_req,
376 grpc_polling_entity* pollent,
377 grpc_iomgr_cb_func response_cb,
378 grpc_core::Timestamp deadline) override {
379 grpc_http_header header = {const_cast<char*>("Metadata-Flavor"),
380 const_cast<char*>("Google")};
381 grpc_http_request request;
382 memset(&request, 0, sizeof(grpc_http_request));
383 request.hdr_count = 1;
384 request.hdrs = &header;
385 /* TODO(ctiller): Carry the memory quota in ctx and share it with the host
386 channel. This would allow us to cancel an authentication query when under
387 extreme memory pressure. */
388 auto uri = grpc_core::URI::Create("http", GRPC_COMPUTE_ENGINE_METADATA_HOST,
389 GRPC_COMPUTE_ENGINE_METADATA_TOKEN_PATH,
390 {} /* query params */, "" /* fragment */);
391 GPR_ASSERT(uri.ok()); // params are hardcoded
392 http_request_ = grpc_core::HttpRequest::Get(
393 std::move(*uri), nullptr /* channel args */, pollent, &request,
394 deadline,
395 GRPC_CLOSURE_INIT(&http_get_cb_closure_, response_cb, metadata_req,
396 grpc_schedule_on_exec_ctx),
397 &metadata_req->response,
398 grpc_core::RefCountedPtr<grpc_channel_credentials>(
399 grpc_insecure_credentials_create()));
400 http_request_->Start();
401 }
402
403 std::string debug_string() override {
404 return absl::StrFormat(
405 "GoogleComputeEngineTokenFetcherCredentials{%s}",
406 grpc_oauth2_token_fetcher_credentials::debug_string());
407 }
408
409 private:
410 grpc_closure http_get_cb_closure_;
411 grpc_core::OrphanablePtr<grpc_core::HttpRequest> http_request_;
412 };
413
414 } // namespace
415
416 grpc_call_credentials* grpc_google_compute_engine_credentials_create(
417 void* reserved) {
418 GRPC_API_TRACE("grpc_compute_engine_credentials_create(reserved=%p)", 1,
419 (reserved));
420 GPR_ASSERT(reserved == nullptr);
421 return grpc_core::MakeRefCounted<
422 grpc_compute_engine_token_fetcher_credentials>()
423 .release();
424 }
425
426 //
427 // Google Refresh Token credentials.
428 //
429
430 grpc_google_refresh_token_credentials::
431 ~grpc_google_refresh_token_credentials() {
432 grpc_auth_refresh_token_destruct(&refresh_token_);
433 }
434
435 void grpc_google_refresh_token_credentials::fetch_oauth2(
436 grpc_credentials_metadata_request* metadata_req,
437 grpc_polling_entity* pollent, grpc_iomgr_cb_func response_cb,
438 grpc_core::Timestamp deadline) {
439 grpc_http_header header = {
440 const_cast<char*>("Content-Type"),
441 const_cast<char*>("application/x-www-form-urlencoded")};
442 grpc_http_request request;
443 std::string body = absl::StrFormat(
444 GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING, refresh_token_.client_id,
445 refresh_token_.client_secret, refresh_token_.refresh_token);
446 memset(&request, 0, sizeof(grpc_http_request));
447 request.hdr_count = 1;
448 request.hdrs = &header;
449 request.body = const_cast<char*>(body.c_str());
450 request.body_length = body.size();
451 /* TODO(ctiller): Carry the memory quota in ctx and share it with the host
452 channel. This would allow us to cancel an authentication query when under
453 extreme memory pressure. */
454 auto uri = grpc_core::URI::Create("https", GRPC_GOOGLE_OAUTH2_SERVICE_HOST,
455 GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH,
456 {} /* query params */, "" /* fragment */);
457 GPR_ASSERT(uri.ok()); // params are hardcoded
458 http_request_ = grpc_core::HttpRequest::Post(
459 std::move(*uri), nullptr /* channel args */, pollent, &request, deadline,
460 GRPC_CLOSURE_INIT(&http_post_cb_closure_, response_cb, metadata_req,
461 grpc_schedule_on_exec_ctx),
462 &metadata_req->response, grpc_core::CreateHttpRequestSSLCredentials());
463 http_request_->Start();
464 }
465
466 grpc_google_refresh_token_credentials::grpc_google_refresh_token_credentials(
467 grpc_auth_refresh_token refresh_token)
468 : refresh_token_(refresh_token) {}
469
470 grpc_core::RefCountedPtr<grpc_call_credentials>
471 grpc_refresh_token_credentials_create_from_auth_refresh_token(
472 grpc_auth_refresh_token refresh_token) {
473 if (!grpc_auth_refresh_token_is_valid(&refresh_token)) {
474 gpr_log(GPR_ERROR, "Invalid input for refresh token credentials creation");
475 return nullptr;
476 }
477 return grpc_core::MakeRefCounted<grpc_google_refresh_token_credentials>(
478 refresh_token);
479 }
480
481 std::string grpc_google_refresh_token_credentials::debug_string() {
482 return absl::StrFormat("GoogleRefreshToken{ClientID:%s,%s}",
483 refresh_token_.client_id,
484 grpc_oauth2_token_fetcher_credentials::debug_string());
485 }
486
487 grpc_core::UniqueTypeName grpc_google_refresh_token_credentials::type() const {
488 static grpc_core::UniqueTypeName::Factory kFactory("GoogleRefreshToken");
489 return kFactory.Create();
490 }
491
492 static std::string create_loggable_refresh_token(
493 grpc_auth_refresh_token* token) {
494 if (strcmp(token->type, GRPC_AUTH_JSON_TYPE_INVALID) == 0) {
495 return "<Invalid json token>";
496 }
497 return absl::StrFormat(
498 "{\n type: %s\n client_id: %s\n client_secret: "
499 "<redacted>\n refresh_token: <redacted>\n}",
500 token->type, token->client_id);
501 }
502
503 grpc_call_credentials* grpc_google_refresh_token_credentials_create(
504 const char* json_refresh_token, void* reserved) {
505 grpc_auth_refresh_token token =
506 grpc_auth_refresh_token_create_from_string(json_refresh_token);
507 if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace)) {
508 gpr_log(GPR_INFO,
509 "grpc_refresh_token_credentials_create(json_refresh_token=%s, "
510 "reserved=%p)",
511 create_loggable_refresh_token(&token).c_str(), reserved);
512 }
513 GPR_ASSERT(reserved == nullptr);
514 return grpc_refresh_token_credentials_create_from_auth_refresh_token(token)
515 .release();
516 }
517
518 //
519 // STS credentials.
520 //
521
522 namespace grpc_core {
523
524 namespace {
525
526 void MaybeAddToBody(const char* field_name, const char* field,
527 std::vector<std::string>* body) {
528 if (field == nullptr || strlen(field) == 0) return;
529 body->push_back(absl::StrFormat("&%s=%s", field_name, field));
530 }
531
532 grpc_error_handle LoadTokenFile(const char* path, gpr_slice* token) {
533 grpc_error_handle err = grpc_load_file(path, 1, token);
534 if (!err.ok()) return err;
535 if (GRPC_SLICE_LENGTH(*token) == 0) {
536 gpr_log(GPR_ERROR, "Token file %s is empty", path);
537 err = GRPC_ERROR_CREATE("Token file is empty.");
538 }
539 return err;
540 }
541
542 class StsTokenFetcherCredentials
543 : public grpc_oauth2_token_fetcher_credentials {
544 public:
545 StsTokenFetcherCredentials(URI sts_url,
546 const grpc_sts_credentials_options* options)
547 : sts_url_(std::move(sts_url)),
548 resource_(gpr_strdup(options->resource)),
549 audience_(gpr_strdup(options->audience)),
550 scope_(gpr_strdup(options->scope)),
551 requested_token_type_(gpr_strdup(options->requested_token_type)),
552 subject_token_path_(gpr_strdup(options->subject_token_path)),
553 subject_token_type_(gpr_strdup(options->subject_token_type)),
554 actor_token_path_(gpr_strdup(options->actor_token_path)),
555 actor_token_type_(gpr_strdup(options->actor_token_type)) {}
556
557 std::string debug_string() override {
558 return absl::StrFormat(
559 "StsTokenFetcherCredentials{Path:%s,Authority:%s,%s}", sts_url_.path(),
560 sts_url_.authority(),
561 grpc_oauth2_token_fetcher_credentials::debug_string());
562 }
563
564 private:
565 void fetch_oauth2(grpc_credentials_metadata_request* metadata_req,
566 grpc_polling_entity* pollent,
567 grpc_iomgr_cb_func response_cb,
568 Timestamp deadline) override {
569 grpc_http_request request;
570 memset(&request, 0, sizeof(grpc_http_request));
571 grpc_error_handle err = FillBody(&request.body, &request.body_length);
572 if (!err.ok()) {
573 response_cb(metadata_req, err);
574 return;
575 }
576 grpc_http_header header = {
577 const_cast<char*>("Content-Type"),
578 const_cast<char*>("application/x-www-form-urlencoded")};
579 request.hdr_count = 1;
580 request.hdrs = &header;
581 /* TODO(ctiller): Carry the memory quota in ctx and share it with the host
582 channel. This would allow us to cancel an authentication query when under
583 extreme memory pressure. */
584 RefCountedPtr<grpc_channel_credentials> http_request_creds;
585 if (sts_url_.scheme() == "http") {
586 http_request_creds = RefCountedPtr<grpc_channel_credentials>(
587 grpc_insecure_credentials_create());
588 } else {
589 http_request_creds = CreateHttpRequestSSLCredentials();
590 }
591 http_request_ = HttpRequest::Post(
592 sts_url_, nullptr /* channel args */, pollent, &request, deadline,
593 GRPC_CLOSURE_INIT(&http_post_cb_closure_, response_cb, metadata_req,
594 grpc_schedule_on_exec_ctx),
595 &metadata_req->response, std::move(http_request_creds));
596 http_request_->Start();
597 gpr_free(request.body);
598 }
599
600 grpc_error_handle FillBody(char** body, size_t* body_length) {
601 *body = nullptr;
602 std::vector<std::string> body_parts;
603 grpc_slice subject_token = grpc_empty_slice();
604 grpc_slice actor_token = grpc_empty_slice();
605 grpc_error_handle err;
606
607 auto cleanup = [&body, &body_length, &body_parts, &subject_token,
608 &actor_token, &err]() {
609 if (err.ok()) {
610 std::string body_str = absl::StrJoin(body_parts, "");
611 *body = gpr_strdup(body_str.c_str());
612 *body_length = body_str.size();
613 }
614 CSliceUnref(subject_token);
615 CSliceUnref(actor_token);
616 return err;
617 };
618
619 err = LoadTokenFile(subject_token_path_.get(), &subject_token);
620 if (!err.ok()) return cleanup();
621 body_parts.push_back(absl::StrFormat(
622 GRPC_STS_POST_MINIMAL_BODY_FORMAT_STRING,
623 reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(subject_token)),
624 subject_token_type_.get()));
625 MaybeAddToBody("resource", resource_.get(), &body_parts);
626 MaybeAddToBody("audience", audience_.get(), &body_parts);
627 MaybeAddToBody("scope", scope_.get(), &body_parts);
628 MaybeAddToBody("requested_token_type", requested_token_type_.get(),
629 &body_parts);
630 if ((actor_token_path_ != nullptr) && *actor_token_path_ != '\0') {
631 err = LoadTokenFile(actor_token_path_.get(), &actor_token);
632 if (!err.ok()) return cleanup();
633 MaybeAddToBody(
634 "actor_token",
635 reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(actor_token)),
636 &body_parts);
637 MaybeAddToBody("actor_token_type", actor_token_type_.get(), &body_parts);
638 }
639 return cleanup();
640 }
641
642 URI sts_url_;
643 grpc_closure http_post_cb_closure_;
644 UniquePtr<char> resource_;
645 UniquePtr<char> audience_;
646 UniquePtr<char> scope_;
647 UniquePtr<char> requested_token_type_;
648 UniquePtr<char> subject_token_path_;
649 UniquePtr<char> subject_token_type_;
650 UniquePtr<char> actor_token_path_;
651 UniquePtr<char> actor_token_type_;
652 OrphanablePtr<HttpRequest> http_request_;
653 };
654
655 } // namespace
656
657 absl::StatusOr<URI> ValidateStsCredentialsOptions(
658 const grpc_sts_credentials_options* options) {
659 std::vector<grpc_error_handle> error_list;
660 absl::StatusOr<URI> sts_url =
661 URI::Parse(options->token_exchange_service_uri == nullptr
662 ? ""
663 : options->token_exchange_service_uri);
664 if (!sts_url.ok()) {
665 error_list.push_back(GRPC_ERROR_CREATE(
666 absl::StrFormat("Invalid or missing STS endpoint URL. Error: %s",
667 sts_url.status().ToString())));
668 } else if (sts_url->scheme() != "https" && sts_url->scheme() != "http") {
669 error_list.push_back(
670 GRPC_ERROR_CREATE("Invalid URI scheme, must be https to http."));
671 }
672 if (options->subject_token_path == nullptr ||
673 strlen(options->subject_token_path) == 0) {
674 error_list.push_back(
675 GRPC_ERROR_CREATE("subject_token needs to be specified"));
676 }
677 if (options->subject_token_type == nullptr ||
678 strlen(options->subject_token_type) == 0) {
679 error_list.push_back(
680 GRPC_ERROR_CREATE("subject_token_type needs to be specified"));
681 }
682 if (error_list.empty()) {
683 return sts_url;
684 }
685 auto grpc_error_vec = GRPC_ERROR_CREATE_FROM_VECTOR(
686 "Invalid STS Credentials Options", &error_list);
687 auto retval = absl::InvalidArgumentError(StatusToString(grpc_error_vec));
688 return retval;
689 }
690
691 } // namespace grpc_core
692
693 grpc_call_credentials* grpc_sts_credentials_create(
694 const grpc_sts_credentials_options* options, void* reserved) {
695 GPR_ASSERT(reserved == nullptr);
696 absl::StatusOr<grpc_core::URI> sts_url =
697 grpc_core::ValidateStsCredentialsOptions(options);
698 if (!sts_url.ok()) {
699 gpr_log(GPR_ERROR, "STS Credentials creation failed. Error: %s.",
700 sts_url.status().ToString().c_str());
701 return nullptr;
702 }
703 return grpc_core::MakeRefCounted<grpc_core::StsTokenFetcherCredentials>(
704 std::move(*sts_url), options)
705 .release();
706 }
707
708 //
709 // Oauth2 Access Token credentials.
710 //
711
712 grpc_core::ArenaPromise<absl::StatusOr<grpc_core::ClientMetadataHandle>>
713 grpc_access_token_credentials::GetRequestMetadata(
714 grpc_core::ClientMetadataHandle initial_metadata,
715 const grpc_call_credentials::GetRequestMetadataArgs*) {
716 initial_metadata->Append(
717 GRPC_AUTHORIZATION_METADATA_KEY, access_token_value_.Ref(),
718 [](absl::string_view, const grpc_core::Slice&) { abort(); });
719 return grpc_core::Immediate(std::move(initial_metadata));
720 }
721
722 grpc_core::UniqueTypeName grpc_access_token_credentials::Type() {
723 static grpc_core::UniqueTypeName::Factory kFactory("AccessToken");
724 return kFactory.Create();
725 }
726
727 grpc_access_token_credentials::grpc_access_token_credentials(
728 const char* access_token)
729 : access_token_value_(grpc_core::Slice::FromCopiedString(
730 absl::StrCat("Bearer ", access_token))) {}
731
732 std::string grpc_access_token_credentials::debug_string() {
733 return absl::StrFormat("AccessTokenCredentials{Token:present}");
734 }
735
736 grpc_call_credentials* grpc_access_token_credentials_create(
737 const char* access_token, void* reserved) {
738 GRPC_API_TRACE(
739 "grpc_access_token_credentials_create(access_token=<redacted>, "
740 "reserved=%p)",
741 1, (reserved));
742 GPR_ASSERT(reserved == nullptr);
743 return grpc_core::MakeRefCounted<grpc_access_token_credentials>(access_token)
744 .release();
745 }