File: test_ssl.py

package info (click to toggle)
litestar 2.19.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,500 kB
  • sloc: python: 70,169; makefile: 254; javascript: 105; sh: 60
file content (344 lines) | stat: -rw-r--r-- 9,824 bytes parent folder | download
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
import sys
from pathlib import Path
from typing import Optional, Protocol, cast
from unittest.mock import MagicMock

import pytest
from click import ClickException
from click.testing import CliRunner
from pytest_mock import MockerFixture

from litestar.cli.main import litestar_group as cli_command


class GetClickExceptionFixture(Protocol):
    def __call__(self, exception: SystemExit) -> ClickException: ...


@pytest.fixture
def get_click_exception() -> GetClickExceptionFixture:
    def _get_click_exception(exception: SystemExit) -> ClickException:
        exc = exception
        while exc.__context__ is not None:
            if isinstance(exc, ClickException):
                break
            exc = exc.__context__  # type: ignore[assignment]
        return cast(ClickException, exc)

    return _get_click_exception


@pytest.mark.parametrize("create_self_signed_cert", (True, False))
@pytest.mark.usefixtures("mock_uvicorn_run")
def test_both_files_provided(app_file: Path, runner: CliRunner, create_self_signed_cert: bool) -> None:
    path = app_file
    app_path = f"{path.stem}:app"

    cert_path = path.parent / "cert.pem"
    with cert_path.open("wb") as certfile:
        certfile.write(b"certfile")

    key_path = path.parent / "key.pem"
    with key_path.open("wb") as keyfile:
        keyfile.write(b"keyfile")

    args = ["--app", app_path, "run", "--ssl-certfile", str(cert_path), "--ssl-keyfile", str(key_path)]

    if create_self_signed_cert:
        args.append("--create-self-signed-cert")

    result = runner.invoke(cli_command, args)

    assert result.exception is None
    assert result.exit_code == 0

    if create_self_signed_cert:
        with cert_path.open("rb") as certfile:
            assert certfile.read() == b"certfile"

        with key_path.open("rb") as keyfile:
            assert keyfile.read() == b"keyfile"


@pytest.mark.parametrize("create_self_signed_cert", (True, False))
@pytest.mark.parametrize(
    "ssl_certfile, ssl_keyfile",
    [("directory", "exists.pem"), ("exists.pem", "directory")],
)
def test_path_is_a_directory(
    app_file: Path,
    runner: CliRunner,
    ssl_certfile: str,
    ssl_keyfile: str,
    create_self_signed_cert: bool,
    get_click_exception: GetClickExceptionFixture,
) -> None:
    path = app_file
    app_path = f"{path.stem}:app"

    (path.parent / "exists.pem").touch()
    (path.parent / "directory").mkdir(exist_ok=True)

    args = ["--app", app_path, "run", "--ssl-certfile", ssl_certfile, "--ssl-keyfile", ssl_keyfile]

    if create_self_signed_cert:
        args.append("--create-self-signed-cert")

    result = runner.invoke(cli_command, args)

    assert result.exit_code == 1

    assert isinstance(result.exception, SystemExit)
    exc = get_click_exception(result.exception)
    assert "Path provided for" in exc.message
    assert "is a directory" in exc.message


@pytest.mark.parametrize("create_self_signed_cert", (True, False))
@pytest.mark.parametrize(
    "ssl_certfile, ssl_keyfile",
    [("exists.pem", None), (None, "exists.pem")],
)
def test_one_file_provided(
    app_file: Path,
    runner: CliRunner,
    ssl_certfile: Optional[str],
    ssl_keyfile: Optional[str],
    create_self_signed_cert: bool,
    get_click_exception: GetClickExceptionFixture,
) -> None:
    path = app_file
    app_path = f"{path.stem}:app"

    (path.parent / "exists.pem").touch()

    args = ["--app", app_path, "run"]

    if ssl_certfile is not None:
        args.extend(["--ssl-certfile", str(ssl_certfile)])

    if ssl_keyfile is not None:
        args.extend(["--ssl-keyfile", str(ssl_keyfile)])

    if create_self_signed_cert:
        args.append("--create-self-signed-cert")

    result = runner.invoke(cli_command, args)

    assert result.exit_code == 1

    assert isinstance(result.exception, SystemExit)
    exc = get_click_exception(result.exception)
    assert "No value provided for" in exc.message


@pytest.mark.parametrize("create_self_signed_cert", (True, False))
@pytest.mark.parametrize(
    "ssl_certfile, ssl_keyfile",
    [("not_exists.pem", "exists.pem"), ("exists.pem", "not_exists.pem")],
)
def test_one_file_not_found(
    app_file: Path,
    runner: CliRunner,
    ssl_certfile: str,
    ssl_keyfile: str,
    create_self_signed_cert: bool,
    get_click_exception: GetClickExceptionFixture,
) -> None:
    path = app_file
    app_path = f"{path.stem}:app"

    (path.parent / "exists.pem").touch()

    args = ["--app", app_path, "run"]

    if ssl_certfile is not None:
        args.extend(["--ssl-certfile", ssl_certfile])

    if ssl_keyfile is not None:
        args.extend(["--ssl-keyfile", ssl_keyfile])

    if create_self_signed_cert:
        args.append("--create-self-signed-cert")

    result = runner.invoke(cli_command, args)

    assert result.exit_code == 1

    assert isinstance(result.exception, SystemExit)
    exc = get_click_exception(result.exception)
    if create_self_signed_cert:
        assert (
            "Both certificate and key file must exists or both must not exists when using --create-self-signed-cert"
            in exc.message
        )
    else:
        assert "File provided for" in exc.message
        assert "was not found" in exc.message


