forked from sanic-org/sanic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_tls.py
743 lines (583 loc) · 21.4 KB
/
test_tls.py
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
import logging
import os
import ssl
import subprocess
import sys
from contextlib import contextmanager
from multiprocessing import Event
from pathlib import Path
from unittest.mock import Mock, patch
from urllib.parse import urlparse
import pytest
from sanic_testing.testing import HOST, PORT, SanicTestClient
import sanic.http.tls.creators
from sanic import Sanic
from sanic.application.constants import Mode
from sanic.compat import use_context
from sanic.constants import LocalCertCreator
from sanic.exceptions import SanicException
from sanic.helpers import _default
from sanic.http.tls.context import SanicSSLContext
from sanic.http.tls.creators import (
MkcertCreator,
TrustmeCreator,
get_ssl_context,
)
from sanic.response import text
from sanic.worker.loader import CertLoader
current_dir = os.path.dirname(os.path.realpath(__file__))
localhost_dir = os.path.join(current_dir, "certs/localhost")
password_dir = os.path.join(current_dir, "certs/password")
sanic_dir = os.path.join(current_dir, "certs/sanic.example")
invalid_dir = os.path.join(current_dir, "certs/invalid.nonexist")
localhost_cert = os.path.join(localhost_dir, "fullchain.pem")
localhost_key = os.path.join(localhost_dir, "privkey.pem")
sanic_cert = os.path.join(sanic_dir, "fullchain.pem")
sanic_key = os.path.join(sanic_dir, "privkey.pem")
password_dict = {
"cert": os.path.join(password_dir, "fullchain.pem"),
"key": os.path.join(password_dir, "privkey.pem"),
"password": "password",
"names": ["localhost"],
}
@pytest.fixture
def server_cert():
return Mock()
@pytest.fixture
def issue_cert(server_cert):
mock = Mock(return_value=server_cert)
return mock
@pytest.fixture
def ca(issue_cert):
ca = Mock()
ca.issue_cert = issue_cert
return ca
@pytest.fixture
def trustme(ca):
module = Mock()
module.CA = Mock(return_value=ca)
return module
@pytest.fixture
def MockMkcertCreator():
class Creator(MkcertCreator):
SUPPORTED = True
def check_supported(self):
if not self.SUPPORTED:
raise SanicException("Nope")
generate_cert = Mock()
return Creator
@pytest.fixture
def MockTrustmeCreator():
class Creator(TrustmeCreator):
SUPPORTED = True
def check_supported(self):
if not self.SUPPORTED:
raise SanicException("Nope")
generate_cert = Mock()
return Creator
@contextmanager
def replace_server_name(hostname):
"""Temporarily replace the server name sent with all TLS requests with
a fake hostname."""
def hack_wrap_bio(
self,
incoming,
outgoing,
server_side=False,
server_hostname=None,
session=None,
):
return orig_wrap_bio(
self, incoming, outgoing, server_side, hostname, session
)
orig_wrap_bio, ssl.SSLContext.wrap_bio = (
ssl.SSLContext.wrap_bio,
hack_wrap_bio,
)
try:
yield
finally:
ssl.SSLContext.wrap_bio = orig_wrap_bio
@pytest.mark.parametrize(
"path,query,expected_url",
[
("/foo", "", "https://{}:{}/foo"),
("/bar/baz", "", "https://{}:{}/bar/baz"),
("/moo/boo", "arg1=val1", "https://{}:{}/moo/boo?arg1=val1"),
],
)
def test_url_attributes_with_ssl_context(app, path, query, expected_url):
context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(localhost_cert, localhost_key)
async def handler(request):
return text("OK")
app.add_route(handler, path)
request, _ = app.test_client.get(
f"https://{HOST}:{PORT}" + path + f"?{query}",
server_kwargs={"ssl": context},
)
assert request.url == expected_url.format(HOST, request.server_port)
parsed = urlparse(request.url)
assert parsed.scheme == request.scheme
assert parsed.path == request.path
assert parsed.query == request.query_string
assert parsed.netloc == request.host
@pytest.mark.parametrize(
"path,query,expected_url",
[
("/foo", "", "https://{}:{}/foo"),
("/bar/baz", "", "https://{}:{}/bar/baz"),
("/moo/boo", "arg1=val1", "https://{}:{}/moo/boo?arg1=val1"),
],
)
def test_url_attributes_with_ssl_dict(app, path, query, expected_url):
ssl_dict = {"cert": localhost_cert, "key": localhost_key}
async def handler(request):
return text("OK")
app.add_route(handler, path)
request, _ = app.test_client.get(
f"https://{HOST}:{PORT}" + path + f"?{query}",
server_kwargs={"ssl": ssl_dict},
)
assert request.url == expected_url.format(HOST, request.server_port)
parsed = urlparse(request.url)
assert parsed.scheme == request.scheme
assert parsed.path == request.path
assert parsed.query == request.query_string
assert parsed.netloc == request.host
def test_cert_sni_single(app):
@app.get("/sni")
async def handler1(request):
return text(request.conn_info.server_name)
@app.get("/commonname")
async def handler2(request):
return text(request.conn_info.cert.get("commonName"))
port = app.test_client.port
_, response = app.test_client.get(
f"https://localhost:{port}/sni",
server_kwargs={"ssl": localhost_dir},
)
assert response.status == 200
assert response.text == "localhost"
_, response = app.test_client.get(
f"https://localhost:{port}/commonname",
server_kwargs={"ssl": localhost_dir},
)
assert response.status == 200
assert response.text == "localhost"
def test_cert_sni_list(app):
ssl_list = [sanic_dir, localhost_dir]
@app.get("/sni")
async def handler1(request):
return text(request.conn_info.server_name)
@app.get("/commonname")
async def handler2(request):
return text(request.conn_info.cert.get("commonName"))
# This test should match the localhost cert
port = app.test_client.port
_, response = app.test_client.get(
f"https://localhost:{port}/sni",
server_kwargs={"ssl": ssl_list},
)
assert response.status == 200
assert response.text == "localhost"
request, response = app.test_client.get(
f"https://localhost:{port}/commonname",
server_kwargs={"ssl": ssl_list},
)
assert response.status == 200
assert response.text == "localhost"
# This part should use the sanic.example cert because it matches
with replace_server_name("www.sanic.example"):
_, response = app.test_client.get(
f"https://127.0.0.1:{port}/sni",
server_kwargs={"ssl": ssl_list},
)
assert response.status == 200
assert response.text == "www.sanic.example"
_, response = app.test_client.get(
f"https://127.0.0.1:{port}/commonname",
server_kwargs={"ssl": ssl_list},
)
assert response.status == 200
assert response.text == "sanic.example"
# This part should use the sanic.example cert, that being the first listed
with replace_server_name("invalid.test"):
_, response = app.test_client.get(
f"https://127.0.0.1:{port}/sni",
server_kwargs={"ssl": ssl_list},
)
assert response.status == 200
assert response.text == "invalid.test"
_, response = app.test_client.get(
f"https://127.0.0.1:{port}/commonname",
server_kwargs={"ssl": ssl_list},
)
assert response.status == 200
assert response.text == "sanic.example"
@pytest.mark.xfail
def test_missing_sni(app):
"""The sanic cert does not list 127.0.0.1 and httpx does not send
IP as SNI anyway."""
ssl_list = [None, sanic_dir]
@app.get("/sni")
async def handler(request):
return text(request.conn_info.server_name)
port = app.test_client.port
with pytest.raises(Exception) as exc:
app.test_client.get(
f"https://127.0.0.1:{port}/sni",
server_kwargs={"ssl": ssl_list},
)
assert "Request and response object expected" in str(exc.value)
@pytest.mark.xfail
def test_no_matching_cert(app):
"""The sanic cert does not list 127.0.0.1 and httpx does not send
IP as SNI anyway."""
ssl_list = [None, sanic_dir]
@app.get("/sni")
async def handler(request):
return text(request.conn_info.server_name)
port = app.test_client.port
with replace_server_name("invalid.test"):
with pytest.raises(Exception) as exc:
app.test_client.get(
f"https://127.0.0.1:{port}/sni",
server_kwargs={"ssl": ssl_list},
)
assert "Request and response object expected" in str(exc.value)
@pytest.mark.xfail
def test_wildcards(app):
ssl_list = [None, localhost_dir, sanic_dir]
@app.get("/sni")
async def handler(request):
return text(request.conn_info.server_name)
port = app.test_client.port
with replace_server_name("foo.sanic.test"):
_, response = app.test_client.get(
f"https://127.0.0.1:{port}/sni",
server_kwargs={"ssl": ssl_list},
)
assert response.status == 200
assert response.text == "foo.sanic.test"
with replace_server_name("sanic.test"):
with pytest.raises(Exception) as exc:
_, response = app.test_client.get(
f"https://127.0.0.1:{port}/sni",
server_kwargs={"ssl": ssl_list},
)
assert "Request and response object expected" in str(exc.value)
with replace_server_name("sub.foo.sanic.test"):
with pytest.raises(Exception) as exc:
_, response = app.test_client.get(
f"https://127.0.0.1:{port}/sni",
server_kwargs={"ssl": ssl_list},
)
assert "Request and response object expected" in str(exc.value)
def test_invalid_ssl_dict(app):
@app.get("/test")
async def handler(request):
return text("ssl test")
ssl_dict = {"cert": None, "key": None}
with pytest.raises(ValueError) as excinfo:
app.test_client.get("/test", server_kwargs={"ssl": ssl_dict})
assert str(excinfo.value) == "SSL dict needs filenames for cert and key."
def test_invalid_ssl_type(app):
@app.get("/test")
async def handler(request):
return text("ssl test")
with pytest.raises(ValueError) as excinfo:
app.test_client.get("/test", server_kwargs={"ssl": False})
assert "Invalid ssl argument" in str(excinfo.value)
def test_cert_file_on_pathlist(app):
@app.get("/test")
async def handler(request):
return text("ssl test")
ssl_list = [sanic_cert]
with pytest.raises(ValueError) as excinfo:
app.test_client.get("/test", server_kwargs={"ssl": ssl_list})
assert "folder expected" in str(excinfo.value)
assert sanic_cert in str(excinfo.value)
def test_missing_cert_path(app):
@app.get("/test")
async def handler(request):
return text("ssl test")
ssl_list = [invalid_dir]
with pytest.raises(ValueError) as excinfo:
app.test_client.get("/test", server_kwargs={"ssl": ssl_list})
assert "not found" in str(excinfo.value)
assert invalid_dir + "/privkey.pem" in str(excinfo.value)
def test_missing_cert_file(app):
@app.get("/test")
async def handler(request):
return text("ssl test")
invalid2 = invalid_dir.replace("nonexist", "certmissing")
ssl_list = [invalid2]
with pytest.raises(ValueError) as excinfo:
app.test_client.get("/test", server_kwargs={"ssl": ssl_list})
assert "not found" in str(excinfo.value)
assert invalid2 + "/fullchain.pem" in str(excinfo.value)
def test_no_certs_on_list(app):
@app.get("/test")
async def handler(request):
return text("ssl test")
ssl_list = [None]
with pytest.raises(ValueError) as excinfo:
app.test_client.get("/test", server_kwargs={"ssl": ssl_list})
assert "No certificates" in str(excinfo.value)
def test_custom_cert_loader():
class MyCertLoader(CertLoader):
def load(self, app: Sanic):
self._ssl_data = {
"key": localhost_key,
"cert": localhost_cert,
}
return super().load(app)
app = Sanic("custom", certloader_class=MyCertLoader)
@app.get("/test")
async def handler(request):
return text("ssl test")
client = SanicTestClient(app, port=44556)
request, response = client.get("https://localhost:44556/test")
assert request.scheme == "https"
assert response.status_code == 200
assert response.text == "ssl test"
def test_logger_vhosts(caplog):
app = Sanic(name="test_logger_vhosts")
@app.after_server_start
def stop(*args):
app.stop()
with caplog.at_level(logging.INFO):
app.run(
host="127.0.0.1",
port=42102,
ssl=[localhost_dir, sanic_dir],
single_process=True,
)
logmsg = [
msg
for name, levelno, msg in caplog.record_tuples
if (msg.startswith("Certificate"))
][0]
assert logmsg == (
"Certificate vhosts: localhost, 127.0.0.1, 0:0:0:0:0:0:0:1, "
"sanic.example, www.sanic.example, *.sanic.test, "
"2001:DB8:0:0:0:0:0:541C"
)
def test_mk_cert_creator_default(app: Sanic):
cert_creator = MkcertCreator(app, _default, _default)
assert isinstance(cert_creator.tmpdir, Path)
assert cert_creator.tmpdir.exists()
def test_mk_cert_creator_is_supported(app):
cert_creator = MkcertCreator(app, _default, _default)
with patch("subprocess.run") as run:
cert_creator.check_supported()
run.assert_called_once_with(
["mkcert", "-help"],
check=True,
stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
)
def test_mk_cert_creator_is_not_supported(app):
cert_creator = MkcertCreator(app, _default, _default)
with patch("subprocess.run") as run:
run.side_effect = Exception("")
with pytest.raises(
SanicException, match="Sanic is attempting to use mkcert"
):
cert_creator.check_supported()
def test_mk_cert_creator_generate_cert_default(app):
cert_creator = MkcertCreator(app, _default, _default)
with patch("subprocess.run") as run:
with patch("sanic.http.tls.creators.CertSimple"):
retval = Mock()
retval.stdout = "foo"
run.return_value = retval
cert_creator.generate_cert("localhost")
run.assert_called_once()
def test_mk_cert_creator_generate_cert_localhost(app):
cert_creator = MkcertCreator(app, localhost_key, localhost_cert)
with patch("subprocess.run") as run:
with patch("sanic.http.tls.creators.CertSimple"):
cert_creator.generate_cert("localhost")
run.assert_not_called()
def test_trustme_creator_default(app: Sanic):
cert_creator = TrustmeCreator(app, _default, _default)
assert isinstance(cert_creator.tmpdir, Path)
assert cert_creator.tmpdir.exists()
def test_trustme_creator_is_supported(app, monkeypatch):
monkeypatch.setattr(sanic.http.tls.creators, "TRUSTME_INSTALLED", True)
cert_creator = TrustmeCreator(app, _default, _default)
cert_creator.check_supported()
def test_trustme_creator_is_not_supported(app, monkeypatch):
monkeypatch.setattr(sanic.http.tls.creators, "TRUSTME_INSTALLED", False)
cert_creator = TrustmeCreator(app, _default, _default)
with pytest.raises(
SanicException, match="Sanic is attempting to use trustme"
):
cert_creator.check_supported()
def test_trustme_creator_generate_cert_default(
app, monkeypatch, trustme, issue_cert, server_cert, ca
):
monkeypatch.setattr(sanic.http.tls.creators, "trustme", trustme)
cert_creator = TrustmeCreator(app, _default, _default)
cert = cert_creator.generate_cert("localhost")
assert isinstance(cert, SanicSSLContext)
trustme.CA.assert_called_once_with()
issue_cert.assert_called_once_with("localhost")
server_cert.configure_cert.assert_called_once()
ca.configure_trust.assert_called_once()
ca.cert_pem.write_to_path.assert_called_once_with(str(cert.sanic["cert"]))
write_to_path = server_cert.private_key_and_cert_chain_pem.write_to_path
write_to_path.assert_called_once_with(str(cert.sanic["key"]))
def test_trustme_creator_generate_cert_localhost(
app, monkeypatch, trustme, server_cert, ca
):
monkeypatch.setattr(sanic.http.tls.creators, "trustme", trustme)
cert_creator = TrustmeCreator(app, localhost_key, localhost_cert)
cert_creator.generate_cert("localhost")
ca.cert_pem.write_to_path.assert_called_once_with(localhost_cert)
write_to_path = server_cert.private_key_and_cert_chain_pem.write_to_path
write_to_path.assert_called_once_with(localhost_key)
def test_get_ssl_context_with_ssl_context(app):
mock_context = Mock()
context = get_ssl_context(app, mock_context)
assert context is mock_context
def test_get_ssl_context_in_production(app):
app.state.mode = Mode.PRODUCTION
with pytest.raises(
SanicException,
match="Cannot run Sanic as an HTTPS server in PRODUCTION mode",
):
get_ssl_context(app, None)
@pytest.mark.parametrize(
"requirement,mk_supported,trustme_supported,mk_called,trustme_called,err",
(
(LocalCertCreator.AUTO, True, False, True, False, None),
(LocalCertCreator.AUTO, True, True, True, False, None),
(LocalCertCreator.AUTO, False, True, False, True, None),
(
LocalCertCreator.AUTO,
False,
False,
False,
False,
"Sanic could not find package to create a TLS certificate",
),
(LocalCertCreator.MKCERT, True, False, True, False, None),
(LocalCertCreator.MKCERT, True, True, True, False, None),
(LocalCertCreator.MKCERT, False, True, False, False, "Nope"),
(LocalCertCreator.MKCERT, False, False, False, False, "Nope"),
(LocalCertCreator.TRUSTME, True, False, False, False, "Nope"),
(LocalCertCreator.TRUSTME, True, True, False, True, None),
(LocalCertCreator.TRUSTME, False, True, False, True, None),
(LocalCertCreator.TRUSTME, False, False, False, False, "Nope"),
),
)
def test_get_ssl_context_only_mkcert(
app,
monkeypatch,
MockMkcertCreator,
MockTrustmeCreator,
requirement,
mk_supported,
trustme_supported,
mk_called,
trustme_called,
err,
):
app.state.mode = Mode.DEBUG
app.config.LOCAL_CERT_CREATOR = requirement
monkeypatch.setattr(
sanic.http.tls.creators, "MkcertCreator", MockMkcertCreator
)
monkeypatch.setattr(
sanic.http.tls.creators, "TrustmeCreator", MockTrustmeCreator
)
MockMkcertCreator.SUPPORTED = mk_supported
MockTrustmeCreator.SUPPORTED = trustme_supported
if err:
with pytest.raises(SanicException, match=err):
get_ssl_context(app, None)
else:
get_ssl_context(app, None)
if mk_called:
MockMkcertCreator.generate_cert.assert_called_once_with("localhost")
else:
MockMkcertCreator.generate_cert.assert_not_called()
if trustme_called:
MockTrustmeCreator.generate_cert.assert_called_once_with("localhost")
else:
MockTrustmeCreator.generate_cert.assert_not_called()
# def test_no_http3_with_trustme(
# app,
# monkeypatch,
# MockTrustmeCreator,
# ):
# monkeypatch.setattr(
# sanic.http.tls.creators, "TrustmeCreator", MockTrustmeCreator
# )
# MockTrustmeCreator.SUPPORTED = True
# app.config.LOCAL_CERT_CREATOR = "TRUSTME"
# with pytest.raises(
# SanicException,
# match=(
# "Sorry, you cannot currently use trustme as a local certificate "
# "generator for an HTTP/3 server"
# ),
# ):
# app.run(version=3, debug=True)
def test_sanic_ssl_context_create():
context = ssl.SSLContext()
sanic_context = SanicSSLContext.create_from_ssl_context(context)
assert sanic_context is context
assert isinstance(sanic_context, SanicSSLContext)
@pytest.mark.skipif(
sys.platform not in ("linux", "darwin"),
reason="This test requires fork context",
)
def test_ssl_in_multiprocess_mode(app: Sanic, caplog):
ssl_dict = {"cert": localhost_cert, "key": localhost_key}
event = Event()
@app.main_process_start
async def main_start(app: Sanic):
app.shared_ctx.event = event
@app.after_server_start
async def shutdown(app):
app.shared_ctx.event.set()
app.stop()
assert not event.is_set()
with use_context("fork"):
with caplog.at_level(logging.INFO):
app.run(ssl=ssl_dict)
assert event.is_set()
assert (
"sanic.root",
logging.INFO,
"Goin' Fast @ https://127.0.0.1:8000",
) in caplog.record_tuples
@pytest.mark.skipif(
sys.platform not in ("linux", "darwin"),
reason="This test requires fork context",
)
def test_ssl_in_multiprocess_mode_password(
app: Sanic, caplog: pytest.LogCaptureFixture
):
event = Event()
@app.main_process_start
async def main_start(app: Sanic):
app.shared_ctx.event = event
@app.after_server_start
async def shutdown(app):
app.shared_ctx.event.set()
app.stop()
assert not event.is_set()
with use_context("fork"):
with caplog.at_level(logging.INFO):
app.run(ssl=password_dict)
assert event.is_set()
assert (
"sanic.root",
logging.INFO,
"Goin' Fast @ https://127.0.0.1:8000",
) in caplog.record_tuples