secure_credentials.cc 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. #include "src/cpp/client/secure_credentials.h"
  19. #include <grpc++/channel.h>
  20. #include <grpc++/impl/grpc_library.h>
  21. #include <grpc++/support/channel_arguments.h>
  22. #include <grpc/support/log.h>
  23. #include "src/cpp/client/create_channel_internal.h"
  24. #include "src/cpp/common/secure_auth_context.h"
  25. namespace grpc {
  26. static internal::GrpcLibraryInitializer g_gli_initializer;
  27. SecureChannelCredentials::SecureChannelCredentials(
  28. grpc_channel_credentials* c_creds)
  29. : c_creds_(c_creds) {
  30. g_gli_initializer.summon();
  31. }
  32. std::shared_ptr<grpc::Channel> SecureChannelCredentials::CreateChannel(
  33. const string& target, const grpc::ChannelArguments& args) {
  34. grpc_channel_args channel_args;
  35. args.SetChannelArgs(&channel_args);
  36. return CreateChannelInternal(
  37. args.GetSslTargetNameOverride(),
  38. grpc_secure_channel_create(c_creds_, target.c_str(), &channel_args,
  39. nullptr));
  40. }
  41. SecureCallCredentials::SecureCallCredentials(grpc_call_credentials* c_creds)
  42. : c_creds_(c_creds) {
  43. g_gli_initializer.summon();
  44. }
  45. bool SecureCallCredentials::ApplyToCall(grpc_call* call) {
  46. return grpc_call_set_credentials(call, c_creds_) == GRPC_CALL_OK;
  47. }
  48. namespace {
  49. std::shared_ptr<ChannelCredentials> WrapChannelCredentials(
  50. grpc_channel_credentials* creds) {
  51. return creds == nullptr ? nullptr : std::shared_ptr<ChannelCredentials>(
  52. new SecureChannelCredentials(creds));
  53. }
  54. std::shared_ptr<CallCredentials> WrapCallCredentials(
  55. grpc_call_credentials* creds) {
  56. return creds == nullptr ? nullptr : std::shared_ptr<CallCredentials>(
  57. new SecureCallCredentials(creds));
  58. }
  59. } // namespace
  60. std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials() {
  61. GrpcLibraryCodegen init; // To call grpc_init().
  62. return WrapChannelCredentials(grpc_google_default_credentials_create());
  63. }
  64. // Builds SSL Credentials given SSL specific options
  65. std::shared_ptr<ChannelCredentials> SslCredentials(
  66. const SslCredentialsOptions& options) {
  67. GrpcLibraryCodegen init; // To call grpc_init().
  68. grpc_ssl_pem_key_cert_pair pem_key_cert_pair = {
  69. options.pem_private_key.c_str(), options.pem_cert_chain.c_str()};
  70. grpc_channel_credentials* c_creds = grpc_ssl_credentials_create(
  71. options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(),
  72. options.pem_private_key.empty() ? nullptr : &pem_key_cert_pair, nullptr);
  73. return WrapChannelCredentials(c_creds);
  74. }
  75. // Builds credentials for use when running in GCE
  76. std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials() {
  77. GrpcLibraryCodegen init; // To call grpc_init().
  78. return WrapCallCredentials(
  79. grpc_google_compute_engine_credentials_create(nullptr));
  80. }
  81. // Builds JWT credentials.
  82. std::shared_ptr<CallCredentials> ServiceAccountJWTAccessCredentials(
  83. const grpc::string& json_key, long token_lifetime_seconds) {
  84. GrpcLibraryCodegen init; // To call grpc_init().
  85. if (token_lifetime_seconds <= 0) {
  86. gpr_log(GPR_ERROR,
  87. "Trying to create JWTCredentials with non-positive lifetime");
  88. return WrapCallCredentials(nullptr);
  89. }
  90. gpr_timespec lifetime =
  91. gpr_time_from_seconds(token_lifetime_seconds, GPR_TIMESPAN);
  92. return WrapCallCredentials(grpc_service_account_jwt_access_credentials_create(
  93. json_key.c_str(), lifetime, nullptr));
  94. }
  95. // Builds refresh token credentials.
  96. std::shared_ptr<CallCredentials> GoogleRefreshTokenCredentials(
  97. const grpc::string& json_refresh_token) {
  98. GrpcLibraryCodegen init; // To call grpc_init().
  99. return WrapCallCredentials(grpc_google_refresh_token_credentials_create(
  100. json_refresh_token.c_str(), nullptr));
  101. }
  102. // Builds access token credentials.
  103. std::shared_ptr<CallCredentials> AccessTokenCredentials(
  104. const grpc::string& access_token) {
  105. GrpcLibraryCodegen init; // To call grpc_init().
  106. return WrapCallCredentials(
  107. grpc_access_token_credentials_create(access_token.c_str(), nullptr));
  108. }
  109. // Builds IAM credentials.
  110. std::shared_ptr<CallCredentials> GoogleIAMCredentials(
  111. const grpc::string& authorization_token,
  112. const grpc::string& authority_selector) {
  113. GrpcLibraryCodegen init; // To call grpc_init().
  114. return WrapCallCredentials(grpc_google_iam_credentials_create(
  115. authorization_token.c_str(), authority_selector.c_str(), nullptr));
  116. }
  117. // Combines one channel credentials and one call credentials into a channel
  118. // composite credentials.
  119. std::shared_ptr<ChannelCredentials> CompositeChannelCredentials(
  120. const std::shared_ptr<ChannelCredentials>& channel_creds,
  121. const std::shared_ptr<CallCredentials>& call_creds) {
  122. // Note that we are not saving shared_ptrs to the two credentials passed in
  123. // here. This is OK because the underlying C objects (i.e., channel_creds and
  124. // call_creds) into grpc_composite_credentials_create will see their refcounts
  125. // incremented.
  126. SecureChannelCredentials* s_channel_creds =
  127. channel_creds->AsSecureCredentials();
  128. SecureCallCredentials* s_call_creds = call_creds->AsSecureCredentials();
  129. if (s_channel_creds && s_call_creds) {
  130. return WrapChannelCredentials(grpc_composite_channel_credentials_create(
  131. s_channel_creds->GetRawCreds(), s_call_creds->GetRawCreds(), nullptr));
  132. }
  133. return nullptr;
  134. }
  135. void MetadataCredentialsPluginWrapper::Destroy(void* wrapper) {
  136. if (wrapper == nullptr) return;
  137. MetadataCredentialsPluginWrapper* w =
  138. reinterpret_cast<MetadataCredentialsPluginWrapper*>(wrapper);
  139. delete w;
  140. }
  141. void MetadataCredentialsPluginWrapper::GetMetadata(
  142. void* wrapper, grpc_auth_metadata_context context,
  143. grpc_credentials_plugin_metadata_cb cb, void* user_data) {
  144. GPR_ASSERT(wrapper);
  145. MetadataCredentialsPluginWrapper* w =
  146. reinterpret_cast<MetadataCredentialsPluginWrapper*>(wrapper);
  147. if (!w->plugin_) {
  148. cb(user_data, NULL, 0, GRPC_STATUS_OK, NULL);
  149. return;
  150. }
  151. if (w->plugin_->IsBlocking()) {
  152. w->thread_pool_->Add(
  153. std::bind(&MetadataCredentialsPluginWrapper::InvokePlugin, w, context,
  154. cb, user_data));
  155. } else {
  156. w->InvokePlugin(context, cb, user_data);
  157. }
  158. }
  159. void MetadataCredentialsPluginWrapper::InvokePlugin(
  160. grpc_auth_metadata_context context, grpc_credentials_plugin_metadata_cb cb,
  161. void* user_data) {
  162. std::multimap<grpc::string, grpc::string> metadata;
  163. // const_cast is safe since the SecureAuthContext does not take owndership and
  164. // the object is passed as a const ref to plugin_->GetMetadata.
  165. SecureAuthContext cpp_channel_auth_context(
  166. const_cast<grpc_auth_context*>(context.channel_auth_context), false);
  167. Status status = plugin_->GetMetadata(context.service_url, context.method_name,
  168. cpp_channel_auth_context, &metadata);
  169. std::vector<grpc_metadata> md;
  170. for (auto it = metadata.begin(); it != metadata.end(); ++it) {
  171. grpc_metadata md_entry;
  172. md_entry.key = SliceFromCopiedString(it->first);
  173. md_entry.value = SliceFromCopiedString(it->second);
  174. md_entry.flags = 0;
  175. md.push_back(md_entry);
  176. }
  177. cb(user_data, md.empty() ? nullptr : &md[0], md.size(),
  178. static_cast<grpc_status_code>(status.error_code()),
  179. status.error_message().c_str());
  180. for (auto it = md.begin(); it != md.end(); ++it) {
  181. grpc_slice_unref(it->key);
  182. grpc_slice_unref(it->value);
  183. }
  184. }
  185. MetadataCredentialsPluginWrapper::MetadataCredentialsPluginWrapper(
  186. std::unique_ptr<MetadataCredentialsPlugin> plugin)
  187. : thread_pool_(CreateDefaultThreadPool()), plugin_(std::move(plugin)) {}
  188. std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
  189. std::unique_ptr<MetadataCredentialsPlugin> plugin) {
  190. GrpcLibraryCodegen init; // To call grpc_init().
  191. const char* type = plugin->GetType();
  192. MetadataCredentialsPluginWrapper* wrapper =
  193. new MetadataCredentialsPluginWrapper(std::move(plugin));
  194. grpc_metadata_credentials_plugin c_plugin = {
  195. MetadataCredentialsPluginWrapper::GetMetadata,
  196. MetadataCredentialsPluginWrapper::Destroy, wrapper, type};
  197. return WrapCallCredentials(
  198. grpc_metadata_credentials_create_from_plugin(c_plugin, nullptr));
  199. }
  200. } // namespace grpc