File: test_browsercontext_client_certificates.py

package info (click to toggle)
python-playwright 1.55.0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,728 kB
  • sloc: python: 53,655; javascript: 383; sh: 216; makefile: 6
file content (268 lines) | stat: -rw-r--r-- 9,601 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
# Copyright (c) Microsoft Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys
import threading
from pathlib import Path
from typing import Dict, Generator, Optional, cast

import OpenSSL.crypto
import OpenSSL.SSL
import pytest
from twisted.internet import reactor as _twisted_reactor
from twisted.internet import ssl
from twisted.internet.selectreactor import SelectReactor
from twisted.web import resource, server
from twisted.web.http import Request

from playwright.async_api import Browser, BrowserType, Playwright, expect

ssl.optionsForClientTLS
reactor = cast(SelectReactor, _twisted_reactor)


@pytest.fixture(scope="function", autouse=True)
def _skip_webkit_darwin(browser_name: str) -> None:
    if browser_name == "webkit" and sys.platform == "darwin":
        pytest.skip("WebKit does not proxy localhost on macOS")


class HttpsResource(resource.Resource):
    serverCertificate: ssl.PrivateCertificate
    isLeaf = True

    def _verify_cert_chain(self, cert: Optional[OpenSSL.crypto.X509]) -> bool:
        if not cert:
            return False
        store = OpenSSL.crypto.X509Store()
        store.add_cert(self.serverCertificate.original)
        store_ctx = OpenSSL.crypto.X509StoreContext(store, cert)
        try:
            store_ctx.verify_certificate()
            return True
        except OpenSSL.crypto.X509StoreContextError:
            return False

    def render_GET(self, request: Request) -> bytes:
        tls_socket: OpenSSL.SSL.Connection = request.transport.getHandle()  # type: ignore
        cert = tls_socket.get_peer_certificate()
        parts = []

        if self._verify_cert_chain(cert):
            request.setResponseCode(200)
            parts.append(
                {
                    "key": "message",
                    "value": f"Hello {cert.get_subject().CN}, your certificate was issued by {cert.get_issuer().CN}!",  # type: ignore
                }
            )
        elif cert and cert.get_subject():
            request.setResponseCode(403)
            parts.append(
                {
                    "key": "message",
                    "value": f"Sorry {cert.get_subject().CN}, certificates from {cert.get_issuer().CN} are not welcome here.",
                }
            )
        else:
            request.setResponseCode(401)
            parts.append(
                {
                    "key": "message",
                    "value": "Sorry, but you need to provide a client certificate to continue.",
                }
            )
        return b"".join(
            [
                f'<div data-testid="{part["key"]}">{part["value"]}</div>'.encode()
                for part in parts
            ]
        )


@pytest.fixture(scope="session", autouse=True)
def _client_certificate_server(assetdir: Path) -> Generator[None, None, None]:
    certAuthCert = ssl.Certificate.loadPEM(
        (assetdir / "client-certificates/server/server_cert.pem").read_text()
    )
    serverCert = ssl.PrivateCertificate.loadPEM(
        (assetdir / "client-certificates/server/server_key.pem").read_text()
        + (assetdir / "client-certificates/server/server_cert.pem").read_text()
    )

    contextFactory = serverCert.options(certAuthCert)
    contextFactory.requireCertificate = False
    resource = HttpsResource()
    resource.serverCertificate = serverCert
    site = server.Site(resource)

    def _run() -> None:
        reactor.listenSSL(8000, site, contextFactory)

    thread = threading.Thread(target=_run)
    thread.start()
    yield
    thread.join()


async def test_should_throw_with_untrusted_client_certs(
    playwright: Playwright, assetdir: Path
) -> None:
    serverURL = "https://localhost:8000/"
    request = await playwright.request.new_context(
        # TODO: Remove this once we can pass a custom CA.
        ignore_https_errors=True,
        client_certificates=[
            {
                "origin": serverURL,
                "certPath": assetdir
                / "client-certificates/client/self-signed/cert.pem",
                "keyPath": assetdir / "client-certificates/client/self-signed/key.pem",
            }
        ],
    )
    with pytest.raises(Exception, match="alert unknown ca"):
        await request.get(serverURL)
    await request.dispose()