@pytest.mark.parametrize(
    "ssl_certfile, ssl_keyfile",
    [("dir_exists/file.pem", "dir_not_exists/file.pem"), ("dir_not_exists/file.pem", "dir_exists/file.pem")],
)
def test_file_parent_doesnt_exist(
    app_file: Path,
    runner: CliRunner,
    ssl_certfile: str,
    ssl_keyfile: str,
    get_click_exception: GetClickExceptionFixture,
) -> None:
    path = app_file
    app_path = f"{path.stem}:app"

    (path.parent / "dir_exists").mkdir(exist_ok=True)

    args = [
        "--app",
        app_path,
        "run",
        "--ssl-certfile",
        ssl_certfile,
        "--ssl-keyfile",
        ssl_keyfile,
        "--create-self-signed-cert",
    ]

    result = runner.invoke(cli_command, args)

    assert result.exit_code == 1

    assert isinstance(result.exception, SystemExit)
    exc = get_click_exception(result.exception)
    assert "Could not create file, parent directory for" in exc.message
    assert "doesn't exist" in exc.message


def test_without_cryptography_installed(
    app_file: Path,
    runner: CliRunner,
    get_click_exception: GetClickExceptionFixture,
    mocker: MockerFixture,
) -> None:
    mocker.patch.dict("sys.modules", {"cryptography": None})

    path = app_file
    app_path = f"{path.stem}:app"

    args = [
        "--app",
        app_path,
        "run",
        "--ssl-certfile",
        "certfile.pem",
        "--ssl-keyfile",
        "keyfile.pem",
        "--create-self-signed-cert",
    ]

    result = runner.invoke(cli_command, args)

    assert result.exit_code == 1

    assert isinstance(result.exception, SystemExit)
    exc = get_click_exception(result.exception)
    assert "Cryptography must be installed when using --create-self-signed-cert" in exc.message


@pytest.mark.usefixtures("mock_uvicorn_run")
def test_create_certificates(app_file: Path, runner: CliRunner) -> None:
    path = app_file
    app_path = f"{path.stem}:app"

    certfile_path = path.parent / "certificate.pem"
    keyfile_path = path.parent / "key.pem"

    args = [
        "--app",
        app_path,
        "run",
        "--ssl-certfile",
        str(certfile_path),
        "--ssl-keyfile",
        str(keyfile_path),
        "--create-self-signed-cert",
    ]

    result = runner.invoke(cli_command, args)

    assert result.exit_code == 0
    assert result.exception is None

    assert certfile_path.exists()
    assert keyfile_path.exists()


@pytest.mark.parametrize(
    "ssl_certfile, ssl_keyfile, create_self_signed_cert", [(None, None, False), ("cert.pem", "key.pem", True)]
)
@pytest.mark.parametrize("run_as_subprocess", (True, False))
def test_arguments_passed(
    app_file: Path,
    runner: CliRunner,
    mock_subprocess_run: MagicMock,
    mock_uvicorn_run: MagicMock,
    ssl_certfile: Optional[str],
    ssl_keyfile: Optional[str],
    create_self_signed_cert: bool,
    run_as_subprocess: bool,
) -> None:
    path = app_file
    app_path = f"{path.stem}:app"

    project_path = path.parent

    args = ["--app", app_path, "run"]

    if run_as_subprocess:
        args.extend(["--web-concurrency", "2"])

    if ssl_certfile is not None:
        args.extend(["--ssl-certfile", str(ssl_certfile)])

    if ssl_keyfile is not None:
        args.extend(["--ssl-keyfile", str(ssl_keyfile)])

    if create_self_signed_cert:
        args.append("--create-self-signed-cert")

    result = runner.invoke(cli_command, args)

    assert result.exit_code == 0
    assert result.exception is None

    if run_as_subprocess:
        expected_args = [
            sys.executable,
            "-m",
            "uvicorn",
            f"{path.stem}:app",
            "--host=127.0.0.1",
            "--port=8000",
            "--workers=2",
            f"--app-dir={path.parent}",
        ]
        if ssl_certfile is not None:
            expected_args.append(f"--ssl-certfile={project_path / ssl_certfile}")
        if ssl_keyfile is not None:
            expected_args.append(f"--ssl-keyfile={project_path / ssl_keyfile}")

        mock_subprocess_run.assert_called_once()
        assert sorted(mock_subprocess_run.call_args_list[0].args[0]) == sorted(expected_args)

    else:
        mock_subprocess_run.assert_not_called()
        mock_uvicorn_run.assert_called_once_with(
            app=f"{path.stem}:app",
            host="127.0.0.1",
            port=8000,
            factory=False,
            fd=None,
            uds=None,
            ssl_certfile=(None if ssl_certfile is None else str(project_path / ssl_certfile)),
            ssl_keyfile=(None if ssl_keyfile is None else str(project_path / ssl_keyfile)),
        )