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"
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>
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"
43 static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
44 SecureChannelCredentials::SecureChannelCredentials(
45 grpc_channel_credentials* c_creds)
47 g_gli_initializer.summon();
50 std::shared_ptr<Channel> SecureChannelCredentials::CreateChannelImpl(
51 const std::string& target, const ChannelArguments& args) {
52 return CreateChannelWithInterceptors(
54 std::vector<std::unique_ptr<
55 grpc::experimental::ClientInterceptorFactoryInterface>>());
58 std::shared_ptr<Channel>
59 SecureChannelCredentials::CreateChannelWithInterceptors(
60 const std::string& target, const ChannelArguments& args,
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,
70 std::move(interceptor_creators));
73 SecureCallCredentials::SecureCallCredentials(grpc_call_credentials* c_creds)
75 g_gli_initializer.summon();
78 bool SecureCallCredentials::ApplyToCall(grpc_call* call) {
79 return grpc_call_set_credentials(call, c_creds_) == GRPC_CALL_OK;
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));
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));
98 std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials() {
99 grpc::GrpcLibraryCodegen init; // To call grpc_init().
100 return WrapChannelCredentials(
101 grpc_google_default_credentials_create(nullptr));
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()};
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,
115 return WrapChannelCredentials(c_creds);
118 namespace experimental {
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();
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.");
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.");
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.");
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.");
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.");
175 options->subject_token_type.assign(value);
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);
191 return grpc::Status();
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.");
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;
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);
212 if (sts_creds_path == nullptr) {
213 status = grpc::Status(grpc::StatusCode::NOT_FOUND,
214 "STS_CREDENTIALS environment variable not set.");
217 error = grpc_load_file(sts_creds_path, 1, &json_string);
218 if (error != GRPC_ERROR_NONE) {
220 grpc::Status(grpc::StatusCode::NOT_FOUND, grpc_error_string(error));
223 status = StsCredentialsOptionsFromJson(
224 reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(json_string)),
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();
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));
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));
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());
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);
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));
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()));
297 } // namespace experimental
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));
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) {
312 "Trying to create JWTCredentials with non-positive lifetime");
313 return WrapCallCredentials(nullptr);
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));
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));
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));
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));
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
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));
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));
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));
392 void DeleteWrapper(void* wrapper, grpc_error* /*ignored*/) {
393 MetadataCredentialsPluginWrapper* w =
394 static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
399 char* MetadataCredentialsPluginWrapper::DebugString(void* wrapper) {
401 MetadataCredentialsPluginWrapper* w =
402 static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
403 return gpr_strdup(w->plugin_->DebugString().c_str());
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),
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) {
421 MetadataCredentialsPluginWrapper* w =
422 static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
425 *status = GRPC_STATUS_OK;
426 *error_details = nullptr;
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);
442 // Synchronous return.
443 w->InvokePlugin(context, cb, user_data, creds_md, num_creds_md, status,
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);
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;
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));
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);
479 md.push_back(md_entry);
481 if (creds_md != nullptr) {
482 // Synchronous return.
483 if (md.size() > GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX) {
485 *status_code = GRPC_STATUS_INTERNAL;
486 *error_details = gpr_strdup(
487 "blocking plugin credentials returned too many metadata keys");
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;
496 *status_code = static_cast<grpc_status_code>(status.error_code());
498 status.ok() ? nullptr : gpr_strdup(status.error_message().c_str());
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());
509 MetadataCredentialsPluginWrapper::MetadataCredentialsPluginWrapper(
510 std::unique_ptr<MetadataCredentialsPlugin> plugin)
511 : thread_pool_(CreateDefaultThreadPool()), plugin_(std::move(plugin)) {}