Debian Codegraph @

tools/run_tests/xds_k8s_test_driver/tests/authz_test.py

raw
1 # Copyright 2021 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 import datetime
16 import time
17 from typing import Optional
18
19 from absl import flags
20 from absl.testing import absltest
21 import grpc
22
23 from framework import xds_k8s_testcase
24 from framework.helpers import skips
25
26 flags.adopt_module_key_flags(xds_k8s_testcase)
27
28 # Type aliases
29 _XdsTestServer = xds_k8s_testcase.XdsTestServer
30 _XdsTestClient = xds_k8s_testcase.XdsTestClient
31 _SecurityMode = xds_k8s_testcase.SecurityXdsKubernetesTestCase.SecurityMode
32 _Lang = skips.Lang
33
34 # The client generates QPS even when it is still loading information from xDS.
35 # Once it finally connects there will be an outpouring of the bufferred RPCs and
36 # the server needs time to chew through the backlog, especially since it is
37 # still a new process and so probably interpreted. The server on one run
38 # processed 225 RPCs a second, so with the client configured for 25 qps this is
39 # 40 seconds worth of buffering before starting to drain the backlog.
40 _SETTLE_DURATION = datetime.timedelta(seconds=5)
41 _SAMPLE_DURATION = datetime.timedelta(seconds=0.5)
42
43
44 class AuthzTest(xds_k8s_testcase.SecurityXdsKubernetesTestCase):
45 RPC_TYPE_CYCLE = {
46 'UNARY_CALL': 'EMPTY_CALL',
47 'EMPTY_CALL': 'UNARY_CALL',
48 }
49
50 @staticmethod
51 def is_supported(config: skips.TestConfig) -> bool:
52 # Per "Authorization (RBAC)" in
53 # https://github.com/grpc/grpc/blob/master/doc/grpc_xds_features.md
54 if config.client_lang in _Lang.CPP | _Lang.PYTHON:
55 return config.version_gte('v1.47.x')
56 elif config.client_lang in _Lang.GO | _Lang.JAVA:
57 return config.version_gte('v1.42.x')
58 elif config.client_lang == _Lang.NODE:
59 return False
60 return True
61
62 def setUp(self):
63 super().setUp()
64 self.next_rpc_type: Optional[int] = None
65
66 def authz_rules(self):
67 return [
68 {
69 "destinations": {
70 "hosts": [f"*:{self.server_xds_port}"],
71 "ports": [self.server_port],
72 "httpHeaderMatch": {
73 "headerName": "test",
74 "regexMatch": "host-wildcard",
75 },
76 },
77 },
78 {
79 "destinations": {
80 "hosts": [f"*:{self.server_xds_port}"],
81 "ports": [self.server_port],
82 "httpHeaderMatch": {
83 "headerName": "test",
84 "regexMatch": "header-regex-a+",
85 },
86 },
87 },
88 {
89 "destinations": [{
90 "hosts": [f"{self.server_xds_host}:{self.server_xds_port}"],
91 "ports": [self.server_port],
92 "httpHeaderMatch": {
93 "headerName": "test",
94 "regexMatch": "host-match1",
95 },
96 }, {
97 "hosts": [
98 f"a-not-it.com:{self.server_xds_port}",
99 f"{self.server_xds_host}:{self.server_xds_port}",
100 "z-not-it.com:1",
101 ],
102 "ports": [1, self.server_port, 65535],
103 "httpHeaderMatch": {
104 "headerName": "test",
105 "regexMatch": "host-match2",
106 },
107 }],
108 },
109 {
110 "destinations": {
111 "hosts": [
112 f"not-the-host:{self.server_xds_port}",
113 "not-the-host",
114 ],
115 "ports": [self.server_port],
116 "httpHeaderMatch": {
117 "headerName": "test",
118 "regexMatch": "never-match-host",
119 },
120 },
121 },
122 {
123 "destinations": {
124 "hosts": [f"*:{self.server_xds_port}"],
125 "ports": [1],
126 "httpHeaderMatch": {
127 "headerName": "test",
128 "regexMatch": "never-match-port",
129 },
130 },
131 },
132 # b/202058316. The wildcard principal is generating invalid config
133 # {
134 # "sources": {
135 # "principals": ["*"],
136 # },
137 # "destinations": {
138 # "hosts": [f"*:{self.server_xds_port}"],
139 # "ports": [self.server_port],
140 # "httpHeaderMatch": {
141 # "headerName": "test",
142 # "regexMatch": "principal-present",
143 # },
144 # },
145 # },
146 {
147 "sources": [{
148 "principals": [
149 f"spiffe://{self.project}.svc.id.goog/not/the/client",
150 ],
151 }, {
152 "principals": [
153 f"spiffe://{self.project}.svc.id.goog/not/the/client",
154 f"spiffe://{self.project}.svc.id.goog/ns/"
155 f"{self.client_namespace}/sa/{self.client_name}",
156 ],
157 }],
158 "destinations": {
159 "hosts": [f"*:{self.server_xds_port}"],
160 "ports": [self.server_port],
161 "httpHeaderMatch": {
162 "headerName": "test",
163 "regexMatch": "match-principal",
164 },
165 },
166 },
167 {
168 "sources": {
169 "principals": [
170 f"spiffe://{self.project}.svc.id.goog/not/the/client",
171 ],
172 },
173 "destinations": {
174 "hosts": [f"*:{self.server_xds_port}"],
175 "ports": [self.server_port],
176 "httpHeaderMatch": {
177 "headerName": "test",
178 "regexMatch": "never-match-principal",
179 },
180 },
181 },
182 ]
183
184 def configure_and_assert(self, test_client: _XdsTestClient,
185 test_metadata_val: Optional[str],
186 status_code: grpc.StatusCode) -> None:
187 # Swap method type every sub-test to avoid mixing results
188 rpc_type = self.next_rpc_type
189 if rpc_type is None:
190 stats = test_client.get_load_balancer_accumulated_stats()
191 for t in self.RPC_TYPE_CYCLE:
192 if not stats.stats_per_method[t].rpcs_started:
193 rpc_type = t
194 self.assertIsNotNone(rpc_type, "All RPC types already used")
195 self.next_rpc_type = self.RPC_TYPE_CYCLE[rpc_type]
196
197 metadata = None
198 if test_metadata_val is not None:
199 metadata = ((rpc_type, "test", test_metadata_val),)
200 test_client.update_config.configure(rpc_types=[rpc_type],
201 metadata=metadata)
202 # b/228743575 Python has as race. Give us time to fix it.
203 stray_rpc_limit = 1 if self.lang_spec.client_lang == _Lang.PYTHON else 0
204 self.assertRpcStatusCodes(test_client,
205 status_code=status_code,
206 duration=_SAMPLE_DURATION,
207 method=rpc_type,
208 stray_rpc_limit=stray_rpc_limit)
209
210 def test_plaintext_allow(self) -> None:
211 self.setupTrafficDirectorGrpc()
212 self.td.create_authz_policy(action='ALLOW', rules=self.authz_rules())
213 self.setupSecurityPolicies(server_tls=False,
214 server_mtls=False,
215 client_tls=False,
216 client_mtls=False)
217
218 test_server: _XdsTestServer = self.startSecureTestServer()
219 self.setupServerBackends()
220 test_client: _XdsTestClient = self.startSecureTestClient(test_server)
221 time.sleep(_SETTLE_DURATION.total_seconds())
222
223 with self.subTest('01_host_wildcard'):
224 self.configure_and_assert(test_client, 'host-wildcard',
225 grpc.StatusCode.OK)
226
227 with self.subTest('02_no_match'):
228 self.configure_and_assert(test_client, 'no-such-rule',
229 grpc.StatusCode.PERMISSION_DENIED)
230 self.configure_and_assert(test_client, None,
231 grpc.StatusCode.PERMISSION_DENIED)
232
233 with self.subTest('03_header_regex'):
234 self.configure_and_assert(test_client, 'header-regex-a',
235 grpc.StatusCode.OK)
236 self.configure_and_assert(test_client, 'header-regex-aa',
237 grpc.StatusCode.OK)
238 self.configure_and_assert(test_client, 'header-regex-',
239 grpc.StatusCode.PERMISSION_DENIED)
240 self.configure_and_assert(test_client, 'header-regex-ab',
241 grpc.StatusCode.PERMISSION_DENIED)
242 self.configure_and_assert(test_client, 'aheader-regex-a',
243 grpc.StatusCode.PERMISSION_DENIED)
244
245 with self.subTest('04_host_match'):
246 self.configure_and_assert(test_client, 'host-match1',
247 grpc.StatusCode.OK)
248 self.configure_and_assert(test_client, 'host-match2',
249 grpc.StatusCode.OK)
250
251 with self.subTest('05_never_match_host'):
252 self.configure_and_assert(test_client, 'never-match-host',
253 grpc.StatusCode.PERMISSION_DENIED)
254
255 with self.subTest('06_never_match_port'):
256 self.configure_and_assert(test_client, 'never-match-port',
257 grpc.StatusCode.PERMISSION_DENIED)
258
259 # b/202058316
260 # with self.subTest('07_principal_present'):
261 # self.configure_and_assert(test_client, 'principal-present',
262 # grpc.StatusCode.PERMISSION_DENIED)
263
264 def test_tls_allow(self) -> None:
265 self.setupTrafficDirectorGrpc()
266 self.td.create_authz_policy(action='ALLOW', rules=self.authz_rules())
267 self.setupSecurityPolicies(server_tls=True,
268 server_mtls=False,
269 client_tls=True,
270 client_mtls=False)
271
272 test_server: _XdsTestServer = self.startSecureTestServer()
273 self.setupServerBackends()
274 test_client: _XdsTestClient = self.startSecureTestClient(test_server)
275 time.sleep(_SETTLE_DURATION.total_seconds())
276
277 with self.subTest('01_host_wildcard'):
278 self.configure_and_assert(test_client, 'host-wildcard',
279 grpc.StatusCode.OK)
280
281 with self.subTest('02_no_match'):
282 self.configure_and_assert(test_client, None,
283 grpc.StatusCode.PERMISSION_DENIED)
284
285 # b/202058316
286 # with self.subTest('03_principal_present'):
287 # self.configure_and_assert(test_client, 'principal-present',
288 # grpc.StatusCode.PERMISSION_DENIED)
289
290 def test_mtls_allow(self) -> None:
291 self.setupTrafficDirectorGrpc()
292 self.td.create_authz_policy(action='ALLOW', rules=self.authz_rules())
293 self.setupSecurityPolicies(server_tls=True,
294 server_mtls=True,
295 client_tls=True,
296 client_mtls=True)
297
298 test_server: _XdsTestServer = self.startSecureTestServer()
299 self.setupServerBackends()
300 test_client: _XdsTestClient = self.startSecureTestClient(test_server)
301 time.sleep(_SETTLE_DURATION.total_seconds())
302
303 with self.subTest('01_host_wildcard'):
304 self.configure_and_assert(test_client, 'host-wildcard',
305 grpc.StatusCode.OK)
306
307 with self.subTest('02_no_match'):
308 self.configure_and_assert(test_client, None,
309 grpc.StatusCode.PERMISSION_DENIED)
310
311 # b/202058316
312 # with self.subTest('03_principal_present'):
313 # self.configure_and_assert(test_client, 'principal-present',
314 # grpc.StatusCode.OK)
315
316 with self.subTest('04_match_principal'):
317 self.configure_and_assert(test_client, 'match-principal',
318 grpc.StatusCode.OK)
319
320 with self.subTest('05_never_match_principal'):
321 self.configure_and_assert(test_client, 'never-match-principal',
322 grpc.StatusCode.PERMISSION_DENIED)
323
324 def test_plaintext_deny(self) -> None:
325 self.setupTrafficDirectorGrpc()
326 self.td.create_authz_policy(action='DENY', rules=self.authz_rules())
327 self.setupSecurityPolicies(server_tls=False,
328 server_mtls=False,
329 client_tls=False,
330 client_mtls=False)
331
332 test_server: _XdsTestServer = self.startSecureTestServer()
333 self.setupServerBackends()
334 test_client: _XdsTestClient = self.startSecureTestClient(test_server)
335 time.sleep(_SETTLE_DURATION.total_seconds())
336
337 with self.subTest('01_host_wildcard'):
338 self.configure_and_assert(test_client, 'host-wildcard',
339 grpc.StatusCode.PERMISSION_DENIED)
340
341 with self.subTest('02_no_match'):
342 self.configure_and_assert(test_client, None, grpc.StatusCode.OK)
343
344
345 if __name__ == '__main__':
346 absltest.main()