Debian Codegraph @

test/cpp/end2end/xds/xds_end2end_test.cc

raw
1 // Copyright 2017 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15
16 // TODO(roth): Split this file up into a common test framework and a set
17 // of test files that use that framework. Need to figure out the best
18 // way to split up the tests. One option would be to split it up by xDS
19 // resource type; another approach would be to have all of the "core"
20 // xDS functionality in one file and then move specific features to
21 // their own files (e.g., mTLS security, fault injection, circuit
22 // breaking, etc).
23
24 #include <deque>
25 #include <memory>
26 #include <mutex>
27 #include <numeric>
28 #include <set>
29 #include <sstream>
30 #include <string>
31 #include <thread>
32 #include <vector>
33
34 #include <gmock/gmock.h>
35 #include <gtest/gtest.h>
36
37 #include "absl/functional/bind_front.h"
38 #include "absl/memory/memory.h"
39 #include "absl/strings/match.h"
40 #include "absl/strings/str_cat.h"
41 #include "absl/strings/str_format.h"
42 #include "absl/strings/str_join.h"
43 #include "absl/strings/str_replace.h"
44 #include "absl/time/time.h"
45 #include "absl/types/optional.h"
46
47 #include <grpc/grpc.h>
48 #include <grpc/grpc_security.h>
49 #include <grpc/support/alloc.h>
50 #include <grpc/support/log.h>
51 #include <grpc/support/time.h>
52 #include <grpcpp/channel.h>
53 #include <grpcpp/client_context.h>
54 #include <grpcpp/create_channel.h>
55 #include <grpcpp/security/tls_certificate_provider.h>
56 #include <grpcpp/server.h>
57 #include <grpcpp/server_builder.h>
58 #include <grpcpp/xds_server_builder.h>
59
60 #include "src/core/ext/filters/client_channel/backup_poller.h"
61 #include "src/core/ext/filters/client_channel/lb_policy/xds/xds_channel_args.h"
62 #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
63 #include "src/core/ext/filters/http/client/http_client_filter.h"
64 #include "src/core/ext/xds/xds_api.h"
65 #include "src/core/ext/xds/xds_channel_args.h"
66 #include "src/core/ext/xds/xds_client.h"
67 #include "src/core/ext/xds/xds_listener.h"
68 #include "src/core/lib/address_utils/parse_address.h"
69 #include "src/core/lib/address_utils/sockaddr_utils.h"
70 #include "src/core/lib/channel/channel_args.h"
71 #include "src/core/lib/config/core_configuration.h"
72 #include "src/core/lib/gpr/string.h"
73 #include "src/core/lib/gpr/time_precise.h"
74 #include "src/core/lib/gpr/tmpfile.h"
75 #include "src/core/lib/gprpp/env.h"
76 #include "src/core/lib/gprpp/ref_counted_ptr.h"
77 #include "src/core/lib/gprpp/sync.h"
78 #include "src/core/lib/gprpp/time.h"
79 #include "src/core/lib/gprpp/time_util.h"
80 #include "src/core/lib/iomgr/load_file.h"
81 #include "src/core/lib/iomgr/sockaddr.h"
82 #include "src/core/lib/resolver/server_address.h"
83 #include "src/core/lib/security/certificate_provider/certificate_provider_registry.h"
84 #include "src/core/lib/security/credentials/fake/fake_credentials.h"
85 #include "src/core/lib/security/credentials/tls/grpc_tls_certificate_provider.h"
86 #include "src/cpp/client/secure_credentials.h"
87 #include "src/cpp/server/secure_server_credentials.h"
88 #include "src/proto/grpc/testing/echo.grpc.pb.h"
89 #include "src/proto/grpc/testing/xds/v3/ads.grpc.pb.h"
90 #include "src/proto/grpc/testing/xds/v3/aggregate_cluster.grpc.pb.h"
91 #include "src/proto/grpc/testing/xds/v3/cluster.grpc.pb.h"
92 #include "src/proto/grpc/testing/xds/v3/discovery.grpc.pb.h"
93 #include "src/proto/grpc/testing/xds/v3/endpoint.grpc.pb.h"
94 #include "src/proto/grpc/testing/xds/v3/fault.grpc.pb.h"
95 #include "src/proto/grpc/testing/xds/v3/http_connection_manager.grpc.pb.h"
96 #include "src/proto/grpc/testing/xds/v3/http_filter_rbac.grpc.pb.h"
97 #include "src/proto/grpc/testing/xds/v3/listener.grpc.pb.h"
98 #include "src/proto/grpc/testing/xds/v3/lrs.grpc.pb.h"
99 #include "src/proto/grpc/testing/xds/v3/route.grpc.pb.h"
100 #include "src/proto/grpc/testing/xds/v3/router.grpc.pb.h"
101 #include "src/proto/grpc/testing/xds/v3/tls.grpc.pb.h"
102 #include "test/core/util/port.h"
103 #include "test/core/util/test_config.h"
104 #include "test/cpp/end2end/xds/xds_end2end_test_lib.h"
105 #include "test/cpp/util/test_config.h"
106 #include "test/cpp/util/tls_test_utils.h"
107
108 namespace grpc {
109 namespace testing {
110 namespace {
111
112 using ::envoy::config::listener::v3::FilterChainMatch;
113 using ::envoy::config::rbac::v3::Policy;
114 using ::envoy::config::rbac::v3::RBAC_Action_ALLOW;
115 using ::envoy::config::rbac::v3::RBAC_Action_DENY;
116 using ::envoy::config::rbac::v3::RBAC_Action_LOG;
117 using ::envoy::extensions::filters::http::rbac::v3::RBAC;
118 using ::envoy::extensions::filters::http::rbac::v3::RBACPerRoute;
119 using ::envoy::extensions::transport_sockets::tls::v3::DownstreamTlsContext;
120 using ::envoy::extensions::transport_sockets::tls::v3::UpstreamTlsContext;
121 using ::envoy::type::matcher::v3::StringMatcher;
122
123 using ::grpc::experimental::ExternalCertificateVerifier;
124 using ::grpc::experimental::IdentityKeyCertPair;
125 using ::grpc::experimental::StaticDataCertificateProvider;
126
127 constexpr char kClientCertPath[] = "src/core/tsi/test_creds/client.pem";
128 constexpr char kClientKeyPath[] = "src/core/tsi/test_creds/client.key";
129 constexpr char kBadClientCertPath[] = "src/core/tsi/test_creds/badclient.pem";
130 constexpr char kBadClientKeyPath[] = "src/core/tsi/test_creds/badclient.key";
131
132 // Based on StaticDataCertificateProvider, but provides alternate certificates
133 // if the certificate name is not empty.
134 class FakeCertificateProvider final : public grpc_tls_certificate_provider {
135 public:
136 struct CertData {
137 std::string root_certificate;
138 grpc_core::PemKeyCertPairList identity_key_cert_pairs;
139 };
140
141 using CertDataMap = std::map<std::string /*cert_name */, CertData>;
142 class CertDataMapWrapper {
143 public:
144 CertDataMap Get() {
145 grpc_core::MutexLock lock(&mu_);
146 return cert_data_map_;
147 }
148
149 void Set(CertDataMap data) {
150 grpc_core::MutexLock lock(&mu_);
151 cert_data_map_ = std::move(data);
152 }
153
154 private:
155 grpc_core::Mutex mu_;
156 CertDataMap cert_data_map_ ABSL_GUARDED_BY(mu_);
157 };
158
159 explicit FakeCertificateProvider(CertDataMap cert_data_map)
160 : distributor_(
161 grpc_core::MakeRefCounted<grpc_tls_certificate_distributor>()),
162 cert_data_map_(std::move(cert_data_map)) {
163 distributor_->SetWatchStatusCallback([this](std::string cert_name,
164 bool root_being_watched,
165 bool identity_being_watched) {
166 if (!root_being_watched && !identity_being_watched) return;
167 auto it = cert_data_map_.find(cert_name);
168 if (it == cert_data_map_.end()) {
169 grpc_error_handle error = GRPC_ERROR_CREATE(absl::StrCat(
170 "No certificates available for cert_name \"", cert_name, "\""));
171 distributor_->SetErrorForCert(cert_name, error, error);
172 } else {
173 absl::optional<std::string> root_certificate;
174 absl::optional<grpc_core::PemKeyCertPairList> pem_key_cert_pairs;
175 if (root_being_watched) {
176 root_certificate = it->second.root_certificate;
177 }
178 if (identity_being_watched) {
179 pem_key_cert_pairs = it->second.identity_key_cert_pairs;
180 }
181 distributor_->SetKeyMaterials(cert_name, std::move(root_certificate),
182 std::move(pem_key_cert_pairs));
183 }
184 });
185 }
186
187 ~FakeCertificateProvider() override {
188 distributor_->SetWatchStatusCallback(nullptr);
189 }
190
191 grpc_core::RefCountedPtr<grpc_tls_certificate_distributor> distributor()
192 const override {
193 return distributor_;
194 }
195
196 grpc_core::UniqueTypeName type() const override {
197 static grpc_core::UniqueTypeName::Factory kFactory("fake");
198 return kFactory.Create();
199 }
200
201 private:
202 int CompareImpl(const grpc_tls_certificate_provider* other) const override {
203 // TODO(yashykt): Maybe do something better here.
204 return grpc_core::QsortCompare(
205 static_cast<const grpc_tls_certificate_provider*>(this), other);
206 }
207
208 grpc_core::RefCountedPtr<grpc_tls_certificate_distributor> distributor_;
209 CertDataMap cert_data_map_;
210 };
211
212 class FakeCertificateProviderFactory
213 : public grpc_core::CertificateProviderFactory {
214 public:
215 class Config : public grpc_core::CertificateProviderFactory::Config {
216 public:
217 explicit Config(const char* name) : name_(name) {}
218
219 const char* name() const override { return name_; }
220
221 std::string ToString() const override { return "{}"; }
222
223 private:
224 const char* name_;
225 };
226
227 FakeCertificateProviderFactory(
228 const char* name,
229 FakeCertificateProvider::CertDataMapWrapper* cert_data_map)
230 : name_(name), cert_data_map_(cert_data_map) {
231 GPR_ASSERT(cert_data_map != nullptr);
232 }
233
234 const char* name() const override { return name_; }
235
236 grpc_core::RefCountedPtr<grpc_core::CertificateProviderFactory::Config>
237 CreateCertificateProviderConfig(const grpc_core::Json& /*config_json*/,
238 grpc_error_handle* /*error*/) override {
239 return grpc_core::MakeRefCounted<Config>(name_);
240 }
241
242 grpc_core::RefCountedPtr<grpc_tls_certificate_provider>
243 CreateCertificateProvider(
244 grpc_core::RefCountedPtr<grpc_core::CertificateProviderFactory::Config>
245 /*config*/) override {
246 GPR_ASSERT(cert_data_map_ != nullptr);
247 return grpc_core::MakeRefCounted<FakeCertificateProvider>(
248 cert_data_map_->Get());
249 }
250
251 private:
252 const char* name_;
253 FakeCertificateProvider::CertDataMapWrapper* cert_data_map_;
254 };
255
256 // Global variables for each provider.
257 FakeCertificateProvider::CertDataMapWrapper* g_fake1_cert_data_map = nullptr;
258 FakeCertificateProvider::CertDataMapWrapper* g_fake2_cert_data_map = nullptr;
259
260 class XdsSecurityTest : public XdsEnd2endTest {
261 protected:
262 void SetUp() override {
263 BootstrapBuilder builder = BootstrapBuilder();
264 builder.AddCertificateProviderPlugin("fake_plugin1", "fake1");
265 builder.AddCertificateProviderPlugin("fake_plugin2", "fake2");
266 std::vector<std::string> fields;
267 fields.push_back(absl::StrFormat(" \"certificate_file\": \"%s\"",
268 kClientCertPath));
269 fields.push_back(absl::StrFormat(" \"private_key_file\": \"%s\"",
270 kClientKeyPath));
271 fields.push_back(absl::StrFormat(" \"ca_certificate_file\": \"%s\"",
272 kCaCertPath));
273 builder.AddCertificateProviderPlugin("file_plugin", "file_watcher",
274 absl::StrJoin(fields, ",\n"));
275 InitClient(builder);
276 CreateAndStartBackends(2);
277 root_cert_ = ReadFile(kCaCertPath);
278 bad_root_cert_ = ReadFile(kBadClientCertPath);
279 identity_pair_ = ReadTlsIdentityPair(kClientKeyPath, kClientCertPath);
280 // TODO(yashykt): Use different client certs here instead of reusing
281 // server certs after https://github.com/grpc/grpc/pull/24876 is merged
282 fallback_identity_pair_ =
283 ReadTlsIdentityPair(kServerKeyPath, kServerCertPath);
284 bad_identity_pair_ =
285 ReadTlsIdentityPair(kBadClientKeyPath, kBadClientCertPath);
286 server_san_exact_.set_exact("*.test.google.fr");
287 server_san_prefix_.set_prefix("waterzooi.test.google");
288 server_san_suffix_.set_suffix("google.fr");
289 server_san_contains_.set_contains("google");
290 server_san_regex_.mutable_safe_regex()->mutable_google_re2();
291 server_san_regex_.mutable_safe_regex()->set_regex(
292 "(foo|waterzooi).test.google.(fr|be)");
293 bad_san_1_.set_exact("192.168.1.4");
294 bad_san_2_.set_exact("foo.test.google.in");
295 authenticated_identity_ = {"testclient"};
296 fallback_authenticated_identity_ = {"*.test.google.fr",
297 "waterzooi.test.google.be",
298 "*.test.youtube.com", "192.168.1.3"};
299 EdsResourceArgs args({
300 {"locality0", CreateEndpointsForBackends(0, 1)},
301 });
302 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
303 }
304
305 // Sends CDS updates with the new security configuration and verifies that
306 // after propagation, this new configuration is used for connections. If \a
307 // identity_instance_name and \a root_instance_name are both empty,
308 // connections are expected to use fallback credentials.
309 void UpdateAndVerifyXdsSecurityConfiguration(
310 absl::string_view root_instance_name,
311 absl::string_view root_certificate_name,
312 absl::string_view identity_instance_name,
313 absl::string_view identity_certificate_name,
314 const std::vector<StringMatcher>& san_matchers,
315 const std::vector<std::string>& expected_authenticated_identity,
316 bool test_expects_failure = false) {
317 // Change the backend and use a unique service name to use so that we know
318 // that the CDS update was applied.
319 std::string service_name = absl::StrCat(
320 "eds_service_name",
321 absl::FormatTime("%H%M%E3S", absl::Now(), absl::LocalTimeZone()));
322 backend_index_ = (backend_index_ + 1) % 2;
323 EdsResourceArgs args({
324 {"locality0",
325 CreateEndpointsForBackends(backend_index_, backend_index_ + 1)},
326 });
327 balancer_->ads_service()->SetEdsResource(
328 BuildEdsResource(args, service_name.c_str()));
329 auto cluster = default_cluster_;
330 cluster.mutable_eds_cluster_config()->set_service_name(service_name);
331 if (!identity_instance_name.empty() || !root_instance_name.empty()) {
332 auto* transport_socket = cluster.mutable_transport_socket();
333 transport_socket->set_name("envoy.transport_sockets.tls");
334 UpstreamTlsContext upstream_tls_context;
335 if (!identity_instance_name.empty()) {
336 upstream_tls_context.mutable_common_tls_context()
337 ->mutable_tls_certificate_provider_instance()
338 ->set_instance_name(std::string(identity_instance_name));
339 upstream_tls_context.mutable_common_tls_context()
340 ->mutable_tls_certificate_provider_instance()
341 ->set_certificate_name(std::string(identity_certificate_name));
342 }
343 if (!root_instance_name.empty()) {
344 upstream_tls_context.mutable_common_tls_context()
345 ->mutable_validation_context()
346 ->mutable_ca_certificate_provider_instance()
347 ->set_instance_name(std::string(root_instance_name));
348 upstream_tls_context.mutable_common_tls_context()
349 ->mutable_validation_context()
350 ->mutable_ca_certificate_provider_instance()
351 ->set_certificate_name(std::string(root_certificate_name));
352 }
353 if (!san_matchers.empty()) {
354 auto* validation_context =
355 upstream_tls_context.mutable_common_tls_context()
356 ->mutable_validation_context();
357 for (const auto& san_matcher : san_matchers) {
358 *validation_context->add_match_subject_alt_names() = san_matcher;
359 }
360 }
361 transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
362 }
363 balancer_->ads_service()->SetCdsResource(cluster);
364 // The updates might take time to have an effect, so use a retry loop.
365 if (test_expects_failure) {
366 SendRpcsUntil(
367 DEBUG_LOCATION,
368 [&](const RpcResult& result) {
369 if (result.status.ok()) {
370 gpr_log(GPR_ERROR,
371 "RPC succeeded. Failure expected. Trying again.");
372 return true;
373 }
374 EXPECT_EQ(result.status.error_code(), StatusCode::UNAVAILABLE);
375 // TODO(yashkt): Change individual test cases to expect the exact
376 // error message here.
377 return false;
378 },
379 /* timeout_ms= */ 20 * 1000, RpcOptions().set_timeout_ms(5000));
380 } else {
381 backends_[backend_index_]->backend_service()->ResetCounters();
382 SendRpcsUntil(
383 DEBUG_LOCATION,
384 [&](const RpcResult& result) {
385 // Make sure that we are hitting the correct backend.
386 // TODO(yashykt): Even if we haven't moved to the correct backend
387 // and are still using the previous update, we should still check
388 // for the status and make sure that it fits our expectations.
389 if (backends_[backend_index_]->backend_service()->request_count() ==
390 0) {
391 return true;
392 }
393 EXPECT_TRUE(result.status.ok())
394 << "code=" << result.status.error_code()
395 << " message=" << result.status.error_message();
396 // Check that the identity is as expected.
397 EXPECT_EQ(backends_[backend_index_]
398 ->backend_service()
399 ->last_peer_identity(),
400 expected_authenticated_identity);
401 return false;
402 },
403 /* timeout_ms= */ 20 * 1000, RpcOptions().set_timeout_ms(5000));
404 }
405 }
406
407 std::string root_cert_;
408 std::string bad_root_cert_;
409 grpc_core::PemKeyCertPairList identity_pair_;
410 grpc_core::PemKeyCertPairList fallback_identity_pair_;
411 grpc_core::PemKeyCertPairList bad_identity_pair_;
412 StringMatcher server_san_exact_;
413 StringMatcher server_san_prefix_;
414 StringMatcher server_san_suffix_;
415 StringMatcher server_san_contains_;
416 StringMatcher server_san_regex_;
417 StringMatcher bad_san_1_;
418 StringMatcher bad_san_2_;
419 std::vector<std::string> authenticated_identity_;
420 std::vector<std::string> fallback_authenticated_identity_;
421 int backend_index_ = 0;
422 };
423
424 TEST_P(XdsSecurityTest, TestTlsConfigurationInCombinedValidationContext) {
425 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
426 auto cluster = default_cluster_;
427 auto* transport_socket = cluster.mutable_transport_socket();
428 transport_socket->set_name("envoy.transport_sockets.tls");
429 UpstreamTlsContext upstream_tls_context;
430 upstream_tls_context.mutable_common_tls_context()
431 ->mutable_combined_validation_context()
432 ->mutable_default_validation_context()
433 ->mutable_ca_certificate_provider_instance()
434 ->set_instance_name("fake_plugin1");
435 transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
436 balancer_->ads_service()->SetCdsResource(cluster);
437 CheckRpcSendOk(DEBUG_LOCATION, 1, RpcOptions().set_timeout_ms(5000));
438 }
439
440 // TODO(yashykt): Remove this test once we stop supporting old fields
441 TEST_P(XdsSecurityTest,
442 TestTlsConfigurationInValidationContextCertificateProviderInstance) {
443 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
444 auto cluster = default_cluster_;
445 auto* transport_socket = cluster.mutable_transport_socket();
446 transport_socket->set_name("envoy.transport_sockets.tls");
447 UpstreamTlsContext upstream_tls_context;
448 upstream_tls_context.mutable_common_tls_context()
449 ->mutable_combined_validation_context()
450 ->mutable_validation_context_certificate_provider_instance()
451 ->set_instance_name("fake_plugin1");
452 transport_socket->mutable_typed_config()->PackFrom(upstream_tls_context);
453 balancer_->ads_service()->SetCdsResource(cluster);
454 CheckRpcSendOk(DEBUG_LOCATION, 1, RpcOptions().set_timeout_ms(5000));
455 }
456
457 TEST_P(XdsSecurityTest, TestMtlsConfigurationWithNoSanMatchers) {
458 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
459 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
460 "", {}, authenticated_identity_);
461 }
462
463 TEST_P(XdsSecurityTest, TestMtlsConfigurationWithExactSanMatcher) {
464 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
465 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
466 "", {server_san_exact_},
467 authenticated_identity_);
468 }
469
470 TEST_P(XdsSecurityTest, TestMtlsConfigurationWithPrefixSanMatcher) {
471 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
472 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
473 "", {server_san_prefix_},
474 authenticated_identity_);
475 }
476
477 TEST_P(XdsSecurityTest, TestMtlsConfigurationWithSuffixSanMatcher) {
478 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
479 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
480 "", {server_san_suffix_},
481 authenticated_identity_);
482 }
483
484 TEST_P(XdsSecurityTest, TestMtlsConfigurationWithContainsSanMatcher) {
485 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
486 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
487 "", {server_san_contains_},
488 authenticated_identity_);
489 }
490
491 TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRegexSanMatcher) {
492 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
493 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
494 "", {server_san_regex_},
495 authenticated_identity_);
496 }
497
498 TEST_P(XdsSecurityTest, TestMtlsConfigurationWithSanMatchersUpdate) {
499 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
500 UpdateAndVerifyXdsSecurityConfiguration(
501 "fake_plugin1", "", "fake_plugin1", "",
502 {server_san_exact_, server_san_prefix_}, authenticated_identity_);
503 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
504 "", {bad_san_1_, bad_san_2_}, {},
505 true /* failure */);
506 UpdateAndVerifyXdsSecurityConfiguration(
507 "fake_plugin1", "", "fake_plugin1", "",
508 {server_san_prefix_, server_san_regex_}, authenticated_identity_);
509 }
510
511 TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRootPluginUpdate) {
512 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
513 g_fake2_cert_data_map->Set({{"", {bad_root_cert_, bad_identity_pair_}}});
514 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
515 "", {server_san_exact_},
516 authenticated_identity_);
517 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin2" /* bad root */, "",
518 "fake_plugin1", "", {}, {},
519 true /* failure */);
520 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
521 "", {server_san_exact_},
522 authenticated_identity_);
523 }
524
525 TEST_P(XdsSecurityTest, TestMtlsConfigurationWithIdentityPluginUpdate) {
526 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
527 g_fake2_cert_data_map->Set({{"", {root_cert_, fallback_identity_pair_}}});
528 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
529 "", {server_san_exact_},
530 authenticated_identity_);
531 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin2",
532 "", {server_san_exact_},
533 fallback_authenticated_identity_);
534 }
535
536 TEST_P(XdsSecurityTest, TestMtlsConfigurationWithBothPluginsUpdated) {
537 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
538 g_fake2_cert_data_map->Set({{"", {bad_root_cert_, bad_identity_pair_}},
539 {"good", {root_cert_, fallback_identity_pair_}}});
540 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin2", "", "fake_plugin2",
541 "", {}, {}, true /* failure */);
542 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
543 "", {server_san_prefix_},
544 authenticated_identity_);
545 UpdateAndVerifyXdsSecurityConfiguration(
546 "fake_plugin2", "good", "fake_plugin2", "good", {server_san_prefix_},
547 fallback_authenticated_identity_);
548 }
549
550 TEST_P(XdsSecurityTest, TestMtlsConfigurationWithRootCertificateNameUpdate) {
551 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}},
552 {"bad", {bad_root_cert_, bad_identity_pair_}}});
553 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
554 "", {server_san_regex_},
555 authenticated_identity_);
556 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "fake_plugin1",
557 "", {server_san_regex_}, {},
558 true /* failure */);
559 }
560
561 TEST_P(XdsSecurityTest,
562 TestMtlsConfigurationWithIdentityCertificateNameUpdate) {
563 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}},
564 {"bad", {bad_root_cert_, bad_identity_pair_}}});
565 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
566 "", {server_san_exact_},
567 authenticated_identity_);
568 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
569 "bad", {server_san_exact_}, {},
570 true /* failure */);
571 }
572
573 TEST_P(XdsSecurityTest,
574 TestMtlsConfigurationWithIdentityCertificateNameUpdateGoodCerts) {
575 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}},
576 {"good", {root_cert_, fallback_identity_pair_}}});
577 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
578 "", {server_san_exact_},
579 authenticated_identity_);
580 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
581 "good", {server_san_exact_},
582 fallback_authenticated_identity_);
583 }
584
585 TEST_P(XdsSecurityTest, TestMtlsConfigurationWithBothCertificateNamesUpdated) {
586 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}},
587 {"bad", {bad_root_cert_, bad_identity_pair_}}});
588 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "fake_plugin1",
589 "bad", {server_san_prefix_}, {},
590 true /* failure */);
591 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
592 "", {server_san_prefix_},
593 authenticated_identity_);
594 }
595
596 TEST_P(XdsSecurityTest, TestTlsConfigurationWithNoSanMatchers) {
597 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
598 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "", {},
599 {} /* unauthenticated */);
600 }
601
602 TEST_P(XdsSecurityTest, TestTlsConfigurationWithSanMatchers) {
603 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
604 UpdateAndVerifyXdsSecurityConfiguration(
605 "fake_plugin1", "", "", "",
606 {server_san_exact_, server_san_prefix_, server_san_regex_},
607 {} /* unauthenticated */);
608 }
609
610 TEST_P(XdsSecurityTest, TestTlsConfigurationWithSanMatchersUpdate) {
611 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
612 UpdateAndVerifyXdsSecurityConfiguration(
613 "fake_plugin1", "", "", "", {server_san_exact_, server_san_prefix_},
614 {} /* unauthenticated */);
615 UpdateAndVerifyXdsSecurityConfiguration(
616 "fake_plugin1", "", "", "", {bad_san_1_, bad_san_2_},
617 {} /* unauthenticated */, true /* failure */);
618 UpdateAndVerifyXdsSecurityConfiguration(
619 "fake_plugin1", "", "", "", {server_san_prefix_, server_san_regex_},
620 {} /* unauthenticated */);
621 }
622
623 TEST_P(XdsSecurityTest, TestTlsConfigurationWithRootCertificateNameUpdate) {
624 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}},
625 {"bad", {bad_root_cert_, bad_identity_pair_}}});
626 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
627 {server_san_exact_},
628 {} /* unauthenticated */);
629 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "bad", "", "",
630 {server_san_exact_}, {},
631 true /* failure */);
632 }
633
634 TEST_P(XdsSecurityTest, TestTlsConfigurationWithRootPluginUpdate) {
635 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
636 g_fake2_cert_data_map->Set({{"", {bad_root_cert_, bad_identity_pair_}}});
637 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
638 {server_san_exact_},
639 {} /* unauthenticated */);
640 UpdateAndVerifyXdsSecurityConfiguration(
641 "fake_plugin2", "", "", "", {server_san_exact_}, {}, true /* failure */);
642 }
643
644 TEST_P(XdsSecurityTest, TestFallbackConfiguration) {
645 UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
646 fallback_authenticated_identity_);
647 }
648
649 TEST_P(XdsSecurityTest, TestMtlsToTls) {
650 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
651 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
652 "", {server_san_exact_},
653 authenticated_identity_);
654 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
655 {server_san_exact_},
656 {} /* unauthenticated */);
657 }
658
659 TEST_P(XdsSecurityTest, TestMtlsToFallback) {
660 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
661 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
662 "", {server_san_exact_},
663 authenticated_identity_);
664 UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
665 fallback_authenticated_identity_);
666 }
667
668 TEST_P(XdsSecurityTest, TestTlsToMtls) {
669 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
670 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
671 {server_san_exact_},
672 {} /* unauthenticated */);
673 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
674 "", {server_san_exact_},
675 authenticated_identity_);
676 }
677
678 TEST_P(XdsSecurityTest, TestTlsToFallback) {
679 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
680 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
681 {server_san_exact_},
682 {} /* unauthenticated */);
683 UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
684 fallback_authenticated_identity_);
685 }
686
687 TEST_P(XdsSecurityTest, TestFallbackToMtls) {
688 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
689 UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
690 fallback_authenticated_identity_);
691 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "fake_plugin1",
692 "", {server_san_exact_},
693 authenticated_identity_);
694 }
695
696 TEST_P(XdsSecurityTest, TestFallbackToTls) {
697 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
698 UpdateAndVerifyXdsSecurityConfiguration("", "", "", "", {},
699 fallback_authenticated_identity_);
700 UpdateAndVerifyXdsSecurityConfiguration("fake_plugin1", "", "", "",
701 {server_san_exact_},
702 {} /* unauthenticated */);
703 }
704
705 TEST_P(XdsSecurityTest, TestFileWatcherCertificateProvider) {
706 UpdateAndVerifyXdsSecurityConfiguration("file_plugin", "", "file_plugin", "",
707 {server_san_exact_},
708 authenticated_identity_);
709 }
710
711 class XdsEnabledServerTest : public XdsEnd2endTest {
712 protected:
713 void SetUp() override {} // No-op -- individual tests do this themselves.
714
715 void DoSetUp(BootstrapBuilder builder = BootstrapBuilder()) {
716 InitClient(builder);
717 CreateBackends(1, /*xds_enabled=*/true);
718 EdsResourceArgs args({{"locality0", CreateEndpointsForBackends(0, 1)}});
719 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
720 }
721 };
722
723 TEST_P(XdsEnabledServerTest, Basic) {
724 DoSetUp();
725 backends_[0]->Start();
726 WaitForBackend(DEBUG_LOCATION, 0);
727 }
728
729 TEST_P(XdsEnabledServerTest, ListenerDeletionIgnored) {
730 DoSetUp(BootstrapBuilder().SetIgnoreResourceDeletion());
731 backends_[0]->Start();
732 WaitForBackend(DEBUG_LOCATION, 0);
733 // Check that we ACKed.
734 // TODO(roth): There may be multiple entries in the resource state response
735 // queue, because the client doesn't necessarily subscribe to all resources
736 // in a single message, and the server currently (I suspect incorrectly?)
737 // thinks that each subscription message is an ACK. So for now, we
738 // drain the entire LDS resource state response queue, ensuring that
739 // all responses are ACKs. Need to look more closely at the protocol
740 // semantics here and make sure the server is doing the right thing,
741 // in which case we may be able to avoid this.
742 while (true) {
743 auto response_state = balancer_->ads_service()->lds_response_state();
744 if (!response_state.has_value()) break;
745 ASSERT_TRUE(response_state.has_value());
746 EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
747 }
748 // Now unset the resource.
749 balancer_->ads_service()->UnsetResource(
750 kLdsTypeUrl, GetServerListenerName(backends_[0]->port()));
751 // Wait for update to be ACKed.
752 absl::Time deadline =
753 absl::Now() + (absl::Seconds(10) * grpc_test_slowdown_factor());
754 while (true) {
755 auto response_state = balancer_->ads_service()->lds_response_state();
756 if (!response_state.has_value()) {
757 gpr_sleep_until(grpc_timeout_seconds_to_deadline(1));
758 continue;
759 }
760 EXPECT_EQ(response_state->state, AdsServiceImpl::ResponseState::ACKED);
761 ASSERT_LT(absl::Now(), deadline);
762 break;
763 }
764 // Make sure server is still serving.
765 CheckRpcSendOk(DEBUG_LOCATION);
766 }
767
768 // Testing just one example of an invalid resource here.
769 // Unit tests for XdsListenerResourceType have exhaustive tests for all
770 // of the invalid cases.
771 TEST_P(XdsEnabledServerTest, BadLdsUpdateNoApiListenerNorAddress) {
772 DoSetUp();
773 Listener listener = default_server_listener_;
774 listener.clear_address();
775 listener.set_name(GetServerListenerName(backends_[0]->port()));
776 balancer_->ads_service()->SetLdsResource(listener);
777 backends_[0]->Start();
778 const auto response_state = WaitForLdsNack(DEBUG_LOCATION);
779 ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
780 EXPECT_THAT(response_state->error_message,
781 ::testing::EndsWith(absl::StrCat(
782 GetServerListenerName(backends_[0]->port()),
783 ": INVALID_ARGUMENT: Listener has neither address nor "
784 "ApiListener]")));
785 }
786
787 // Verify that a non-TCP listener results in "not serving" status.
788 TEST_P(XdsEnabledServerTest, NonTcpListener) {
789 DoSetUp();
790 Listener listener = default_listener_; // Client-side listener.
791 listener = PopulateServerListenerNameAndPort(listener, backends_[0]->port());
792 auto hcm = ClientHcmAccessor().Unpack(listener);
793 auto* rds = hcm.mutable_rds();
794 rds->set_route_config_name(kDefaultRouteConfigurationName);
795 rds->mutable_config_source()->mutable_self();
796 ClientHcmAccessor().Pack(hcm, &listener);
797 balancer_->ads_service()->SetLdsResource(listener);
798 backends_[0]->Start();
799 backends_[0]->notifier()->WaitOnServingStatusChange(
800 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
801 grpc::StatusCode::FAILED_PRECONDITION);
802 }
803
804 // Verify that a mismatch of listening address results in "not serving"
805 // status.
806 TEST_P(XdsEnabledServerTest, ListenerAddressMismatch) {
807 DoSetUp();
808 Listener listener = default_server_listener_;
809 // Set a different listening address in the LDS update
810 listener.mutable_address()->mutable_socket_address()->set_address(
811 "192.168.1.1");
812 SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
813 backends_[0]->port(),
814 default_server_route_config_);
815 backends_[0]->Start();
816 backends_[0]->notifier()->WaitOnServingStatusChange(
817 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
818 grpc::StatusCode::FAILED_PRECONDITION);
819 }
820
821 class XdsServerSecurityTest : public XdsEnd2endTest {
822 protected:
823 void SetUp() override {
824 BootstrapBuilder builder = BootstrapBuilder();
825 builder.AddCertificateProviderPlugin("fake_plugin1", "fake1");
826 builder.AddCertificateProviderPlugin("fake_plugin2", "fake2");
827 std::vector<std::string> fields;
828 fields.push_back(absl::StrFormat(" \"certificate_file\": \"%s\"",
829 kClientCertPath));
830 fields.push_back(absl::StrFormat(" \"private_key_file\": \"%s\"",
831 kClientKeyPath));
832 fields.push_back(absl::StrFormat(" \"ca_certificate_file\": \"%s\"",
833 kCaCertPath));
834 builder.AddCertificateProviderPlugin("file_plugin", "file_watcher",
835 absl::StrJoin(fields, ",\n"));
836 InitClient(builder);
837 CreateBackends(1, /*xds_enabled=*/true);
838 root_cert_ = ReadFile(kCaCertPath);
839 bad_root_cert_ = ReadFile(kBadClientCertPath);
840 identity_pair_ = ReadTlsIdentityPair(kServerKeyPath, kServerCertPath);
841 bad_identity_pair_ =
842 ReadTlsIdentityPair(kBadClientKeyPath, kBadClientCertPath);
843 identity_pair_2_ = ReadTlsIdentityPair(kClientKeyPath, kClientCertPath);
844 server_authenticated_identity_ = {"*.test.google.fr",
845 "waterzooi.test.google.be",
846 "*.test.youtube.com", "192.168.1.3"};
847 server_authenticated_identity_2_ = {"testclient"};
848 client_authenticated_identity_ = {"*.test.google.fr",
849 "waterzooi.test.google.be",
850 "*.test.youtube.com", "192.168.1.3"};
851 EdsResourceArgs args({
852 {"locality0", CreateEndpointsForBackends(0, 1)},
853 });
854 balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
855 }
856
857 void SetLdsUpdate(absl::string_view root_instance_name,
858 absl::string_view root_certificate_name,
859 absl::string_view identity_instance_name,
860 absl::string_view identity_certificate_name,
861 bool require_client_certificates) {
862 Listener listener = default_server_listener_;
863 auto* filter_chain = listener.mutable_default_filter_chain();
864 if (!identity_instance_name.empty()) {
865 auto* transport_socket = filter_chain->mutable_transport_socket();
866 transport_socket->set_name("envoy.transport_sockets.tls");
867 DownstreamTlsContext downstream_tls_context;
868 downstream_tls_context.mutable_common_tls_context()
869 ->mutable_tls_certificate_provider_instance()
870 ->set_instance_name(std::string(identity_instance_name));
871 downstream_tls_context.mutable_common_tls_context()
872 ->mutable_tls_certificate_provider_instance()
873 ->set_certificate_name(std::string(identity_certificate_name));
874 if (!root_instance_name.empty()) {
875 downstream_tls_context.mutable_common_tls_context()
876 ->mutable_validation_context()
877 ->mutable_ca_certificate_provider_instance()
878 ->set_instance_name(std::string(root_instance_name));
879 downstream_tls_context.mutable_common_tls_context()
880 ->mutable_validation_context()
881 ->mutable_ca_certificate_provider_instance()
882 ->set_certificate_name(std::string(root_certificate_name));
883 downstream_tls_context.mutable_require_client_certificate()->set_value(
884 require_client_certificates);
885 }
886 transport_socket->mutable_typed_config()->PackFrom(
887 downstream_tls_context);
888 }
889 SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
890 backends_[0]->port(),
891 default_server_route_config_);
892 }
893
894 std::shared_ptr<grpc::Channel> CreateMtlsChannel() {
895 ChannelArguments args;
896 // Override target name for host name check
897 args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
898 ipv6_only_ ? "::1" : "127.0.0.1");
899 args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
900 std::string uri = absl::StrCat(
901 ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", backends_[0]->port());
902 IdentityKeyCertPair key_cert_pair;
903 key_cert_pair.private_key = ReadFile(kServerKeyPath);
904 key_cert_pair.certificate_chain = ReadFile(kServerCertPath);
905 std::vector<IdentityKeyCertPair> identity_key_cert_pairs;
906 identity_key_cert_pairs.emplace_back(key_cert_pair);
907 auto certificate_provider = std::make_shared<StaticDataCertificateProvider>(
908 ReadFile(kCaCertPath), identity_key_cert_pairs);
909 grpc::experimental::TlsChannelCredentialsOptions options;
910 options.set_certificate_provider(std::move(certificate_provider));
911 options.watch_root_certs();
912 options.watch_identity_key_cert_pairs();
913 auto verifier =
914 ExternalCertificateVerifier::Create<SyncCertificateVerifier>(true);
915 options.set_verify_server_certs(true);
916 options.set_certificate_verifier(std::move(verifier));
917 auto channel_creds = grpc::experimental::TlsCredentials(options);
918 GPR_ASSERT(channel_creds.get() != nullptr);
919 return CreateCustomChannel(uri, channel_creds, args);
920 }
921
922 std::shared_ptr<grpc::Channel> CreateTlsChannel() {
923 ChannelArguments args;
924 // Override target name for host name check
925 args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
926 ipv6_only_ ? "::1" : "127.0.0.1");
927 args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
928 std::string uri = absl::StrCat(
929 ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", backends_[0]->port());
930 auto certificate_provider =
931 std::make_shared<StaticDataCertificateProvider>(ReadFile(kCaCertPath));
932 grpc::experimental::TlsChannelCredentialsOptions options;
933 options.set_certificate_provider(std::move(certificate_provider));
934 options.watch_root_certs();
935 auto verifier =
936 ExternalCertificateVerifier::Create<SyncCertificateVerifier>(true);
937 options.set_verify_server_certs(true);
938 options.set_certificate_verifier(std::move(verifier));
939 auto channel_creds = grpc::experimental::TlsCredentials(options);
940 GPR_ASSERT(channel_creds.get() != nullptr);
941 return CreateCustomChannel(uri, channel_creds, args);
942 }
943
944 std::shared_ptr<grpc::Channel> CreateInsecureChannel(
945 bool use_put_requests = false) {
946 ChannelArguments args;
947 // Override target name for host name check
948 args.SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG,
949 ipv6_only_ ? "::1" : "127.0.0.1");
950 args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
951 if (use_put_requests) {
952 args.SetInt(GRPC_ARG_TEST_ONLY_USE_PUT_REQUESTS, 1);
953 }
954 std::string uri = absl::StrCat(
955 ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", backends_[0]->port());
956 return CreateCustomChannel(uri, InsecureChannelCredentials(), args);
957 }
958
959 void SendRpc(
960 std::function<std::shared_ptr<grpc::Channel>()> channel_creator,
961 std::vector<std::string> expected_server_identity,
962 std::vector<std::string> expected_client_identity,
963 bool test_expects_failure = false,
964 absl::optional<grpc::StatusCode> expected_status = absl::nullopt) {
965 gpr_log(GPR_INFO, "Sending RPC");
966 int num_tries = 0;
967 constexpr int kRetryCount = 100;
968 auto overall_deadline = absl::Now() + absl::Seconds(5);
969 for (; num_tries < kRetryCount || absl::Now() < overall_deadline;
970 num_tries++) {
971 auto channel = channel_creator();
972 auto stub = grpc::testing::EchoTestService::NewStub(channel);
973 ClientContext context;
974 context.set_wait_for_ready(true);
975 context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
976 EchoRequest request;
977 // TODO(yashykt): Skipping the cancelled check on the server since the
978 // server's graceful shutdown isn't as per spec and the check isn't
979 // necessary for what we want to test here anyway.
980 // https://github.com/grpc/grpc/issues/24237
981 request.mutable_param()->set_skip_cancelled_check(true);
982 request.set_message(kRequestMessage);
983 EchoResponse response;
984 Status status = stub->Echo(&context, request, &response);
985 if (test_expects_failure) {
986 if (status.ok()) {
987 gpr_log(GPR_ERROR, "RPC succeeded. Failure expected. Trying again.");
988 continue;
989 }
990 if (expected_status.has_value() &&
991 *expected_status != status.error_code()) {
992 gpr_log(GPR_ERROR,
993 "Expected status does not match Actual(%d) vs Expected(%d)",
994 status.error_code(), *expected_status);
995 continue;
996 }
997 } else {
998 if (!status.ok()) {
999 gpr_log(GPR_ERROR, "RPC failed. code=%d message=%s Trying again.",
1000 status.error_code(), status.error_message().c_str());
1001 continue;
1002 }
1003 EXPECT_EQ(response.message(), kRequestMessage);
1004 std::vector<std::string> peer_identity;
1005 for (const auto& entry : context.auth_context()->GetPeerIdentity()) {
1006 peer_identity.emplace_back(
1007 std::string(entry.data(), entry.size()).c_str());
1008 }
1009 if (peer_identity != expected_server_identity) {
1010 gpr_log(GPR_ERROR,
1011 "Expected server identity does not match. (actual) %s vs "
1012 "(expected) %s Trying again.",
1013 absl::StrJoin(peer_identity, ",").c_str(),
1014 absl::StrJoin(expected_server_identity, ",").c_str());
1015 continue;
1016 }
1017 if (backends_[0]->backend_service()->last_peer_identity() !=
1018 expected_client_identity) {
1019 gpr_log(
1020 GPR_ERROR,
1021 "Expected client identity does not match. (actual) %s vs "
1022 "(expected) %s Trying again.",
1023 absl::StrJoin(
1024 backends_[0]->backend_service()->last_peer_identity(), ",")
1025 .c_str(),
1026 absl::StrJoin(expected_client_identity, ",").c_str());
1027 continue;
1028 }
1029 }
1030 break;
1031 }
1032 EXPECT_LT(num_tries, kRetryCount);
1033 }
1034
1035 std::string root_cert_;
1036 std::string bad_root_cert_;
1037 grpc_core::PemKeyCertPairList identity_pair_;
1038 grpc_core::PemKeyCertPairList bad_identity_pair_;
1039 grpc_core::PemKeyCertPairList identity_pair_2_;
1040 std::vector<std::string> server_authenticated_identity_;
1041 std::vector<std::string> server_authenticated_identity_2_;
1042 std::vector<std::string> client_authenticated_identity_;
1043 };
1044
1045 TEST_P(XdsServerSecurityTest,
1046 TestDeprecateTlsCertificateCertificateProviderInstanceField) {
1047 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1048 Listener listener = default_server_listener_;
1049 auto* filter_chain = listener.mutable_default_filter_chain();
1050 filter_chain->mutable_filters()->at(0).mutable_typed_config()->PackFrom(
1051 ServerHcmAccessor().Unpack(listener));
1052 auto* transport_socket = filter_chain->mutable_transport_socket();
1053 transport_socket->set_name("envoy.transport_sockets.tls");
1054 DownstreamTlsContext downstream_tls_context;
1055 downstream_tls_context.mutable_common_tls_context()
1056 ->mutable_tls_certificate_certificate_provider_instance()
1057 ->set_instance_name("fake_plugin1");
1058 transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
1059 SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
1060 backends_[0]->port(),
1061 default_server_route_config_);
1062 backends_[0]->Start();
1063 SendRpc([this]() { return CreateTlsChannel(); },
1064 server_authenticated_identity_, {});
1065 }
1066
1067 TEST_P(XdsServerSecurityTest, CertificatesNotAvailable) {
1068 g_fake1_cert_data_map->Set({});
1069 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
1070 SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
1071 true /* test_expects_failure */);
1072 }
1073
1074 TEST_P(XdsServerSecurityTest, TestMtls) {
1075 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1076 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
1077 backends_[0]->Start();
1078 SendRpc([this]() { return CreateMtlsChannel(); },
1079 server_authenticated_identity_, client_authenticated_identity_);
1080 }
1081
1082 TEST_P(XdsServerSecurityTest, TestMtlsWithRootPluginUpdate) {
1083 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1084 g_fake2_cert_data_map->Set({{"", {bad_root_cert_, bad_identity_pair_}}});
1085 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
1086 backends_[0]->Start();
1087 SendRpc([this]() { return CreateMtlsChannel(); },
1088 server_authenticated_identity_, client_authenticated_identity_);
1089 SetLdsUpdate("fake_plugin2", "", "fake_plugin1", "", true);
1090 SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
1091 true /* test_expects_failure */);
1092 }
1093
1094 TEST_P(XdsServerSecurityTest, TestMtlsWithIdentityPluginUpdate) {
1095 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1096 g_fake2_cert_data_map->Set({{"", {root_cert_, identity_pair_2_}}});
1097 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
1098 backends_[0]->Start();
1099 SendRpc([this]() { return CreateMtlsChannel(); },
1100 server_authenticated_identity_, client_authenticated_identity_);
1101 SetLdsUpdate("fake_plugin1", "", "fake_plugin2", "", true);
1102 SendRpc([this]() { return CreateMtlsChannel(); },
1103 server_authenticated_identity_2_, client_authenticated_identity_);
1104 }
1105
1106 TEST_P(XdsServerSecurityTest, TestMtlsWithBothPluginsUpdated) {
1107 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1108 g_fake2_cert_data_map->Set({{"good", {root_cert_, identity_pair_2_}},
1109 {"", {bad_root_cert_, bad_identity_pair_}}});
1110 SetLdsUpdate("fake_plugin2", "", "fake_plugin2", "", true);
1111 backends_[0]->Start();
1112 SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
1113 true /* test_expects_failure */);
1114 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
1115 SendRpc([this]() { return CreateMtlsChannel(); },
1116 server_authenticated_identity_, client_authenticated_identity_);
1117 SetLdsUpdate("fake_plugin2", "good", "fake_plugin2", "good", true);
1118 SendRpc([this]() { return CreateMtlsChannel(); },
1119 server_authenticated_identity_2_, client_authenticated_identity_);
1120 }
1121
1122 TEST_P(XdsServerSecurityTest, TestMtlsWithRootCertificateNameUpdate) {
1123 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}},
1124 {"bad", {bad_root_cert_, bad_identity_pair_}}});
1125 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
1126 backends_[0]->Start();
1127 SendRpc([this]() { return CreateMtlsChannel(); },
1128 server_authenticated_identity_, client_authenticated_identity_);
1129 SetLdsUpdate("fake_plugin1", "bad", "fake_plugin1", "", true);
1130 SendRpc([this]() { return CreateMtlsChannel(); }, {}, {},
1131 true /* test_expects_failure */);
1132 }
1133
1134 TEST_P(XdsServerSecurityTest, TestMtlsWithIdentityCertificateNameUpdate) {
1135 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}},
1136 {"good", {root_cert_, identity_pair_2_}}});
1137 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
1138 backends_[0]->Start();
1139 SendRpc([this]() { return CreateMtlsChannel(); },
1140 server_authenticated_identity_, client_authenticated_identity_);
1141 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "good", true);
1142 SendRpc([this]() { return CreateMtlsChannel(); },
1143 server_authenticated_identity_2_, client_authenticated_identity_);
1144 }
1145
1146 TEST_P(XdsServerSecurityTest, TestMtlsWithBothCertificateNamesUpdated) {
1147 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}},
1148 {"good", {root_cert_, identity_pair_2_}}});
1149 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
1150 backends_[0]->Start();
1151 SendRpc([this]() { return CreateMtlsChannel(); },
1152 server_authenticated_identity_, client_authenticated_identity_);
1153 SetLdsUpdate("fake_plugin1", "good", "fake_plugin1", "good", true);
1154 SendRpc([this]() { return CreateMtlsChannel(); },
1155 server_authenticated_identity_2_, client_authenticated_identity_);
1156 }
1157
1158 TEST_P(XdsServerSecurityTest, TestMtlsNotRequiringButProvidingClientCerts) {
1159 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1160 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", false);
1161 backends_[0]->Start();
1162 SendRpc([this]() { return CreateMtlsChannel(); },
1163 server_authenticated_identity_, client_authenticated_identity_);
1164 }
1165
1166 TEST_P(XdsServerSecurityTest, TestMtlsNotRequiringAndNotProvidingClientCerts) {
1167 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1168 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", false);
1169 backends_[0]->Start();
1170 SendRpc([this]() { return CreateTlsChannel(); },
1171 server_authenticated_identity_, {});
1172 }
1173
1174 TEST_P(XdsServerSecurityTest, TestTls) {
1175 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1176 SetLdsUpdate("", "", "fake_plugin1", "", false);
1177 backends_[0]->Start();
1178 SendRpc([this]() { return CreateTlsChannel(); },
1179 server_authenticated_identity_, {});
1180 }
1181
1182 TEST_P(XdsServerSecurityTest, TestTlsWithIdentityPluginUpdate) {
1183 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1184 g_fake2_cert_data_map->Set({{"", {root_cert_, identity_pair_2_}}});
1185 SetLdsUpdate("", "", "fake_plugin1", "", false);
1186 backends_[0]->Start();
1187 SendRpc([this]() { return CreateTlsChannel(); },
1188 server_authenticated_identity_, {});
1189 SetLdsUpdate("", "", "fake_plugin2", "", false);
1190 SendRpc([this]() { return CreateTlsChannel(); },
1191 server_authenticated_identity_2_, {});
1192 }
1193
1194 TEST_P(XdsServerSecurityTest, TestTlsWithIdentityCertificateNameUpdate) {
1195 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}},
1196 {"good", {root_cert_, identity_pair_2_}}});
1197 SetLdsUpdate("", "", "fake_plugin1", "", false);
1198 backends_[0]->Start();
1199 SendRpc([this]() { return CreateTlsChannel(); },
1200 server_authenticated_identity_, {});
1201 SetLdsUpdate("", "", "fake_plugin1", "good", false);
1202 SendRpc([this]() { return CreateTlsChannel(); },
1203 server_authenticated_identity_2_, {});
1204 }
1205
1206 TEST_P(XdsServerSecurityTest, TestFallback) {
1207 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1208 SetLdsUpdate("", "", "", "", false);
1209 backends_[0]->Start();
1210 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1211 }
1212
1213 TEST_P(XdsServerSecurityTest, TestMtlsToTls) {
1214 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1215 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
1216 backends_[0]->Start();
1217 SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
1218 true /* test_expects_failure */);
1219 SetLdsUpdate("", "", "fake_plugin1", "", false);
1220 SendRpc([this]() { return CreateTlsChannel(); },
1221 server_authenticated_identity_, {});
1222 }
1223
1224 TEST_P(XdsServerSecurityTest, TestTlsToMtls) {
1225 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1226 SetLdsUpdate("", "", "fake_plugin1", "", false);
1227 backends_[0]->Start();
1228 SendRpc([this]() { return CreateTlsChannel(); },
1229 server_authenticated_identity_, {});
1230 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
1231 SendRpc([this]() { return CreateTlsChannel(); }, {}, {},
1232 true /* test_expects_failure */);
1233 }
1234
1235 TEST_P(XdsServerSecurityTest, TestMtlsToFallback) {
1236 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1237 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", false);
1238 backends_[0]->Start();
1239 SendRpc([this]() { return CreateMtlsChannel(); },
1240 server_authenticated_identity_, client_authenticated_identity_);
1241 SetLdsUpdate("", "", "", "", false);
1242 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1243 }
1244
1245 TEST_P(XdsServerSecurityTest, TestFallbackToMtls) {
1246 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1247 SetLdsUpdate("", "", "", "", false);
1248 backends_[0]->Start();
1249 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1250 SetLdsUpdate("fake_plugin1", "", "fake_plugin1", "", true);
1251 SendRpc([this]() { return CreateMtlsChannel(); },
1252 server_authenticated_identity_, client_authenticated_identity_);
1253 }
1254
1255 TEST_P(XdsServerSecurityTest, TestTlsToFallback) {
1256 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1257 SetLdsUpdate("", "", "fake_plugin1", "", false);
1258 backends_[0]->Start();
1259 SendRpc([this]() { return CreateTlsChannel(); },
1260 server_authenticated_identity_, {});
1261 SetLdsUpdate("", "", "", "", false);
1262 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1263 }
1264
1265 TEST_P(XdsServerSecurityTest, TestFallbackToTls) {
1266 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1267 SetLdsUpdate("", "", "", "", false);
1268 backends_[0]->Start();
1269 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1270 SetLdsUpdate("", "", "fake_plugin1", "", false);
1271 SendRpc([this]() { return CreateTlsChannel(); },
1272 server_authenticated_identity_, {});
1273 }
1274
1275 class XdsEnabledServerStatusNotificationTest : public XdsServerSecurityTest {
1276 protected:
1277 void SetValidLdsUpdate() { SetLdsUpdate("", "", "", "", false); }
1278
1279 void SetInvalidLdsUpdate() {
1280 Listener listener = default_server_listener_;
1281 listener.clear_address();
1282 listener.set_name(absl::StrCat(
1283 "grpc/server?xds.resource.listening_address=",
1284 ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()));
1285 balancer_->ads_service()->SetLdsResource(listener);
1286 }
1287
1288 void UnsetLdsUpdate() {
1289 balancer_->ads_service()->UnsetResource(
1290 kLdsTypeUrl, absl::StrCat("grpc/server?xds.resource.listening_address=",
1291 ipv6_only_ ? "[::1]:" : "127.0.0.1:",
1292 backends_[0]->port()));
1293 }
1294 };
1295
1296 TEST_P(XdsEnabledServerStatusNotificationTest, ServingStatus) {
1297 SetValidLdsUpdate();
1298 backends_[0]->Start();
1299 backends_[0]->notifier()->WaitOnServingStatusChange(
1300 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1301 grpc::StatusCode::OK);
1302 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1303 }
1304
1305 TEST_P(XdsEnabledServerStatusNotificationTest, NotServingStatus) {
1306 SetInvalidLdsUpdate();
1307 backends_[0]->Start();
1308 backends_[0]->notifier()->WaitOnServingStatusChange(
1309 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1310 grpc::StatusCode::UNAVAILABLE);
1311 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
1312 true /* test_expects_failure */);
1313 }
1314
1315 TEST_P(XdsEnabledServerStatusNotificationTest, ErrorUpdateWhenAlreadyServing) {
1316 SetValidLdsUpdate();
1317 backends_[0]->Start();
1318 backends_[0]->notifier()->WaitOnServingStatusChange(
1319 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1320 grpc::StatusCode::OK);
1321 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1322 // Invalid update does not lead to a change in the serving status.
1323 SetInvalidLdsUpdate();
1324 do {
1325 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1326 } while (!balancer_->ads_service()->lds_response_state().has_value());
1327 backends_[0]->notifier()->WaitOnServingStatusChange(
1328 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1329 grpc::StatusCode::OK);
1330 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1331 }
1332
1333 TEST_P(XdsEnabledServerStatusNotificationTest,
1334 NotServingStatusToServingStatusTransition) {
1335 SetInvalidLdsUpdate();
1336 backends_[0]->Start();
1337 backends_[0]->notifier()->WaitOnServingStatusChange(
1338 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1339 grpc::StatusCode::UNAVAILABLE);
1340 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
1341 true /* test_expects_failure */);
1342 // Send a valid LDS update to change to serving status
1343 SetValidLdsUpdate();
1344 backends_[0]->notifier()->WaitOnServingStatusChange(
1345 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1346 grpc::StatusCode::OK);
1347 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1348 }
1349
1350 // This test verifies that the resource getting deleted when already serving
1351 // results in future connections being dropped.
1352 TEST_P(XdsEnabledServerStatusNotificationTest,
1353 ServingStatusToNonServingStatusTransition) {
1354 SetValidLdsUpdate();
1355 backends_[0]->Start();
1356 backends_[0]->notifier()->WaitOnServingStatusChange(
1357 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1358 grpc::StatusCode::OK);
1359 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1360 // Deleting the resource should result in a non-serving status.
1361 UnsetLdsUpdate();
1362 backends_[0]->notifier()->WaitOnServingStatusChange(
1363 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1364 grpc::StatusCode::NOT_FOUND);
1365 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
1366 true /* test_expects_failure */);
1367 }
1368
1369 TEST_P(XdsEnabledServerStatusNotificationTest, RepeatedServingStatusChanges) {
1370 backends_[0]->Start();
1371 for (int i = 0; i < 5; i++) {
1372 // Send a valid LDS update to get the server to start listening
1373 SetValidLdsUpdate();
1374 backends_[0]->notifier()->WaitOnServingStatusChange(
1375 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:",
1376 backends_[0]->port()),
1377 grpc::StatusCode::OK);
1378 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1379 // Deleting the resource will make the server start rejecting connections
1380 UnsetLdsUpdate();
1381 backends_[0]->notifier()->WaitOnServingStatusChange(
1382 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:",
1383 backends_[0]->port()),
1384 grpc::StatusCode::NOT_FOUND);
1385 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
1386 true /* test_expects_failure */);
1387 }
1388 }
1389
1390 TEST_P(XdsEnabledServerStatusNotificationTest, ExistingRpcsOnResourceDeletion) {
1391 // Send a valid LDS update to get the server to start listening
1392 SetValidLdsUpdate();
1393 backends_[0]->Start();
1394 backends_[0]->notifier()->WaitOnServingStatusChange(
1395 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1396 grpc::StatusCode::OK);
1397 constexpr int kNumChannels = 10;
1398 struct StreamingRpc {
1399 std::shared_ptr<Channel> channel;
1400 std::unique_ptr<grpc::testing::EchoTestService::Stub> stub;
1401 ClientContext context;
1402 std::unique_ptr<ClientReaderWriter<EchoRequest, EchoResponse>> stream;
1403 } streaming_rpcs[kNumChannels];
1404 EchoRequest request;
1405 EchoResponse response;
1406 request.set_message("Hello");
1407 for (int i = 0; i < kNumChannels; i++) {
1408 streaming_rpcs[i].channel = CreateInsecureChannel();
1409 streaming_rpcs[i].stub =
1410 grpc::testing::EchoTestService::NewStub(streaming_rpcs[i].channel);
1411 streaming_rpcs[i].context.set_wait_for_ready(true);
1412 streaming_rpcs[i].stream =
1413 streaming_rpcs[i].stub->BidiStream(&streaming_rpcs[i].context);
1414 EXPECT_TRUE(streaming_rpcs[i].stream->Write(request));
1415 streaming_rpcs[i].stream->Read(&response);
1416 EXPECT_EQ(request.message(), response.message());
1417 }
1418 // Deleting the resource will make the server start rejecting connections
1419 UnsetLdsUpdate();
1420 backends_[0]->notifier()->WaitOnServingStatusChange(
1421 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1422 grpc::StatusCode::NOT_FOUND);
1423 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
1424 true /* test_expects_failure */);
1425 for (int i = 0; i < kNumChannels; i++) {
1426 EXPECT_TRUE(streaming_rpcs[i].stream->Write(request));
1427 streaming_rpcs[i].stream->Read(&response);
1428 EXPECT_EQ(request.message(), response.message());
1429 EXPECT_TRUE(streaming_rpcs[i].stream->WritesDone());
1430 auto status = streaming_rpcs[i].stream->Finish();
1431 EXPECT_TRUE(status.ok())
1432 << status.error_message() << ", " << status.error_details() << ", "
1433 << streaming_rpcs[i].context.debug_error_string();
1434 // New RPCs on the existing channels should fail.
1435 ClientContext new_context;
1436 new_context.set_deadline(grpc_timeout_milliseconds_to_deadline(1000));
1437 EXPECT_FALSE(
1438 streaming_rpcs[i].stub->Echo(&new_context, request, &response).ok());
1439 }
1440 }
1441
1442 TEST_P(XdsEnabledServerStatusNotificationTest,
1443 ExistingRpcsFailOnResourceUpdateAfterDrainGraceTimeExpires) {
1444 constexpr int kDrainGraceTimeMs = 100;
1445 xds_drain_grace_time_ms_ = kDrainGraceTimeMs;
1446 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
1447 // Send a valid LDS update to get the server to start listening
1448 SetValidLdsUpdate();
1449 backends_[0]->Start();
1450 backends_[0]->notifier()->WaitOnServingStatusChange(
1451 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1452 grpc::StatusCode::OK);
1453 constexpr int kNumChannels = 10;
1454 struct StreamingRpc {
1455 std::shared_ptr<Channel> channel;
1456 std::unique_ptr<grpc::testing::EchoTestService::Stub> stub;
1457 ClientContext context;
1458 std::unique_ptr<ClientReaderWriter<EchoRequest, EchoResponse>> stream;
1459 } streaming_rpcs[kNumChannels];
1460 EchoRequest request;
1461 EchoResponse response;
1462 request.set_message("Hello");
1463 for (int i = 0; i < kNumChannels; i++) {
1464 streaming_rpcs[i].channel = CreateInsecureChannel();
1465 streaming_rpcs[i].stub =
1466 grpc::testing::EchoTestService::NewStub(streaming_rpcs[i].channel);
1467 streaming_rpcs[i].context.set_wait_for_ready(true);
1468 streaming_rpcs[i].stream =
1469 streaming_rpcs[i].stub->BidiStream(&streaming_rpcs[i].context);
1470 EXPECT_TRUE(streaming_rpcs[i].stream->Write(request));
1471 streaming_rpcs[i].stream->Read(&response);
1472 EXPECT_EQ(request.message(), response.message());
1473 }
1474 grpc_core::Timestamp update_time = NowFromCycleCounter();
1475 // Update the resource.
1476 SetLdsUpdate("", "", "fake_plugin1", "", false);
1477 // Wait for the updated resource to take effect.
1478 SendRpc([this]() { return CreateTlsChannel(); },
1479 server_authenticated_identity_, {});
1480 // After the drain grace time expires, the existing RPCs should all fail.
1481 for (int i = 0; i < kNumChannels; i++) {
1482 // Wait for the drain grace time to expire
1483 EXPECT_FALSE(streaming_rpcs[i].stream->Read(&response));
1484 // Make sure that the drain grace interval is honored.
1485 EXPECT_GE(NowFromCycleCounter() - update_time,
1486 grpc_core::Duration::Milliseconds(kDrainGraceTimeMs));
1487 auto status = streaming_rpcs[i].stream->Finish();
1488 EXPECT_EQ(status.error_code(), grpc::StatusCode::UNAVAILABLE)
1489 << status.error_code() << ", " << status.error_message() << ", "
1490 << status.error_details() << ", "
1491 << streaming_rpcs[i].context.debug_error_string();
1492 }
1493 }
1494
1495 class XdsServerFilterChainMatchTest : public XdsServerSecurityTest {
1496 public:
1497 HttpConnectionManager GetHttpConnectionManager(const Listener& listener) {
1498 HttpConnectionManager http_connection_manager =
1499 ServerHcmAccessor().Unpack(listener);
1500 *http_connection_manager.mutable_route_config() =
1501 default_server_route_config_;
1502 return http_connection_manager;
1503 }
1504 };
1505
1506 TEST_P(XdsServerFilterChainMatchTest,
1507 DefaultFilterChainUsedWhenNoFilterChainMentioned) {
1508 backends_[0]->Start();
1509 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1510 }
1511
1512 TEST_P(XdsServerFilterChainMatchTest,
1513 DefaultFilterChainUsedWhenOtherFilterChainsDontMatch) {
1514 Listener listener = default_server_listener_;
1515 // Add a filter chain that will never get matched
1516 auto* filter_chain = listener.add_filter_chains();
1517 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1518 GetHttpConnectionManager(listener));
1519 filter_chain->mutable_filter_chain_match()
1520 ->mutable_destination_port()
1521 ->set_value(8080);
1522 SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
1523 backends_[0]->port(),
1524 default_server_route_config_);
1525 backends_[0]->Start();
1526 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1527 }
1528
1529 TEST_P(XdsServerFilterChainMatchTest,
1530 FilterChainsWithDestinationPortDontMatch) {
1531 Listener listener = default_server_listener_;
1532 // Add filter chain with destination port that should never get matched
1533 auto* filter_chain = listener.add_filter_chains();
1534 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1535 GetHttpConnectionManager(listener));
1536 filter_chain->mutable_filter_chain_match()
1537 ->mutable_destination_port()
1538 ->set_value(8080);
1539 listener.clear_default_filter_chain();
1540 balancer_->ads_service()->SetLdsResource(
1541 PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
1542 backends_[0]->Start();
1543 // RPC should fail since no matching filter chain was found and no default
1544 // filter chain is configured.
1545 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
1546 true /* test_expects_failure */);
1547 }
1548
1549 TEST_P(XdsServerFilterChainMatchTest, FilterChainsWithServerNamesDontMatch) {
1550 Listener listener = default_server_listener_;
1551 // Add filter chain with server name that should never get matched
1552 auto* filter_chain = listener.add_filter_chains();
1553 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1554 GetHttpConnectionManager(listener));
1555 filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
1556 listener.clear_default_filter_chain();
1557 balancer_->ads_service()->SetLdsResource(
1558 PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
1559 backends_[0]->Start();
1560 // RPC should fail since no matching filter chain was found and no default
1561 // filter chain is configured.
1562 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
1563 true /* test_expects_failure */);
1564 }
1565
1566 TEST_P(XdsServerFilterChainMatchTest,
1567 FilterChainsWithTransportProtocolsOtherThanRawBufferDontMatch) {
1568 Listener listener = default_server_listener_;
1569 // Add filter chain with transport protocol "tls" that should never match
1570 auto* filter_chain = listener.add_filter_chains();
1571 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1572 GetHttpConnectionManager(listener));
1573 filter_chain->mutable_filter_chain_match()->set_transport_protocol("tls");
1574 listener.clear_default_filter_chain();
1575 balancer_->ads_service()->SetLdsResource(
1576 PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
1577 backends_[0]->Start();
1578 // RPC should fail since no matching filter chain was found and no default
1579 // filter chain is configured.
1580 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
1581 true /* test_expects_failure */);
1582 }
1583
1584 TEST_P(XdsServerFilterChainMatchTest,
1585 FilterChainsWithApplicationProtocolsDontMatch) {
1586 Listener listener = default_server_listener_;
1587 // Add filter chain with application protocol that should never get matched
1588 auto* filter_chain = listener.add_filter_chains();
1589 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1590 GetHttpConnectionManager(listener));
1591 filter_chain->mutable_filter_chain_match()->add_application_protocols("h2");
1592 listener.clear_default_filter_chain();
1593 balancer_->ads_service()->SetLdsResource(
1594 PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
1595 backends_[0]->Start();
1596 // RPC should fail since no matching filter chain was found and no default
1597 // filter chain is configured.
1598 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
1599 true /* test_expects_failure */);
1600 }
1601
1602 TEST_P(XdsServerFilterChainMatchTest,
1603 FilterChainsWithTransportProtocolRawBufferIsPreferred) {
1604 Listener listener = default_server_listener_;
1605 // Add filter chain with "raw_buffer" transport protocol
1606 auto* filter_chain = listener.add_filter_chains();
1607 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1608 GetHttpConnectionManager(listener));
1609 filter_chain->mutable_filter_chain_match()->set_transport_protocol(
1610 "raw_buffer");
1611 // Add another filter chain with no transport protocol set but application
1612 // protocol set (fails match)
1613 filter_chain = listener.add_filter_chains();
1614 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1615 GetHttpConnectionManager(listener));
1616 filter_chain->mutable_filter_chain_match()->add_application_protocols("h2");
1617 listener.clear_default_filter_chain();
1618 balancer_->ads_service()->SetLdsResource(
1619 PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
1620 backends_[0]->Start();
1621 // A successful RPC proves that filter chains that mention "raw_buffer" as
1622 // the transport protocol are chosen as the best match in the round.
1623 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1624 }
1625
1626 TEST_P(XdsServerFilterChainMatchTest,
1627 FilterChainsWithMoreSpecificDestinationPrefixRangesArePreferred) {
1628 Listener listener = default_server_listener_;
1629 // Add filter chain with prefix range (length 4 and 16) but with server name
1630 // mentioned. (Prefix range is matched first.)
1631 auto* filter_chain = listener.add_filter_chains();
1632 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1633 GetHttpConnectionManager(listener));
1634 auto* prefix_range =
1635 filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
1636 prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
1637 prefix_range->mutable_prefix_len()->set_value(4);
1638 prefix_range =
1639 filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
1640 prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
1641 prefix_range->mutable_prefix_len()->set_value(16);
1642 filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
1643 // Add filter chain with two prefix ranges (length 8 and 24). Since 24 is
1644 // the highest match, it should be chosen.
1645 filter_chain = listener.add_filter_chains();
1646 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1647 GetHttpConnectionManager(listener));
1648 prefix_range =
1649 filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
1650 prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
1651 prefix_range->mutable_prefix_len()->set_value(8);
1652 prefix_range =
1653 filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
1654 prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
1655 prefix_range->mutable_prefix_len()->set_value(24);
1656 // Add another filter chain with a non-matching prefix range (with length
1657 // 30)
1658 filter_chain = listener.add_filter_chains();
1659 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1660 GetHttpConnectionManager(listener));
1661 prefix_range =
1662 filter_chain->mutable_filter_chain_match()->add_prefix_ranges();
1663 prefix_range->set_address_prefix("192.168.1.1");
1664 prefix_range->mutable_prefix_len()->set_value(30);
1665 filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
1666 // Add another filter chain with no prefix range mentioned
1667 filter_chain = listener.add_filter_chains();
1668 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1669 GetHttpConnectionManager(listener));
1670 filter_chain->mutable_filter_chain_match()->add_server_names("server_name");
1671 listener.clear_default_filter_chain();
1672 balancer_->ads_service()->SetLdsResource(
1673 PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
1674 backends_[0]->Start();
1675 // A successful RPC proves that the filter chain with the longest matching
1676 // prefix range was the best match.
1677 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1678 }
1679
1680 TEST_P(XdsServerFilterChainMatchTest,
1681 FilterChainsThatMentionSourceTypeArePreferred) {
1682 Listener listener = default_server_listener_;
1683 // Add filter chain with the local source type (best match)
1684 auto* filter_chain = listener.add_filter_chains();
1685 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1686 GetHttpConnectionManager(listener));
1687 filter_chain->mutable_filter_chain_match()->set_source_type(
1688 FilterChainMatch::SAME_IP_OR_LOOPBACK);
1689 // Add filter chain with the external source type but bad source port.
1690 // Note that backends_[0]->port() will never be a match for the source port
1691 // because it is already being used by a backend.
1692 filter_chain = listener.add_filter_chains();
1693 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1694 GetHttpConnectionManager(listener));
1695 filter_chain->mutable_filter_chain_match()->set_source_type(
1696 FilterChainMatch::EXTERNAL);
1697 filter_chain->mutable_filter_chain_match()->add_source_ports(
1698 backends_[0]->port());
1699 // Add filter chain with the default source type (ANY) but bad source port.
1700 filter_chain = listener.add_filter_chains();
1701 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1702 GetHttpConnectionManager(listener));
1703 filter_chain->mutable_filter_chain_match()->add_source_ports(
1704 backends_[0]->port());
1705 listener.clear_default_filter_chain();
1706 balancer_->ads_service()->SetLdsResource(
1707 PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
1708 backends_[0]->Start();
1709 // A successful RPC proves that the filter chain with the longest matching
1710 // prefix range was the best match.
1711 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1712 }
1713
1714 TEST_P(XdsServerFilterChainMatchTest,
1715 FilterChainsWithMoreSpecificSourcePrefixRangesArePreferred) {
1716 Listener listener = default_server_listener_;
1717 // Add filter chain with source prefix range (length 16) but with a bad
1718 // source port mentioned. (Prefix range is matched first.) Note that
1719 // backends_[0]->port() will never be a match for the source port because it
1720 // is already being used by a backend.
1721 auto* filter_chain = listener.add_filter_chains();
1722 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1723 GetHttpConnectionManager(listener));
1724 auto* source_prefix_range =
1725 filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
1726 source_prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
1727 source_prefix_range->mutable_prefix_len()->set_value(4);
1728 source_prefix_range =
1729 filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
1730 source_prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
1731 source_prefix_range->mutable_prefix_len()->set_value(16);
1732 filter_chain->mutable_filter_chain_match()->add_source_ports(
1733 backends_[0]->port());
1734 // Add filter chain with two source prefix ranges (length 8 and 24). Since
1735 // 24 is the highest match, it should be chosen.
1736 filter_chain = listener.add_filter_chains();
1737 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1738 GetHttpConnectionManager(listener));
1739 source_prefix_range =
1740 filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
1741 source_prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
1742 source_prefix_range->mutable_prefix_len()->set_value(8);
1743 source_prefix_range =
1744 filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
1745 source_prefix_range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
1746 source_prefix_range->mutable_prefix_len()->set_value(24);
1747 // Add another filter chain with a non-matching source prefix range (with
1748 // length 30) and bad source port
1749 filter_chain = listener.add_filter_chains();
1750 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1751 GetHttpConnectionManager(listener));
1752 source_prefix_range =
1753 filter_chain->mutable_filter_chain_match()->add_source_prefix_ranges();
1754 source_prefix_range->set_address_prefix("192.168.1.1");
1755 source_prefix_range->mutable_prefix_len()->set_value(30);
1756 filter_chain->mutable_filter_chain_match()->add_source_ports(
1757 backends_[0]->port());
1758 // Add another filter chain with no source prefix range mentioned and bad
1759 // source port
1760 filter_chain = listener.add_filter_chains();
1761 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1762 GetHttpConnectionManager(listener));
1763 filter_chain->mutable_filter_chain_match()->add_source_ports(
1764 backends_[0]->port());
1765 listener.clear_default_filter_chain();
1766 balancer_->ads_service()->SetLdsResource(
1767 PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
1768 backends_[0]->Start();
1769 // A successful RPC proves that the filter chain with the longest matching
1770 // source prefix range was the best match.
1771 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1772 }
1773
1774 TEST_P(XdsServerFilterChainMatchTest,
1775 FilterChainsWithMoreSpecificSourcePortArePreferred) {
1776 Listener listener = default_server_listener_;
1777 auto* filter_chain = listener.add_filter_chains();
1778 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1779 GetHttpConnectionManager(listener));
1780 // Since we don't know which port will be used by the channel, just add all
1781 // ports except for 0.
1782 for (int i = 1; i < 65536; i++) {
1783 filter_chain->mutable_filter_chain_match()->add_source_ports(i);
1784 }
1785 // Add another filter chain with no source port mentioned with a bad
1786 // DownstreamTlsContext configuration.
1787 filter_chain = listener.add_filter_chains();
1788 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1789 GetHttpConnectionManager(listener));
1790 auto* transport_socket = filter_chain->mutable_transport_socket();
1791 transport_socket->set_name("envoy.transport_sockets.tls");
1792 DownstreamTlsContext downstream_tls_context;
1793 downstream_tls_context.mutable_common_tls_context()
1794 ->mutable_tls_certificate_provider_instance()
1795 ->set_instance_name("fake_plugin1");
1796 transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
1797 listener.clear_default_filter_chain();
1798 balancer_->ads_service()->SetLdsResource(
1799 PopulateServerListenerNameAndPort(listener, backends_[0]->port()));
1800 backends_[0]->Start();
1801 // A successful RPC proves that the filter chain with matching source port
1802 // was chosen.
1803 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1804 }
1805
1806 using XdsServerRdsTest = XdsEnabledServerStatusNotificationTest;
1807
1808 TEST_P(XdsServerRdsTest, Basic) {
1809 backends_[0]->Start();
1810 backends_[0]->notifier()->WaitOnServingStatusChange(
1811 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1812 grpc::StatusCode::OK);
1813 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1814 }
1815
1816 TEST_P(XdsServerRdsTest, NacksInvalidDomainPattern) {
1817 RouteConfiguration route_config = default_server_route_config_;
1818 route_config.mutable_virtual_hosts()->at(0).add_domains("");
1819 SetServerListenerNameAndRouteConfiguration(
1820 balancer_.get(), default_server_listener_, backends_[0]->port(),
1821 route_config);
1822 backends_[0]->Start();
1823 const auto response_state = WaitForRouteConfigNack(DEBUG_LOCATION);
1824 ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
1825 EXPECT_THAT(response_state->error_message,
1826 ::testing::HasSubstr("Invalid domain pattern \"\""));
1827 }
1828
1829 TEST_P(XdsServerRdsTest, NacksEmptyDomainsList) {
1830 RouteConfiguration route_config = default_server_route_config_;
1831 route_config.mutable_virtual_hosts()->at(0).clear_domains();
1832 SetServerListenerNameAndRouteConfiguration(
1833 balancer_.get(), default_server_listener_, backends_[0]->port(),
1834 route_config);
1835 backends_[0]->Start();
1836 const auto response_state = WaitForRouteConfigNack(DEBUG_LOCATION);
1837 ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
1838 EXPECT_THAT(response_state->error_message,
1839 ::testing::HasSubstr("VirtualHost has no domains"));
1840 }
1841
1842 TEST_P(XdsServerRdsTest, NacksEmptyRoutesList) {
1843 RouteConfiguration route_config = default_server_route_config_;
1844 route_config.mutable_virtual_hosts()->at(0).clear_routes();
1845 SetServerListenerNameAndRouteConfiguration(
1846 balancer_.get(), default_server_listener_, backends_[0]->port(),
1847 route_config);
1848 backends_[0]->Start();
1849 const auto response_state = WaitForRouteConfigNack(DEBUG_LOCATION);
1850 ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
1851 EXPECT_THAT(response_state->error_message,
1852 ::testing::HasSubstr("No route found in the virtual host"));
1853 }
1854
1855 TEST_P(XdsServerRdsTest, NacksEmptyMatch) {
1856 RouteConfiguration route_config = default_server_route_config_;
1857 route_config.mutable_virtual_hosts()
1858 ->at(0)
1859 .mutable_routes()
1860 ->at(0)
1861 .clear_match();
1862 SetServerListenerNameAndRouteConfiguration(
1863 balancer_.get(), default_server_listener_, backends_[0]->port(),
1864 route_config);
1865 backends_[0]->Start();
1866 const auto response_state = WaitForRouteConfigNack(DEBUG_LOCATION);
1867 ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
1868 EXPECT_THAT(response_state->error_message,
1869 ::testing::HasSubstr("Match can't be null"));
1870 }
1871
1872 TEST_P(XdsServerRdsTest, FailsRouteMatchesOtherThanNonForwardingAction) {
1873 SetServerListenerNameAndRouteConfiguration(
1874 balancer_.get(), default_server_listener_, backends_[0]->port(),
1875 default_route_config_ /* inappropriate route config for servers */);
1876 backends_[0]->Start();
1877 // The server should be ready to serve but RPCs should fail.
1878 backends_[0]->notifier()->WaitOnServingStatusChange(
1879 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1880 grpc::StatusCode::OK);
1881 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
1882 true /* test_expects_failure */);
1883 }
1884
1885 // Test that non-inline route configuration also works for non-default filter
1886 // chains
1887 TEST_P(XdsServerRdsTest, NonInlineRouteConfigurationNonDefaultFilterChain) {
1888 if (!GetParam().enable_rds_testing()) {
1889 return;
1890 }
1891 Listener listener = default_server_listener_;
1892 auto* filter_chain = listener.add_filter_chains();
1893 HttpConnectionManager http_connection_manager =
1894 ServerHcmAccessor().Unpack(listener);
1895 auto* rds = http_connection_manager.mutable_rds();
1896 rds->set_route_config_name(kDefaultServerRouteConfigurationName);
1897 rds->mutable_config_source()->mutable_self();
1898 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1899 http_connection_manager);
1900 SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
1901 backends_[0]->port(),
1902 default_server_route_config_);
1903 backends_[0]->Start();
1904 backends_[0]->notifier()->WaitOnServingStatusChange(
1905 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1906 grpc::StatusCode::OK);
1907 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1908 }
1909
1910 TEST_P(XdsServerRdsTest, NonInlineRouteConfigurationNotAvailable) {
1911 if (!GetParam().enable_rds_testing()) {
1912 return;
1913 }
1914 Listener listener = default_server_listener_;
1915 PopulateServerListenerNameAndPort(listener, backends_[0]->port());
1916 HttpConnectionManager http_connection_manager =
1917 ServerHcmAccessor().Unpack(listener);
1918 auto* rds = http_connection_manager.mutable_rds();
1919 rds->set_route_config_name("unknown_server_route_config");
1920 rds->mutable_config_source()->mutable_self();
1921 listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
1922 http_connection_manager);
1923 SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
1924 backends_[0]->port(),
1925 default_server_route_config_);
1926 backends_[0]->Start();
1927 backends_[0]->notifier()->WaitOnServingStatusChange(
1928 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1929 grpc::StatusCode::OK);
1930 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
1931 true /* test_expects_failure */);
1932 }
1933
1934 // TODO(yashykt): Once https://github.com/grpc/grpc/issues/24035 is fixed, we
1935 // should add tests that make sure that different route configs are used for
1936 // incoming connections with a different match.
1937 TEST_P(XdsServerRdsTest, MultipleRouteConfigurations) {
1938 Listener listener = default_server_listener_;
1939 // Set a filter chain with a new route config name
1940 auto new_route_config = default_server_route_config_;
1941 new_route_config.set_name("new_server_route_config");
1942 HttpConnectionManager http_connection_manager =
1943 ServerHcmAccessor().Unpack(listener);
1944 auto* rds = http_connection_manager.mutable_rds();
1945 rds->set_route_config_name(new_route_config.name());
1946 rds->mutable_config_source()->mutable_self();
1947 listener.add_filter_chains()->add_filters()->mutable_typed_config()->PackFrom(
1948 http_connection_manager);
1949 // Set another filter chain with another route config name
1950 auto another_route_config = default_server_route_config_;
1951 another_route_config.set_name("another_server_route_config");
1952 http_connection_manager.mutable_rds()->set_route_config_name(
1953 another_route_config.name());
1954 auto* filter_chain = listener.add_filter_chains();
1955 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1956 http_connection_manager);
1957 filter_chain->mutable_filter_chain_match()->set_source_type(
1958 FilterChainMatch::SAME_IP_OR_LOOPBACK);
1959 // Add another filter chain with the same route config name
1960 filter_chain = listener.add_filter_chains();
1961 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1962 http_connection_manager);
1963 filter_chain->mutable_filter_chain_match()->set_source_type(
1964 FilterChainMatch::EXTERNAL);
1965 // Add another filter chain with an inline route config
1966 filter_chain = listener.add_filter_chains();
1967 filter_chain->mutable_filter_chain_match()->add_source_ports(1234);
1968 http_connection_manager = ServerHcmAccessor().Unpack(listener);
1969 *http_connection_manager.mutable_route_config() =
1970 default_server_route_config_;
1971 filter_chain->add_filters()->mutable_typed_config()->PackFrom(
1972 http_connection_manager);
1973 // Set resources on the ADS service
1974 balancer_->ads_service()->SetRdsResource(new_route_config);
1975 balancer_->ads_service()->SetRdsResource(another_route_config);
1976 SetServerListenerNameAndRouteConfiguration(balancer_.get(), listener,
1977 backends_[0]->port(),
1978 default_server_route_config_);
1979 backends_[0]->Start();
1980 backends_[0]->notifier()->WaitOnServingStatusChange(
1981 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
1982 grpc::StatusCode::OK);
1983 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
1984 }
1985
1986 // Tests RBAC configurations on the server with RDS testing and route config
1987 // override permutations.
1988 class XdsRbacTest : public XdsServerRdsTest {
1989 protected:
1990 void SetServerRbacPolicies(Listener listener,
1991 const std::vector<RBAC>& rbac_policies) {
1992 HttpConnectionManager http_connection_manager =
1993 ServerHcmAccessor().Unpack(listener);
1994 http_connection_manager.clear_http_filters();
1995 RouteConfiguration route_config = default_server_route_config_;
1996 int count = 0;
1997 for (auto& rbac : rbac_policies) {
1998 auto* filter = http_connection_manager.add_http_filters();
1999 std::string filter_name = absl::StrFormat("rbac%d", ++count);
2000 filter->set_name(filter_name);
2001 switch (GetParam().filter_config_setup()) {
2002 case XdsTestType::HttpFilterConfigLocation::kHttpFilterConfigInListener:
2003 filter->mutable_typed_config()->PackFrom(rbac);
2004 break;
2005 case XdsTestType::HttpFilterConfigLocation::kHttpFilterConfigInRoute:
2006 filter->mutable_typed_config()->PackFrom(RBAC());
2007 google::protobuf::Any filter_config;
2008 RBACPerRoute rbac_per_route;
2009 *rbac_per_route.mutable_rbac() = rbac;
2010 filter_config.PackFrom(rbac_per_route);
2011 auto* config_map = route_config.mutable_virtual_hosts(0)
2012 ->mutable_routes(0)
2013 ->mutable_typed_per_filter_config();
2014 (*config_map)[filter_name] = std::move(filter_config);
2015 }
2016 }
2017 auto* filter = http_connection_manager.add_http_filters();
2018 filter->set_name("router");
2019 filter->mutable_typed_config()->PackFrom(
2020 envoy::extensions::filters::http::router::v3::Router());
2021 ServerHcmAccessor().Pack(http_connection_manager, &listener);
2022 SetServerListenerNameAndRouteConfiguration(
2023 balancer_.get(), listener, backends_[0]->port(), route_config);
2024 }
2025
2026 void SetServerRbacPolicy(Listener listener, const RBAC& rbac) {
2027 SetServerRbacPolicies(std::move(listener), {rbac});
2028 }
2029
2030 void SetServerRbacPolicy(const RBAC& rbac) {
2031 SetServerRbacPolicy(default_server_listener_, rbac);
2032 }
2033 };
2034
2035 TEST_P(XdsRbacTest, AbsentRbacPolicy) {
2036 SetServerRbacPolicy(RBAC());
2037 backends_[0]->Start();
2038 backends_[0]->notifier()->WaitOnServingStatusChange(
2039 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2040 grpc::StatusCode::OK);
2041 // An absent RBAC policy leads to all RPCs being accepted.
2042 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
2043 }
2044
2045 TEST_P(XdsRbacTest, LogAction) {
2046 RBAC rbac;
2047 auto* rules = rbac.mutable_rules();
2048 rules->set_action(RBAC_Action_LOG);
2049 SetServerRbacPolicy(rbac);
2050 backends_[0]->Start();
2051 backends_[0]->notifier()->WaitOnServingStatusChange(
2052 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2053 grpc::StatusCode::OK);
2054 // A Log action is identical to no rbac policy being configured.
2055 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
2056 }
2057
2058 // Tests RBAC policies where a route override is always present. Action
2059 // permutations are not added.
2060 using XdsRbacTestWithRouteOverrideAlwaysPresent = XdsRbacTest;
2061
2062 TEST_P(XdsRbacTestWithRouteOverrideAlwaysPresent, EmptyRBACPerRouteOverride) {
2063 HttpConnectionManager http_connection_manager;
2064 Listener listener = default_server_listener_;
2065 RouteConfiguration route_config = default_server_route_config_;
2066 auto* filter = http_connection_manager.add_http_filters();
2067 filter->set_name("rbac");
2068 // Create a top-level RBAC policy with a DENY action for all RPCs
2069 RBAC rbac;
2070 auto* rules = rbac.mutable_rules();
2071 rules->set_action(RBAC_Action_DENY);
2072 Policy policy;
2073 policy.add_permissions()->set_any(true);
2074 policy.add_principals()->set_any(true);
2075 (*rules->mutable_policies())["policy"] = policy;
2076 filter->mutable_typed_config()->PackFrom(rbac);
2077 // Override with an Empty RBACPerRoute policy which should result in RBAC
2078 // being disabled and RPCs being allowed.
2079 google::protobuf::Any filter_config;
2080 filter_config.PackFrom(RBACPerRoute());
2081 auto* config_map = route_config.mutable_virtual_hosts(0)
2082 ->mutable_routes(0)
2083 ->mutable_typed_per_filter_config();
2084 (*config_map)["rbac"] = std::move(filter_config);
2085 filter = http_connection_manager.add_http_filters();
2086 filter->set_name("router");
2087 filter->mutable_typed_config()->PackFrom(
2088 envoy::extensions::filters::http::router::v3::Router());
2089 ServerHcmAccessor().Pack(http_connection_manager, &listener);
2090 SetServerListenerNameAndRouteConfiguration(
2091 balancer_.get(), listener, backends_[0]->port(), route_config);
2092 backends_[0]->Start();
2093 backends_[0]->notifier()->WaitOnServingStatusChange(
2094 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2095 grpc::StatusCode::OK);
2096 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
2097 }
2098
2099 // Test a non-empty top level RBAC with a non-empty RBACPerRouteOverride
2100 TEST_P(XdsRbacTestWithRouteOverrideAlwaysPresent,
2101 NonEmptyTopLevelRBACNonEmptyPerRouteOverride) {
2102 HttpConnectionManager http_connection_manager;
2103 Listener listener = default_server_listener_;
2104 RouteConfiguration route_config = default_server_route_config_;
2105 auto* filter = http_connection_manager.add_http_filters();
2106 filter->set_name("rbac");
2107 // Create a top-level RBAC policy with a DENY action for all RPCs
2108 RBAC rbac;
2109 auto* rules = rbac.mutable_rules();
2110 rules->set_action(RBAC_Action_DENY);
2111 Policy policy;
2112 policy.add_permissions()->set_any(true);
2113 policy.add_principals()->set_any(true);
2114 (*rules->mutable_policies())["policy"] = policy;
2115 filter->mutable_typed_config()->PackFrom(rbac);
2116 // Override with a non-empty RBACPerRoute policy which allows all RPCs.
2117 google::protobuf::Any filter_config;
2118 RBACPerRoute rbac_per_route;
2119 rules = rbac_per_route.mutable_rbac()->mutable_rules();
2120 rules->set_action(RBAC_Action_ALLOW);
2121 (*rules->mutable_policies())["policy"] = policy;
2122 filter_config.PackFrom(RBACPerRoute());
2123 auto* config_map = route_config.mutable_virtual_hosts(0)
2124 ->mutable_routes(0)
2125 ->mutable_typed_per_filter_config();
2126 (*config_map)["rbac"] = std::move(filter_config);
2127 filter = http_connection_manager.add_http_filters();
2128 filter->set_name("router");
2129 filter->mutable_typed_config()->PackFrom(
2130 envoy::extensions::filters::http::router::v3::Router());
2131 ServerHcmAccessor().Pack(http_connection_manager, &listener);
2132 SetServerListenerNameAndRouteConfiguration(
2133 balancer_.get(), listener, backends_[0]->port(), route_config);
2134 backends_[0]->Start();
2135 backends_[0]->notifier()->WaitOnServingStatusChange(
2136 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2137 grpc::StatusCode::OK);
2138 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {});
2139 }
2140
2141 // Adds Action Permutations to XdsRbacTest
2142 using XdsRbacTestWithActionPermutations = XdsRbacTest;
2143
2144 TEST_P(XdsRbacTestWithActionPermutations, EmptyRbacPolicy) {
2145 RBAC rbac;
2146 rbac.mutable_rules()->set_action(GetParam().rbac_action());
2147 SetServerRbacPolicy(rbac);
2148 backends_[0]->Start();
2149 backends_[0]->notifier()->WaitOnServingStatusChange(
2150 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2151 grpc::StatusCode::OK);
2152 // An empty RBAC policy leads to all RPCs being rejected.
2153 SendRpc(
2154 [this]() { return CreateInsecureChannel(); }, {}, {},
2155 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2156 grpc::StatusCode::PERMISSION_DENIED);
2157 }
2158
2159 TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionAnyPrincipal) {
2160 RBAC rbac;
2161 auto* rules = rbac.mutable_rules();
2162 rules->set_action(GetParam().rbac_action());
2163 Policy policy;
2164 policy.add_permissions()->set_any(true);
2165 policy.add_principals()->set_any(true);
2166 (*rules->mutable_policies())["policy"] = policy;
2167 SetServerRbacPolicy(rbac);
2168 backends_[0]->Start();
2169 backends_[0]->notifier()->WaitOnServingStatusChange(
2170 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2171 grpc::StatusCode::OK);
2172 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2173 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2174 grpc::StatusCode::PERMISSION_DENIED);
2175 }
2176
2177 TEST_P(XdsRbacTestWithActionPermutations, MultipleRbacPolicies) {
2178 RBAC always_allow;
2179 auto* rules = always_allow.mutable_rules();
2180 rules->set_action(RBAC_Action_ALLOW);
2181 Policy policy;
2182 policy.add_permissions()->set_any(true);
2183 policy.add_principals()->set_any(true);
2184 (*rules->mutable_policies())["policy"] = policy;
2185 RBAC rbac;
2186 rules = rbac.mutable_rules();
2187 rules->set_action(GetParam().rbac_action());
2188 (*rules->mutable_policies())["policy"] = policy;
2189 SetServerRbacPolicies(default_server_listener_,
2190 {always_allow, rbac, always_allow});
2191 backends_[0]->Start();
2192 backends_[0]->notifier()->WaitOnServingStatusChange(
2193 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2194 grpc::StatusCode::OK);
2195 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2196 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2197 grpc::StatusCode::PERMISSION_DENIED);
2198 }
2199
2200 TEST_P(XdsRbacTestWithActionPermutations, MethodPostPermissionAnyPrincipal) {
2201 RBAC rbac;
2202 auto* rules = rbac.mutable_rules();
2203 rules->set_action(GetParam().rbac_action());
2204 Policy policy;
2205 auto* header = policy.add_permissions()->mutable_header();
2206 header->set_name(":method");
2207 header->set_exact_match("POST");
2208 policy.add_principals()->set_any(true);
2209 (*rules->mutable_policies())["policy"] = policy;
2210 SetServerRbacPolicy(rbac);
2211 backends_[0]->set_allow_put_requests(true);
2212 backends_[0]->Start();
2213 backends_[0]->notifier()->WaitOnServingStatusChange(
2214 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2215 grpc::StatusCode::OK);
2216 // All RPCs use POST method by default
2217 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2218 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2219 grpc::StatusCode::PERMISSION_DENIED);
2220 // Test that an RPC with PUT method is handled properly.
2221 SendRpc([this]() { return CreateInsecureChannel(/*use_put_requests=*/true); },
2222 {}, {},
2223 /*test_expects_failure=*/GetParam().rbac_action() != RBAC_Action_DENY,
2224 grpc::StatusCode::PERMISSION_DENIED);
2225 }
2226
2227 TEST_P(XdsRbacTestWithActionPermutations, MethodGetPermissionAnyPrincipal) {
2228 RBAC rbac;
2229 auto* rules = rbac.mutable_rules();
2230 rules->set_action(GetParam().rbac_action());
2231 Policy policy;
2232 auto* header = policy.add_permissions()->mutable_header();
2233 header->set_name(":method");
2234 header->set_exact_match("GET");
2235 policy.add_principals()->set_any(true);
2236 (*rules->mutable_policies())["policy"] = policy;
2237 SetServerRbacPolicy(rbac);
2238 backends_[0]->Start();
2239 backends_[0]->notifier()->WaitOnServingStatusChange(
2240 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2241 grpc::StatusCode::OK);
2242 // Test that an RPC with a POST method gets rejected
2243 SendRpc(
2244 [this]() { return CreateInsecureChannel(); }, {}, {},
2245 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2246 grpc::StatusCode::PERMISSION_DENIED);
2247 // TODO(yashykt): When we start supporting GET requests in the future, this
2248 // should be modified to test that they are accepted with this rule.
2249 }
2250
2251 TEST_P(XdsRbacTestWithActionPermutations, MethodPutPermissionAnyPrincipal) {
2252 RBAC rbac;
2253 auto* rules = rbac.mutable_rules();
2254 rules->set_action(GetParam().rbac_action());
2255 Policy policy;
2256 auto* header = policy.add_permissions()->mutable_header();
2257 header->set_name(":method");
2258 header->set_exact_match("PUT");
2259 policy.add_principals()->set_any(true);
2260 (*rules->mutable_policies())["policy"] = policy;
2261 SetServerRbacPolicy(rbac);
2262 backends_[0]->set_allow_put_requests(true);
2263 backends_[0]->Start();
2264 backends_[0]->notifier()->WaitOnServingStatusChange(
2265 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2266 grpc::StatusCode::OK);
2267 // Test that an RPC with a POST method gets rejected
2268 SendRpc(
2269 [this]() { return CreateInsecureChannel(); }, {}, {},
2270 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2271 grpc::StatusCode::PERMISSION_DENIED);
2272 // Test that an RPC with a PUT method gets accepted
2273 SendRpc(
2274 [this]() { return CreateInsecureChannel(/*use_put_requests=*/true); }, {},
2275 {},
2276 /*test_expects_failure=*/GetParam().rbac_action() != RBAC_Action_ALLOW,
2277 grpc::StatusCode::PERMISSION_DENIED);
2278 }
2279
2280 TEST_P(XdsRbacTestWithActionPermutations, UrlPathPermissionAnyPrincipal) {
2281 RBAC rbac;
2282 auto* rules = rbac.mutable_rules();
2283 rules->set_action(GetParam().rbac_action());
2284 Policy policy;
2285 policy.add_permissions()->mutable_url_path()->mutable_path()->set_exact(
2286 "/grpc.testing.EchoTestService/Echo");
2287 policy.add_principals()->set_any(true);
2288 (*rules->mutable_policies())["policy"] = policy;
2289 SetServerRbacPolicy(rbac);
2290 backends_[0]->Start();
2291 backends_[0]->notifier()->WaitOnServingStatusChange(
2292 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2293 grpc::StatusCode::OK);
2294 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2295 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2296 grpc::StatusCode::PERMISSION_DENIED);
2297 // Test an RPC with a different URL path
2298 auto stub = grpc::testing::EchoTestService::NewStub(CreateInsecureChannel());
2299 ClientContext context;
2300 context.set_wait_for_ready(true);
2301 context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
2302 EchoRequest request;
2303 request.set_message(kRequestMessage);
2304 EchoResponse response;
2305 Status status = stub->Echo1(&context, request, &response);
2306 EXPECT_TRUE(GetParam().rbac_action() == RBAC_Action_DENY ? status.ok()
2307 : !status.ok())
2308 << status.error_code() << ", " << status.error_message() << ", "
2309 << status.error_details() << ", " << context.debug_error_string();
2310 }
2311
2312 TEST_P(XdsRbacTestWithActionPermutations, DestinationIpPermissionAnyPrincipal) {
2313 RBAC rbac;
2314 auto* rules = rbac.mutable_rules();
2315 rules->set_action(GetParam().rbac_action());
2316 Policy policy;
2317 auto* range = policy.add_permissions()->mutable_destination_ip();
2318 range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
2319 range->mutable_prefix_len()->set_value(ipv6_only_ ? 128 : 32);
2320 policy.add_principals()->set_any(true);
2321 (*rules->mutable_policies())["policy"] = policy;
2322 SetServerRbacPolicy(rbac);
2323 backends_[0]->Start();
2324 backends_[0]->notifier()->WaitOnServingStatusChange(
2325 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2326 grpc::StatusCode::OK);
2327 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2328 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2329 grpc::StatusCode::PERMISSION_DENIED);
2330 // Change the policy itself for a negative test where there is no match.
2331 policy.clear_permissions();
2332 range = policy.add_permissions()->mutable_destination_ip();
2333 range->set_address_prefix(ipv6_only_ ? "::2" : "127.0.0.2");
2334 range->mutable_prefix_len()->set_value(ipv6_only_ ? 128 : 32);
2335 (*rules->mutable_policies())["policy"] = policy;
2336 SetServerRbacPolicy(rbac);
2337 SendRpc(
2338 [this]() { return CreateInsecureChannel(); }, {}, {},
2339 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2340 grpc::StatusCode::PERMISSION_DENIED);
2341 }
2342
2343 TEST_P(XdsRbacTestWithActionPermutations,
2344 DestinationPortPermissionAnyPrincipal) {
2345 RBAC rbac;
2346 auto* rules = rbac.mutable_rules();
2347 rules->set_action(GetParam().rbac_action());
2348 Policy policy;
2349 policy.add_permissions()->set_destination_port(backends_[0]->port());
2350 policy.add_principals()->set_any(true);
2351 (*rules->mutable_policies())["policy"] = policy;
2352 SetServerRbacPolicy(rbac);
2353 backends_[0]->Start();
2354 backends_[0]->notifier()->WaitOnServingStatusChange(
2355 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2356 grpc::StatusCode::OK);
2357 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2358 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2359 grpc::StatusCode::PERMISSION_DENIED);
2360 // Change the policy itself for a negative test where there is no match.
2361 policy.clear_permissions();
2362 policy.add_permissions()->set_destination_port(1);
2363 (*rules->mutable_policies())["policy"] = policy;
2364 SetServerRbacPolicy(rbac);
2365 SendRpc(
2366 [this]() { return CreateInsecureChannel(); }, {}, {},
2367 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2368 grpc::StatusCode::PERMISSION_DENIED);
2369 }
2370
2371 TEST_P(XdsRbacTestWithActionPermutations, MetadataPermissionAnyPrincipal) {
2372 RBAC rbac;
2373 auto* rules = rbac.mutable_rules();
2374 rules->set_action(GetParam().rbac_action());
2375 Policy policy;
2376 policy.add_permissions()->mutable_metadata();
2377 policy.add_principals()->set_any(true);
2378 (*rules->mutable_policies())["policy"] = policy;
2379 SetServerRbacPolicy(rbac);
2380 backends_[0]->Start();
2381 backends_[0]->notifier()->WaitOnServingStatusChange(
2382 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2383 grpc::StatusCode::OK);
2384 SendRpc(
2385 [this]() { return CreateInsecureChannel(); }, {}, {},
2386 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2387 grpc::StatusCode::PERMISSION_DENIED);
2388 // Test metadata with inverted match
2389 policy.clear_permissions();
2390 policy.add_permissions()->mutable_metadata()->set_invert(true);
2391 (*rules->mutable_policies())["policy"] = policy;
2392 SetServerRbacPolicy(rbac);
2393 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2394 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2395 grpc::StatusCode::PERMISSION_DENIED);
2396 }
2397
2398 TEST_P(XdsRbacTestWithActionPermutations, ReqServerNamePermissionAnyPrincipal) {
2399 RBAC rbac;
2400 auto* rules = rbac.mutable_rules();
2401 rules->set_action(GetParam().rbac_action());
2402 Policy policy;
2403 policy.add_principals()->set_any(true);
2404 policy.add_permissions()->mutable_requested_server_name()->set_exact(
2405 "server_name");
2406 (*rules->mutable_policies())["policy"] = policy;
2407 SetServerRbacPolicy(rbac);
2408 backends_[0]->Start();
2409 backends_[0]->notifier()->WaitOnServingStatusChange(
2410 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2411 grpc::StatusCode::OK);
2412 SendRpc(
2413 [this]() { return CreateInsecureChannel(); }, {}, {},
2414 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2415 grpc::StatusCode::PERMISSION_DENIED);
2416 policy.clear_permissions();
2417 policy.add_permissions()->mutable_requested_server_name()->set_exact("");
2418 (*rules->mutable_policies())["policy"] = policy;
2419 SetServerRbacPolicy(rbac);
2420 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2421 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2422 grpc::StatusCode::PERMISSION_DENIED);
2423 }
2424
2425 TEST_P(XdsRbacTestWithActionPermutations, NotRulePermissionAnyPrincipal) {
2426 RBAC rbac;
2427 auto* rules = rbac.mutable_rules();
2428 rules->set_action(GetParam().rbac_action());
2429 Policy policy;
2430 policy.add_permissions()
2431 ->mutable_not_rule()
2432 ->mutable_requested_server_name()
2433 ->set_exact("server_name");
2434 policy.add_principals()->set_any(true);
2435 (*rules->mutable_policies())["policy"] = policy;
2436 SetServerRbacPolicy(rbac);
2437 backends_[0]->Start();
2438 backends_[0]->notifier()->WaitOnServingStatusChange(
2439 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2440 grpc::StatusCode::OK);
2441 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2442 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2443 grpc::StatusCode::PERMISSION_DENIED);
2444 // Change the policy itself for a negative test where there is no match.
2445 policy.clear_permissions();
2446 policy.add_permissions()->mutable_not_rule()->set_any(true);
2447 (*rules->mutable_policies())["policy"] = policy;
2448 SetServerRbacPolicy(rbac);
2449 SendRpc(
2450 [this]() { return CreateInsecureChannel(); }, {}, {},
2451 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2452 grpc::StatusCode::PERMISSION_DENIED);
2453 }
2454
2455 TEST_P(XdsRbacTestWithActionPermutations, AndRulePermissionAnyPrincipal) {
2456 RBAC rbac;
2457 auto* rules = rbac.mutable_rules();
2458 rules->set_action(GetParam().rbac_action());
2459 Policy policy;
2460 auto* and_rules = policy.add_permissions()->mutable_and_rules();
2461 and_rules->add_rules()->set_any(true);
2462 and_rules->add_rules()->set_destination_port(backends_[0]->port());
2463 policy.add_principals()->set_any(true);
2464 (*rules->mutable_policies())["policy"] = policy;
2465 SetServerRbacPolicy(rbac);
2466 backends_[0]->Start();
2467 backends_[0]->notifier()->WaitOnServingStatusChange(
2468 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2469 grpc::StatusCode::OK);
2470 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2471 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2472 grpc::StatusCode::PERMISSION_DENIED);
2473 // Change the policy itself for a negative test where there is no match.
2474 and_rules = (*policy.mutable_permissions())[0].mutable_and_rules();
2475 (*and_rules->mutable_rules())[1].set_destination_port(1);
2476 (*rules->mutable_policies())["policy"] = policy;
2477 SetServerRbacPolicy(rbac);
2478 SendRpc(
2479 [this]() { return CreateInsecureChannel(); }, {}, {},
2480 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2481 grpc::StatusCode::PERMISSION_DENIED);
2482 }
2483
2484 TEST_P(XdsRbacTestWithActionPermutations, OrRulePermissionAnyPrincipal) {
2485 RBAC rbac;
2486 auto* rules = rbac.mutable_rules();
2487 rules->set_action(GetParam().rbac_action());
2488 Policy policy;
2489 auto* or_rules = policy.add_permissions()->mutable_or_rules();
2490 or_rules->add_rules()->mutable_not_rule()->set_any(true);
2491 or_rules->add_rules()->set_destination_port(backends_[0]->port());
2492 policy.add_principals()->set_any(true);
2493 (*rules->mutable_policies())["policy"] = policy;
2494 SetServerRbacPolicy(rbac);
2495 backends_[0]->Start();
2496 backends_[0]->notifier()->WaitOnServingStatusChange(
2497 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2498 grpc::StatusCode::OK);
2499 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2500 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2501 grpc::StatusCode::PERMISSION_DENIED);
2502 // Change the policy itself for a negative test where there is no match.
2503 or_rules = (*policy.mutable_permissions())[0].mutable_or_rules();
2504 (*or_rules->mutable_rules())[1].set_destination_port(1);
2505 (*rules->mutable_policies())["policy"] = policy;
2506 SetServerRbacPolicy(rbac);
2507 SendRpc(
2508 [this]() { return CreateInsecureChannel(); }, {}, {},
2509 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2510 grpc::StatusCode::PERMISSION_DENIED);
2511 }
2512
2513 TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionMethodPostPrincipal) {
2514 RBAC rbac;
2515 auto* rules = rbac.mutable_rules();
2516 rules->set_action(GetParam().rbac_action());
2517 Policy policy;
2518 auto* header = policy.add_principals()->mutable_header();
2519 header->set_name(":method");
2520 header->set_exact_match("POST");
2521 policy.add_permissions()->set_any(true);
2522 (*rules->mutable_policies())["policy"] = policy;
2523 SetServerRbacPolicy(rbac);
2524 backends_[0]->set_allow_put_requests(true);
2525 backends_[0]->Start();
2526 backends_[0]->notifier()->WaitOnServingStatusChange(
2527 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2528 grpc::StatusCode::OK);
2529 // All RPCs use POST method by default
2530 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2531 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2532 grpc::StatusCode::PERMISSION_DENIED);
2533 // Test that an RPC with PUT method is handled properly.
2534 SendRpc([this]() { return CreateInsecureChannel(/*use_put_requests=*/true); },
2535 {}, {},
2536 /*test_expects_failure=*/GetParam().rbac_action() != RBAC_Action_DENY,
2537 grpc::StatusCode::PERMISSION_DENIED);
2538 }
2539
2540 TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionMethodGetPrincipal) {
2541 RBAC rbac;
2542 auto* rules = rbac.mutable_rules();
2543 rules->set_action(GetParam().rbac_action());
2544 Policy policy;
2545 auto* header = policy.add_principals()->mutable_header();
2546 header->set_name(":method");
2547 header->set_exact_match("GET");
2548 policy.add_permissions()->set_any(true);
2549 (*rules->mutable_policies())["policy"] = policy;
2550 SetServerRbacPolicy(rbac);
2551 backends_[0]->Start();
2552 backends_[0]->notifier()->WaitOnServingStatusChange(
2553 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2554 grpc::StatusCode::OK);
2555 // Test that an RPC with a POST method gets rejected
2556 SendRpc(
2557 [this]() { return CreateInsecureChannel(); }, {}, {},
2558 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2559 grpc::StatusCode::PERMISSION_DENIED);
2560 // TODO(yashykt): When we start supporting GET requests in the future, this
2561 // should be modified to test that they are accepted with this rule.
2562 }
2563
2564 TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionMethodPutPrincipal) {
2565 RBAC rbac;
2566 auto* rules = rbac.mutable_rules();
2567 rules->set_action(GetParam().rbac_action());
2568 Policy policy;
2569 auto* header = policy.add_principals()->mutable_header();
2570 header->set_name(":method");
2571 header->set_exact_match("PUT");
2572 policy.add_permissions()->set_any(true);
2573 (*rules->mutable_policies())["policy"] = policy;
2574 SetServerRbacPolicy(rbac);
2575 backends_[0]->set_allow_put_requests(true);
2576 backends_[0]->Start();
2577 backends_[0]->notifier()->WaitOnServingStatusChange(
2578 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2579 grpc::StatusCode::OK);
2580 // Test that an RPC with a PUT method gets accepted
2581 SendRpc(
2582 [this]() { return CreateInsecureChannel(/*use_put_requests=*/true); }, {},
2583 {},
2584 /*test_expects_failure=*/GetParam().rbac_action() != RBAC_Action_ALLOW,
2585 grpc::StatusCode::PERMISSION_DENIED);
2586 // Test that an RPC with a POST method gets rejected
2587 SendRpc(
2588 [this]() { return CreateInsecureChannel(); }, {}, {},
2589 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2590 grpc::StatusCode::PERMISSION_DENIED);
2591 }
2592
2593 TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionUrlPathPrincipal) {
2594 RBAC rbac;
2595 auto* rules = rbac.mutable_rules();
2596 rules->set_action(GetParam().rbac_action());
2597 Policy policy;
2598 policy.add_principals()->mutable_url_path()->mutable_path()->set_exact(
2599 "/grpc.testing.EchoTestService/Echo");
2600 policy.add_permissions()->set_any(true);
2601 (*rules->mutable_policies())["policy"] = policy;
2602 SetServerRbacPolicy(rbac);
2603 backends_[0]->Start();
2604 backends_[0]->notifier()->WaitOnServingStatusChange(
2605 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2606 grpc::StatusCode::OK);
2607 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2608 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2609 grpc::StatusCode::PERMISSION_DENIED);
2610 // Test an RPC with a different URL path
2611 auto stub = grpc::testing::EchoTestService::NewStub(CreateInsecureChannel());
2612 ClientContext context;
2613 context.set_wait_for_ready(true);
2614 context.set_deadline(grpc_timeout_milliseconds_to_deadline(2000));
2615 EchoRequest request;
2616 request.set_message(kRequestMessage);
2617 EchoResponse response;
2618 Status status = stub->Echo1(&context, request, &response);
2619 EXPECT_TRUE(GetParam().rbac_action() == RBAC_Action_DENY ? status.ok()
2620 : !status.ok())
2621 << status.error_code() << ", " << status.error_message() << ", "
2622 << status.error_details() << ", " << context.debug_error_string();
2623 }
2624
2625 TEST_P(XdsRbacTestWithActionPermutations,
2626 AnyPermissionDirectRemoteIpPrincipal) {
2627 RBAC rbac;
2628 auto* rules = rbac.mutable_rules();
2629 rules->set_action(GetParam().rbac_action());
2630 Policy policy;
2631 auto* range = policy.add_principals()->mutable_direct_remote_ip();
2632 range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
2633 range->mutable_prefix_len()->set_value(ipv6_only_ ? 128 : 32);
2634 policy.add_permissions()->set_any(true);
2635 (*rules->mutable_policies())["policy"] = policy;
2636 SetServerRbacPolicy(rbac);
2637 backends_[0]->Start();
2638 backends_[0]->notifier()->WaitOnServingStatusChange(
2639 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2640 grpc::StatusCode::OK);
2641 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2642 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2643 grpc::StatusCode::PERMISSION_DENIED);
2644 // Change the policy itself for a negative test where there is no match.
2645 policy.clear_principals();
2646 range = policy.add_principals()->mutable_direct_remote_ip();
2647 range->set_address_prefix(ipv6_only_ ? "::2" : "127.0.0.2");
2648 range->mutable_prefix_len()->set_value(ipv6_only_ ? 128 : 32);
2649 (*rules->mutable_policies())["policy"] = policy;
2650 SetServerRbacPolicy(rbac);
2651 SendRpc(
2652 [this]() { return CreateInsecureChannel(); }, {}, {},
2653 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2654 grpc::StatusCode::PERMISSION_DENIED);
2655 }
2656
2657 TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionRemoteIpPrincipal) {
2658 RBAC rbac;
2659 auto* rules = rbac.mutable_rules();
2660 rules->set_action(GetParam().rbac_action());
2661 Policy policy;
2662 auto* range = policy.add_principals()->mutable_remote_ip();
2663 range->set_address_prefix(ipv6_only_ ? "::1" : "127.0.0.1");
2664 range->mutable_prefix_len()->set_value(ipv6_only_ ? 128 : 32);
2665 policy.add_permissions()->set_any(true);
2666 (*rules->mutable_policies())["policy"] = policy;
2667 SetServerRbacPolicy(rbac);
2668 backends_[0]->Start();
2669 backends_[0]->notifier()->WaitOnServingStatusChange(
2670 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2671 grpc::StatusCode::OK);
2672 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2673 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2674 grpc::StatusCode::PERMISSION_DENIED);
2675 // Change the policy itself for a negative test where there is no match.
2676 policy.clear_principals();
2677 range = policy.add_principals()->mutable_remote_ip();
2678 range->set_address_prefix(ipv6_only_ ? "::2" : "127.0.0.2");
2679 range->mutable_prefix_len()->set_value(ipv6_only_ ? 128 : 32);
2680 (*rules->mutable_policies())["policy"] = policy;
2681 SetServerRbacPolicy(rbac);
2682 SendRpc(
2683 [this]() { return CreateInsecureChannel(); }, {}, {},
2684 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2685 grpc::StatusCode::PERMISSION_DENIED);
2686 }
2687
2688 TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionAuthenticatedPrincipal) {
2689 g_fake1_cert_data_map->Set({{"", {root_cert_, identity_pair_}}});
2690 Listener listener = default_server_listener_;
2691 auto* filter_chain = listener.mutable_default_filter_chain();
2692 auto* transport_socket = filter_chain->mutable_transport_socket();
2693 transport_socket->set_name("envoy.transport_sockets.tls");
2694 DownstreamTlsContext downstream_tls_context;
2695 downstream_tls_context.mutable_common_tls_context()
2696 ->mutable_tls_certificate_provider_instance()
2697 ->set_instance_name("fake_plugin1");
2698 downstream_tls_context.mutable_common_tls_context()
2699 ->mutable_validation_context()
2700 ->mutable_ca_certificate_provider_instance()
2701 ->set_instance_name("fake_plugin1");
2702 downstream_tls_context.mutable_require_client_certificate()->set_value(true);
2703 transport_socket->mutable_typed_config()->PackFrom(downstream_tls_context);
2704 RBAC rbac;
2705 auto* rules = rbac.mutable_rules();
2706 rules->set_action(GetParam().rbac_action());
2707 Policy policy;
2708 policy.add_principals()
2709 ->mutable_authenticated()
2710 ->mutable_principal_name()
2711 ->set_exact("*.test.google.fr");
2712 policy.add_permissions()->set_any(true);
2713 (*rules->mutable_policies())["policy"] = policy;
2714 SetServerRbacPolicy(listener, rbac);
2715 backends_[0]->Start();
2716 backends_[0]->notifier()->WaitOnServingStatusChange(
2717 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2718 grpc::StatusCode::OK);
2719 SendRpc([this]() { return CreateMtlsChannel(); },
2720 server_authenticated_identity_, client_authenticated_identity_,
2721 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2722 grpc::StatusCode::PERMISSION_DENIED);
2723 }
2724
2725 TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionMetadataPrincipal) {
2726 RBAC rbac;
2727 auto* rules = rbac.mutable_rules();
2728 rules->set_action(GetParam().rbac_action());
2729 Policy policy;
2730 policy.add_principals()->mutable_metadata();
2731 policy.add_permissions()->set_any(true);
2732 (*rules->mutable_policies())["policy"] = policy;
2733 SetServerRbacPolicy(rbac);
2734 backends_[0]->Start();
2735 backends_[0]->notifier()->WaitOnServingStatusChange(
2736 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2737 grpc::StatusCode::OK);
2738 SendRpc(
2739 [this]() { return CreateInsecureChannel(); }, {}, {},
2740 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2741 grpc::StatusCode::PERMISSION_DENIED);
2742 // Test metadata with inverted match
2743 policy.clear_principals();
2744 policy.add_principals()->mutable_metadata()->set_invert(true);
2745 (*rules->mutable_policies())["policy"] = policy;
2746 SetServerRbacPolicy(rbac);
2747 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2748 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2749 grpc::StatusCode::PERMISSION_DENIED);
2750 }
2751
2752 TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionNotIdPrincipal) {
2753 RBAC rbac;
2754 auto* rules = rbac.mutable_rules();
2755 rules->set_action(GetParam().rbac_action());
2756 Policy policy;
2757 policy.add_principals()
2758 ->mutable_not_id()
2759 ->mutable_url_path()
2760 ->mutable_path()
2761 ->set_exact("/grpc.testing.EchoTestService/Echo1");
2762 policy.add_permissions()->set_any(true);
2763 (*rules->mutable_policies())["policy"] = policy;
2764 SetServerRbacPolicy(rbac);
2765 backends_[0]->Start();
2766 backends_[0]->notifier()->WaitOnServingStatusChange(
2767 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2768 grpc::StatusCode::OK);
2769 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2770 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2771 grpc::StatusCode::PERMISSION_DENIED);
2772 // Change the policy itself for a negative test where there is no match.
2773 policy.clear_principals();
2774 policy.add_principals()->mutable_not_id()->set_any(true);
2775 (*rules->mutable_policies())["policy"] = policy;
2776 SetServerRbacPolicy(rbac);
2777 SendRpc(
2778 [this]() { return CreateInsecureChannel(); }, {}, {},
2779 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2780 grpc::StatusCode::PERMISSION_DENIED);
2781 }
2782
2783 TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionAndIdPrincipal) {
2784 RBAC rbac;
2785 auto* rules = rbac.mutable_rules();
2786 rules->set_action(GetParam().rbac_action());
2787 Policy policy;
2788 auto* and_ids = policy.add_principals()->mutable_and_ids();
2789 and_ids->add_ids()->set_any(true);
2790 and_ids->add_ids()->mutable_url_path()->mutable_path()->set_exact(
2791 "/grpc.testing.EchoTestService/Echo");
2792 policy.add_permissions()->set_any(true);
2793 (*rules->mutable_policies())["policy"] = policy;
2794 SetServerRbacPolicy(rbac);
2795 backends_[0]->Start();
2796 backends_[0]->notifier()->WaitOnServingStatusChange(
2797 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2798 grpc::StatusCode::OK);
2799 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2800 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2801 grpc::StatusCode::PERMISSION_DENIED);
2802 // Change the policy itself for a negative test where there is no match.
2803 and_ids = (*policy.mutable_principals())[0].mutable_and_ids();
2804 (*and_ids->mutable_ids())[1].mutable_url_path()->mutable_path()->set_exact(
2805 "/grpc.testing.EchoTestService/Echo1");
2806 (*rules->mutable_policies())["policy"] = policy;
2807 SetServerRbacPolicy(rbac);
2808 SendRpc(
2809 [this]() { return CreateInsecureChannel(); }, {}, {},
2810 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2811 grpc::StatusCode::PERMISSION_DENIED);
2812 }
2813
2814 TEST_P(XdsRbacTestWithActionPermutations, AnyPermissionOrIdPrincipal) {
2815 RBAC rbac;
2816 auto* rules = rbac.mutable_rules();
2817 rules->set_action(GetParam().rbac_action());
2818 Policy policy;
2819 auto* or_ids = policy.add_principals()->mutable_or_ids();
2820 or_ids->add_ids()->mutable_not_id()->set_any(true);
2821 or_ids->add_ids()->mutable_url_path()->mutable_path()->set_exact(
2822 "/grpc.testing.EchoTestService/Echo");
2823 policy.add_permissions()->set_any(true);
2824 (*rules->mutable_policies())["policy"] = policy;
2825 SetServerRbacPolicy(rbac);
2826 backends_[0]->Start();
2827 backends_[0]->notifier()->WaitOnServingStatusChange(
2828 absl::StrCat(ipv6_only_ ? "[::1]:" : "127.0.0.1:", backends_[0]->port()),
2829 grpc::StatusCode::OK);
2830 SendRpc([this]() { return CreateInsecureChannel(); }, {}, {},
2831 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_DENY,
2832 grpc::StatusCode::PERMISSION_DENIED);
2833 // Change the policy itself for a negative test where there is no match.
2834 or_ids = (*policy.mutable_principals())[0].mutable_or_ids();
2835 (*or_ids->mutable_ids())[1].mutable_url_path()->mutable_path()->set_exact(
2836 "/grpc.testing.EchoTestService/Echo1");
2837 (*rules->mutable_policies())["policy"] = policy;
2838 SetServerRbacPolicy(rbac);
2839 SendRpc(
2840 [this]() { return CreateInsecureChannel(); }, {}, {},
2841 /*test_expects_failure=*/GetParam().rbac_action() == RBAC_Action_ALLOW,
2842 grpc::StatusCode::PERMISSION_DENIED);
2843 }
2844
2845 // CDS depends on XdsResolver.
2846 // Security depends on v3.
2847 // Not enabling load reporting or RDS, since those are irrelevant to these
2848 // tests.
2849 INSTANTIATE_TEST_SUITE_P(
2850 XdsTest, XdsSecurityTest,
2851 ::testing::Values(XdsTestType().set_use_xds_credentials()),
2852 &XdsTestType::Name);
2853
2854 // We are only testing the server here.
2855 // Run with bootstrap from env var, so that we use a global XdsClient
2856 // instance. Otherwise, we would need to use a separate fake resolver
2857 // result generator on the client and server sides.
2858 INSTANTIATE_TEST_SUITE_P(XdsTest, XdsEnabledServerTest,
2859 ::testing::Values(XdsTestType().set_bootstrap_source(
2860 XdsTestType::kBootstrapFromEnvVar)),
2861 &XdsTestType::Name);
2862
2863 // We are only testing the server here.
2864 // Run with bootstrap from env var so that we use one XdsClient.
2865 INSTANTIATE_TEST_SUITE_P(
2866 XdsTest, XdsServerSecurityTest,
2867 ::testing::Values(
2868 XdsTestType()
2869 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar)
2870 .set_use_xds_credentials()),
2871 &XdsTestType::Name);
2872
2873 INSTANTIATE_TEST_SUITE_P(
2874 XdsTest, XdsEnabledServerStatusNotificationTest,
2875 ::testing::Values(XdsTestType().set_use_xds_credentials()),
2876 &XdsTestType::Name);
2877
2878 // Run with bootstrap from env var so that we use one XdsClient.
2879 INSTANTIATE_TEST_SUITE_P(
2880 XdsTest, XdsServerFilterChainMatchTest,
2881 ::testing::Values(
2882 XdsTestType()
2883 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar)
2884 .set_use_xds_credentials()),
2885 &XdsTestType::Name);
2886
2887 // Test xDS-enabled server with and without RDS.
2888 // Run with bootstrap from env var so that we use one XdsClient.
2889 INSTANTIATE_TEST_SUITE_P(
2890 XdsTest, XdsServerRdsTest,
2891 ::testing::Values(
2892 XdsTestType()
2893 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar)
2894 .set_use_xds_credentials(),
2895 XdsTestType()
2896 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar)
2897 .set_use_xds_credentials()
2898 .set_enable_rds_testing()),
2899 &XdsTestType::Name);
2900
2901 // We are only testing the server here.
2902 // Run with bootstrap from env var, so that we use a global XdsClient
2903 // instance. Otherwise, we would need to use a separate fake resolver
2904 // result generator on the client and server sides.
2905 INSTANTIATE_TEST_SUITE_P(
2906 XdsTest, XdsRbacTest,
2907 ::testing::Values(
2908 XdsTestType().set_use_xds_credentials().set_bootstrap_source(
2909 XdsTestType::kBootstrapFromEnvVar),
2910 XdsTestType()
2911 .set_use_xds_credentials()
2912 .set_enable_rds_testing()
2913 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar),
2914 XdsTestType()
2915 .set_use_xds_credentials()
2916 .set_filter_config_setup(
2917 XdsTestType::HttpFilterConfigLocation::kHttpFilterConfigInRoute)
2918 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar),
2919 XdsTestType()
2920 .set_use_xds_credentials()
2921 .set_enable_rds_testing()
2922 .set_filter_config_setup(
2923 XdsTestType::HttpFilterConfigLocation::kHttpFilterConfigInRoute)
2924 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar)),
2925 &XdsTestType::Name);
2926
2927 // We are only testing the server here.
2928 // Run with bootstrap from env var, so that we use a global XdsClient
2929 // instance. Otherwise, we would need to use a separate fake resolver
2930 // result generator on the client and server sides.
2931 INSTANTIATE_TEST_SUITE_P(
2932 XdsTest, XdsRbacTestWithRouteOverrideAlwaysPresent,
2933 ::testing::Values(
2934 XdsTestType()
2935 .set_use_xds_credentials()
2936 .set_filter_config_setup(
2937 XdsTestType::HttpFilterConfigLocation::kHttpFilterConfigInRoute)
2938 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar),
2939 XdsTestType()
2940 .set_use_xds_credentials()
2941 .set_enable_rds_testing()
2942 .set_filter_config_setup(
2943 XdsTestType::HttpFilterConfigLocation::kHttpFilterConfigInRoute)
2944 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar)),
2945 &XdsTestType::Name);
2946
2947 // We are only testing the server here.
2948 // Run with bootstrap from env var, so that we use a global XdsClient
2949 // instance. Otherwise, we would need to use a separate fake resolver
2950 // result generator on the client and server sides.
2951 INSTANTIATE_TEST_SUITE_P(
2952 XdsTest, XdsRbacTestWithActionPermutations,
2953 ::testing::Values(
2954 XdsTestType()
2955 .set_use_xds_credentials()
2956 .set_rbac_action(RBAC_Action_ALLOW)
2957 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar),
2958 XdsTestType()
2959 .set_use_xds_credentials()
2960 .set_rbac_action(RBAC_Action_DENY)
2961 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar),
2962 XdsTestType()
2963 .set_use_xds_credentials()
2964 .set_enable_rds_testing()
2965 .set_rbac_action(RBAC_Action_ALLOW)
2966 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar),
2967 XdsTestType()
2968 .set_use_xds_credentials()
2969 .set_enable_rds_testing()
2970 .set_rbac_action(RBAC_Action_DENY)
2971 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar),
2972 XdsTestType()
2973 .set_use_xds_credentials()
2974 .set_filter_config_setup(
2975 XdsTestType::HttpFilterConfigLocation::kHttpFilterConfigInRoute)
2976 .set_rbac_action(RBAC_Action_ALLOW)
2977 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar),
2978 XdsTestType()
2979 .set_use_xds_credentials()
2980 .set_filter_config_setup(
2981 XdsTestType::HttpFilterConfigLocation::kHttpFilterConfigInRoute)
2982 .set_rbac_action(RBAC_Action_DENY)
2983 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar),
2984 XdsTestType()
2985 .set_use_xds_credentials()
2986 .set_enable_rds_testing()
2987 .set_filter_config_setup(
2988 XdsTestType::HttpFilterConfigLocation::kHttpFilterConfigInRoute)
2989 .set_rbac_action(RBAC_Action_ALLOW)
2990 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar),
2991 XdsTestType()
2992 .set_use_xds_credentials()
2993 .set_enable_rds_testing()
2994 .set_filter_config_setup(
2995 XdsTestType::HttpFilterConfigLocation::kHttpFilterConfigInRoute)
2996 .set_rbac_action(RBAC_Action_DENY)
2997 .set_bootstrap_source(XdsTestType::kBootstrapFromEnvVar)),
2998 &XdsTestType::Name);
2999
3000 } // namespace
3001 } // namespace testing
3002 } // namespace grpc
3003
3004 int main(int argc, char** argv) {
3005 grpc::testing::TestEnvironment env(&argc, argv);
3006 ::testing::InitGoogleTest(&argc, argv);
3007 // Make the backup poller poll very frequently in order to pick up
3008 // updates from all the subchannels's FDs.
3009 GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
3010 #if TARGET_OS_IPHONE
3011 // Workaround Apple CFStream bug
3012 grpc_core::SetEnv("grpc_cfstream", "0");
3013 #endif
3014 grpc::testing::FakeCertificateProvider::CertDataMapWrapper cert_data_map_1;
3015 grpc::testing::g_fake1_cert_data_map = &cert_data_map_1;
3016 grpc::testing::FakeCertificateProvider::CertDataMapWrapper cert_data_map_2;
3017 grpc::testing::g_fake2_cert_data_map = &cert_data_map_2;
3018 grpc_core::CoreConfiguration::RegisterBuilder(
3019 [](grpc_core::CoreConfiguration::Builder* builder) {
3020 builder->certificate_provider_registry()
3021 ->RegisterCertificateProviderFactory(
3022 std::make_unique<grpc::testing::FakeCertificateProviderFactory>(
3023 "fake1", grpc::testing::g_fake1_cert_data_map));
3024 builder->certificate_provider_registry()
3025 ->RegisterCertificateProviderFactory(
3026 std::make_unique<grpc::testing::FakeCertificateProviderFactory>(
3027 "fake2", grpc::testing::g_fake2_cert_data_map));
3028 });
3029 grpc_init();
3030 const auto result = RUN_ALL_TESTS();
3031 grpc_shutdown();
3032 return result;
3033 }