aboutsummaryrefslogtreecommitdiffstats
path: root/test/pathod/test_pathoc.py
blob: 7c9127733a881364a327bd0dfdd397e44857dd35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import json
import cStringIO
import re
import OpenSSL
import pytest
from mock import Mock

from netlib import tcp, http, socks
from netlib.exceptions import HttpException, TcpException, NetlibException
from netlib.http import http1, http2

from libpathod import pathoc, test, version, pathod, language
from netlib.tutils import raises
import tutils


def test_response():
    r = http.Response("HTTP/1.1", 200, "Message", {}, None, None)
    assert repr(r)


class _TestDaemon:
    ssloptions = pathod.SSLOptions()

    @classmethod
    def setup_class(cls):
        cls.d = test.Daemon(
            ssl=cls.ssl,
            ssloptions=cls.ssloptions,
            staticdir=tutils.test_data.path("data"),
            anchors=[
                (re.compile("/anchor/.*"), "202")
            ]
        )

    @classmethod
    def teardown_class(cls):
        cls.d.shutdown()

    def setUp(self):
        self.d.clear_log()

    def test_info(self):
        c = pathoc.Pathoc(
            ("127.0.0.1", self.d.port),
            ssl=self.ssl,
            fp=None
        )
        c.connect()
        resp = c.request("get:/api/info")
        assert tuple(json.loads(resp.content)["version"]) == version.IVERSION

    def tval(
        self,
        requests,
        showreq=False,
        showresp=False,
        explain=False,
        showssl=False,
        hexdump=False,
        timeout=None,
        ignorecodes=(),
        ignoretimeout=None,
        showsummary=True
    ):
        s = cStringIO.StringIO()
        c = pathoc.Pathoc(
            ("127.0.0.1", self.d.port),
            ssl=self.ssl,
            showreq=showreq,
            showresp=showresp,
            explain=explain,
            hexdump=hexdump,
            ignorecodes=ignorecodes,
            ignoretimeout=ignoretimeout,
            showsummary=showsummary,
            fp=s
        )
        c.connect(showssl=showssl, fp=s)
        if timeout:
            c.settimeout(timeout)
        for i in requests:
            r = language.parse_pathoc(i).next()
            if explain:
                r = r.freeze(language.Settings())
            try:
                c.request(r)
            except NetlibException:
                pass
        return s.getvalue()


class TestDaemonSSL(_TestDaemon):
    ssl = True
    ssloptions = pathod.SSLOptions(
        request_client_cert=True,
        sans=["test1.com", "test2.com"],
        alpn_select=b'h2',
    )

    def test_sni(self):
        c = pathoc.Pathoc(
            ("127.0.0.1", self.d.port),
            ssl=True,
            sni="foobar.com",
            fp=None
        )
        c.connect()
        c.request("get:/p/200")
        r = c.request("get:/api/log")
        d = json.loads(r.content)
        assert d["log"][0]["request"]["sni"] == "foobar.com"

    def test_showssl(self):
        assert "certificate chain" in self.tval(["get:/p/200"], showssl=True)

    def test_clientcert(self):
        c = pathoc.Pathoc(
            ("127.0.0.1", self.d.port),
            ssl=True,
            clientcert=tutils.test_data.path("data/clientcert/client.pem"),
            fp=None
        )
        c.connect()
        c.request("get:/p/200")
        r = c.request("get:/api/log")
        d = json.loads(r.content)
        assert d["log"][0]["request"]["clientcert"]["keyinfo"]

    def test_http2_without_ssl(self):
        fp = cStringIO.StringIO()
        c = pathoc.Pathoc(
            ("127.0.0.1", self.d.port),
            use_http2=True,
            ssl=False,
            fp = fp
        )
        tutils.raises(NotImplementedError, c.connect)


