• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "src/cpp/client/secure_credentials.h"
20 
21 #include <grpc/impl/codegen/slice.h>
22 #include <grpc/slice.h>
23 #include <grpc/support/alloc.h>
24 #include <grpc/support/log.h>
25 #include <grpc/support/string_util.h>
26 #include <grpcpp/channel.h>
27 #include <grpcpp/impl/codegen/status.h>
28 #include <grpcpp/impl/grpc_library.h>
29 #include <grpcpp/support/channel_arguments.h>
30 
31 #include "absl/strings/str_join.h"
32 
33 // TODO(yashykt): We shouldn't be including "src/core" headers.
34 #include "src/core/lib/gpr/env.h"
35 #include "src/core/lib/iomgr/error.h"
36 #include "src/core/lib/iomgr/executor.h"
37 #include "src/core/lib/iomgr/load_file.h"
38 #include "src/core/lib/json/json.h"
39 #include "src/core/lib/security/transport/auth_filters.h"
40 #include "src/core/lib/security/util/json_util.h"
41 #include "src/cpp/client/create_channel_internal.h"
42 #include "src/cpp/common/secure_auth_context.h"
43 
44 namespace grpc {
45 
46 static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
SecureChannelCredentials(grpc_channel_credentials * c_creds)47 SecureChannelCredentials::SecureChannelCredentials(
48     grpc_channel_credentials* c_creds)
49     : c_creds_(c_creds) {
50   g_gli_initializer.summon();
51 }
52 
CreateChannelImpl(const std::string & target,const ChannelArguments & args)53 std::shared_ptr<Channel> SecureChannelCredentials::CreateChannelImpl(
54     const std::string& target, const ChannelArguments& args) {
55   return CreateChannelWithInterceptors(
56       target, args,
57       std::vector<std::unique_ptr<
58           grpc::experimental::ClientInterceptorFactoryInterface>>());
59 }
60 
61 std::shared_ptr<Channel>
CreateChannelWithInterceptors(const std::string & target,const ChannelArguments & args,std::vector<std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_creators)62 SecureChannelCredentials::CreateChannelWithInterceptors(
63     const std::string& target, const ChannelArguments& args,
64     std::vector<
65         std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
66         interceptor_creators) {
67   grpc_channel_args channel_args;
68   args.SetChannelArgs(&channel_args);
69   return ::grpc::CreateChannelInternal(
70       args.GetSslTargetNameOverride(),
71       grpc_secure_channel_create(c_creds_, target.c_str(), &channel_args,
72                                  nullptr),
73       std::move(interceptor_creators));
74 }
75 
SecureCallCredentials(grpc_call_credentials * c_creds)76 SecureCallCredentials::SecureCallCredentials(grpc_call_credentials* c_creds)
77     : c_creds_(c_creds) {
78   g_gli_initializer.summon();
79 }
80 
ApplyToCall(grpc_call * call)81 bool SecureCallCredentials::ApplyToCall(grpc_call* call) {
82   return grpc_call_set_credentials(call, c_creds_) == GRPC_CALL_OK;
83 }
84 
85 namespace internal {
86 
WrapChannelCredentials(grpc_channel_credentials * creds)87 std::shared_ptr<ChannelCredentials> WrapChannelCredentials(
88     grpc_channel_credentials* creds) {
89   return creds == nullptr ? nullptr
90                           : std::shared_ptr<ChannelCredentials>(
91                                 new SecureChannelCredentials(creds));
92 }
93 
94 }  // namespace internal
95 
96 namespace {
97 
WrapCallCredentials(grpc_call_credentials * creds)98 std::shared_ptr<CallCredentials> WrapCallCredentials(
99     grpc_call_credentials* creds) {
100   return creds == nullptr ? nullptr
101                           : std::shared_ptr<CallCredentials>(
102                                 new SecureCallCredentials(creds));
103 }
104 }  // namespace
105 
GoogleDefaultCredentials()106 std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials() {
107   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
108   return internal::WrapChannelCredentials(
109       grpc_google_default_credentials_create(nullptr));
110 }
111 
ExternalAccountCredentials(const grpc::string & json_string,const std::vector<grpc::string> & scopes)112 std::shared_ptr<CallCredentials> ExternalAccountCredentials(
113     const grpc::string& json_string, const std::vector<grpc::string>& scopes) {
114   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
115   return WrapCallCredentials(grpc_external_account_credentials_create(
116       json_string.c_str(), absl::StrJoin(scopes, ",").c_str()));
117 }
118 
119 // Builds SSL Credentials given SSL specific options
SslCredentials(const SslCredentialsOptions & options)120 std::shared_ptr<ChannelCredentials> SslCredentials(
121     const SslCredentialsOptions& options) {
122   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
123   grpc_ssl_pem_key_cert_pair pem_key_cert_pair = {
124       options.pem_private_key.c_str(), options.pem_cert_chain.c_str()};
125 
126   grpc_channel_credentials* c_creds = grpc_ssl_credentials_create(
127       options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(),
128       options.pem_private_key.empty() ? nullptr : &pem_key_cert_pair, nullptr,
129       nullptr);
130   return internal::WrapChannelCredentials(c_creds);
131 }
132 
133 namespace experimental {
134 
135 namespace {
136 
ClearStsCredentialsOptions(StsCredentialsOptions * options)137 void ClearStsCredentialsOptions(StsCredentialsOptions* options) {
138   if (options == nullptr) return;
139   options->token_exchange_service_uri.clear();
140   options->resource.clear();
141   options->audience.clear();
142   options->scope.clear();
143   options->requested_token_type.clear();
144   options->subject_token_path.clear();
145   options->subject_token_type.clear();
146   options->actor_token_path.clear();
147   options->actor_token_type.clear();
148 }
149 
150 }  // namespace
151 
152 // Builds STS credentials options from JSON.
StsCredentialsOptionsFromJson(const std::string & json_string,StsCredentialsOptions * options)153 grpc::Status StsCredentialsOptionsFromJson(const std::string& json_string,
154                                            StsCredentialsOptions* options) {
155   if (options == nullptr) {
156     return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
157                         "options cannot be nullptr.");
158   }
159   ClearStsCredentialsOptions(options);
160   grpc_error* error = GRPC_ERROR_NONE;
161   grpc_core::Json json = grpc_core::Json::Parse(json_string.c_str(), &error);
162   if (error != GRPC_ERROR_NONE ||
163       json.type() != grpc_core::Json::Type::OBJECT) {
164     GRPC_ERROR_UNREF(error);
165     return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "Invalid json.");
166   }
167 
168   // Required fields.
169   const char* value = grpc_json_get_string_property(
170       json, "token_exchange_service_uri", nullptr);
171   if (value == nullptr) {
172     ClearStsCredentialsOptions(options);
173     return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
174                         "token_exchange_service_uri must be specified.");
175   }
176   options->token_exchange_service_uri.assign(value);
177   value = grpc_json_get_string_property(json, "subject_token_path", nullptr);
178   if (value == nullptr) {
179     ClearStsCredentialsOptions(options);
180     return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
181                         "subject_token_path must be specified.");
182   }
183   options->subject_token_path.assign(value);
184   value = grpc_json_get_string_property(json, "subject_token_type", nullptr);
185   if (value == nullptr) {
186     ClearStsCredentialsOptions(options);
187     return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
188                         "subject_token_type must be specified.");
189   }
190   options->subject_token_type.assign(value);
191 
192   // Optional fields.
193   value = grpc_json_get_string_property(json, "resource", nullptr);
194   if (value != nullptr) options->resource.assign(value);
195   value = grpc_json_get_string_property(json, "audience", nullptr);
196   if (value != nullptr) options->audience.assign(value);
197   value = grpc_json_get_string_property(json, "scope", nullptr);
198   if (value != nullptr) options->scope.assign(value);
199   value = grpc_json_get_string_property(json, "requested_token_type", nullptr);
200   if (value != nullptr) options->requested_token_type.assign(value);
201   value = grpc_json_get_string_property(json, "actor_token_path", nullptr);
202   if (value != nullptr) options->actor_token_path.assign(value);
203   value = grpc_json_get_string_property(json, "actor_token_type", nullptr);
204   if (value != nullptr) options->actor_token_type.assign(value);
205 
206   return grpc::Status();
207 }
208 
209 // Builds STS credentials Options from the $STS_CREDENTIALS env var.
StsCredentialsOptionsFromEnv(StsCredentialsOptions * options)210 grpc::Status StsCredentialsOptionsFromEnv(StsCredentialsOptions* options) {
211   if (options == nullptr) {
212     return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
213                         "options cannot be nullptr.");
214   }
215   ClearStsCredentialsOptions(options);
216   grpc_slice json_string = grpc_empty_slice();
217   char* sts_creds_path = gpr_getenv("STS_CREDENTIALS");
218   grpc_error* error = GRPC_ERROR_NONE;
219   grpc::Status status;
220   auto cleanup = [&json_string, &sts_creds_path, &error, &status]() {
221     grpc_slice_unref_internal(json_string);
222     gpr_free(sts_creds_path);
223     GRPC_ERROR_UNREF(error);
224     return status;
225   };
226 
227   if (sts_creds_path == nullptr) {
228     status = grpc::Status(grpc::StatusCode::NOT_FOUND,
229                           "STS_CREDENTIALS environment variable not set.");
230     return cleanup();
231   }
232   error = grpc_load_file(sts_creds_path, 1, &json_string);
233   if (error != GRPC_ERROR_NONE) {
234     status =
235         grpc::Status(grpc::StatusCode::NOT_FOUND, grpc_error_string(error));
236     return cleanup();
237   }
238   status = StsCredentialsOptionsFromJson(
239       reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(json_string)),
240       options);
241   return cleanup();
242 }
243 
244 // C++ to Core STS Credentials options.
StsCredentialsCppToCoreOptions(const StsCredentialsOptions & options)245 grpc_sts_credentials_options StsCredentialsCppToCoreOptions(
246     const StsCredentialsOptions& options) {
247   grpc_sts_credentials_options opts;
248   memset(&opts, 0, sizeof(opts));
249   opts.token_exchange_service_uri = options.token_exchange_service_uri.c_str();
250   opts.resource = options.resource.c_str();
251   opts.audience = options.audience.c_str();
252   opts.scope = options.scope.c_str();
253   opts.requested_token_type = options.requested_token_type.c_str();
254   opts.subject_token_path = options.subject_token_path.c_str();
255   opts.subject_token_type = options.subject_token_type.c_str();
256   opts.actor_token_path = options.actor_token_path.c_str();
257   opts.actor_token_type = options.actor_token_type.c_str();
258   return opts;
259 }
260 
261 // Builds STS credentials.
StsCredentials(const StsCredentialsOptions & options)262 std::shared_ptr<CallCredentials> StsCredentials(
263     const StsCredentialsOptions& options) {
264   auto opts = StsCredentialsCppToCoreOptions(options);
265   return WrapCallCredentials(grpc_sts_credentials_create(&opts, nullptr));
266 }
267 
MetadataCredentialsFromPlugin(std::unique_ptr<MetadataCredentialsPlugin> plugin,grpc_security_level min_security_level)268 std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
269     std::unique_ptr<MetadataCredentialsPlugin> plugin,
270     grpc_security_level min_security_level) {
271   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
272   const char* type = plugin->GetType();
273   grpc::MetadataCredentialsPluginWrapper* wrapper =
274       new grpc::MetadataCredentialsPluginWrapper(std::move(plugin));
275   grpc_metadata_credentials_plugin c_plugin = {
276       grpc::MetadataCredentialsPluginWrapper::GetMetadata,
277       grpc::MetadataCredentialsPluginWrapper::DebugString,
278       grpc::MetadataCredentialsPluginWrapper::Destroy, wrapper, type};
279   return WrapCallCredentials(grpc_metadata_credentials_create_from_plugin(
280       c_plugin, min_security_level, nullptr));
281 }
282 
283 // Builds ALTS Credentials given ALTS specific options
AltsCredentials(const AltsCredentialsOptions & options)284 std::shared_ptr<ChannelCredentials> AltsCredentials(
285     const AltsCredentialsOptions& options) {
286   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
287   grpc_alts_credentials_options* c_options =
288       grpc_alts_credentials_client_options_create();
289   for (const auto& service_account : options.target_service_accounts) {
290     grpc_alts_credentials_client_options_add_target_service_account(
291         c_options, service_account.c_str());
292   }
293   grpc_channel_credentials* c_creds = grpc_alts_credentials_create(c_options);
294   grpc_alts_credentials_options_destroy(c_options);
295   return internal::WrapChannelCredentials(c_creds);
296 }
297 
298 // Builds Local Credentials
LocalCredentials(grpc_local_connect_type type)299 std::shared_ptr<ChannelCredentials> LocalCredentials(
300     grpc_local_connect_type type) {
301   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
302   return internal::WrapChannelCredentials(grpc_local_credentials_create(type));
303 }
304 
305 // Builds TLS Credentials given TLS options.
TlsCredentials(const TlsChannelCredentialsOptions & options)306 std::shared_ptr<ChannelCredentials> TlsCredentials(
307     const TlsChannelCredentialsOptions& options) {
308   return internal::WrapChannelCredentials(
309       grpc_tls_credentials_create(options.c_credentials_options()));
310 }
311 
312 }  // namespace experimental
313 
314 // Builds credentials for use when running in GCE
GoogleComputeEngineCredentials()315 std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials() {
316   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
317   return WrapCallCredentials(
318       grpc_google_compute_engine_credentials_create(nullptr));
319 }
320 
321 // Builds JWT credentials.
ServiceAccountJWTAccessCredentials(const std::string & json_key,long token_lifetime_seconds)322 std::shared_ptr<CallCredentials> ServiceAccountJWTAccessCredentials(
323     const std::string& json_key, long token_lifetime_seconds) {
324   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
325   if (token_lifetime_seconds <= 0) {
326     gpr_log(GPR_ERROR,
327             "Trying to create JWTCredentials with non-positive lifetime");
328     return WrapCallCredentials(nullptr);
329   }
330   gpr_timespec lifetime =
331       gpr_time_from_seconds(token_lifetime_seconds, GPR_TIMESPAN);
332   return WrapCallCredentials(grpc_service_account_jwt_access_credentials_create(
333       json_key.c_str(), lifetime, nullptr));
334 }
335 
336 // Builds refresh token credentials.
GoogleRefreshTokenCredentials(const std::string & json_refresh_token)337 std::shared_ptr<CallCredentials> GoogleRefreshTokenCredentials(
338     const std::string& json_refresh_token) {
339   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
340   return WrapCallCredentials(grpc_google_refresh_token_credentials_create(
341       json_refresh_token.c_str(), nullptr));
342 }
343 
344 // Builds access token credentials.
AccessTokenCredentials(const std::string & access_token)345 std::shared_ptr<CallCredentials> AccessTokenCredentials(
346     const std::string& access_token) {
347   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
348   return WrapCallCredentials(
349       grpc_access_token_credentials_create(access_token.c_str(), nullptr));
350 }
351 
352 // Builds IAM credentials.
GoogleIAMCredentials(const std::string & authorization_token,const std::string & authority_selector)353 std::shared_ptr<CallCredentials> GoogleIAMCredentials(
354     const std::string& authorization_token,
355     const std::string& authority_selector) {
356   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
357   return WrapCallCredentials(grpc_google_iam_credentials_create(
358       authorization_token.c_str(), authority_selector.c_str(), nullptr));
359 }
360 
361 // Combines one channel credentials and one call credentials into a channel
362 // composite credentials.
CompositeChannelCredentials(const std::shared_ptr<ChannelCredentials> & channel_creds,const std::shared_ptr<CallCredentials> & call_creds)363 std::shared_ptr<ChannelCredentials> CompositeChannelCredentials(
364     const std::shared_ptr<ChannelCredentials>& channel_creds,
365     const std::shared_ptr<CallCredentials>& call_creds) {
366   // Note that we are not saving shared_ptrs to the two credentials passed in
367   // here. This is OK because the underlying C objects (i.e., channel_creds and
368   // call_creds) into grpc_composite_credentials_create will see their refcounts
369   // incremented.
370   SecureChannelCredentials* s_channel_creds =
371       channel_creds->AsSecureCredentials();
372   SecureCallCredentials* s_call_creds = call_creds->AsSecureCredentials();
373   if (s_channel_creds && s_call_creds) {
374     return internal::WrapChannelCredentials(
375         grpc_composite_channel_credentials_create(
376             s_channel_creds->GetRawCreds(), s_call_creds->GetRawCreds(),
377             nullptr));
378   }
379   return nullptr;
380 }
381 
CompositeCallCredentials(const std::shared_ptr<CallCredentials> & creds1,const std::shared_ptr<CallCredentials> & creds2)382 std::shared_ptr<CallCredentials> CompositeCallCredentials(
383     const std::shared_ptr<CallCredentials>& creds1,
384     const std::shared_ptr<CallCredentials>& creds2) {
385   SecureCallCredentials* s_creds1 = creds1->AsSecureCredentials();
386   SecureCallCredentials* s_creds2 = creds2->AsSecureCredentials();
387   if (s_creds1 != nullptr && s_creds2 != nullptr) {
388     return WrapCallCredentials(grpc_composite_call_credentials_create(
389         s_creds1->GetRawCreds(), s_creds2->GetRawCreds(), nullptr));
390   }
391   return nullptr;
392 }
393 
MetadataCredentialsFromPlugin(std::unique_ptr<MetadataCredentialsPlugin> plugin)394 std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
395     std::unique_ptr<MetadataCredentialsPlugin> plugin) {
396   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
397   const char* type = plugin->GetType();
398   grpc::MetadataCredentialsPluginWrapper* wrapper =
399       new grpc::MetadataCredentialsPluginWrapper(std::move(plugin));
400   grpc_metadata_credentials_plugin c_plugin = {
401       grpc::MetadataCredentialsPluginWrapper::GetMetadata,
402       grpc::MetadataCredentialsPluginWrapper::DebugString,
403       grpc::MetadataCredentialsPluginWrapper::Destroy, wrapper, type};
404   return WrapCallCredentials(grpc_metadata_credentials_create_from_plugin(
405       c_plugin, GRPC_PRIVACY_AND_INTEGRITY, nullptr));
406 }
407 
408 namespace {
DeleteWrapper(void * wrapper,grpc_error *)409 void DeleteWrapper(void* wrapper, grpc_error* /*ignored*/) {
410   MetadataCredentialsPluginWrapper* w =
411       static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
412   delete w;
413 }
414 }  // namespace
415 
DebugString(void * wrapper)416 char* MetadataCredentialsPluginWrapper::DebugString(void* wrapper) {
417   GPR_ASSERT(wrapper);
418   MetadataCredentialsPluginWrapper* w =
419       static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
420   return gpr_strdup(w->plugin_->DebugString().c_str());
421 }
422 
Destroy(void * wrapper)423 void MetadataCredentialsPluginWrapper::Destroy(void* wrapper) {
424   if (wrapper == nullptr) return;
425   grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
426   grpc_core::ExecCtx exec_ctx;
427   grpc_core::Executor::Run(GRPC_CLOSURE_CREATE(DeleteWrapper, wrapper, nullptr),
428                            GRPC_ERROR_NONE);
429 }
430 
GetMetadata(void * wrapper,grpc_auth_metadata_context context,grpc_credentials_plugin_metadata_cb cb,void * user_data,grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],size_t * num_creds_md,grpc_status_code * status,const char ** error_details)431 int MetadataCredentialsPluginWrapper::GetMetadata(
432     void* wrapper, grpc_auth_metadata_context context,
433     grpc_credentials_plugin_metadata_cb cb, void* user_data,
434     grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
435     size_t* num_creds_md, grpc_status_code* status,
436     const char** error_details) {
437   GPR_ASSERT(wrapper);
438   MetadataCredentialsPluginWrapper* w =
439       static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
440   if (!w->plugin_) {
441     *num_creds_md = 0;
442     *status = GRPC_STATUS_OK;
443     *error_details = nullptr;
444     return 1;
445   }
446   if (w->plugin_->IsBlocking()) {
447     // The internals of context may be destroyed if GetMetadata is cancelled.
448     // Make a copy for InvokePlugin.
449     grpc_auth_metadata_context context_copy = grpc_auth_metadata_context();
450     grpc_auth_metadata_context_copy(&context, &context_copy);
451     // Asynchronous return.
452     w->thread_pool_->Add([w, context_copy, cb, user_data]() mutable {
453       w->MetadataCredentialsPluginWrapper::InvokePlugin(
454           context_copy, cb, user_data, nullptr, nullptr, nullptr, nullptr);
455       grpc_auth_metadata_context_reset(&context_copy);
456     });
457     return 0;
458   } else {
459     // Synchronous return.
460     w->InvokePlugin(context, cb, user_data, creds_md, num_creds_md, status,
461                     error_details);
462     return 1;
463   }
464 }
465 
466 namespace {
467 
UnrefMetadata(const std::vector<grpc_metadata> & md)468 void UnrefMetadata(const std::vector<grpc_metadata>& md) {
469   for (const auto& metadatum : md) {
470     grpc_slice_unref(metadatum.key);
471     grpc_slice_unref(metadatum.value);
472   }
473 }
474 
475 }  // namespace
476 
InvokePlugin(grpc_auth_metadata_context context,grpc_credentials_plugin_metadata_cb cb,void * user_data,grpc_metadata creds_md[4],size_t * num_creds_md,grpc_status_code * status_code,const char ** error_details)477 void MetadataCredentialsPluginWrapper::InvokePlugin(
478     grpc_auth_metadata_context context, grpc_credentials_plugin_metadata_cb cb,
479     void* user_data, grpc_metadata creds_md[4], size_t* num_creds_md,
480     grpc_status_code* status_code, const char** error_details) {
481   std::multimap<std::string, std::string> metadata;
482 
483   // const_cast is safe since the SecureAuthContext only inc/dec the refcount
484   // and the object is passed as a const ref to plugin_->GetMetadata.
485   SecureAuthContext cpp_channel_auth_context(
486       const_cast<grpc_auth_context*>(context.channel_auth_context));
487 
488   Status status = plugin_->GetMetadata(context.service_url, context.method_name,
489                                        cpp_channel_auth_context, &metadata);
490   std::vector<grpc_metadata> md;
491   for (auto& metadatum : metadata) {
492     grpc_metadata md_entry;
493     md_entry.key = SliceFromCopiedString(metadatum.first);
494     md_entry.value = SliceFromCopiedString(metadatum.second);
495     md_entry.flags = 0;
496     md.push_back(md_entry);
497   }
498   if (creds_md != nullptr) {
499     // Synchronous return.
500     if (md.size() > GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX) {
501       *num_creds_md = 0;
502       *status_code = GRPC_STATUS_INTERNAL;
503       *error_details = gpr_strdup(
504           "blocking plugin credentials returned too many metadata keys");
505       UnrefMetadata(md);
506     } else {
507       for (const auto& elem : md) {
508         creds_md[*num_creds_md].key = elem.key;
509         creds_md[*num_creds_md].value = elem.value;
510         creds_md[*num_creds_md].flags = elem.flags;
511         ++(*num_creds_md);
512       }
513       *status_code = static_cast<grpc_status_code>(status.error_code());
514       *error_details =
515           status.ok() ? nullptr : gpr_strdup(status.error_message().c_str());
516     }
517   } else {
518     // Asynchronous return.
519     cb(user_data, md.empty() ? nullptr : &md[0], md.size(),
520        static_cast<grpc_status_code>(status.error_code()),
521        status.error_message().c_str());
522     UnrefMetadata(md);
523   }
524 }
525 
MetadataCredentialsPluginWrapper(std::unique_ptr<MetadataCredentialsPlugin> plugin)526 MetadataCredentialsPluginWrapper::MetadataCredentialsPluginWrapper(
527     std::unique_ptr<MetadataCredentialsPlugin> plugin)
528     : thread_pool_(CreateDefaultThreadPool()), plugin_(std::move(plugin)) {}
529 
530 }  // namespace grpc
531