10000 [Worker support] test for no cors headers by madhur-tandon · Pull Request #1374 · pyscript/pyscript · GitHub
[go: up one dir, main page]

Skip to content

[Worker support] test for no cors headers #1374

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
May 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions pyscriptjs/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,21 @@ export class PyScriptApp {
);
}
this.config = loadConfigFromElement(el);
if (this.config.execution_thread === 'worker' && crossOriginIsolated === false) {
throw new UserError(
ErrorCode.BAD_CONFIG,
`When execution_thread is "worker", the site must be cross origin isolated, but crossOriginIsolated is false.
To be cross origin isolated, the server must use https and also serve with the following headers: ${JSON.stringify(
{
'Cross-Origin-Embedder-Policy': 'require-corp',
'Cross-Origin-Opener-Policy': 'same-origin',
},
)}.

The problem may be that one or both of these are missing.
`,
);
}
logger.info('config loaded:\n' + JSON.stringify(this.config, null, 2));
}

Expand Down
27 changes: 21 additions & 6 deletions pyscriptjs/tests/integration/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,17 @@ def browser_type_launch_args(request):
return launch_options


class HTTPServer(SuperHTTPServer):
class DevServer(SuperHTTPServer):
"""
Class for wrapper to run SimpleHTTPServer on Thread.
Ctrl +Only Thread remains dead when terminated with C.
Keyboard Interrupt passes.
"""

def __init__(self, base_url, *args, **kwargs):
self.base_url = base_url
super().__init__(*args, **kwargs)

def run(self):
try:
self.serve_forever()
Expand All @@ -140,15 +144,26 @@ def run(self):


@pytest.fixture(scope="session")
def http_server(logger):
def dev_server(logger):
class MyHTTPRequestHandler(SimpleHTTPRequestHandler):
enable_cors_headers = True

@classmethod
def my_headers(cls):
if cls.enable_cors_headers:
return {
"Cross-Origin-Embedder-Policy": "require-corp",
"Cross-Origin-Opener-Policy": "same-origin",
}
return {}

def end_headers(self):
self.send_my_headers()
SimpleHTTPRequestHandler.end_headers(self)

def send_my_headers(self):
self.send_header("Cross-Origin-Embedder-Policy", "require-corp")
self.send_header("Cross-Origin-Opener-Policy", "same-origin")
for k, v in self.my_headers().items():
self.send_header(k, v)

def log_message(self, fmt, *args):
logger.log("http_server", fmt % args, color="blue")
Expand All @@ -157,12 +172,12 @@ def log_message(self, fmt, *args):
base_url = f"http://{host}:{port}"

# serve_Run forever under thread
server = HTTPServer((host, port), MyHTTPRequestHandler)
server = DevServer(base_url, (host, port), MyHTTPRequestHandler)

thread = threading.Thread(None, server.run)
thread.start()

yield base_url # Transition to test here
yield server # Transition to test here

# End thread
server.shutdown()
Expand Down
44 changes: 31 additions & 13 deletions pyscriptjs/tests/integration/support.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,24 +158,24 @@ def init(self, request, tmpdir, logger, page, execution_thread):
self.tmpdir.chdir()
self.logger = logger
self.execution_thread = execution_thread
self.dev_server = None

if request.config.option.no_fake_server:
# use a real HTTP server. Note that as soon as we request the
# fixture, the server automatically starts in its own thread.
self.http_server = request.getfixturevalue("http_server")
self.dev_server = request.getfixturevalue("dev_server")
self.http_server_addr = self.dev_server.base_url
self.router = None
self.is_fake_server = False
else:
# use the internal playwright routing
self.http_server = "https://fake_server"
self.http_server_addr = "https://fake_server"
self.router = SmartRouter(
"fake_server",
cache=request.config.cache,
logger=logger,
usepdb=request.config.option.usepdb,
)
self.router.install(page)
self.is_fake_server = True
#
self.init_page(page)
#
Expand Down Expand Up @@ -211,6 +211,18 @@ def init_page(self, page):
page.on("console", self._on_console)
page.on("pageerror", self._on_pageerror)

