Debian Codegraph @

src/cpp/client/secure_credentials.cc

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