auth_context_test.py
Go to the documentation of this file.
1 # Copyright 2020 The 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 """Porting auth context tests from sync stack."""
15 
16 import logging
17 import pickle
18 import unittest
19 
20 import grpc
21 from grpc.experimental import aio
22 from grpc.experimental import session_cache
23 import six
24 
25 from tests.unit import resources
26 from tests_aio.unit._test_base import AioTestBase
27 
28 _REQUEST = b'\x00\x00\x00'
29 _RESPONSE = b'\x00\x00\x00'
30 
31 _UNARY_UNARY = '/test/UnaryUnary'
32 
33 _SERVER_HOST_OVERRIDE = 'foo.test.google.fr'
34 _CLIENT_IDS = (
35  b'*.test.google.fr',
36  b'waterzooi.test.google.be',
37  b'*.test.youtube.com',
38  b'192.168.1.3',
39 )
40 _ID = 'id'
41 _ID_KEY = 'id_key'
42 _AUTH_CTX = 'auth_ctx'
43 
44 _PRIVATE_KEY = resources.private_key()
45 _CERTIFICATE_CHAIN = resources.certificate_chain()
46 _TEST_ROOT_CERTIFICATES = resources.test_root_certificates()
47 _SERVER_CERTS = ((_PRIVATE_KEY, _CERTIFICATE_CHAIN),)
48 _PROPERTY_OPTIONS = ((
49  'grpc.ssl_target_name_override',
50  _SERVER_HOST_OVERRIDE,
51 ),)
52 
53 
54 async def handle_unary_unary(unused_request: bytes,
55  servicer_context: aio.ServicerContext):
56  return pickle.dumps({
57  _ID: servicer_context.peer_identities(),
58  _ID_KEY: servicer_context.peer_identity_key(),
59  _AUTH_CTX: servicer_context.auth_context()
60  })
61 
62 
64 
65  async def test_insecure(self):
66  handler = grpc.method_handlers_generic_handler('test', {
67  'UnaryUnary':
68  grpc.unary_unary_rpc_method_handler(handle_unary_unary)
69  })
70  server = aio.server()
71  server.add_generic_rpc_handlers((handler,))
72  port = server.add_insecure_port('[::]:0')
73  await server.start()
74 
75  async with aio.insecure_channel('localhost:%d' % port) as channel:
76  response = await channel.unary_unary(_UNARY_UNARY)(_REQUEST)
77  await server.stop(None)
78 
79  auth_data = pickle.loads(response)
80  self.assertIsNone(auth_data[_ID])
81  self.assertIsNone(auth_data[_ID_KEY])
82  self.assertDictEqual(
83  {
84  'security_level': [b'TSI_SECURITY_NONE'],
85  'transport_security_type': [b'insecure'],
86  }, auth_data[_AUTH_CTX])
87 
88  async def test_secure_no_cert(self):
89  handler = grpc.method_handlers_generic_handler('test', {
90  'UnaryUnary':
91  grpc.unary_unary_rpc_method_handler(handle_unary_unary)
92  })
93  server = aio.server()
94  server.add_generic_rpc_handlers((handler,))
95  server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
96  port = server.add_secure_port('[::]:0', server_cred)
97  await server.start()
98 
99  channel_creds = grpc.ssl_channel_credentials(
100  root_certificates=_TEST_ROOT_CERTIFICATES)
101  channel = aio.secure_channel('localhost:{}'.format(port),
102  channel_creds,
103  options=_PROPERTY_OPTIONS)
104  response = await channel.unary_unary(_UNARY_UNARY)(_REQUEST)
105  await channel.close()
106  await server.stop(None)
107 
108  auth_data = pickle.loads(response)
109  self.assertIsNone(auth_data[_ID])
110  self.assertIsNone(auth_data[_ID_KEY])
111  self.assertDictEqual(
112  {
113  'security_level': [b'TSI_PRIVACY_AND_INTEGRITY'],
114  'transport_security_type': [b'ssl'],
115  'ssl_session_reused': [b'false'],
116  }, auth_data[_AUTH_CTX])
117 
118  async def test_secure_client_cert(self):
119  handler = grpc.method_handlers_generic_handler('test', {
120  'UnaryUnary':
121  grpc.unary_unary_rpc_method_handler(handle_unary_unary)
122  })
123  server = aio.server()
124  server.add_generic_rpc_handlers((handler,))
125  server_cred = grpc.ssl_server_credentials(
126  _SERVER_CERTS,
127  root_certificates=_TEST_ROOT_CERTIFICATES,
128  require_client_auth=True)
129  port = server.add_secure_port('[::]:0', server_cred)
130  await server.start()
131 
132  channel_creds = grpc.ssl_channel_credentials(
133  root_certificates=_TEST_ROOT_CERTIFICATES,
134  private_key=_PRIVATE_KEY,
135  certificate_chain=_CERTIFICATE_CHAIN)
136  channel = aio.secure_channel('localhost:{}'.format(port),
137  channel_creds,
138  options=_PROPERTY_OPTIONS)
139 
140  response = await channel.unary_unary(_UNARY_UNARY)(_REQUEST)
141  await channel.close()
142  await server.stop(None)
143 
144  auth_data = pickle.loads(response)
145  auth_ctx = auth_data[_AUTH_CTX]
146  self.assertCountEqual(_CLIENT_IDS, auth_data[_ID])
147  self.assertEqual('x509_subject_alternative_name', auth_data[_ID_KEY])
148  self.assertSequenceEqual([b'ssl'], auth_ctx['transport_security_type'])
149  self.assertSequenceEqual([b'*.test.google.com'],
150  auth_ctx['x509_common_name'])
151 
152  async def _do_one_shot_client_rpc(self, channel_creds, channel_options,
153  port, expect_ssl_session_reused):
154  channel = aio.secure_channel('localhost:{}'.format(port),
155  channel_creds,
156  options=channel_options)
157  response = await channel.unary_unary(_UNARY_UNARY)(_REQUEST)
158  auth_data = pickle.loads(response)
159  self.assertEqual(expect_ssl_session_reused,
160  auth_data[_AUTH_CTX]['ssl_session_reused'])
161  await channel.close()
162 
163  async def test_session_resumption(self):
164  # Set up a secure server
165  handler = grpc.method_handlers_generic_handler('test', {
166  'UnaryUnary':
167  grpc.unary_unary_rpc_method_handler(handle_unary_unary)
168  })
169  server = aio.server()
170  server.add_generic_rpc_handlers((handler,))
171  server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
172  port = server.add_secure_port('[::]:0', server_cred)
173  await server.start()
174 
175  # Create a cache for TLS session tickets
176  cache = session_cache.ssl_session_cache_lru(1)
177  channel_creds = grpc.ssl_channel_credentials(
178  root_certificates=_TEST_ROOT_CERTIFICATES)
179  channel_options = _PROPERTY_OPTIONS + (
180  ('grpc.ssl_session_cache', cache),)
181 
182  # Initial connection has no session to resume
183  await self._do_one_shot_client_rpc(channel_creds,
184  channel_options,
185  port,
186  expect_ssl_session_reused=[b'false'])
187 
188  # Subsequent connections resume sessions
189  await self._do_one_shot_client_rpc(channel_creds,
190  channel_options,
191  port,
192  expect_ssl_session_reused=[b'true'])
193  await server.stop(None)
194 
195 
196 if __name__ == '__main__':
197  logging.basicConfig(level=logging.DEBUG)
198  unittest.main()
tests_aio.unit.auth_context_test.handle_unary_unary
def handle_unary_unary(bytes unused_request, aio.ServicerContext servicer_context)
Definition: auth_context_test.py:54
grpc.unary_unary_rpc_method_handler
def unary_unary_rpc_method_handler(behavior, request_deserializer=None, response_serializer=None)
Definition: src/python/grpcio/grpc/__init__.py:1510
http2_test_server.format
format
Definition: http2_test_server.py:118
tests_aio.unit._test_base
Definition: _test_base.py:1
tests_aio.unit.auth_context_test.TestAuthContext.test_insecure
def test_insecure(self)
Definition: auth_context_test.py:65
grpc::experimental
Definition: include/grpcpp/channel.h:46
grpc.ssl_server_credentials
def ssl_server_credentials(private_key_certificate_chain_pairs, root_certificates=None, require_client_auth=False)
Definition: src/python/grpcio/grpc/__init__.py:1709
tests_aio.unit.auth_context_test.TestAuthContext
Definition: auth_context_test.py:63
grpc.method_handlers_generic_handler
def method_handlers_generic_handler(service, method_handlers)
Definition: src/python/grpcio/grpc/__init__.py:1590
tests.unit
Definition: src/python/grpcio_tests/tests/unit/__init__.py:1
grpc.ssl_channel_credentials
def ssl_channel_credentials(root_certificates=None, private_key=None, certificate_chain=None)
Definition: src/python/grpcio/grpc/__init__.py:1607
tests_aio.unit._test_base.AioTestBase
Definition: _test_base.py:49


grpc
Author(s):
autogenerated on Thu Mar 13 2025 02:58:35