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