Truly independent web browser
#!/usr/bin/env python3
import argparse
import base64
import hashlib
import http.server
import ipaddress
import itertools
import json
import logging
import os
import socket
import socketserver
import ssl
import sys
import threading
import time
import urllib.parse
from collections import defaultdict
from functools import lru_cache
from types import SimpleNamespace
from typing import Any
from typing import Callable
from typing import Dict
from typing import Optional
from typing import cast
"""
Description:
This script starts a simple HTTP and WebSocket echo server on localhost for use in our in-tree tests.
The port is assigned by the OS on startup and printed to stdout.
Endpoints:
- POST /echo <json body>, Creates an echo response for later use. See "Echo" class below for body properties.
- Echo responses accept chunks=<byte-counts> and chunk_unblock_tokens=<tokens> query parameters.
- Echo responses accept request_body_read_size=<bytes> and request_body_read_delay_ms=<ms> query parameters,
which read the request's body that many bytes at a time, waiting that long before each read.
Each named token holds the response after the corresponding chunk until GET /unblock/<token>.
- An echo response's body may contain $BODY, which the server replaces with the request's body.
- An echo answers a Range request with the requested part of its body, unless it was created with
"ignore_range": true. Then it sends the entire body, as a server that doesn't support ranges does.
- GET <any path> with an "Upgrade: websocket" header: Performs a WebSocket handshake and then echoes
every text/binary frame back to the client verbatim. With a "send-binary=<size>" query parameter, the
server first sends a binary frame of that many bytes: a 1, zeros, and then a 2.
- GET /reflect-websocket-cookie with an "Upgrade: websocket" header: As above, but first sends the
handshake's Cookie header (or an empty string) as a text frame.
- GET /reflect-websocket-accept-language does the same for the handshake's Accept-Language header.
- GET /websocket-close-without-response with an "Upgrade: websocket" header: Closes the connection without
responding to the handshake.
- GET /recorded-request-count/<echo path>: Responds with the number of requests the server has seen at <echo path>,
with any query ignored.
- GET /downloads/<name>: Reports the browser's download of <name> into the --downloads-directory: 404 while
there is none, 202 while it is in progress, and the downloaded file once it has finished. A <name> longer
than 188 bytes in UTF-8 gets a 400.
"""
class Echo:
method: str
path: str
status: int
headers: Dict[str, str]
body: Optional[str]
body_encoding: str
delay_ms: Optional[int]
reason_phrase: Optional[str]
reflect_headers_in_body: bool
close_connection: bool
ignore_range: bool
wait_for_unblock: Optional[str]
def __eq__(self, other):
if not isinstance(other, Echo):
return NotImplemented
return (
self.method == other.method
and self.path == other.path
and self.status == other.status
and self.body == other.body
and self.body_encoding == other.body_encoding
and self.delay_ms == other.delay_ms
and self.headers == other.headers
and self.reason_phrase == other.reason_phrase
and self.reflect_headers_in_body == other.reflect_headers_in_body
and self.close_connection == other.close_connection
and self.ignore_range == other.ignore_range
and self.wait_for_unblock == other.wait_for_unblock
)
# In-memory store for echo responses
echo_store: Dict[str, Echo] = {}
# Headers from the most recent request at each echo path, queryable via GET /recorded-request-headers<echo-path>.
recorded_request_headers: Dict[str, Dict[str, list]] = {}
# Number of requests seen at each echo path, query excluded, queryable via GET /recorded-request-count<echo-path>.
recorded_request_counts: Dict[str, int] = {}
recorded_request_counts_lock = threading.Lock()
# Named events used by tests that need deterministic delayed responses.
unblock_events: Dict[str, threading.Event] = {}
stalled_tls_port = 0
stalled_tls_connection_count = 0
# Per RFC 6455: appended to Sec-WebSocket-Key before hashing to compute the Sec-WebSocket-Accept value.
WEBSOCKET_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
def websocket_handshake_response(key):
accept = base64.b64encode(hashlib.sha1((key + WEBSOCKET_ACCEPT_GUID).encode("utf-8")).digest()).decode("ascii")
return (
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
f"Sec-WebSocket-Accept: {accept}\r\n"
"\r\n"
).encode("ascii")
# The browser saves a download as <name>.<id>.<uuid>.download until it finishes. That suffix takes at most 67 of the
# 255 bytes a filename may have, so a name of up to 188 bytes is never cut short.
MAXIMUM_REPORTED_DOWNLOAD_NAME_LENGTH = 188
def name_of_download_in_progress(filename: str) -> Optional[str]:
if not filename.endswith(".download"):
return None
parts = filename[: -len(".download")].rsplit(".", 2)
if len(parts) != 3:
return None
name, download_id, uuid = parts
if not (download_id.isascii() and download_id.isdigit()) or len(uuid) != 36:
return None
return name
def test_web_host_for(hostname):
# A test's subdomains and its -alt host belong to the test-web-*.localhost or test-web-*.test host of the test.
rest, _, top_level_domain = hostname.rpartition(".")
host = rest.rpartition(".")[2].removesuffix("-alt")
if top_level_domain not in ("localhost", "test") or not host.startswith("test-web-"):
return None
return f"{host}.{top_level_domain}"
class WPTContext:
def __init__(self, wpt_directory):
vendored_tools_root = os.path.join(wpt_directory, "_wpttools")
for path in (wpt_directory, vendored_tools_root):
sys.path.insert(0, path)
import _wpttools as vendored_tools
import localpaths
# Make the copied tree behave like the upstream `tools` package so
# vendored modules can keep importing `tools.*` and `localpaths`.
cast(Any, vendored_tools).localpaths = localpaths
sys.modules["tools"] = vendored_tools
sys.modules["tools.localpaths"] = localpaths
sys.modules["localpaths"] = localpaths
localpaths.repo_root = os.path.abspath(wpt_directory)
from wptserve.config import ConfigBuilder
from wptserve.handlers import AsIsHandler
from wptserve.handlers import FileHandler
from wptserve.handlers import python_script_handler
from wptserve.request import Request
from wptserve.request import Server
from wptserve.response import Response
from wptserve.stash import Stash
from wptserve.stash import start_server as start_stash_server
from wptserve.utils import HTTPException
class TestWebConfigBuilder(ConfigBuilder):
# Our own servers serve HTTPS, not wptserve's, so keep the HTTPS ports that wptserve drops when its own TLS
# support is not configured.
def _get_ports(self, data):
return defaultdict(list, {scheme: list(ports) for scheme, ports in data["ports"].items()})
self.config_builder_class = TestWebConfigBuilder
self.server_class = Server
self.request_class = Request
self.response_class = Response
self.file_handler_class = FileHandler
self.as_is_handler_class = AsIsHandler
self.python_script_handler = python_script_handler
self.http_exception = HTTPException
self.stash_class = Stash
self.stash_manager, self.stash_address, self.stash_authkey = start_stash_server()
def create_file_handler(self, base_path, url_base="/"):
file_handler = self.file_handler_class(base_path=base_path, url_base=url_base)
as_is_handler = self.as_is_handler_class(base_path=base_path, url_base=url_base)
def handler(request, response):
# Like upstream wptserve, send .asis files without generating any response headers.
if request.url_parts.path.endswith(".asis"):
return as_is_handler(request, response)
return file_handler(request, response)
return handler
def configure_server(self, http_ports, https_ports):
# The HTTP(S) servers also accept WebSocket connections.
self.ports = {"http": http_ports, "https": https_ports, "ws": http_ports[:1], "wss": https_ports}
self.configs_by_host = {}
self.configs_by_host_lock = threading.Lock()
cast(Any, self.server_class).config = self._build_config("web-platform.localhost")
def _build_config(self, browser_host, alternate_host="not-localhost.localhost"):
def make_subdomains_product(subdomains, depth=2):
return {
".".join(labels)
for length in range(1, depth + 1)
for labels in itertools.product(subdomains, repeat=length)
}
subdomains = make_subdomains_product({"www", "www1", "www2"})
not_subdomains = make_subdomains_product({"nonexistent"})
logger = logging.getLogger("test-web-wptserve")
with self.config_builder_class(
logger,
browser_host=browser_host,
alternate_hosts={"alt": alternate_host},
ports=self.ports,
subdomains=subdomains,
not_subdomains=not_subdomains,
check_subdomains=False,
) as config:
return config
def apply_config_for_request(self, request):
# test-web uses unique test-web-*.localhost hosts, or test-web-*.test for insecure-origin tests.
# Substitutions like {{host}} and {{domains[www1]}} must name that test host and its subdomains.
hostname = request.url_parts.hostname or ""
test_host = test_web_host_for(hostname)
if not test_host:
return
is_https = request.url_parts.scheme == "https"
key = (test_host, is_https)
with self.configs_by_host_lock:
config = self.configs_by_host.get(key)
if config is None:
# Each test has its own host, so only keep the configs of the most recent ones.
if len(self.configs_by_host) >= 64:
self.configs_by_host.pop(next(iter(self.configs_by_host)))
if is_https:
config = self._build_config(test_host, test_host.removesuffix(".localhost") + "-alt.localhost")
else:
config = self._build_config(test_host)
self.configs_by_host[key] = config
request.server.config = config
def close(self):
self.stash_manager.shutdown()
class TestHTTPServer(socketserver.ThreadingTCPServer):
request_queue_size = socket.SOMAXCONN
scheme: str
router: SimpleNamespace
wpt: WPTContext
wpt_file_handler: Callable[[Any, Any], Any]
static_file_handler: Callable[[Any, Any], Any]
class TestHTTPServerIPv6(TestHTTPServer):
address_family = socket.AF_INET6
class TestHTTPSServer(TestHTTPServer):
ssl_context: ssl.SSLContext
def get_request(self):
sock, addr = super().get_request()
# Leave the handshake to the first read, which happens on the request's own thread.
return self.ssl_context.wrap_socket(sock, server_side=True, do_handshake_on_connect=False), addr
class TestHTTPSServerIPv6(TestHTTPSServer):
address_family = socket.AF_INET6
class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
static_directory: str
wpt_directory: str
downloads_directory: Optional[str] = None
aia_artifacts: dict
aia_config: Optional[dict]
def __init__(self, *arguments, **kwargs):
super().__init__(*arguments, directory=self.static_directory, **kwargs)
def _test_server(self):
return cast(TestHTTPServer, self.server)
def end_headers(self):
extra_headers = getattr(self, "_extra_headers", None)
if extra_headers is not None:
self._sending_extra_headers = True
for key, value in extra_headers:
self.send_header(key, value)
self._sending_extra_headers = False
delattr(self, "_extra_headers")
delattr(self, "_extra_header_names")
super().end_headers()
def send_header(self, keyword, value):
# Headers from .headers files override headers created by SimpleHTTPRequestHandler.
extra_header_names = getattr(self, "_extra_header_names", None)
if (
extra_header_names is not None
and not getattr(self, "_sending_extra_headers", False)
and keyword.lower() in extra_header_names
):
return
super().send_header(keyword, value)
def _request_target(self):
if self.path.startswith("/static/"):
# Explicit /static/ URLs continue to serve files from the general test root.
return self.static_directory, self.path[7:]
# All other non-echo URLs are served from the imported WPT tree.
# This lets absolute WPT paths like /html/... resolve through the test server.
return self.wpt_directory, self.path
def _serve_wpt_python_script(self):
self.directory, self.path = self._request_target()
server = self._test_server()
server.router.doc_root = self.directory
request, response = self._create_wpt_request_response()
try:
server.wpt.python_script_handler(request, response)
except server.wpt.http_exception as exception:
response.set_error(exception.code, exception)
except Exception as exception:
response.set_error(500, exception)
if not response.writer.content_written:
response.write()
if response.close_connection:
self.close_connection = True
request.close()
def _create_wpt_request_response(self):
server = self._test_server()
request = server.wpt.request_class(self)
server.wpt.apply_config_for_request(request)
request.server._stash = server.wpt.stash_class(
request.url_parts.path,
server.wpt.stash_address,
server.wpt.stash_authkey,
)
response = server.wpt.response_class(self, request)
return request, response
def _serve_wpt_file_request(self):
self.directory, _ = self._request_target()
server = self._test_server()
server.router.doc_root = self.directory
request, response = self._create_wpt_request_response()
if self.path.startswith("/static/"):
handler = server.static_file_handler
else:
handler = server.wpt_file_handler
try:
handler(request, response)
except server.wpt.http_exception as exception:
response.set_error(exception.code, exception)
except Exception as exception:
response.set_error(500, exception)
if not response.writer.content_written:
response.write()
if response.close_connection:
self.close_connection = True
request.close()
def _serve_static_request(self):
self._serve_wpt_file_request()
def _serve_aia_artifact(self, request_path):
# Serves the intermediate certificate that the broken-chain HTTPS hosts point at via their AIA caIssuers URL.
# Fetched by RequestServer, not by the page.
entry = getattr(TestHTTPRequestHandler, "aia_artifacts", {}).get(request_path)
if entry is None:
# for example, /aia/dead: a deliberately missing artifact, to exercise the failure path.
self.send_error(404, "Not Found")
return
content_type, body = entry
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _serve_stalled_tls_config(self):
# Lets the test page discover a port that accepts connections and never answers a TLS handshake, and how many
# connections it has accepted so far.
body = json.dumps({"port": stalled_tls_port, "connections": stalled_tls_connection_count}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _serve_aia_config(self):
# Lets the test page discover the per-scenario HTTPS ports (each an OS-assigned port).
config = getattr(TestHTTPRequestHandler, "aia_config", None)
body = json.dumps(config or {}).encode("utf-8")
self.send_response(200 if config else 503)
self.send_header("Content-Type", "application/json")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.headers.get("Upgrade", "").lower() == "websocket":
self._serve_websocket_echo()
return
request_path = self.path.partition("?")[0]
if request_path.startswith("/unblock/"):
self._serve_unblock()
elif request_path.startswith("/echo"):
self.handle_echo()
elif request_path.startswith("/recorded-request-headers/"):
self._serve_recorded_request_headers()
elif request_path.startswith("/recorded-request-count/"):
self._serve_recorded_request_count()
elif request_path.startswith("/downloads/"):
self._serve_download()
elif request_path.endswith(".py"):
self._serve_wpt_python_script()
elif request_path.startswith("/aia/"):
self._serve_aia_artifact(request_path)
elif request_path == "/aia-test/config":
self._serve_aia_config()
elif request_path == "/stalled-tls/config":
self._serve_stalled_tls_config()
else:
self._serve_static_request()
def do_POST(self):
request_path = self.path.partition("?")[0]
if request_path == "/echo":
self._register_echo()
elif request_path.startswith("/echo/"):
self.handle_echo()
elif request_path.endswith(".py"):
self._serve_wpt_python_script()
else:
self.send_error(405, "Method Not Allowed")
def do_OPTIONS(self):
request_path = self.path.partition("?")[0]
if request_path.startswith("/echo"):
# Requests with "credentials=include" cannot have "Access-Control-Allow-Origin=*". If the test registered
# an OPTIONS echo, return the headers that it specified.
key = f"OPTIONS {self.path}"
if key in echo_store:
self.handle_echo()
return
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "*")
self.send_header("Access-Control-Allow-Headers", "*")
self.end_headers()
else:
self.do_other()
def do_PUT(self):
self.do_other()
def do_HEAD(self):
self.do_other()
def do_DELETE(self):
self.do_other()
def do_PROPFIND(self):
self.do_other()
def do_REPORT(self):
self.do_other()
def do_SAFE(self):
self.do_other()
def do_safe(self):
self.do_other()
def _register_echo(self):
"""Handle a request to register an echo server handler"""
content_length = int(self.headers["Content-Length"])
post_data = self.rfile.read(content_length)
data = json.loads(post_data.decode("utf-8"))
echo = Echo()
echo.method = data.get("method", None)
echo.path = data.get("path", None)
echo.status = data.get("status", None)
echo.body = data.get("body", None)
echo.body_encoding = data.get("body_encoding", "raw")
echo.delay_ms = data.get("delay_ms", None)
echo.headers = data.get("headers", {})
echo.reason_phrase = data.get("reason_phrase", None)
echo.reflect_headers_in_body = data.get("reflect_headers_in_body", False)
echo.close_connection = data.get("close_connection", False)
echo.ignore_range = data.get("ignore_range", False)
echo.wait_for_unblock = data.get("wait_for_unblock", None)
is_invalid_echo_path = echo.path is None or not echo.path.startswith("/echo/")
# Return 400: Bad Request if invalid params are given or a reserved path is given
if (
echo.method is None
or echo.path is None
or echo.status is None
or echo.body_encoding not in ("raw", "base64")
or (echo.body is not None and "$HEADERS" not in echo.body and echo.reflect_headers_in_body)
or is_invalid_echo_path
):
self.send_response(400)
self.send_header("Content-Type", "text/plain")
self.end_headers()
return
# Return 409: Conflict if the method+path combination already exists
key = f"{echo.method} {urllib.parse.urlparse(echo.path).path}"
if key in echo_store and echo_store[key] != echo:
self.send_response(409)
self.send_header("Content-Type", "text/plain")
self.end_headers()
message = (
"Echo already exists for method+path, but with a different definition.\n"
f"key: {key}\n"
"Hint: Use a unique path per test run (or keep the same definition).\n"
)
self.wfile.write(message.encode("utf-8"))
return
echo_store[key] = echo
if echo.wait_for_unblock is not None:
unblock_events[echo.wait_for_unblock] = threading.Event()
host = self.headers.get("host", "localhost")
path = echo.path.lstrip("/")
fetch_url = f"http://{host}/{path}"
# The params to use on the client when making a request to the newly created echo endpoint
fetch_config = {
"method": echo.method,
"url": fetch_url,
}
self.send_response(201)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(fetch_config).encode("utf-8"))
def _serve_unblock(self):
token = urllib.parse.unquote(self.path.partition("?")[0][len("/unblock/") :])
event = unblock_events.setdefault(token, threading.Event())
event.set()
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
def _serve_recorded_request_headers(self):
echo_path = self.path[len("/recorded-request-headers") :]
headers = recorded_request_headers.get(echo_path)
if headers is None:
self.send_error(404, f"No recorded request at {echo_path}")
return
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(headers).encode("utf-8"))
def _serve_recorded_request_count(self):
echo_path = self.path.partition("?")[0][len("/recorded-request-count") :]
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(recorded_request_counts.get(echo_path, 0)).encode("utf-8"))
def _serve_download(self):
name = urllib.parse.unquote(self.path.partition("?")[0][len("/downloads/") :])
directory = TestHTTPRequestHandler.downloads_directory
body = b""
status = 404
if len(name.encode("utf-8")) > MAXIMUM_REPORTED_DOWNLOAD_NAME_LENGTH:
status = 400
elif directory is not None and name not in ("", ".", "..") and os.path.basename(name) == name:
path = os.path.join(directory, name)
if os.path.isfile(path):
with open(path, "rb") as file:
body = file.read()
status = 200
elif any(name_of_download_in_progress(entry) == name for entry in os.listdir(directory)):
status = 202
self.send_response(status)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def handle_echo(self):
method = self.command.upper()
parsed_url = urllib.parse.urlparse(self.path)
query = urllib.parse.parse_qs(parsed_url.query)
key = f"{method} {self.path}"
if key not in echo_store:
key = f"{method} {parsed_url.path}"
headers_for_path: Dict[str, list[str]] = {}
for header, value in self.headers.items():
headers_for_path.setdefault(header, []).append(value)
recorded_request_headers[self.path] = headers_for_path
with recorded_request_counts_lock:
recorded_request_counts[parsed_url.path] = recorded_request_counts.get(parsed_url.path, 0) + 1
if parsed_url.path != self.path:
recorded_request_headers[parsed_url.path] = recorded_request_headers[self.path]
# The request's body is read before responding, so closing the connection does not reset it.
content_length = int(self.headers.get("Content-Length", 0))
request_body = bytearray()
if content_length:
read_size = int(query.get("request_body_read_size", [content_length])[0])
read_delay_ms = int(query.get("request_body_read_delay_ms", [0])[0])
remaining = content_length
while remaining > 0:
if read_delay_ms:
time.sleep(read_delay_ms / 1000)
data = self.rfile.read(min(read_size, remaining))
# The client closed the connection before sending the whole body.
if not data:
break
request_body += data
remaining -= len(data)
is_revalidation_request = "If-Modified-Since" in self.headers
send_not_modified = is_revalidation_request and "X-Ladybird-Respond-With-Not-Modified" in self.headers
send_incomplete_response = "X-Ladybird-Respond-With-Incomplete-Response" in self.headers
set_invalid_cookie = "X-Ladybird-Set-Invalid-Cookie" in self.headers
if key not in echo_store:
self.send_error(404, f"Echo response not found for {key}")
return
echo = echo_store[key]
if echo.close_connection:
self.connection.shutdown(socket.SHUT_WR)
self.connection.close()
return
if echo.wait_for_unblock is not None:
event = unblock_events.setdefault(echo.wait_for_unblock, threading.Event())
event.wait()
response_headers = echo.headers.copy()
if echo.delay_ms is not None:
time.sleep(echo.delay_ms / 1000)
if send_not_modified:
self.send_response(304)
else:
self.send_response_only(echo.status, echo.reason_phrase)
if is_revalidation_request:
# Override the Last-Modified header to prevent cURL from thinking the response is still fresh.
response_headers["Last-Modified"] = "Thu, 01 Jan 1970 00:00:00 GMT"
elif send_incomplete_response:
# We emulate an incomplete response by advertising a 10KB file, but only sending 2KB.
response_headers["Content-Length"] = str(10 * 1024)
if set_invalid_cookie:
response_headers["Set-Cookie"] = "invalid=foo; Domain=\xc3\xa9\x6c\xc3\xa8\x76\x65\xff"
# Set only the headers defined in the echo definition
if response_headers:
for header, value in response_headers.items():
self.send_header(header, value)
self.end_headers()
if send_not_modified:
return
if send_incomplete_response:
self.wfile.write(b"a" * (2 * 1024))
self.wfile.flush()
self.connection.shutdown(socket.SHUT_WR)
self.connection.close()
return
if echo.reflect_headers_in_body:
headers = {}
for key in self.headers.keys():
headers[key] = self.headers.get_all(key)
headers = json.dumps(headers)
response_body = echo.body.replace("$HEADERS", headers) if echo.body else headers
else:
response_body = echo.body or ""
response_body = response_body.replace("$BODY", request_body.decode("utf-8", "replace"))
# FIXME: This only supports "Range: bytes=start-end" and "Range: bytes=start-". There are other formats to
# support if needed: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Range#syntax
if "Range" in self.headers and not echo.ignore_range:
range_value = self.headers["Range"].strip()
assert range_value.startswith("bytes=")
assert range_value.count("-") == 1
range_value = range_value[len("bytes=") :]
start, end = range_value.split("-")
if end:
response_body = response_body[int(start) : min(int(end), len(response_body))]
else:
response_body = response_body[int(start) :]
if echo.body_encoding == "base64":
response_body_bytes = base64.b64decode(response_body)
else:
response_body_bytes = response_body.encode("utf-8")
chunks = query.get("chunks", [])
chunk_delay_ms = int(query.get("chunk_delay_ms", [0])[0] or 0)
if chunks:
chunk_sizes = [int(chunk_size) for chunk_size in chunks[0].split(",") if chunk_size]
offset = 0
chunk_unblock_tokens = query.get("chunk_unblock_tokens", [""])[0].split(",")
for chunk_index, chunk_size in enumerate(chunk_sizes):
self.wfile.write(response_body_bytes[offset : offset + chunk_size])
self.wfile.flush()
offset += chunk_size
if chunk_index < len(chunk_unblock_tokens) and chunk_unblock_tokens[chunk_index]:
token = chunk_unblock_tokens[chunk_index]
unblock_events.setdefault(token, threading.Event()).wait()
if chunk_delay_ms > 0:
time.sleep(chunk_delay_ms / 1000)
if offset < len(response_body_bytes):
self.wfile.write(response_body_bytes[offset:])
return
self.wfile.write(response_body_bytes)
def do_other(self):
request_path = self.path.partition("?")[0]
if request_path.startswith("/echo"):
self.handle_echo()
elif request_path.endswith(".py"):
self._serve_wpt_python_script()
else:
self.send_error(405, "Method Not Allowed")
# --- Minimal RFC 6455 WebSocket echo --------------------------------------------------------------
# Reached when a request carries an "Upgrade: websocket" header. The tests use this in place of an
# externally-hosted echo server, so they have no network dependency. The client sends first; every
# text/binary frame it sends is echoed back verbatim.
def _serve_websocket_echo(self):
if self.path == "/websocket-close-without-response":
self.close_connection = True
return
key = self.headers.get("Sec-WebSocket-Key")
if not key:
self.send_error(400, "Missing Sec-WebSocket-Key")
return
# We now own the raw socket; stop the HTTP handler from parsing another request on it.
self.close_connection = True
self.connection.sendall(websocket_handshake_response(key))
if self.path == "/reflect-websocket-cookie":
self._send_websocket_frame(self.headers.get("Cookie", "").encode("utf-8"))
elif self.path == "/reflect-websocket-accept-language":
self._send_websocket_frame(self.headers.get("Accept-Language", "").encode("utf-8"))
query = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query)
if "send-binary" in query:
payload = bytearray(int(query["send-binary"][0]))
payload[0] = 1
payload[-1] = 2
self._send_websocket_frame(bytes(payload), opcode=0x2)
while True:
frame = self._read_websocket_frame()
if frame is None:
break
opcode, payload = frame
if opcode == 0x8: # Close
self._send_websocket_close()
break
if opcode == 0x9: # Ping -> Pong
self._send_websocket_frame(payload, opcode=0xA)
continue
if opcode in (0x1, 0x2): # Text / Binary -> echo verbatim
self._send_websocket_frame(payload, opcode=opcode)
def _recv_exact(self, count):
data = bytearray()
while len(data) < count:
chunk = self.rfile.read(count - len(data))
if not chunk:
return None
data += chunk
return bytes(data)
def _read_websocket_frame(self):
header = self._recv_exact(2)
if header is None:
return None
opcode = header[0] & 0x0F
is_masked = (header[1] & 0x80) != 0
length = header[1] & 0x7F
if length == 126:
extended = self._recv_exact(2)
if extended is None:
return None
length = int.from_bytes(extended, "big")
elif length == 127:
extended = self._recv_exact(8)
if extended is None:
return None
length = int.from_bytes(extended, "big")
mask = b""
if is_masked:
mask = self._recv_exact(4)
if mask is None:
return None
payload = self._recv_exact(length) if length else b""
if payload is None:
return None
if is_masked:
payload = bytes(payload[i] ^ mask[i % 4] for i in range(length))
return opcode, payload
def _build_ws_frame(self, data, opcode=0x1):
header = bytearray([0x80 | opcode])
length = len(data)
if length < 126:
header.append(length)
elif length < 65536:
header.append(126)
header += length.to_bytes(2, "big")
else:
header.append(127)
header += length.to_bytes(8, "big")
return bytes(header) + data
def _send_websocket_frame(self, data, opcode=0x1):
if isinstance(data, str):
data = data.encode("utf-8")
try:
self.connection.sendall(self._build_ws_frame(data, opcode))
except OSError:
pass
def _send_websocket_close(self):
try:
self.connection.sendall(bytes([0x88, 0x00])) # FIN + Close opcode, empty payload.
except OSError:
pass
class AIALeafHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.headers.get("Upgrade", "").lower() == "websocket":
# Accept the handshake and hang up, so a test can tell whether a wss:// connection got past TLS.
self.wfile.write(websocket_handshake_response(self.headers.get("Sec-WebSocket-Key", "")))
self.close_connection = True
return
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", "2")
self.end_headers()
self.wfile.write(b"ok")
def log_message(self, format: str, *args: Any) -> None:
pass
class AIATLSServer(socketserver.ThreadingTCPServer):
daemon_threads = True
allow_reuse_address = True
def __init__(self, server_address, handler, ssl_context):
super().__init__(server_address, handler)
self._ssl_context = ssl_context
def get_request(self):
sock, addr = super().get_request()
try:
return self._ssl_context.wrap_socket(sock, server_side=True), addr
except OSError:
sock.close()
raise
def _setup_tls_test_servers(http_port, ca_cert_output):
import datetime
import tempfile
from cryptography import x509 # type: ignore[import-not-found]
from cryptography.hazmat.primitives import hashes # type: ignore[import-not-found]
from cryptography.hazmat.primitives.asymmetric import ec # type: ignore[import-not-found]
from cryptography.hazmat.primitives.serialization import Encoding # type: ignore[import-not-found]
from cryptography.hazmat.primitives.serialization import NoEncryption # type: ignore[import-not-found]
from cryptography.hazmat.primitives.serialization import PrivateFormat # type: ignore[import-not-found]
from cryptography.hazmat.primitives.serialization import pkcs7 # type: ignore[import-not-found]
from cryptography.x509.oid import AuthorityInformationAccessOID # type: ignore[import-not-found]
from cryptography.x509.oid import ExtendedKeyUsageOID # type: ignore[import-not-found]
from cryptography.x509.oid import NameOID # type: ignore[import-not-found]
def new_key():
return ec.generate_private_key(ec.SECP256R1())
def dn(common_name):
return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)])
not_before, not_after = datetime.datetime(2020, 1, 1), datetime.datetime(2050, 1, 1)
root_key = new_key()
root = (
x509.CertificateBuilder()
.subject_name(dn("Ladybird AIA Test Root"))
.issuer_name(dn("Ladybird AIA Test Root"))
.public_key(root_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(not_before)
.not_valid_after(not_after)
.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
.sign(root_key, hashes.SHA256())
)
aia_base = f"http://127.0.0.1:{http_port}/aia"
artifacts = {}
scenarios = {}
def add_scenario(name, host, artifact_name, encoding, shared=None):
# By default, each scenario gets its own intermediate — so fetching one never populates the cache for another
# (which would mask whether that scenario's own fetch and parse ran). The de-dupe scenarios instead share one
# intermediate — to check it's fetched only once.
if shared is not None:
intermediate, intermediate_key = shared
else:
intermediate_key = new_key()
intermediate = (
x509.CertificateBuilder()
.subject_name(dn(f"Ladybird AIA Test Intermediate ({name})"))
.issuer_name(root.subject)
.public_key(intermediate_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(not_before)
.not_valid_after(not_after)
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
.sign(root_key, hashes.SHA256())
)
if encoding == "der":
artifacts[f"/aia/{artifact_name}"] = ("application/pkix-cert", intermediate.public_bytes(Encoding.DER))
aia_url = f"{aia_base}/{artifact_name}"
elif encoding == "pkcs7":
artifacts[f"/aia/{artifact_name}"] = (
"application/pkcs7-mime",
pkcs7.serialize_certificates([intermediate], Encoding.DER),
)
aia_url = f"{aia_base}/{artifact_name}"
else:
aia_url = f"{aia_base}/dead" # 404: the intermediate is never published
leaf_key = new_key()
leaf = (
x509.CertificateBuilder()
.subject_name(dn(host))
.issuer_name(intermediate.subject)
.public_key(leaf_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(not_before)
.not_valid_after(not_after)
.add_extension(x509.SubjectAlternativeName([x509.DNSName("localhost")]), critical=False)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
.add_extension(
x509.AuthorityInformationAccess(
[
x509.AccessDescription(
AuthorityInformationAccessOID.CA_ISSUERS, x509.UniformResourceIdentifier(aia_url)
)
]
),
critical=False,
)
.sign(intermediate_key, hashes.SHA256())
)
scenarios[name] = (leaf, leaf_key)
return intermediate, intermediate_key
add_scenario("good_der", "good-der.localhost", "intermediate-der.der", "der")
add_scenario("good_pkcs7", "good-pkcs7.localhost", "intermediate-pkcs7.p7c", "pkcs7")
add_scenario("dead", "dead.localhost", None, "dead")
shared_intermediate = add_scenario("dedup_a", "dedup-a.localhost", "intermediate-dedup.der", "der")
add_scenario("dedup_b", "dedup-b.localhost", "intermediate-dedup.der", "der", shared_intermediate)
# Negative trust control: The caIssuers URL serves a self-signed cert that's *not* anchored in the trusted test
# root. A fetched intermediate must never complete a chain to an untrusted anchor — so this host must fail to load.
untrusted_key = new_key()
untrusted = (
x509.CertificateBuilder()
.subject_name(dn("Ladybird AIA Test UNTRUSTED root"))
.issuer_name(dn("Ladybird AIA Test UNTRUSTED root"))
.public_key(untrusted_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(not_before)
.not_valid_after(not_after)
.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
.sign(untrusted_key, hashes.SHA256())
)
artifacts["/aia/untrusted.der"] = ("application/pkix-cert", untrusted.public_bytes(Encoding.DER))
untrusted_leaf_key = new_key()
untrusted_leaf = (
x509.CertificateBuilder()
.subject_name(dn("untrusted-leaf.localhost"))
.issuer_name(untrusted.subject)
.public_key(untrusted_leaf_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(not_before)
.not_valid_after(not_after)
.add_extension(x509.SubjectAlternativeName([x509.DNSName("localhost")]), critical=False)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
.add_extension(
x509.AuthorityInformationAccess(
[
x509.AccessDescription(
AuthorityInformationAccessOID.CA_ISSUERS,
x509.UniformResourceIdentifier(f"{aia_base}/untrusted.der"),
)
]
),
critical=False,
)
.sign(untrusted_key, hashes.SHA256())
)
scenarios["untrusted"] = (untrusted_leaf, untrusted_leaf_key)
# Leaves issued by the root itself, naming localhost either only in the Common Name or also in a subjectAltName.
def add_root_issued_scenario(name, subject_alt_names):
leaf_key = new_key()
builder = (
x509.CertificateBuilder()
.subject_name(dn("localhost"))
.issuer_name(root.subject)
.public_key(leaf_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(not_before)
.not_valid_after(not_after)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
)
if subject_alt_names:
builder = builder.add_extension(x509.SubjectAlternativeName(subject_alt_names), critical=False)
scenarios[name] = (builder.sign(root_key, hashes.SHA256()), leaf_key)
add_root_issued_scenario("common_name_only", [])
add_root_issued_scenario("subject_alt_name", [x509.DNSName("localhost")])
TestHTTPRequestHandler.aia_artifacts = artifacts
# Write the root CA so RequestServer (via --certificate/CAINFO) trusts the completed chains.
with open(ca_cert_output, "wb") as ca_file:
ca_file.write(root.public_bytes(Encoding.PEM))
# WPT tests reach HTTPS origins on localhost and 127.0.0.1, and cross-origin ones on the alternate host and its
# subdomains ({{hosts[alt][]}} and {{hosts[alt][www]}}), so the WPT HTTPS server presents a leaf for all of them,
# issued by the root itself.
wpt_leaf_key = new_key()
def make_wpt_leaf(names):
return (
x509.CertificateBuilder()
.subject_name(dn("localhost"))
.issuer_name(root.subject)
.public_key(wpt_leaf_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(not_before)
.not_valid_after(not_after)
.add_extension(x509.SubjectAlternativeName(names), critical=False)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
.sign(root_key, hashes.SHA256())
)
wpt_leaf = make_wpt_leaf(
[
x509.DNSName("localhost"),
# NB: curl ignores a wildcard with fewer than two dots, so the alternate host is named outright.
x509.DNSName("not-localhost.localhost"),
x509.DNSName("*.not-localhost.localhost"),
x509.IPAddress(ipaddress.ip_address("127.0.0.1")),
x509.IPAddress(ipaddress.ip_address("::1")),
]
)
scenarios["wpt"] = (wpt_leaf, wpt_leaf_key)
scratch = tempfile.mkdtemp(prefix="ladybird-aia-")
config = {}
wpt_ssl_context = None
for name, (leaf, leaf_key) in scenarios.items():
# The cert file holds *only* the leaf — so, each HTTPS host presents a broken chain (the intermediate is omitted
# and must be fetched via AIA).
cert_path = os.path.join(scratch, f"{name}.crt")
key_path = os.path.join(scratch, f"{name}.key")
with open(cert_path, "wb") as f:
f.write(leaf.public_bytes(Encoding.PEM))
with open(key_path, "wb") as f:
f.write(leaf_key.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()))
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(certfile=cert_path, keyfile=key_path)
if name == "wpt":
wpt_ssl_context = context
continue
server = AIATLSServer(("127.0.0.1", 0), AIALeafHandler, context)
config[name] = server.socket.getsockname()[1]
threading.Thread(target=server.serve_forever, daemon=True).start()
# Tests reach HTTPS origins on unique *.localhost hosts, which no wildcard can cover, so each host gets a leaf.
@lru_cache(maxsize=128)
def context_for_host(host):
leaf = make_wpt_leaf([x509.DNSName(host)])
with tempfile.TemporaryDirectory(dir=scratch) as certificate_directory:
certificate_path = os.path.join(certificate_directory, "leaf.pem")
with open(certificate_path, "wb") as certificate:
certificate.write(leaf.public_bytes(Encoding.PEM))
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(certfile=certificate_path, keyfile=os.path.join(scratch, "wpt.key"))
return context
def use_host_certificate(socket, server_name, _context):
if server_name and server_name.endswith(".localhost"):
socket.context = context_for_host(server_name)
assert wpt_ssl_context is not None
wpt_ssl_context.sni_callback = use_host_certificate
TestHTTPRequestHandler.aia_config = config
logging.info("AIA test servers ready: %s (root CA at %s)", config, ca_cert_output)
return wpt_ssl_context
def start_mirror_server(server, server_class, address, ssl_context=None):
mirror = server_class(address, TestHTTPRequestHandler)
mirror.daemon_threads = True
mirror.scheme = server.scheme
if ssl_context:
mirror.ssl_context = ssl_context
mirror.scheme = "https"
mirror.router = server.router
mirror.wpt = server.wpt
mirror.wpt_file_handler = server.wpt_file_handler
mirror.static_file_handler = server.static_file_handler
threading.Thread(target=mirror.serve_forever, daemon=True).start()
return mirror
def start_server(port, static_directory, ca_cert_output=None, exit_when_stdin_closes=False, downloads_directory=None):
TestHTTPRequestHandler.static_directory = os.path.abspath(static_directory)
TestHTTPRequestHandler.wpt_directory = os.path.join(
TestHTTPRequestHandler.static_directory, "Text", "input", "wpt-import"
)
TestHTTPRequestHandler.downloads_directory = downloads_directory
httpd = TestHTTPServer(("127.0.0.1", port), TestHTTPRequestHandler)
httpd.daemon_threads = True
httpd.scheme = "http"
httpd.router = SimpleNamespace(doc_root=TestHTTPRequestHandler.wpt_directory)
httpd.wpt = WPTContext(TestHTTPRequestHandler.wpt_directory)
httpd.wpt_file_handler = httpd.wpt.create_file_handler(base_path=TestHTTPRequestHandler.wpt_directory)
httpd.static_file_handler = httpd.wpt.create_file_handler(
base_path=TestHTTPRequestHandler.static_directory,
url_base="/static/",
)
# WPT tests reach a second HTTP origin through {{ports[http][1]}}, so serve the same content on another port.
alternate_httpd = start_mirror_server(httpd, TestHTTPServer, ("127.0.0.1", 0))
https_httpd = None
if ca_cert_output:
# Avoid trusting a stale CA if setup fails. Preserve the inode granted by the sandbox.
open(ca_cert_output, "wb").close()
try:
wpt_ssl_context = _setup_tls_test_servers(httpd.socket.getsockname()[1], ca_cert_output)
if wpt_ssl_context:
# WPT tests reach HTTPS origins through {{ports[https][0]}}, so serve the same content over TLS too.
https_httpd = start_mirror_server(httpd, TestHTTPSServer, ("127.0.0.1", 0), wpt_ssl_context)
except Exception as error:
logging.exception("TLS test setup failed: %s", error)
# A localhost name resolves to ::1 first, which Windows is slow to refuse, so serve there too.
ipv6_servers = []
for server in (httpd, alternate_httpd):
try:
ipv6_servers.append(start_mirror_server(server, TestHTTPServerIPv6, ("::1", server.server_address[1])))
except OSError as error:
logging.warning("Not serving on ::1: %s", error)
if https_httpd:
try:
ipv6_servers.append(
start_mirror_server(
https_httpd, TestHTTPSServerIPv6, ("::1", https_httpd.server_address[1]), https_httpd.ssl_context
)
)
except OSError as error:
logging.warning("Not serving HTTPS on ::1: %s", error)
https_ports = [https_httpd.socket.getsockname()[1]] if https_httpd else []
httpd.wpt.configure_server([httpd.socket.getsockname()[1], alternate_httpd.socket.getsockname()[1]], https_ports)
start_stalled_tls_listener()
# The first line holds the HTTP port, followed by the HTTPS port if there is one.
print(" ".join(str(port) for port in [httpd.socket.getsockname()[1], *https_ports]))
sys.stdout.flush()
if exit_when_stdin_closes:
def shut_down_when_stdin_closes():
sys.stdin.buffer.read()
httpd.shutdown()
threading.Thread(target=shut_down_when_stdin_closes, daemon=True).start()
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
finally:
httpd.wpt.close()
for server in ipv6_servers:
server.server_close()
alternate_httpd.server_close()
if https_httpd:
https_httpd.server_close()
httpd.server_close()
def start_stalled_tls_listener():
global stalled_tls_port
listener = socket.create_server(("127.0.0.1", 0))
stalled_tls_port = listener.getsockname()[1]
def hold_until_closed(connection):
with connection:
try:
while connection.recv(4096):
pass
except OSError:
pass
def accept_connections():
global stalled_tls_connection_count
while True:
connection = listener.accept()[0]
stalled_tls_connection_count += 1
threading.Thread(target=hold_until_closed, args=(connection,), daemon=True).start()
threading.Thread(target=accept_connections, daemon=True).start()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run a HTTP echo server")
parser.add_argument(
"-d",
"--directory",
type=str,
default=".",
help="Directory to serve static files from",
)
parser.add_argument(
"-p",
"--port",
type=int,
default=0,
help="Port to run the server on",
)
parser.add_argument(
"--exit-when-stdin-closes",
action="store_true",
help="Shut down once stdin reaches end-of-file, as when the process that started the server closes it or exits",
)
parser.add_argument(
"--ca-cert-output",
type=str,
default=None,
help="Path to write the AIA test root CA (PEM) to; enables the AIA broken-chain HTTPS servers",
)
parser.add_argument(
"--downloads-directory",
type=str,
default=None,
help="Directory the browser saves downloads to, as reported by GET /downloads/<name>",
)
args = parser.parse_args()
start_server(
port=args.port,
static_directory=args.directory,
ca_cert_output=args.ca_cert_output,
exit_when_stdin_closes=args.exit_when_stdin_closes,
downloads_directory=args.downloads_directory,
)