source: mod_gnutls/test/https-test-client.py @ d5f5356

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

https-test-client.py: Support YAML test configuration

  • Property mode set to 100755
File size: 7.2 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 socket
19import subprocess
20import yaml
21
22from http.client import HTTPConnection
23from time import sleep
24
25class HTTPSubprocessConnection(HTTPConnection):
26    def __init__(self, command, host, port=None,
27                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
28                 blocksize=8192):
29        super(HTTPSubprocessConnection, self).__init__(host, port, timeout,
30                                                       source_address=None,
31                                                       blocksize=blocksize)
32        # "command" must be a list containing binary and command line
33        # parameters
34        self.command = command
35        # This will be the subprocess reference when connected
36        self._sproc = None
37        # The subprocess return code is stored here on close()
38        self.returncode = None
39        # The set_tunnel method of the super class is not supported
40        # (see exception doc)
41        self.set_tunnel = None
42
43    def connect(self):
44        s_local, s_remote = socket.socketpair(socket.AF_UNIX,
45                                              socket.SOCK_STREAM)
46        s_local.settimeout(self.timeout)
47
48        # TODO: Maybe capture stderr?
49        self._sproc = subprocess.Popen(self.command, stdout=s_remote,
50                                       stdin=s_remote, close_fds=True)
51        s_remote.close()
52        self.sock = s_local
53
54    def close(self):
55        super().close()
56        # Wait for the process to stop, send SIGTERM/SIGKILL if
57        # necessary
58        self.returncode = self._sproc.wait(self.timeout)
59        if self.returncode == None:
60            self._sproc.terminate()
61            self.returncode = self._sproc.wait(self.timeout)
62            if self.returncode == None:
63                self._sproc.kill()
64                self.returncode = self._sproc.wait(self.timeout)
65
66
67
68class TestRequest(yaml.YAMLObject):
69    yaml_tag = '!request'
70    def __init__(self, path, expect=dict(status=200), method='GET'):
71        self.method = method
72        self.path = path
73        self.expect = expect
74
75    def __repr__(self):
76        return (f'{self.__class__.__name__!s}(path={self.path!r}, '
77                f'expect={self.expect!r}, method={self.method!r})')
78
79    def check_response(self, response, body):
80        if response.status != self.expect['status']:
81            raise TestExpectationFailed(
82                f'Unexpected status: {response.status} != '
83                f'{self.expect["status"]}')
84        if 'body' in self.expect and self.expect['body'] != body:
85            raise TestExpectationFailed(
86                f'Unexpected body: {body!r} != {self.expect["body"]!r}')
87
88    @classmethod
89    def _from_yaml(cls, loader, node):
90        fields = loader.construct_mapping(node)
91        req = TestRequest(**fields)
92        return req
93
94class TestConnection(yaml.YAMLObject):
95    yaml_tag = '!connection'
96
97    def __init__(self, actions, gnutls_params=[], protocol='https'):
98        self.gnutls_params = gnutls_params
99        self.actions = actions
100        self.protocol = protocol
101
102    def __repr__(self):
103        return (f'{self.__class__.__name__!s}'
104                f'(gnutls_params={self.gnutls_params!r}, '
105                f'actions={self.actions!r}, protocol={self.protocol!r})')
106
107    @classmethod
108    def _from_yaml(cls, loader, node):
109        fields = loader.construct_mapping(node)
110        conn = TestConnection(**fields)
111        return conn
112
113# Override the default constructors. Pyyaml ignores default parameters
114# otherwise.
115yaml.add_constructor('!request', TestRequest._from_yaml, yaml.Loader)
116yaml.add_constructor('!connection', TestConnection._from_yaml, yaml.Loader)
117
118
119
120class TestExpectationFailed(Exception):
121    """Raise if a test failed. The constructor should be called with a
122    string describing the problem."""
123    pass
124
125
126
127def format_response(resp, body):
128    s = f'{resp.status} {resp.reason}\n'
129    s = s + '\n'.join(f'{name}: {value}' for name, value in resp.getheaders())
130    s = s + '\n\n' + body
131    return s
132
133
134
135if __name__ == "__main__":
136    import argparse
137    parser = argparse.ArgumentParser(
138        description='Send HTTP requests through gnutls-cli',
139        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
140    parser.add_argument('host', nargs='?', help='Access the specified host',
141                        default='localhost')
142    parser.add_argument('--insecure', action='store_true',
143                        help='do not validate the server certificate')
144    parser.add_argument('-p', '--port', type=int,
145                        help='Access the specified port', default='8000')
146    parser.add_argument('--x509cafile', type=str,
147                        help='Use the specified CA to validate the '
148                        'server certificate')
149    parser.add_argument('--test-config', type=argparse.FileType('r'),
150                        help='load YAML test configuration')
151
152    # enable bash completion if argcomplete is available
153    try:
154        import argcomplete
155        argcomplete.autocomplete(parser)
156    except ImportError:
157        pass
158
159    args = parser.parse_args()
160
161    test_conn = None
162    test_actions = None
163
164    if args.test_config:
165        config = yaml.load(args.test_config, Loader=yaml.Loader)
166        if type(config) is TestConnection:
167            test_conn = config
168            print(test_conn)
169            test_actions = test_conn.actions
170    else:
171        # simple default request
172        test_actions = [TestRequest(path='/test.txt',
173                                    expect={'status': 200, 'body': 'test\n'},
174                                    method='GET')]
175
176
177    # note: "--logfile" option requires GnuTLS version >= 3.6.7
178    command = ['gnutls-cli', '--logfile=/dev/stderr']
179    if args.insecure:
180        command.append('--insecure')
181    if args.x509cafile:
182        command.append('--x509cafile')
183        command.append(args.x509cafile)
184    if test_conn != None:
185        for s in test_conn.gnutls_params:
186            command.append('--' + s)
187    command = command + ['-p', str(args.port), args.host]
188
189    conn = HTTPSubprocessConnection(command, args.host, port=args.port,
190                                    timeout=6.0)
191
192    try:
193        for act in test_actions:
194            if type(act) is TestRequest:
195                # Add headers={'Host': 'test.host'} to provoke "421
196                # Misdirected
197                conn.request(act.method, act.path)
198                resp = conn.getresponse()
199                body = resp.read().decode()
200                print(format_response(resp, body))
201                act.check_response(resp, body)
202            else:
203                raise TypeError(f'Unsupported action requested: {act!r}')
204    finally:
205        conn.close()
Note: See TracBrowser for help on using the repository browser.