Imported Upstream version 1.22.0
[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 #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"
29
30 namespace grpc_impl {
31
32 static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
33 SecureChannelCredentials::SecureChannelCredentials(
34     grpc_channel_credentials* c_creds)
35     : c_creds_(c_creds) {
36   g_gli_initializer.summon();
37 }
38
39 std::shared_ptr<grpc::Channel> SecureChannelCredentials::CreateChannelImpl(
40     const grpc::string& target, const grpc::ChannelArguments& args) {
41   return CreateChannelWithInterceptors(
42       target, args,
43       std::vector<std::unique_ptr<
44           grpc::experimental::ClientInterceptorFactoryInterface>>());
45 }
46
47 std::shared_ptr<grpc::Channel>
48 SecureChannelCredentials::CreateChannelWithInterceptors(
49     const grpc::string& target, const grpc::ChannelArguments& args,
50     std::vector<
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,
58                                  nullptr),
59       std::move(interceptor_creators));
60 }
61
62 SecureCallCredentials::SecureCallCredentials(grpc_call_credentials* c_creds)
63     : c_creds_(c_creds) {
64   g_gli_initializer.summon();
65 }
66
67 bool SecureCallCredentials::ApplyToCall(grpc_call* call) {
68   return grpc_call_set_credentials(call, c_creds_) == GRPC_CALL_OK;
69 }
70
71 namespace {
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));
77 }
78
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));
84 }
85 }  // namespace
86
87 std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials() {
88   grpc::GrpcLibraryCodegen init;  // To call grpc_init().
89   return WrapChannelCredentials(grpc_google_default_credentials_create());
90 }
91
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()};
98
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,
102       nullptr);
103   return WrapChannelCredentials(c_creds);
104 }
105
106 namespace experimental {
107
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();
116        service_account++) {
117     grpc_alts_credentials_client_options_add_target_service_account(
118         c_options, service_account->c_str());
119   }
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);
123 }
124
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));
130 }
131
132 }  // namespace experimental
133
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));
139 }
140
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) {
146     gpr_log(GPR_ERROR,
147             "Trying to create JWTCredentials with non-positive lifetime");
148     return WrapCallCredentials(nullptr);
149   }
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));
154 }
155
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));
162 }
163
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));
170 }
171
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));
179 }
180
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
189   // incremented.
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));
196   }
197   return nullptr;
198 }
199
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));
208   }
209   return nullptr;
210 }
211
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));
223 }
224
225 }  // namespace grpc_impl
226
227 namespace grpc {
228 namespace {
229 void DeleteWrapper(void* wrapper, grpc_error* ignored) {
230   MetadataCredentialsPluginWrapper* w =
231       static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
232   delete w;
233 }
234 }  // namespace
235
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)),
243                    GRPC_ERROR_NONE);
244 }
245
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) {
252   GPR_ASSERT(wrapper);
253   MetadataCredentialsPluginWrapper* w =
254       static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
255   if (!w->plugin_) {
256     *num_creds_md = 0;
257     *status = GRPC_STATUS_OK;
258     *error_details = nullptr;
259     return true;
260   }
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);
271     });
272     return 0;
273   } else {
274     // Synchronous return.
275     w->InvokePlugin(context, cb, user_data, creds_md, num_creds_md, status,
276                     error_details);
277     return 1;
278   }
279 }
280
281 namespace {
282
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);
287   }
288 }
289
290 }  // namespace
291
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;
297
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));
302
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);
310     md_entry.flags = 0;
311     md.push_back(md_entry);
312   }
313   if (creds_md != nullptr) {
314     // Synchronous return.
315     if (md.size() > GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX) {
316       *num_creds_md = 0;
317       *status_code = GRPC_STATUS_INTERNAL;
318       *error_details = gpr_strdup(
319           "blocking plugin credentials returned too many metadata keys");
320       UnrefMetadata(md);
321     } else {
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;
326         ++(*num_creds_md);
327       }
328       *status_code = static_cast<grpc_status_code>(status.error_code());
329       *error_details =
330           status.ok() ? nullptr : gpr_strdup(status.error_message().c_str());
331     }
332   } else {
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());
337     UnrefMetadata(md);
338   }
339 }
340
341 MetadataCredentialsPluginWrapper::MetadataCredentialsPluginWrapper(
342     std::unique_ptr<MetadataCredentialsPlugin> plugin)
343     : thread_pool_(CreateDefaultThreadPool()), plugin_(std::move(plugin)) {}
344
345 }  // namespace grpc