Debian Codegraph @

src/python/grpcio_tests/tests/unit/_auth_context_test.py

raw
1 # Copyright 2017 gRPC authors.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """Tests exposure of SSL auth context"""
15
16 import logging
17 import pickle
18 import unittest
19
20 import grpc
21 from grpc import _channel
22 from grpc.experimental import session_cache
23
24 from tests.unit import resources
25 from tests.unit import test_common
26
27 _REQUEST = b'\x00\x00\x00'
28 _RESPONSE = b'\x00\x00\x00'
29
30 _UNARY_UNARY = '/test/UnaryUnary'
31
32 _SERVER_HOST_OVERRIDE = 'foo.test.google.fr'
33 _CLIENT_IDS = (
34 b'*.test.google.fr',
35 b'waterzooi.test.google.be',
36 b'*.test.youtube.com',
37 b'192.168.1.3',
38 )
39 _ID = 'id'
40 _ID_KEY = 'id_key'
41 _AUTH_CTX = 'auth_ctx'
42
43 _PRIVATE_KEY = resources.private_key()
44 _CERTIFICATE_CHAIN = resources.certificate_chain()
45 _TEST_ROOT_CERTIFICATES = resources.test_root_certificates()
46 _SERVER_CERTS = ((_PRIVATE_KEY, _CERTIFICATE_CHAIN),)
47 _PROPERTY_OPTIONS = ((
48 'grpc.ssl_target_name_override',
49 _SERVER_HOST_OVERRIDE,
50 ),)
51
52
53 def handle_unary_unary(request, servicer_context):
54 return pickle.dumps({
55 _ID: servicer_context.peer_identities(),
56 _ID_KEY: servicer_context.peer_identity_key(),
57 _AUTH_CTX: servicer_context.auth_context()
58 })
59
60
61 class AuthContextTest(unittest.TestCase):
62
63 def testInsecure(self):
64 handler = grpc.method_handlers_generic_handler('test', {
65 'UnaryUnary':
66 grpc.unary_unary_rpc_method_handler(handle_unary_unary)
67 })
68 server = test_common.test_server()
69 server.add_generic_rpc_handlers((handler,))
70 port = server.add_insecure_port('[::]:0')
71 server.start()
72
73 with grpc.insecure_channel('localhost:%d' % port) as channel:
74 response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
75 server.stop(None)
76
77 auth_data = pickle.loads(response)
78 self.assertIsNone(auth_data[_ID])
79 self.assertIsNone(auth_data[_ID_KEY])
80 self.assertDictEqual(
81 {
82 'security_level': [b'TSI_SECURITY_NONE'],
83 'transport_security_type': [b'insecure'],
84 }, auth_data[_AUTH_CTX])
85
86 def testSecureNoCert(self):
87 handler = grpc.method_handlers_generic_handler('test', {
88 'UnaryUnary':
89 grpc.unary_unary_rpc_method_handler(handle_unary_unary)
90 })
91 server = test_common.test_server()
92 server.add_generic_rpc_handlers((handler,))
93 server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
94 port = server.add_secure_port('[::]:0', server_cred)
95 server.start()
96
97 channel_creds = grpc.ssl_channel_credentials(
98 root_certificates=_TEST_ROOT_CERTIFICATES)
99 channel = grpc.secure_channel('localhost:{}'.format(port),
100 channel_creds,
101 options=_PROPERTY_OPTIONS)
102 response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
103 channel.close()
104 server.stop(None)
105
106 auth_data = pickle.loads(response)
107 self.assertIsNone(auth_data[_ID])
108 self.assertIsNone(auth_data[_ID_KEY])
109 self.assertDictEqual(
110 {
111 'security_level': [b'TSI_PRIVACY_AND_INTEGRITY'],
112 'transport_security_type': [b'ssl'],
113 'ssl_session_reused': [b'false'],
114 }, auth_data[_AUTH_CTX])
115
116 def testSecureClientCert(self):
117 handler = grpc.method_handlers_generic_handler('test', {
118 'UnaryUnary':
119 grpc.unary_unary_rpc_method_handler(handle_unary_unary)
120 })
121 server = test_common.test_server()
122 server.add_generic_rpc_handlers((handler,))
123 server_cred = grpc.ssl_server_credentials(
124 _SERVER_CERTS,
125 root_certificates=_TEST_ROOT_CERTIFICATES,
126 require_client_auth=True)
127 port = server.add_secure_port('[::]:0', server_cred)
128 server.start()
129
130 channel_creds = grpc.ssl_channel_credentials(
131 root_certificates=_TEST_ROOT_CERTIFICATES,
132 private_key=_PRIVATE_KEY,
133 certificate_chain=_CERTIFICATE_CHAIN)
134 channel = grpc.secure_channel('localhost:{}'.format(port),
135 channel_creds,
136 options=_PROPERTY_OPTIONS)
137
138 response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
139 channel.close()
140 server.stop(None)
141
142 auth_data = pickle.loads(response)
143 auth_ctx = auth_data[_AUTH_CTX]
144 self.assertCountEqual(_CLIENT_IDS, auth_data[_ID])
145 self.assertEqual('x509_subject_alternative_name', auth_data[_ID_KEY])
146 self.assertSequenceEqual([b'ssl'], auth_ctx['transport_security_type'])
147 self.assertSequenceEqual([b'*.test.google.com'],
148 auth_ctx['x509_common_name'])
149
150 def _do_one_shot_client_rpc(self, channel_creds, channel_options, port,
151 expect_ssl_session_reused):
152 channel = grpc.secure_channel('localhost:{}'.format(port),
153 channel_creds,
154 options=channel_options)
155 response = channel.unary_unary(_UNARY_UNARY)(_REQUEST)
156 auth_data = pickle.loads(response)
157 self.assertEqual(expect_ssl_session_reused,
158 auth_data[_AUTH_CTX]['ssl_session_reused'])
159 channel.close()
160
161 def testSessionResumption(self):
162 # Set up a secure server
163 handler = grpc.method_handlers_generic_handler('test', {
164 'UnaryUnary':
165 grpc.unary_unary_rpc_method_handler(handle_unary_unary)
166 })
167 server = test_common.test_server()
168 server.add_generic_rpc_handlers((handler,))
169 server_cred = grpc.ssl_server_credentials(_SERVER_CERTS)
170 port = server.add_secure_port('[::]:0', server_cred)
171 server.start()
172
173 # Create a cache for TLS session tickets
174 cache = session_cache.ssl_session_cache_lru(1)
175 channel_creds = grpc.ssl_channel_credentials(
176 root_certificates=_TEST_ROOT_CERTIFICATES)
177 channel_options = _PROPERTY_OPTIONS + (
178 ('grpc.ssl_session_cache', cache),)
179
180 # Initial connection has no session to resume
181 self._do_one_shot_client_rpc(channel_creds,
182 channel_options,
183 port,
184 expect_ssl_session_reused=[b'false'])
185
186 # Subsequent connections resume sessions
187 self._do_one_shot_client_rpc(channel_creds,
188 channel_options,
189 port,
190 expect_ssl_session_reused=[b'true'])
191 server.stop(None)
192
193
194 if __name__ == '__main__':
195 logging.basicConfig()
196 unittest.main(verbosity=2)