forked from mtusi2026/mtusi2026lab7
fix: address https-tooling verify findings
Disable TLS 1.3 session tickets on the API so an aborted upload body frees its slot at once; k6 trusts only the run CA. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -249,6 +249,7 @@ def _client_exchange(
|
||||
async def _serving(
|
||||
tls: ApiTls,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
app: Callable[..., Awaitable[None]] = _ok_app,
|
||||
) -> AsyncIterator[tuple[int, _Recorder]]:
|
||||
"""uvicorn с TLS API (контекст и протокол процесса) на loopback."""
|
||||
recorder = _Recorder()
|
||||
@@ -257,7 +258,7 @@ async def _serving(
|
||||
monkeypatch.setattr(settings.api_tls, name, getattr(tls, name))
|
||||
port = _free_port()
|
||||
config = uvicorn.Config(
|
||||
_ok_app,
|
||||
app,
|
||||
host="127.0.0.1",
|
||||
port=port,
|
||||
lifespan="off",
|
||||
@@ -406,6 +407,131 @@ async def test_revoked_client_and_expired_crl(
|
||||
assert rec.records == []
|
||||
|
||||
|
||||
def _bytes_after_handshake(
|
||||
server_context: ssl.SSLContext,
|
||||
client_context: ssl.SSLContext,
|
||||
server_hostname: str,
|
||||
) -> int:
|
||||
"""Рукопожатие в памяти до конца с обеих сторон; сколько байт сервер
|
||||
отдал клиенту сверх того, что клиент прочитал в рукопожатии."""
|
||||
s_in, s_out, c_in, c_out = (ssl.MemoryBIO() for _ in range(4))
|
||||
server = server_context.wrap_bio(s_in, s_out, server_side=True)
|
||||
client = client_context.wrap_bio(
|
||||
c_in,
|
||||
c_out,
|
||||
server_hostname=server_hostname,
|
||||
)
|
||||
done = {"client": False, "server": False}
|
||||
for _ in range(10):
|
||||
for name, conn in (("client", client), ("server", server)):
|
||||
if not done[name]:
|
||||
with contextlib.suppress(ssl.SSLWantReadError):
|
||||
conn.do_handshake()
|
||||
done[name] = True
|
||||
s_in.write(c_out.read())
|
||||
c_in.write(s_out.read())
|
||||
if all(done.values()):
|
||||
break
|
||||
assert all(done.values()), done
|
||||
return c_in.pending
|
||||
|
||||
|
||||
@pytest.mark.parametrize("client_auth", [True, False])
|
||||
def test_no_messages_after_handshake(pki: Path, client_auth: bool) -> None:
|
||||
"""Verify C1 change `https-tooling`: билеты сессии TLS 1.3 после
|
||||
рукопожатия — непрочитанные байты у клиента, который только пишет тело;
|
||||
его обрыв тогда — RST, и процесс API его не замечал."""
|
||||
stand = pki / "stand"
|
||||
client_context = ssl.create_default_context(cafile=stand / "ca.crt")
|
||||
if client_auth:
|
||||
tls = _stand_tls(pki)
|
||||
client_context.load_cert_chain(
|
||||
certfile=stand / "haproxy.crt",
|
||||
keyfile=stand / "haproxy.key",
|
||||
)
|
||||
name = "api"
|
||||
else:
|
||||
tls = _stand_tls(
|
||||
pki,
|
||||
client_auth=False,
|
||||
cert_file=str(stand / "ingress.crt"),
|
||||
key_file=str(stand / "ingress.key"),
|
||||
)
|
||||
name = "localhost"
|
||||
after = _bytes_after_handshake(
|
||||
build_server_context(tls),
|
||||
client_context,
|
||||
name,
|
||||
)
|
||||
assert after == 0
|
||||
|
||||
|
||||
# тело обрываемой загрузки и срок, за который сервер обязан заметить обрыв
|
||||
ABORTED_BODY = b"\x89PNG\r\n\x1a\n" + bytes(1024 * 1024)
|
||||
ABORT_NOTICED_S = 1.0
|
||||
ABORT_ROUNDS = 3
|
||||
|
||||
|
||||
def _aborted_upload(port: int, root: Path) -> None:
|
||||
"""Клиент в роли LB: заголовки, 1 MiB тела частью chunked, закрытие
|
||||
сокета без чтения ответа (как httpx на исключении итератора тела)."""
|
||||
stand = root / "stand"
|
||||
context = ssl.create_default_context(cafile=stand / "ca.crt")
|
||||
context.load_cert_chain(
|
||||
certfile=stand / "haproxy.crt",
|
||||
keyfile=stand / "haproxy.key",
|
||||
)
|
||||
with (
|
||||
socket.create_connection(("127.0.0.1", port), timeout=5) as raw,
|
||||
context.wrap_socket(raw, server_hostname="api") as conn,
|
||||
):
|
||||
conn.sendall(
|
||||
b"POST /upload HTTP/1.1\r\nHost: api\r\n"
|
||||
b"Transfer-Encoding: chunked\r\n\r\n",
|
||||
)
|
||||
conn.sendall(
|
||||
f"{len(ABORTED_BODY):x}\r\n".encode() + ABORTED_BODY + b"\r\n",
|
||||
)
|
||||
|
||||
|
||||
async def test_aborted_body_noticed(
|
||||
pki: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Обрыв тела по mTLS доходит до приложения как `http.disconnect` сразу,
|
||||
а не по сроку (verify C1 change `https-tooling`)."""
|
||||
outcomes: list[str] = []
|
||||
|
||||
async def body_app(_scope: Any, receive: Any, send: Any) -> None:
|
||||
outcome = "complete"
|
||||
try:
|
||||
async with asyncio.timeout(ABORT_NOTICED_S * 5):
|
||||
while True:
|
||||
message = await receive()
|
||||
if message["type"] == "http.disconnect":
|
||||
outcome = "disconnect"
|
||||
break
|
||||
if not message.get("more_body"):
|
||||
break
|
||||
except TimeoutError:
|
||||
outcome = "timeout"
|
||||
outcomes.append(outcome)
|
||||
with contextlib.suppress(OSError):
|
||||
await send(
|
||||
{"type": "http.response.start", "status": 200, "headers": []},
|
||||
)
|
||||
await send({"type": "http.response.body", "body": b""})
|
||||
|
||||
async with _serving(_stand_tls(pki), monkeypatch, body_app) as (port, _):
|
||||
for attempt in range(ABORT_ROUNDS):
|
||||
await asyncio.to_thread(_aborted_upload, port, pki)
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + ABORT_NOTICED_S
|
||||
while len(outcomes) <= attempt and loop.time() < deadline:
|
||||
await asyncio.sleep(0.02)
|
||||
assert outcomes[attempt:] == ["disconnect"], (attempt, outcomes)
|
||||
|
||||
|
||||
async def _raw_request(port: int, request: bytes) -> bytes:
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||
writer.write(request)
|
||||
|
||||
Reference in New Issue
Block a user