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