xref: /aosp_15_r20/external/grpc-grpc/test/cpp/end2end/ssl_credentials_test.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 //
2 //
3 // Copyright 2023 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 #include <memory>
19 
20 #include <gmock/gmock.h>
21 #include <gtest/gtest.h>
22 
23 #include "absl/synchronization/notification.h"
24 
25 #include <grpc/grpc_security.h>
26 #include <grpcpp/channel.h>
27 #include <grpcpp/client_context.h>
28 #include <grpcpp/create_channel.h>
29 #include <grpcpp/server.h>
30 #include <grpcpp/server_builder.h>
31 
32 #include "test/core/util/port.h"
33 #include "test/core/util/test_config.h"
34 #include "test/core/util/tls_utils.h"
35 #include "test/cpp/end2end/test_service_impl.h"
36 
37 namespace grpc {
38 namespace testing {
39 namespace {
40 
41 constexpr char kCaCertPath[] = "src/core/tsi/test_creds/ca.pem";
42 constexpr char kServerCertPath[] = "src/core/tsi/test_creds/server1.pem";
43 constexpr char kServerKeyPath[] = "src/core/tsi/test_creds/server1.key";
44 constexpr char kClientCertPath[] = "src/core/tsi/test_creds/client.pem";
45 constexpr char kClientKeyPath[] = "src/core/tsi/test_creds/client.key";
46 constexpr char kMessage[] = "Hello";
47 
48 class SslCredentialsTest : public ::testing::Test {
49  protected:
RunServer(absl::Notification * notification)50   void RunServer(absl::Notification* notification) {
51     std::string root_cert = grpc_core::testing::GetFileContents(kCaCertPath);
52     grpc::SslServerCredentialsOptions::PemKeyCertPair key_cert_pair = {
53         grpc_core::testing::GetFileContents(kServerKeyPath),
54         grpc_core::testing::GetFileContents(kServerCertPath)};
55     // TODO(gtcooke94) Parametrize this test for TLS and mTLS as well
56     grpc::SslServerCredentialsOptions ssl_options;
57     ssl_options.pem_key_cert_pairs.push_back(key_cert_pair);
58     ssl_options.pem_root_certs = root_cert;
59     ssl_options.force_client_auth = true;
60 
61     grpc::ServerBuilder builder;
62     TestServiceImpl service_;
63 
64     builder.AddListeningPort(server_addr_,
65                              grpc::SslServerCredentials(ssl_options));
66     builder.RegisterService("foo.test.google.fr", &service_);
67     server_ = builder.BuildAndStart();
68     notification->Notify();
69     server_->Wait();
70   }
71 
TearDown()72   void TearDown() override {
73     if (server_ != nullptr) {
74       server_->Shutdown();
75       server_thread_->join();
76       delete server_thread_;
77     }
78   }
79 
80   TestServiceImpl service_;
81   std::unique_ptr<Server> server_ = nullptr;
82   std::thread* server_thread_ = nullptr;
83   std::string server_addr_;
84 };
85 
DoRpc(const std::string & server_addr,const SslCredentialsOptions & ssl_options,grpc_ssl_session_cache * cache,bool expect_session_reuse)86 void DoRpc(const std::string& server_addr,
87            const SslCredentialsOptions& ssl_options,
88            grpc_ssl_session_cache* cache, bool expect_session_reuse) {
89   ChannelArguments channel_args;
90   channel_args.SetPointer(std::string(GRPC_SSL_SESSION_CACHE_ARG), cache);
91   channel_args.SetSslTargetNameOverride("foo.test.google.fr");
92 
93   std::shared_ptr<Channel> channel = grpc::CreateCustomChannel(
94       server_addr, grpc::SslCredentials(ssl_options), channel_args);
95 
96   auto stub = grpc::testing::EchoTestService::NewStub(channel);
97   grpc::testing::EchoRequest request;
98   grpc::testing::EchoResponse response;
99   request.set_message(kMessage);
100   ClientContext context;
101   context.set_deadline(grpc_timeout_seconds_to_deadline(/*time_s=*/10));
102   grpc::Status result = stub->Echo(&context, request, &response);
103   EXPECT_TRUE(result.ok());
104   if (!result.ok()) {
105     gpr_log(GPR_ERROR, "%s, %s", result.error_message().c_str(),
106             result.error_details().c_str());
107   }
108   EXPECT_EQ(response.message(), kMessage);
109   std::shared_ptr<const AuthContext> auth_context = context.auth_context();
110   std::vector<grpc::string_ref> properties =
111       auth_context->FindPropertyValues(GRPC_SSL_SESSION_REUSED_PROPERTY);
112   ASSERT_EQ(properties.size(), 1u);
113   if (expect_session_reuse) {
114     EXPECT_EQ("true", ToString(properties[0]));
115   } else {
116     EXPECT_EQ("false", ToString(properties[0]));
117   }
118 }
119 
TEST_F(SslCredentialsTest,SequentialResumption)120 TEST_F(SslCredentialsTest, SequentialResumption) {
121   server_addr_ = absl::StrCat("localhost:",
122                               std::to_string(grpc_pick_unused_port_or_die()));
123   absl::Notification notification;
124   server_thread_ = new std::thread([&]() { RunServer(&notification); });
125   notification.WaitForNotification();
126 
127   std::string root_cert = grpc_core::testing::GetFileContents(kCaCertPath);
128   std::string client_key = grpc_core::testing::GetFileContents(kClientKeyPath);
129   std::string client_cert =
130       grpc_core::testing::GetFileContents(kClientCertPath);
131   grpc::SslCredentialsOptions ssl_options;
132   ssl_options.pem_root_certs = root_cert;
133   ssl_options.pem_private_key = client_key;
134   ssl_options.pem_cert_chain = client_cert;
135 
136   grpc_ssl_session_cache* cache = grpc_ssl_session_cache_create_lru(16);
137 
138   DoRpc(server_addr_, ssl_options, cache, /*expect_session_reuse=*/false);
139   for (int i = 0; i < 10; i++) {
140     DoRpc(server_addr_, ssl_options, cache, /*expect_session_reuse=*/true);
141   }
142 
143   grpc_ssl_session_cache_destroy(cache);
144 }
145 
TEST_F(SslCredentialsTest,ConcurrentResumption)146 TEST_F(SslCredentialsTest, ConcurrentResumption) {
147   server_addr_ = absl::StrCat("localhost:",
148                               std::to_string(grpc_pick_unused_port_or_die()));
149   absl::Notification notification;
150   server_thread_ = new std::thread([&]() { RunServer(&notification); });
151   notification.WaitForNotification();
152 
153   std::string root_cert = grpc_core::testing::GetFileContents(kCaCertPath);
154   std::string client_key = grpc_core::testing::GetFileContents(kClientKeyPath);
155   std::string client_cert =
156       grpc_core::testing::GetFileContents(kClientCertPath);
157   grpc::SslCredentialsOptions ssl_options;
158   ssl_options.pem_root_certs = root_cert;
159   ssl_options.pem_private_key = client_key;
160   ssl_options.pem_cert_chain = client_cert;
161 
162   grpc_ssl_session_cache* cache = grpc_ssl_session_cache_create_lru(16);
163 
164   DoRpc(server_addr_, ssl_options, cache, /*expect_session_reuse=*/false);
165   std::vector<std::thread> threads;
166   threads.reserve(10);
167   for (int i = 0; i < 10; i++) {
168     threads.push_back(std::thread([&]() {
169       DoRpc(server_addr_, ssl_options, cache, /*expect_session_reuse=*/true);
170     }));
171   }
172   for (auto& t : threads) {
173     t.join();
174   }
175 
176   grpc_ssl_session_cache_destroy(cache);
177 }
178 
TEST_F(SslCredentialsTest,ResumptionFailsDueToNoCapacityInCache)179 TEST_F(SslCredentialsTest, ResumptionFailsDueToNoCapacityInCache) {
180   server_addr_ = absl::StrCat("localhost:",
181                               std::to_string(grpc_pick_unused_port_or_die()));
182   absl::Notification notification;
183   server_thread_ = new std::thread([&]() { RunServer(&notification); });
184   notification.WaitForNotification();
185 
186   std::string root_cert = grpc_core::testing::GetFileContents(kCaCertPath);
187   std::string client_key = grpc_core::testing::GetFileContents(kClientKeyPath);
188   std::string client_cert =
189       grpc_core::testing::GetFileContents(kClientCertPath);
190   grpc::SslCredentialsOptions ssl_options;
191   ssl_options.pem_root_certs = root_cert;
192   ssl_options.pem_private_key = client_key;
193   ssl_options.pem_cert_chain = client_cert;
194 
195   grpc_ssl_session_cache* cache = grpc_ssl_session_cache_create_lru(0);
196 
197   DoRpc(server_addr_, ssl_options, cache, /*expect_session_reuse=*/false);
198   DoRpc(server_addr_, ssl_options, cache, /*expect_session_reuse=*/false);
199 
200   grpc_ssl_session_cache_destroy(cache);
201 }
202 
203 }  // namespace
204 }  // namespace testing
205 }  // namespace grpc
206 
main(int argc,char ** argv)207 int main(int argc, char** argv) {
208   grpc::testing::TestEnvironment env(&argc, argv);
209   ::testing::InitGoogleTest(&argc, argv);
210   int ret = RUN_ALL_TESTS();
211   return ret;
212 }
213