class TestDaemon(_TestDaemon):
    ssl = False

    def test_ssl_error(self):
        c = pathoc.Pathoc(("127.0.0.1", self.d.port), ssl=True, fp=None)
        tutils.raises("ssl handshake", c.connect)

    def test_showssl(self):
        assert not "certificate chain" in self.tval(
            ["get:/p/200"],
            showssl=True)

    def test_ignorecodes(self):
        assert "200" in self.tval(["get:'/p/200:b@1'"])
        assert "200" in self.tval(["get:'/p/200:b@1'"])
        assert "200" in self.tval(["get:'/p/200:b@1'"])
        assert "200" not in self.tval(["get:'/p/200:b@1'"], ignorecodes=[200])
        assert "200" not in self.tval(
            ["get:'/p/200:b@1'"],
            ignorecodes=[
                200,
                201])
        assert "202" in self.tval(["get:'/p/202:b@1'"], ignorecodes=[200, 201])

    def test_timeout(self):
        assert "Timeout" in self.tval(["get:'/p/200:p0,100'"], timeout=0.01)
        assert "HTTP" in self.tval(
            ["get:'/p/200:p5,100'"],
            showresp=True,
            timeout=1
        )
        assert not "HTTP" in self.tval(
            ["get:'/p/200:p3,100'"],
            showresp=True,
            timeout=1,
            ignoretimeout=True
        )

    def test_showresp(self):
        reqs = ["get:/api/info:p0,0", "get:/api/info:p0,0"]
        assert self.tval(reqs).count("200") == 2
        assert self.tval(reqs, showresp=True).count("HTTP/1.1 200 OK") == 2
        assert self.tval(
            reqs, showresp=True, hexdump=True
        ).count("0000000000") == 2

    def test_showresp_httperr(self):
        v = self.tval(["get:'/p/200:d20'"], showresp=True, showsummary=True)
        assert "Invalid headers" in v
        assert "HTTP/" in v

    def test_explain(self):
        reqs = ["get:/p/200:b@100"]
        assert "b@100" not in self.tval(reqs, explain=True)

    def test_showreq(self):
        reqs = ["get:/api/info:p0,0", "get:/api/info:p0,0"]
        assert self.tval(reqs, showreq=True).count("GET /api") == 2
        assert self.tval(
            reqs, showreq=True, hexdump=True
        ).count("0000000000") == 2

    def test_conn_err(self):
        assert "Invalid server response" in self.tval(["get:'/p/200:d2'"])

    def test_websocket_shutdown(self):
        c = pathoc.Pathoc(("127.0.0.1", self.d.port), fp=None)
        c.connect()
        c.request("ws:/")
        c.stop()

    @pytest.mark.xfail
    def test_wait_finish(self):
        c = pathoc.Pathoc(
            ("127.0.0.1", self.d.port),
            fp=None,
            ws_read_limit=1
        )
        c.connect()
        c.request("ws:/")
        c.request("wf:f'wf:x100'")
        [i for i in c.wait(timeout=0, finish=False)]
        [i for i in c.wait(timeout=0)]

    def test_connect_fail(self):
        to = ("foobar", 80)
        c = pathoc.Pathoc(("127.0.0.1", self.d.port), fp=None)
        c.rfile, c.wfile = cStringIO.StringIO(), cStringIO.StringIO()
        with raises("connect failed"):
            c.http_connect(to)
        c.rfile = cStringIO.StringIO(
            "HTTP/1.1 500 OK\r\n"
        )
        with raises("connect failed"):
            c.http_connect(to)
        c.rfile = cStringIO.StringIO(
            "HTTP/1.1 200 OK\r\n"
        )
        c.http_connect(to)

    def test_socks_connect(self):
        to = ("foobar", 80)
        c = pathoc.Pathoc(("127.0.0.1", self.d.port), fp=None)
        c.rfile, c.wfile = tutils.treader(""), cStringIO.StringIO()
        tutils.raises(pathoc.PathocError, c.socks_connect, to)

        c.rfile = tutils.treader(
            "\x05\xEE"
        )
        tutils.raises("SOCKS without authentication", c.socks_connect, ("example.com", 0xDEAD))

        c.rfile = tutils.treader(
            "\x05\x00" +
            "\x05\xEE\x00\x03\x0bexample.com\xDE\xAD"
        )
        tutils.raises("SOCKS server error", c.socks_connect, ("example.com", 0xDEAD))

        c.rfile = tutils.treader(
            "\x05\x00" +
            "\x05\x00\x00\x03\x0bexample.com\xDE\xAD"
        )
        c.socks_connect(("example.com", 0xDEAD))


class TestDaemonHTTP2(_TestDaemon):
    ssl = True

    if tcp.HAS_ALPN:

        def test_http2(self):
            c = pathoc.Pathoc(
                ("127.0.0.1", self.d.port),
                fp=None,
                ssl=True,
                use_http2=True,
            )
            assert isinstance(c.protocol, http2.HTTP2Protocol)

            c = pathoc.Pathoc(
                ("127.0.0.1", self.d.port),
            )
            assert c.protocol == http1

        def test_http2_alpn(self):
            c = pathoc.Pathoc(
                ("127.0.0.1", self.d.port),
                fp=None,
                ssl=True,
                use_http2=True,
                http2_skip_connection_preface=True,
            )

            tmp_convert_to_ssl = c.convert_to_ssl
            c.convert_to_ssl = Mock()
            c.convert_to_ssl.side_effect = tmp_convert_to_ssl
            c.connect()

            _, kwargs = c.convert_to_ssl.call_args
            assert set(kwargs['alpn_protos']) == set([b'http/1.1', b'h2'])

        def test_request(self):
            c = pathoc.Pathoc(
                ("127.0.0.1", self.d.port),
                fp=None,
                ssl=True,
                use_http2=True,
            )
            c.connect()
            resp = c.request("get:/p/200")
            assert resp.status_code == 200