source: mod_gnutls/test/https-test-client.py @ 6ea34b1

asyncioproxy-ticket
Last change on this file since 6ea34b1 was 6ea34b1, checked in by Fiona Klute <fiona.klute@…>, 23 months ago

Rename TestRequest?.check_body() to show it is shared API

  • Property mode set to 100755
File size: 14.1 KB
Line 
1#!/usr/bin/python3
2# PYTHON_ARGCOMPLETE_OK
3
4# Copyright 2019 Fiona Klute
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#     http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18import re
19import socket
20import subprocess
21import yaml
22
23from http.client import HTTPConnection
24from multiprocessing import Process
25from time import sleep
26
27class HTTPSubprocessConnection(HTTPConnection):
28    def __init__(self, command, host, port=None,
29                 output_filter=None,
30                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
31                 blocksize=8192):
32        super(HTTPSubprocessConnection, self).__init__(host, port, timeout,
33                                                       source_address=None,
34                                                       blocksize=blocksize)
35        # "command" must be a list containing binary and command line
36        # parameters
37        self.command = command
38        # This will be the subprocess reference when connected
39        self._sproc = None
40        # The subprocess return code is stored here on close()
41        self.returncode = None
42        # The set_tunnel method of the super class is not supported
43        # (see exception doc)
44        self.set_tunnel = None
45        # This method will be run in a separate process and filter the
46        # stdout of self._sproc. Its arguments are self._sproc.stdout
47        # and the socket back to the HTTP connection (write-only).
48        self._output_filter = output_filter
49        # output filter process
50        self._fproc = None
51
52    def connect(self):
53        s_local, s_remote = socket.socketpair(socket.AF_UNIX,
54                                              socket.SOCK_STREAM)
55        s_local.settimeout(self.timeout)
56
57        # TODO: Maybe capture stderr?
58        if self._output_filter:
59            self._sproc = subprocess.Popen(self.command, stdout=subprocess.PIPE,
60                                           stdin=s_remote, close_fds=True,
61                                           bufsize=0)
62            self._fproc = Process(target=self._output_filter,
63                                  args=(self._sproc.stdout, s_remote))
64            self._fproc.start()
65        else:
66            self._sproc = subprocess.Popen(self.command, stdout=s_remote,
67                                           stdin=s_remote, close_fds=True,
68                                           bufsize=0)
69        s_remote.close()
70        self.sock = s_local
71
72    def close(self):
73        # close socket to subprocess for writing
74        if self.sock:
75            self.sock.shutdown(socket.SHUT_WR)
76
77        # Wait for the process to stop, send SIGTERM/SIGKILL if
78        # necessary
79        if self._sproc:
80            try:
81                self.returncode = self._sproc.wait(self.timeout)
82            except subprocess.TimeoutExpired:
83                try:
84                    self._sproc.terminate()
85                    self.returncode = self._sproc.wait(self.timeout)
86                except subprocess.TimeoutExpired:
87                    self._sproc.kill()
88                    self.returncode = self._sproc.wait(self.timeout)
89
90        # filter process receives HUP on pipe when the subprocess
91        # terminates
92        if self._fproc:
93            self._fproc.join()
94
95        # close the connection in the super class, which also calls
96        # self.sock.close()
97        super().close()
98
99
100
101class TestRequest(yaml.YAMLObject):
102    yaml_tag = '!request'
103    def __init__(self, path, method='GET', headers=dict(),
104                 expect=dict(status=200)):
105        self.method = method
106        self.path = path
107        self.headers = headers
108        self.expect = expect
109
110    def __repr__(self):
111        return (f'{self.__class__.__name__!s}(path={self.path!r}, '
112                f'method={self.method!r}, headers={self.headers!r}, '
113                f'expect={self.expect!r})')
114
115    def run(self, conn):
116        try:
117            conn.request(self.method, self.path, headers=self.headers)
118            resp = conn.getresponse()
119        except ConnectionResetError as err:
120            if self.expects_conn_reset():
121                print('connection reset as expected.')
122                return
123            else:
124                raise err
125        body = resp.read().decode()
126        print(format_response(resp, body))
127        self.check_response(resp, body)
128
129    def check_body(self, body):
130        """
131        >>> r1 = TestRequest(path='/test.txt', method='GET', headers={}, expect={'status': 200, 'body': {'exactly': 'test\\n'}})
132        >>> r1.check_body('test\\n')
133        >>> r1.check_body('xyz\\n')
134        Traceback (most recent call last):
135        ...
136        https-test-client.TestExpectationFailed: Unexpected body: 'xyz\\n' != 'test\\n'
137        >>> r2 = TestRequest(path='/test.txt', method='GET', headers={}, expect={'status': 200, 'body': {'contains': ['tes', 'est']}})
138        >>> r2.check_body('test\\n')
139        >>> r2.check_body('est\\n')
140        Traceback (most recent call last):
141        ...
142        https-test-client.TestExpectationFailed: Unexpected body: 'est\\n' does not contain 'tes'
143        >>> r3 = TestRequest(path='/test.txt', method='GET', headers={}, expect={'status': 200, 'body': {'contains': 'test'}})
144        >>> r3.check_body('test\\n')
145        """
146        if 'exactly' in self.expect['body'] \
147           and body != self.expect['body']['exactly']:
148            raise TestExpectationFailed(
149                f'Unexpected body: {body!r} != '
150                f'{self.expect["body"]["exactly"]!r}')
151        if 'contains' in self.expect['body']:
152            if type(self.expect['body']['contains']) is str:
153                self.expect['body']['contains'] = [
154                    self.expect['body']['contains']]
155            for s in self.expect['body']['contains']:
156                if not s in body:
157                    raise TestExpectationFailed(
158                        f'Unexpected body: {body!r} does not contain '
159                        f'{s!r}')
160
161    def check_response(self, response, body):
162        if self.expects_conn_reset():
163            raise TestExpectationFailed(
164                'Got a response, but connection should have failed!')
165        if response.status != self.expect['status']:
166            raise TestExpectationFailed(
167                f'Unexpected status: {response.status} != '
168                f'{self.expect["status"]}')
169        if 'body' in self.expect:
170            self.check_body(body)
171
172    def expects_conn_reset(self):
173        if 'reset' in self.expect:
174            return self.expect['reset']
175        return False
176
177    @classmethod
178    def _from_yaml(cls, loader, node):
179        fields = loader.construct_mapping(node)
180        req = TestRequest(**fields)
181        return req
182
183class TestConnection(yaml.YAMLObject):
184    yaml_tag = '!connection'
185
186    def __init__(self, actions, gnutls_params=[], transport='gnutls'):
187        self.gnutls_params = gnutls_params
188        self.actions = actions
189        self.transport = transport
190
191    def __repr__(self):
192        return (f'{self.__class__.__name__!s}'
193                f'(gnutls_params={self.gnutls_params!r}, '
194                f'actions={self.actions!r}, transport={self.transport!r})')
195
196    def run(self, host, port, timeout=5.0):
197        # note: "--logfile" option requires GnuTLS version >= 3.6.7
198        command = ['gnutls-cli', '--logfile=/dev/stderr']
199        for s in self.gnutls_params:
200            command.append('--' + s)
201        command = command + ['-p', str(port), host]
202
203        conn = HTTPSubprocessConnection(command, host, port,
204                                        output_filter=filter_cert_log,
205                                        timeout=timeout)
206
207        try:
208            for act in self.actions:
209                if type(act) is TestRequest:
210                    act.run(conn)
211                elif type(act) is TestRaw10:
212                    act.run(command, timeout)
213                else:
214                    raise TypeError(f'Unsupported action requested: {act!r}')
215        finally:
216            conn.close()
217
218    @classmethod
219    def _from_yaml(cls, loader, node):
220        fields = loader.construct_mapping(node)
221        conn = TestConnection(**fields)
222        return conn
223
224class TestRaw10(TestRequest):
225    """This is a minimal (and likely incomplete) HTTP/1.0 test client for
226    the one test case that strictly requires HTTP/1.0. All request
227    parameters (method, path, headers) MUST be specified in the config
228    file.
229
230    """
231    yaml_tag = '!raw10'
232    status_re = re.compile('^HTTP/([\d\.]+) (\d+) (.*)$')
233
234    def __init__(self, method, path, headers, expect):
235        self.method = method
236        self.path = path
237        self.headers = headers
238        self.expect = expect
239
240    def __repr__(self):
241        return (f'{self.__class__.__name__!s}'
242                f'(method={self.method!r}, path={self.path!r}, '
243                f'headers={self.headers!r}, expect={self.expect!r})')
244
245    def run(self, command, timeout=None):
246        req = f'{self.method} {self.path} HTTP/1.0\r\n'
247        for name, value in self.headers.items():
248            req = req + f'{name}: {value}\r\n'
249        req = req + f'\r\n'
250        proc = subprocess.Popen(command, stdout=subprocess.PIPE,
251                                stdin=subprocess.PIPE, close_fds=True,
252                                bufsize=0)
253        try:
254            # Note: errs will be empty because stderr is not captured
255            outs, errs = proc.communicate(input=req.encode(),
256                                          timeout=timeout)
257        except TimeoutExpired:
258            proc.kill()
259            outs, errs = proc.communicate()
260
261        # first line of the received data must be the status
262        status, rest = outs.decode().split('\r\n', maxsplit=1)
263        # headers and body are separated by double newline
264        headers, body = rest.split('\r\n\r\n', maxsplit=1)
265        # log response for debugging
266        print(f'{status}\n{headers}\n\n{body}')
267
268        m = self.status_re.match(status)
269        if m:
270            status_code = int(m.group(2))
271            status_expect = self.expect.get('status')
272            if status_expect and not status_code == status_expect:
273                raise TestExpectationFailed('Unexpected status code: '
274                                            f'{status}, expected '
275                                            f'{status_expect}')
276        else:
277            raise TestExpectationFailed(f'Invalid status line: "{status}"')
278
279        if 'body' in self.expect:
280            self.check_body(body)
281
282# Override the default constructors. Pyyaml ignores default parameters
283# otherwise.
284yaml.add_constructor('!request', TestRequest._from_yaml, yaml.Loader)
285yaml.add_constructor('!connection', TestConnection._from_yaml, yaml.Loader)
286
287
288
289class TestExpectationFailed(Exception):
290    """Raise if a test failed. The constructor should be called with a
291    string describing the problem."""
292    pass
293
294
295
296def filter_cert_log(in_stream, out_stream):
297    import fcntl
298    import os
299    import select
300    # This filters out a log line about loading client
301    # certificates that is mistakenly sent to stdout. My fix has
302    # been merged, but buggy binaries will probably be around for
303    # a while.
304    # https://gitlab.com/gnutls/gnutls/merge_requests/1125
305    cert_log = b'Processed 1 client X.509 certificates...\n'
306
307    # Set the input to non-blocking mode
308    fd = in_stream.fileno()
309    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
310    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
311
312    # The poll object allows waiting for events on non-blocking IO
313    # channels.
314    poller = select.poll()
315    poller.register(fd)
316
317    init_done = False
318    run_loop = True
319    while run_loop:
320        # The returned tuples are file descriptor and event, but
321        # we're only listening on one stream anyway, so we don't
322        # need to check it here.
323        for x, event in poller.poll():
324            # Critical: "event" is a bitwise OR of the POLL* constants
325            if event & select.POLLIN or event & select.POLLPRI:
326                data = in_stream.read()
327                if not init_done:
328                    # If the erroneous log line shows up it's the
329                    # first piece of data we receive. Just copy
330                    # everything after.
331                    init_done = True
332                    if cert_log in data:
333                        data = data.replace(cert_log, b'')
334                out_stream.send(data)
335            if event & select.POLLHUP or event & select.POLLRDHUP:
336                # Stop the loop, but process any other events that
337                # might be in the list returned by poll() first.
338                run_loop = False
339
340    in_stream.close()
341    out_stream.close()
342
343
344
345def format_response(resp, body):
346    s = f'{resp.status} {resp.reason}\n'
347    s = s + '\n'.join(f'{name}: {value}' for name, value in resp.getheaders())
348    s = s + '\n\n' + body
349    return s
350
351
352
353if __name__ == "__main__":
354    import argparse
355    parser = argparse.ArgumentParser(
356        description='Send HTTP requests through gnutls-cli',
357        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
358    parser.add_argument('host', nargs='?', help='Access the specified host',
359                        default='localhost')
360    parser.add_argument('-p', '--port', type=int,
361                        help='Access the specified port', default='8000')
362    parser.add_argument('--test-config', type=argparse.FileType('r'),
363                        required=True, help='load YAML test configuration')
364
365    # enable bash completion if argcomplete is available
366    try:
367        import argcomplete
368        argcomplete.autocomplete(parser)
369    except ImportError:
370        pass
371
372    args = parser.parse_args()
373
374    test_conn = None
375
376    config = yaml.load(args.test_config, Loader=yaml.Loader)
377    if type(config) is TestConnection:
378        test_conn = config
379        print(test_conn)
380    else:
381        raise TypeError(f'Unsupported configuration: {config!r}')
382
383    test_conn.run(host=args.host, port=args.port)
Note: See TracBrowser for help on using the repository browser.