@property
def headers(self):
if self.dev_server is None:
return self.router.headers
return self.dev_server.RequestHandlerClass.my_headers()

def disable_cors_headers(self):
if self.dev_server is None:
self.router.enable_cors_headers = False
else:
self.dev_server.RequestHandlerClass.enable_cors_headers = False

def run_js(self, code):
"""
allows top level await to be present in the `code` parameter
Expand Down Expand Up @@ -301,7 +313,7 @@ def writefile(self, filename, content):
def goto(self, path):
self.logger.reset()
self.logger.log("page.goto", path, color="yellow")
url = f"{self.http_server}/{path}"
url = f"{self.http_server_addr}/{path}"
self.page.goto(url, timeout=0)

def wait_for_console(
Expand Down Expand Up @@ -433,8 +445,8 @@ def _pyscript_format(self, snippet, *, execution_thread, extra_head=""):
doc = f"""
<html>
<head>
<link rel="stylesheet" href="{self.http_server}/build/pyscript.css" />
<script defer src="{self.http_server}/build/pyscript.js"></script>
<link rel="stylesheet" href="{self.http_server_addr}/build/pyscript.css" />
<script defer src="{self.http_server_addr}/build/pyscript.js"></script>
{extra_head}
</head>
<body>
Expand Down Expand Up @@ -851,6 +863,16 @@ def __init__(self, fake_server, *, cache, logger, usepdb=False):
self.usepdb = usepdb
self.page = None
self.requests = [] # (status, kind, url)
self.enable_cors_headers = True

@property
def headers(self):
if self.enable_cors_headers:
return {
"Cross-Origin-Embedder-Policy": "require-corp",
"Cross-Origin-Opener-Policy": "same-origin",
}
return {}

def install(self, page):
"""
Expand Down Expand Up @@ -903,13 +925,9 @@ def _router(self, route):
assert url.path[0] == "/"
relative_path = url.path[1:]
if os.path.exists(relative_path):
headers = {
"Cross-Origin-Embedder-Policy": "require-corp",
"Cross-Origin-Opener-Policy": "same-origin",
}
route.fulfill(status=200, headers=headers, path=relative_path)
route.fulfill(status=200, headers=self.headers, path=relative_path)
else:
route.fulfill(status=404)
route.fulfill(status=404, headers=self.headers)
return

# network requests might be cached
Expand Down
2 changes: 1 addition & 1 deletion pyscriptjs/tests/integration/test_00_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def test_check_js_errors_simple(self):
f"""
JS errors found: 1
Error: this is an error
at {self.http_server}/mytest.html:.*
at {self.http_server_addr}/mytest.html:.*
"""
).strip()
assert re.search(expected, msg)
Expand Down
24 changes: 24 additions & 0 deletions pyscriptjs/tests/integration/test_01_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,30 @@ def test_execution_thread(self):
expected = f"[pyscript/main] Starting the interpreter in {where}"
assert expected in self.console.info.lines

def test_no_cors_headers(self):
self.disable_cors_headers()
self.pyscript_run(
"""
<!-- we don't really need anything here, we just want to check that
pyscript starts -->
""",
wait_for_pyscript=False,
)
assert self.headers == {}
if self.execution_thread == "worker":
expected_alert_banner_msg = (
'(PY1000): When execution_thread is "worker", the site must be cross origin '
"isolated, but crossOriginIsolated is false. To be cross origin isolated, "
"the server must use https and also serve with the following headers: "
'{"Cross-Origin-Embedder-Policy":"require-corp",'
'"Cross-Origin-Opener-Policy":"same-origin"}. '
"The problem may be that one or both of these are missing."
)
alert_banner = self.page.wait_for_selector(".alert-banner")
assert expected_alert_banner_msg in alert_banner.inner_text()
else:
self.assert_no_banners()

def test_print(self):
self.pyscript_run(
"""
Expand Down
0