async def test_should_work_with_new_context(browser: Browser, assetdir: Path) -> None:
    context = await browser.new_context(
        # TODO: Remove this once we can pass a custom CA.
        ignore_https_errors=True,
        client_certificates=[
            {
                "origin": "https://127.0.0.1:8000",
                "certPath": assetdir / "client-certificates/client/trusted/cert.pem",
                "keyPath": assetdir / "client-certificates/client/trusted/key.pem",
            }
        ],
    )
    page = await context.new_page()
    await page.goto("https://localhost:8000")
    await expect(page.get_by_test_id("message")).to_have_text(
        "Sorry, but you need to provide a client certificate to continue."
    )
    await page.goto("https://127.0.0.1:8000")
    await expect(page.get_by_test_id("message")).to_have_text(
        "Hello Alice, your certificate was issued by localhost!"
    )

    response = await page.context.request.get("https://localhost:8000")
    assert (
        "Sorry, but you need to provide a client certificate to continue."
        in await response.text()
    )
    response = await page.context.request.get("https://127.0.0.1:8000")
    assert (
        "Hello Alice, your certificate was issued by localhost!"
        in await response.text()
    )
    await context.close()


async def test_should_work_with_new_context_passing_as_content(
    browser: Browser, assetdir: Path
) -> None:
    context = await browser.new_context(
        # TODO: Remove this once we can pass a custom CA.
        ignore_https_errors=True,
        client_certificates=[
            {
                "origin": "https://127.0.0.1:8000",
                "cert": (
                    assetdir / "client-certificates/client/trusted/cert.pem"
                ).read_bytes(),
                "key": (
                    assetdir / "client-certificates/client/trusted/key.pem"
                ).read_bytes(),
            }
        ],
    )
    page = await context.new_page()
    await page.goto("https://localhost:8000")
    await expect(page.get_by_test_id("message")).to_have_text(
        "Sorry, but you need to provide a client certificate to continue."
    )
    await page.goto("https://127.0.0.1:8000")
    await expect(page.get_by_test_id("message")).to_have_text(
        "Hello Alice, your certificate was issued by localhost!"
    )

    response = await page.context.request.get("https://localhost:8000")
    assert (
        "Sorry, but you need to provide a client certificate to continue."
        in await response.text()
    )
    response = await page.context.request.get("https://127.0.0.1:8000")
    assert (
        "Hello Alice, your certificate was issued by localhost!"
        in await response.text()
    )
    await context.close()


async def test_should_work_with_new_persistent_context(
    browser_type: BrowserType, assetdir: Path, launch_arguments: Dict
) -> None:
    context = await browser_type.launch_persistent_context(
        "",
        **launch_arguments,
        # TODO: Remove this once we can pass a custom CA.
        ignore_https_errors=True,
        client_certificates=[
            {
                "origin": "https://127.0.0.1:8000",
                "certPath": assetdir / "client-certificates/client/trusted/cert.pem",
                "keyPath": assetdir / "client-certificates/client/trusted/key.pem",
            }
        ],
    )
    page = await context.new_page()
    await page.goto("https://localhost:8000")
    await expect(page.get_by_test_id("message")).to_have_text(
        "Sorry, but you need to provide a client certificate to continue."
    )
    await page.goto("https://127.0.0.1:8000")
    await expect(page.get_by_test_id("message")).to_have_text(
        "Hello Alice, your certificate was issued by localhost!"
    )
    await context.close()


async def test_should_work_with_global_api_request_context(
    playwright: Playwright, assetdir: Path
) -> None:
    request = await playwright.request.new_context(
        # TODO: Remove this once we can pass a custom CA.
        ignore_https_errors=True,
        client_certificates=[
            {
                "origin": "https://127.0.0.1:8000",
                "certPath": assetdir / "client-certificates/client/trusted/cert.pem",
                "keyPath": assetdir / "client-certificates/client/trusted/key.pem",
            }
        ],
    )
    response = await request.get("https://localhost:8000")
    assert (
        "Sorry, but you need to provide a client certificate to continue."
        in await response.text()
    )
    response = await request.get("https://127.0.0.1:8000")
    assert (
        "Hello Alice, your certificate was issued by localhost!"
        in await response.text()
    )
    await request.dispose()