3 * Copyright 2015 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "src/cpp/client/secure_credentials.h"
20 #include <grpc/support/log.h>
21 #include <grpc/support/string_util.h>
22 #include <grpcpp/channel.h>
23 #include <grpcpp/impl/grpc_library.h>
24 #include <grpcpp/support/channel_arguments.h>
25 #include "src/core/lib/iomgr/executor.h"
26 #include "src/core/lib/security/transport/auth_filters.h"
27 #include "src/cpp/client/create_channel_internal.h"
28 #include "src/cpp/common/secure_auth_context.h"
32 static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
33 SecureChannelCredentials::SecureChannelCredentials(
34 grpc_channel_credentials* c_creds)
36 g_gli_initializer.summon();
39 std::shared_ptr<grpc::Channel> SecureChannelCredentials::CreateChannelImpl(
40 const grpc::string& target, const grpc::ChannelArguments& args) {
41 return CreateChannelWithInterceptors(
43 std::vector<std::unique_ptr<
44 grpc::experimental::ClientInterceptorFactoryInterface>>());
47 std::shared_ptr<grpc::Channel>
48 SecureChannelCredentials::CreateChannelWithInterceptors(
49 const grpc::string& target, const grpc::ChannelArguments& args,
51 std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
52 interceptor_creators) {
53 grpc_channel_args channel_args;
54 args.SetChannelArgs(&channel_args);
55 return ::grpc::CreateChannelInternal(
56 args.GetSslTargetNameOverride(),
57 grpc_secure_channel_create(c_creds_, target.c_str(), &channel_args,
59 std::move(interceptor_creators));
62 SecureCallCredentials::SecureCallCredentials(grpc_call_credentials* c_creds)
64 g_gli_initializer.summon();
67 bool SecureCallCredentials::ApplyToCall(grpc_call* call) {
68 return grpc_call_set_credentials(call, c_creds_) == GRPC_CALL_OK;
72 std::shared_ptr<ChannelCredentials> WrapChannelCredentials(
73 grpc_channel_credentials* creds) {
74 return creds == nullptr ? nullptr
75 : std::shared_ptr<ChannelCredentials>(
76 new SecureChannelCredentials(creds));
79 std::shared_ptr<CallCredentials> WrapCallCredentials(
80 grpc_call_credentials* creds) {
81 return creds == nullptr ? nullptr
82 : std::shared_ptr<CallCredentials>(
83 new SecureCallCredentials(creds));
87 std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials() {
88 grpc::GrpcLibraryCodegen init; // To call grpc_init().
89 return WrapChannelCredentials(grpc_google_default_credentials_create());
92 // Builds SSL Credentials given SSL specific options
93 std::shared_ptr<ChannelCredentials> SslCredentials(
94 const SslCredentialsOptions& options) {
95 grpc::GrpcLibraryCodegen init; // To call grpc_init().
96 grpc_ssl_pem_key_cert_pair pem_key_cert_pair = {
97 options.pem_private_key.c_str(), options.pem_cert_chain.c_str()};
99 grpc_channel_credentials* c_creds = grpc_ssl_credentials_create(
100 options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(),
101 options.pem_private_key.empty() ? nullptr : &pem_key_cert_pair, nullptr,
103 return WrapChannelCredentials(c_creds);
106 namespace experimental {
108 // Builds ALTS Credentials given ALTS specific options
109 std::shared_ptr<ChannelCredentials> AltsCredentials(
110 const AltsCredentialsOptions& options) {
111 grpc::GrpcLibraryCodegen init; // To call grpc_init().
112 grpc_alts_credentials_options* c_options =
113 grpc_alts_credentials_client_options_create();
114 for (auto service_account = options.target_service_accounts.begin();
115 service_account != options.target_service_accounts.end();
117 grpc_alts_credentials_client_options_add_target_service_account(
118 c_options, service_account->c_str());
120 grpc_channel_credentials* c_creds = grpc_alts_credentials_create(c_options);
121 grpc_alts_credentials_options_destroy(c_options);
122 return WrapChannelCredentials(c_creds);
125 // Builds Local Credentials
126 std::shared_ptr<ChannelCredentials> LocalCredentials(
127 grpc_local_connect_type type) {
128 grpc::GrpcLibraryCodegen init; // To call grpc_init().
129 return WrapChannelCredentials(grpc_local_credentials_create(type));
132 } // namespace experimental
134 // Builds credentials for use when running in GCE
135 std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials() {
136 grpc::GrpcLibraryCodegen init; // To call grpc_init().
137 return WrapCallCredentials(
138 grpc_google_compute_engine_credentials_create(nullptr));
141 // Builds JWT credentials.
142 std::shared_ptr<CallCredentials> ServiceAccountJWTAccessCredentials(
143 const grpc::string& json_key, long token_lifetime_seconds) {
144 grpc::GrpcLibraryCodegen init; // To call grpc_init().
145 if (token_lifetime_seconds <= 0) {
147 "Trying to create JWTCredentials with non-positive lifetime");
148 return WrapCallCredentials(nullptr);
150 gpr_timespec lifetime =
151 gpr_time_from_seconds(token_lifetime_seconds, GPR_TIMESPAN);
152 return WrapCallCredentials(grpc_service_account_jwt_access_credentials_create(
153 json_key.c_str(), lifetime, nullptr));
156 // Builds refresh token credentials.
157 std::shared_ptr<CallCredentials> GoogleRefreshTokenCredentials(
158 const grpc::string& json_refresh_token) {
159 grpc::GrpcLibraryCodegen init; // To call grpc_init().
160 return WrapCallCredentials(grpc_google_refresh_token_credentials_create(
161 json_refresh_token.c_str(), nullptr));
164 // Builds access token credentials.
165 std::shared_ptr<CallCredentials> AccessTokenCredentials(
166 const grpc::string& access_token) {
167 grpc::GrpcLibraryCodegen init; // To call grpc_init().
168 return WrapCallCredentials(
169 grpc_access_token_credentials_create(access_token.c_str(), nullptr));
172 // Builds IAM credentials.
173 std::shared_ptr<CallCredentials> GoogleIAMCredentials(
174 const grpc::string& authorization_token,
175 const grpc::string& authority_selector) {
176 grpc::GrpcLibraryCodegen init; // To call grpc_init().
177 return WrapCallCredentials(grpc_google_iam_credentials_create(
178 authorization_token.c_str(), authority_selector.c_str(), nullptr));
181 // Combines one channel credentials and one call credentials into a channel
182 // composite credentials.
183 std::shared_ptr<ChannelCredentials> CompositeChannelCredentials(
184 const std::shared_ptr<ChannelCredentials>& channel_creds,
185 const std::shared_ptr<CallCredentials>& call_creds) {
186 // Note that we are not saving shared_ptrs to the two credentials passed in
187 // here. This is OK because the underlying C objects (i.e., channel_creds and
188 // call_creds) into grpc_composite_credentials_create will see their refcounts
190 SecureChannelCredentials* s_channel_creds =
191 channel_creds->AsSecureCredentials();
192 SecureCallCredentials* s_call_creds = call_creds->AsSecureCredentials();
193 if (s_channel_creds && s_call_creds) {
194 return WrapChannelCredentials(grpc_composite_channel_credentials_create(
195 s_channel_creds->GetRawCreds(), s_call_creds->GetRawCreds(), nullptr));
200 std::shared_ptr<CallCredentials> CompositeCallCredentials(
201 const std::shared_ptr<CallCredentials>& creds1,
202 const std::shared_ptr<CallCredentials>& creds2) {
203 SecureCallCredentials* s_creds1 = creds1->AsSecureCredentials();
204 SecureCallCredentials* s_creds2 = creds2->AsSecureCredentials();
205 if (s_creds1 != nullptr && s_creds2 != nullptr) {
206 return WrapCallCredentials(grpc_composite_call_credentials_create(
207 s_creds1->GetRawCreds(), s_creds2->GetRawCreds(), nullptr));
212 std::shared_ptr<grpc_impl::CallCredentials> MetadataCredentialsFromPlugin(
213 std::unique_ptr<MetadataCredentialsPlugin> plugin) {
214 grpc::GrpcLibraryCodegen init; // To call grpc_init().
215 const char* type = plugin->GetType();
216 grpc::MetadataCredentialsPluginWrapper* wrapper =
217 new grpc::MetadataCredentialsPluginWrapper(std::move(plugin));
218 grpc_metadata_credentials_plugin c_plugin = {
219 grpc::MetadataCredentialsPluginWrapper::GetMetadata,
220 grpc::MetadataCredentialsPluginWrapper::Destroy, wrapper, type};
221 return WrapCallCredentials(
222 grpc_metadata_credentials_create_from_plugin(c_plugin, nullptr));
225 } // namespace grpc_impl
229 void DeleteWrapper(void* wrapper, grpc_error* ignored) {
230 MetadataCredentialsPluginWrapper* w =
231 static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
236 void MetadataCredentialsPluginWrapper::Destroy(void* wrapper) {
237 if (wrapper == nullptr) return;
238 grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
239 grpc_core::ExecCtx exec_ctx;
240 GRPC_CLOSURE_RUN(GRPC_CLOSURE_CREATE(DeleteWrapper, wrapper,
241 grpc_core::Executor::Scheduler(
242 grpc_core::ExecutorJobType::SHORT)),
246 int MetadataCredentialsPluginWrapper::GetMetadata(
247 void* wrapper, grpc_auth_metadata_context context,
248 grpc_credentials_plugin_metadata_cb cb, void* user_data,
249 grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
250 size_t* num_creds_md, grpc_status_code* status,
251 const char** error_details) {
253 MetadataCredentialsPluginWrapper* w =
254 static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
257 *status = GRPC_STATUS_OK;
258 *error_details = nullptr;
261 if (w->plugin_->IsBlocking()) {
262 // The internals of context may be destroyed if GetMetadata is cancelled.
263 // Make a copy for InvokePlugin.
264 grpc_auth_metadata_context context_copy = grpc_auth_metadata_context();
265 grpc_auth_metadata_context_copy(&context, &context_copy);
266 // Asynchronous return.
267 w->thread_pool_->Add([w, context_copy, cb, user_data]() mutable {
268 w->MetadataCredentialsPluginWrapper::InvokePlugin(
269 context_copy, cb, user_data, nullptr, nullptr, nullptr, nullptr);
270 grpc_auth_metadata_context_reset(&context_copy);
274 // Synchronous return.
275 w->InvokePlugin(context, cb, user_data, creds_md, num_creds_md, status,
283 void UnrefMetadata(const std::vector<grpc_metadata>& md) {
284 for (auto it = md.begin(); it != md.end(); ++it) {
285 grpc_slice_unref(it->key);
286 grpc_slice_unref(it->value);
292 void MetadataCredentialsPluginWrapper::InvokePlugin(
293 grpc_auth_metadata_context context, grpc_credentials_plugin_metadata_cb cb,
294 void* user_data, grpc_metadata creds_md[4], size_t* num_creds_md,
295 grpc_status_code* status_code, const char** error_details) {
296 std::multimap<grpc::string, grpc::string> metadata;
298 // const_cast is safe since the SecureAuthContext only inc/dec the refcount
299 // and the object is passed as a const ref to plugin_->GetMetadata.
300 SecureAuthContext cpp_channel_auth_context(
301 const_cast<grpc_auth_context*>(context.channel_auth_context));
303 Status status = plugin_->GetMetadata(context.service_url, context.method_name,
304 cpp_channel_auth_context, &metadata);
305 std::vector<grpc_metadata> md;
306 for (auto it = metadata.begin(); it != metadata.end(); ++it) {
307 grpc_metadata md_entry;
308 md_entry.key = SliceFromCopiedString(it->first);
309 md_entry.value = SliceFromCopiedString(it->second);
311 md.push_back(md_entry);
313 if (creds_md != nullptr) {
314 // Synchronous return.
315 if (md.size() > GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX) {
317 *status_code = GRPC_STATUS_INTERNAL;
318 *error_details = gpr_strdup(
319 "blocking plugin credentials returned too many metadata keys");
322 for (const auto& elem : md) {
323 creds_md[*num_creds_md].key = elem.key;
324 creds_md[*num_creds_md].value = elem.value;
325 creds_md[*num_creds_md].flags = elem.flags;
328 *status_code = static_cast<grpc_status_code>(status.error_code());
330 status.ok() ? nullptr : gpr_strdup(status.error_message().c_str());
333 // Asynchronous return.
334 cb(user_data, md.empty() ? nullptr : &md[0], md.size(),
335 static_cast<grpc_status_code>(status.error_code()),
336 status.error_message().c_str());
341 MetadataCredentialsPluginWrapper::MetadataCredentialsPluginWrapper(
342 std::unique_ptr<MetadataCredentialsPlugin> plugin)
343 : thread_pool_(CreateDefaultThreadPool()), plugin_(std::move(plugin)) {}