Imported Upstream version 1.34.0
[platform/upstream/grpc.git] / test / cpp / client / credentials_test.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 <gmock/gmock.h>
20 #include <grpc/grpc.h>
21 #include <grpc/grpc_security.h>
22 #include <grpcpp/security/credentials.h>
23 #include <grpcpp/security/server_credentials.h>
24 #include <grpcpp/security/tls_credentials_options.h>
25 #include <grpcpp/server_builder.h>
26 #include <gtest/gtest.h>
27
28 #include <memory>
29
30 #include "src/core/lib/gpr/env.h"
31 #include "src/core/lib/gpr/tmpfile.h"
32 #include "src/cpp/client/secure_credentials.h"
33 #include "src/cpp/common/tls_credentials_options_util.h"
34
35 namespace {
36
37 constexpr const char* kRootCertName = "root_cert_name";
38 constexpr const char* kRootCertContents = "root_cert_contents";
39 constexpr const char* kIdentityCertName = "identity_cert_name";
40 constexpr const char* kIdentityCertPrivateKey = "identity_private_key";
41 constexpr const char* kIdentityCertContents = "identity_cert_contents";
42
43 using ::grpc::experimental::StaticDataCertificateProvider;
44 using ::grpc::experimental::TlsServerAuthorizationCheckArg;
45 using ::grpc::experimental::TlsServerAuthorizationCheckConfig;
46 using ::grpc::experimental::TlsServerAuthorizationCheckInterface;
47
48 static void tls_server_authorization_check_callback(
49     grpc_tls_server_authorization_check_arg* arg) {
50   GPR_ASSERT(arg != nullptr);
51   std::string cb_user_data = "cb_user_data";
52   arg->cb_user_data = static_cast<void*>(gpr_strdup(cb_user_data.c_str()));
53   arg->success = 1;
54   arg->target_name = gpr_strdup("callback_target_name");
55   arg->peer_cert = gpr_strdup("callback_peer_cert");
56   arg->status = GRPC_STATUS_OK;
57   arg->error_details->set_error_details("callback_error_details");
58 }
59
60 class TestTlsServerAuthorizationCheck
61     : public TlsServerAuthorizationCheckInterface {
62   int Schedule(TlsServerAuthorizationCheckArg* arg) override {
63     GPR_ASSERT(arg != nullptr);
64     std::string cb_user_data = "cb_user_data";
65     arg->set_cb_user_data(static_cast<void*>(gpr_strdup(cb_user_data.c_str())));
66     arg->set_success(1);
67     arg->set_target_name("sync_target_name");
68     arg->set_peer_cert("sync_peer_cert");
69     arg->set_status(GRPC_STATUS_OK);
70     arg->set_error_details("sync_error_details");
71     return 1;
72   }
73
74   void Cancel(TlsServerAuthorizationCheckArg* arg) override {
75     GPR_ASSERT(arg != nullptr);
76     arg->set_status(GRPC_STATUS_PERMISSION_DENIED);
77     arg->set_error_details("cancelled");
78   }
79 };
80 }  // namespace
81
82 namespace grpc {
83 namespace testing {
84 namespace {
85
86 TEST(CredentialsTest, InvalidGoogleRefreshToken) {
87   std::shared_ptr<CallCredentials> bad1 = GoogleRefreshTokenCredentials("");
88   EXPECT_EQ(static_cast<CallCredentials*>(nullptr), bad1.get());
89 }
90
91 TEST(CredentialsTest, DefaultCredentials) {
92   auto creds = GoogleDefaultCredentials();
93 }
94
95 TEST(CredentialsTest, StsCredentialsOptionsCppToCore) {
96   grpc::experimental::StsCredentialsOptions options;
97   options.token_exchange_service_uri = "https://foo.com/exchange";
98   options.resource = "resource";
99   options.audience = "audience";
100   options.scope = "scope";
101   // options.requested_token_type explicitly not set.
102   options.subject_token_path = "/foo/bar";
103   options.subject_token_type = "nice_token_type";
104   options.actor_token_path = "/foo/baz";
105   options.actor_token_type = "even_nicer_token_type";
106   grpc_sts_credentials_options core_opts =
107       grpc::experimental::StsCredentialsCppToCoreOptions(options);
108   EXPECT_EQ(options.token_exchange_service_uri,
109             core_opts.token_exchange_service_uri);
110   EXPECT_EQ(options.resource, core_opts.resource);
111   EXPECT_EQ(options.audience, core_opts.audience);
112   EXPECT_EQ(options.scope, core_opts.scope);
113   EXPECT_EQ(options.requested_token_type, core_opts.requested_token_type);
114   EXPECT_EQ(options.subject_token_path, core_opts.subject_token_path);
115   EXPECT_EQ(options.subject_token_type, core_opts.subject_token_type);
116   EXPECT_EQ(options.actor_token_path, core_opts.actor_token_path);
117   EXPECT_EQ(options.actor_token_type, core_opts.actor_token_type);
118 }
119
120 TEST(CredentialsTest, StsCredentialsOptionsJson) {
121   const char valid_json[] = R"(
122   {
123     "token_exchange_service_uri": "https://foo/exchange",
124     "resource": "resource",
125     "audience": "audience",
126     "scope": "scope",
127     "requested_token_type": "requested_token_type",
128     "subject_token_path": "subject_token_path",
129     "subject_token_type": "subject_token_type",
130     "actor_token_path": "actor_token_path",
131     "actor_token_type": "actor_token_type"
132   })";
133   grpc::experimental::StsCredentialsOptions options;
134   EXPECT_TRUE(
135       grpc::experimental::StsCredentialsOptionsFromJson(valid_json, &options)
136           .ok());
137   EXPECT_EQ(options.token_exchange_service_uri, "https://foo/exchange");
138   EXPECT_EQ(options.resource, "resource");
139   EXPECT_EQ(options.audience, "audience");
140   EXPECT_EQ(options.scope, "scope");
141   EXPECT_EQ(options.requested_token_type, "requested_token_type");
142   EXPECT_EQ(options.subject_token_path, "subject_token_path");
143   EXPECT_EQ(options.subject_token_type, "subject_token_type");
144   EXPECT_EQ(options.actor_token_path, "actor_token_path");
145   EXPECT_EQ(options.actor_token_type, "actor_token_type");
146
147   const char minimum_valid_json[] = R"(
148   {
149     "token_exchange_service_uri": "https://foo/exchange",
150     "subject_token_path": "subject_token_path",
151     "subject_token_type": "subject_token_type"
152   })";
153   EXPECT_TRUE(grpc::experimental::StsCredentialsOptionsFromJson(
154                   minimum_valid_json, &options)
155                   .ok());
156   EXPECT_EQ(options.token_exchange_service_uri, "https://foo/exchange");
157   EXPECT_EQ(options.resource, "");
158   EXPECT_EQ(options.audience, "");
159   EXPECT_EQ(options.scope, "");
160   EXPECT_EQ(options.requested_token_type, "");
161   EXPECT_EQ(options.subject_token_path, "subject_token_path");
162   EXPECT_EQ(options.subject_token_type, "subject_token_type");
163   EXPECT_EQ(options.actor_token_path, "");
164   EXPECT_EQ(options.actor_token_type, "");
165
166   const char invalid_json[] = R"(
167   I'm not a valid JSON.
168   )";
169   EXPECT_EQ(
170       grpc::StatusCode::INVALID_ARGUMENT,
171       grpc::experimental::StsCredentialsOptionsFromJson(invalid_json, &options)
172           .error_code());
173
174   const char invalid_json_missing_subject_token_type[] = R"(
175   {
176     "token_exchange_service_uri": "https://foo/exchange",
177     "subject_token_path": "subject_token_path"
178   })";
179   auto status = grpc::experimental::StsCredentialsOptionsFromJson(
180       invalid_json_missing_subject_token_type, &options);
181   EXPECT_EQ(grpc::StatusCode::INVALID_ARGUMENT, status.error_code());
182   EXPECT_THAT(status.error_message(),
183               ::testing::HasSubstr("subject_token_type"));
184
185   const char invalid_json_missing_subject_token_path[] = R"(
186   {
187     "token_exchange_service_uri": "https://foo/exchange",
188     "subject_token_type": "subject_token_type"
189   })";
190   status = grpc::experimental::StsCredentialsOptionsFromJson(
191       invalid_json_missing_subject_token_path, &options);
192   EXPECT_EQ(grpc::StatusCode::INVALID_ARGUMENT, status.error_code());
193   EXPECT_THAT(status.error_message(),
194               ::testing::HasSubstr("subject_token_path"));
195
196   const char invalid_json_missing_token_exchange_uri[] = R"(
197   {
198     "subject_token_path": "subject_token_path",
199     "subject_token_type": "subject_token_type"
200   })";
201   status = grpc::experimental::StsCredentialsOptionsFromJson(
202       invalid_json_missing_token_exchange_uri, &options);
203   EXPECT_EQ(grpc::StatusCode::INVALID_ARGUMENT, status.error_code());
204   EXPECT_THAT(status.error_message(),
205               ::testing::HasSubstr("token_exchange_service_uri"));
206 }
207
208 TEST(CredentialsTest, StsCredentialsOptionsFromEnv) {
209   // Unset env and check expected failure.
210   gpr_unsetenv("STS_CREDENTIALS");
211   grpc::experimental::StsCredentialsOptions options;
212   auto status = grpc::experimental::StsCredentialsOptionsFromEnv(&options);
213   EXPECT_EQ(grpc::StatusCode::NOT_FOUND, status.error_code());
214
215   // Set env and check for success.
216   const char valid_json[] = R"(
217   {
218     "token_exchange_service_uri": "https://foo/exchange",
219     "subject_token_path": "subject_token_path",
220     "subject_token_type": "subject_token_type"
221   })";
222   char* creds_file_name;
223   FILE* creds_file = gpr_tmpfile("sts_creds_options", &creds_file_name);
224   ASSERT_NE(creds_file_name, nullptr);
225   ASSERT_NE(creds_file, nullptr);
226   ASSERT_EQ(sizeof(valid_json),
227             fwrite(valid_json, 1, sizeof(valid_json), creds_file));
228   fclose(creds_file);
229   gpr_setenv("STS_CREDENTIALS", creds_file_name);
230   gpr_free(creds_file_name);
231   status = grpc::experimental::StsCredentialsOptionsFromEnv(&options);
232   EXPECT_TRUE(status.ok());
233   EXPECT_EQ(options.token_exchange_service_uri, "https://foo/exchange");
234   EXPECT_EQ(options.resource, "");
235   EXPECT_EQ(options.audience, "");
236   EXPECT_EQ(options.scope, "");
237   EXPECT_EQ(options.requested_token_type, "");
238   EXPECT_EQ(options.subject_token_path, "subject_token_path");
239   EXPECT_EQ(options.subject_token_type, "subject_token_type");
240   EXPECT_EQ(options.actor_token_path, "");
241   EXPECT_EQ(options.actor_token_type, "");
242
243   // Cleanup.
244   gpr_unsetenv("STS_CREDENTIALS");
245 }
246
247 TEST(CredentialsTest, TlsServerAuthorizationCheckArgCallback) {
248   grpc_tls_server_authorization_check_arg* c_arg =
249       new grpc_tls_server_authorization_check_arg;
250   c_arg->cb = tls_server_authorization_check_callback;
251   c_arg->context = nullptr;
252   c_arg->error_details = new grpc_tls_error_details();
253   TlsServerAuthorizationCheckArg* arg =
254       new TlsServerAuthorizationCheckArg(c_arg);
255   arg->set_cb_user_data(nullptr);
256   arg->set_success(0);
257   arg->set_target_name("target_name");
258   arg->set_peer_cert("peer_cert");
259   arg->set_status(GRPC_STATUS_UNAUTHENTICATED);
260   arg->set_error_details("error_details");
261   const char* target_name_before_callback = c_arg->target_name;
262   const char* peer_cert_before_callback = c_arg->peer_cert;
263
264   arg->OnServerAuthorizationCheckDoneCallback();
265   EXPECT_STREQ(static_cast<char*>(arg->cb_user_data()), "cb_user_data");
266   gpr_free(arg->cb_user_data());
267   EXPECT_EQ(arg->success(), 1);
268   EXPECT_STREQ(arg->target_name().c_str(), "callback_target_name");
269   EXPECT_STREQ(arg->peer_cert().c_str(), "callback_peer_cert");
270   EXPECT_EQ(arg->status(), GRPC_STATUS_OK);
271   EXPECT_STREQ(arg->error_details().c_str(), "callback_error_details");
272
273   // Cleanup.
274   gpr_free(const_cast<char*>(target_name_before_callback));
275   gpr_free(const_cast<char*>(peer_cert_before_callback));
276   gpr_free(const_cast<char*>(c_arg->target_name));
277   gpr_free(const_cast<char*>(c_arg->peer_cert));
278   delete c_arg->error_details;
279   delete arg;
280   delete c_arg;
281 }
282
283 TEST(CredentialsTest, TlsServerAuthorizationCheckConfigSchedule) {
284   std::shared_ptr<TestTlsServerAuthorizationCheck>
285       test_server_authorization_check(new TestTlsServerAuthorizationCheck());
286   TlsServerAuthorizationCheckConfig config(test_server_authorization_check);
287   grpc_tls_server_authorization_check_arg* c_arg =
288       new grpc_tls_server_authorization_check_arg();
289   c_arg->error_details = new grpc_tls_error_details();
290   c_arg->context = nullptr;
291   TlsServerAuthorizationCheckArg* arg =
292       new TlsServerAuthorizationCheckArg(c_arg);
293   arg->set_cb_user_data(nullptr);
294   arg->set_success(0);
295   arg->set_target_name("target_name");
296   arg->set_peer_cert("peer_cert");
297   arg->set_status(GRPC_STATUS_PERMISSION_DENIED);
298   arg->set_error_details("error_details");
299   const char* target_name_before_schedule = c_arg->target_name;
300   const char* peer_cert_before_schedule = c_arg->peer_cert;
301
302   int schedule_output = config.Schedule(arg);
303   EXPECT_EQ(schedule_output, 1);
304   EXPECT_STREQ(static_cast<char*>(arg->cb_user_data()), "cb_user_data");
305   EXPECT_EQ(arg->success(), 1);
306   EXPECT_STREQ(arg->target_name().c_str(), "sync_target_name");
307   EXPECT_STREQ(arg->peer_cert().c_str(), "sync_peer_cert");
308   EXPECT_EQ(arg->status(), GRPC_STATUS_OK);
309   EXPECT_STREQ(arg->error_details().c_str(), "sync_error_details");
310
311   // Cleanup.
312   gpr_free(arg->cb_user_data());
313   gpr_free(const_cast<char*>(target_name_before_schedule));
314   gpr_free(const_cast<char*>(peer_cert_before_schedule));
315   gpr_free(const_cast<char*>(c_arg->target_name));
316   gpr_free(const_cast<char*>(c_arg->peer_cert));
317   delete c_arg->error_details;
318   if (c_arg->destroy_context != nullptr) {
319     c_arg->destroy_context(c_arg->context);
320   }
321   delete c_arg;
322 }
323
324 TEST(CredentialsTest, TlsServerAuthorizationCheckConfigCppToC) {
325   std::shared_ptr<TestTlsServerAuthorizationCheck>
326       test_server_authorization_check(new TestTlsServerAuthorizationCheck());
327   TlsServerAuthorizationCheckConfig config(test_server_authorization_check);
328   grpc_tls_server_authorization_check_arg c_arg;
329   c_arg.cb = tls_server_authorization_check_callback;
330   c_arg.cb_user_data = nullptr;
331   c_arg.success = 0;
332   c_arg.target_name = "target_name";
333   c_arg.peer_cert = "peer_cert";
334   c_arg.status = GRPC_STATUS_UNAUTHENTICATED;
335   c_arg.error_details = new grpc_tls_error_details();
336   c_arg.error_details->set_error_details("error_details");
337   c_arg.config = config.c_config();
338   c_arg.context = nullptr;
339   int c_schedule_output = (c_arg.config)->Schedule(&c_arg);
340   EXPECT_EQ(c_schedule_output, 1);
341   EXPECT_STREQ(static_cast<char*>(c_arg.cb_user_data), "cb_user_data");
342   EXPECT_EQ(c_arg.success, 1);
343   EXPECT_STREQ(c_arg.target_name, "sync_target_name");
344   EXPECT_STREQ(c_arg.peer_cert, "sync_peer_cert");
345   EXPECT_EQ(c_arg.status, GRPC_STATUS_OK);
346   EXPECT_STREQ(c_arg.error_details->error_details().c_str(),
347                "sync_error_details");
348
349   // Cleanup.
350   gpr_free(c_arg.cb_user_data);
351   c_arg.destroy_context(c_arg.context);
352   delete c_arg.error_details;
353   gpr_free(const_cast<char*>(c_arg.target_name));
354   gpr_free(const_cast<char*>(c_arg.peer_cert));
355 }
356
357 TEST(
358     CredentialsTest,
359     TlsChannelCredentialsWithStaticDataCertificateProviderLoadingRootAndIdentity) {
360   experimental::IdentityKeyCertPair key_cert_pair;
361   key_cert_pair.private_key = kIdentityCertPrivateKey;
362   key_cert_pair.certificate_chain = kIdentityCertContents;
363   std::vector<experimental::IdentityKeyCertPair> identity_key_cert_pairs;
364   identity_key_cert_pairs.emplace_back(key_cert_pair);
365   auto certificate_provider = std::make_shared<StaticDataCertificateProvider>(
366       kRootCertContents, identity_key_cert_pairs);
367   auto test_server_authorization_check =
368       std::make_shared<TestTlsServerAuthorizationCheck>();
369   auto server_authorization_check_config =
370       std::make_shared<TlsServerAuthorizationCheckConfig>(
371           test_server_authorization_check);
372   grpc::experimental::TlsChannelCredentialsOptions options(
373       certificate_provider);
374   options.watch_root_certs();
375   options.set_root_cert_name(kRootCertName);
376   options.watch_identity_key_cert_pairs();
377   options.set_identity_cert_name(kIdentityCertName);
378   options.set_server_verification_option(GRPC_TLS_SERVER_VERIFICATION);
379   options.set_server_authorization_check_config(
380       server_authorization_check_config);
381   auto channel_credentials = grpc::experimental::TlsCredentials(options);
382   GPR_ASSERT(channel_credentials.get() != nullptr);
383 }
384
385 // ChannelCredentials should always have root credential presented.
386 // Otherwise the system root certificates will be loaded, which will cause
387 // failure in some tests under MacOS/Windows.
388 TEST(CredentialsTest,
389      TlsChannelCredentialsWithStaticDataCertificateProviderLoadingRootOnly) {
390   auto certificate_provider =
391       std::make_shared<StaticDataCertificateProvider>(kRootCertContents);
392   auto test_server_authorization_check =
393       std::make_shared<TestTlsServerAuthorizationCheck>();
394   auto server_authorization_check_config =
395       std::make_shared<TlsServerAuthorizationCheckConfig>(
396           test_server_authorization_check);
397   GPR_ASSERT(certificate_provider != nullptr);
398   GPR_ASSERT(certificate_provider->c_provider() != nullptr);
399   grpc::experimental::TlsChannelCredentialsOptions options(
400       certificate_provider);
401   options.watch_root_certs();
402   options.set_root_cert_name(kRootCertName);
403   options.set_server_verification_option(GRPC_TLS_SERVER_VERIFICATION);
404   options.set_server_authorization_check_config(
405       server_authorization_check_config);
406   auto channel_credentials = grpc::experimental::TlsCredentials(options);
407   GPR_ASSERT(channel_credentials.get() != nullptr);
408 }
409
410 TEST(CredentialsTest, TlsServerAuthorizationCheckConfigErrorMessages) {
411   std::shared_ptr<TlsServerAuthorizationCheckConfig> config(
412       new TlsServerAuthorizationCheckConfig(nullptr));
413   grpc_tls_server_authorization_check_arg* c_arg =
414       new grpc_tls_server_authorization_check_arg;
415   c_arg->error_details = new grpc_tls_error_details();
416   c_arg->context = nullptr;
417   TlsServerAuthorizationCheckArg* arg =
418       new TlsServerAuthorizationCheckArg(c_arg);
419   int schedule_output = config->Schedule(arg);
420
421   EXPECT_EQ(schedule_output, 1);
422   EXPECT_EQ(arg->status(), GRPC_STATUS_NOT_FOUND);
423   EXPECT_STREQ(
424       arg->error_details().c_str(),
425       "the interface of the server authorization check config is nullptr");
426
427   arg->set_status(GRPC_STATUS_OK);
428   config->Cancel(arg);
429   EXPECT_EQ(arg->status(), GRPC_STATUS_NOT_FOUND);
430   EXPECT_STREQ(
431       arg->error_details().c_str(),
432       "the interface of the server authorization check config is nullptr");
433
434   // Cleanup.
435   delete c_arg->error_details;
436   if (c_arg->destroy_context != nullptr) {
437     c_arg->destroy_context(c_arg->context);
438   }
439   delete c_arg;
440 }
441
442 }  // namespace
443 }  // namespace testing
444 }  // namespace grpc
445
446 int main(int argc, char** argv) {
447   ::testing::InitGoogleTest(&argc, argv);
448   int ret = RUN_ALL_TESTS();
449   return ret;
450 }