Skip to content
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
2 changes: 1 addition & 1 deletion pipegate/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ async def handle_request(
typer.echo(f"Error processing request {request.correlation_id}: {e}", err=True)
payload = BufferGateResponse(
correlation_id=request.correlation_id,
headers="",
headers="{}",
body="",
status_code=504,
)
Expand Down
9 changes: 5 additions & 4 deletions pipegate/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,15 @@ async def handle_http_request(
detail=f"Request body exceeds limit of {settings.max_body_bytes} bytes",
)

loop = asyncio.get_event_loop()
future: asyncio.Future[BufferGateResponse] = loop.create_future()
future: asyncio.Future[BufferGateResponse] = asyncio.Future()
futures[correlation_id] = future

if connection_id not in buffers:
buffers[connection_id] = asyncio.Queue(maxsize=settings.max_queue_depth)
queue = buffers[connection_id]

try:
buffers[connection_id].put_nowait(
queue.put_nowait(
BufferGateRequest(
correlation_id=correlation_id,
method=cast(Methods, request.method),
Expand Down Expand Up @@ -149,6 +149,7 @@ async def handle_websocket(

if connection_id not in buffers:
buffers[connection_id] = asyncio.Queue(maxsize=settings.max_queue_depth)
queue = buffers[connection_id]

async def receive() -> None:
try:
Expand All @@ -170,7 +171,7 @@ async def receive() -> None:

async def send() -> None:
while True:
request = await buffers[connection_id].get()
request = await queue.get()
try:
await websocket.send_text(request.model_dump_json())
except WebSocketDisconnect:
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ dev = [
[tool.pytest.ini_options]
testpaths = ["tests"]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"

[tool.ruff]
target-version = "py312"
Expand Down
33 changes: 33 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,39 @@ def handler(req: httpx.Request) -> httpx.Response:
assert resp.status_code == 504
assert resp.body == ""

async def test_error_response_headers_is_valid_json(self) -> None:
"""PR #24: client error path must emit parseable headers.

headers="" fails orjson.loads("") → JSONDecodeError if any consumer
calls orjson.loads without a falsy guard.
headers="{}" is valid JSON and the correct fix.

This test FAILS on the original code (headers="") and PASSES on the fix.
"""
ws = AsyncMock()
request = BufferGateRequest(
correlation_id=uuid.uuid4(),
url_path="api/data",
url_query=orjson.dumps([]).decode(),
method="GET",
headers=orjson.dumps({}).decode(),
body="",
)

def handler(req: httpx.Request) -> httpx.Response:
raise httpx.ConnectError("connection refused")

async with httpx.AsyncClient(
transport=httpx.MockTransport(handler)
) as http_client:
await handle_request("http://localhost:9000", request, http_client, ws)

resp = BufferGateResponse.model_validate_json(ws.send.call_args[0][0])
assert resp.status_code == 504
# Must be parseable JSON — orjson.loads("") raises JSONDecodeError
parsed = orjson.loads(resp.headers)
assert parsed == {}


class TestMainReconnect:
async def test_retries_on_connection_refused(self) -> None:
Expand Down
116 changes: 114 additions & 2 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
import base64
import contextlib
import json
import uuid
from typing import cast

import orjson
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient, Response

from pipegate.schemas import BufferGateResponse, Settings
from pipegate.schemas import BufferGateRequest, BufferGateResponse, Settings
from pipegate.server import create_app

from .conftest import make_token
Expand All @@ -37,6 +38,7 @@ async def _ws_roundtrip(
query: str = "",
response_body: bytes = b"tunnel-response",
response_status: int = 200,
response_headers: str | None = None,
) -> tuple[Response, dict[str, str]]:
"""Full tunnel round-trip: HTTP -> WS forward -> WS response -> HTTP."""
transport = ASGITransport(app=app)
Expand Down Expand Up @@ -80,7 +82,9 @@ async def ws_client() -> None:

response = BufferGateResponse(
correlation_id=fwd["correlation_id"],
headers=orjson.dumps({"x-tunnel": "ok"}).decode(),
headers=response_headers
if response_headers is not None
else orjson.dumps({"x-tunnel": "ok"}).decode(),
body=base64.b64encode(response_body).decode(),
status_code=response_status,
)
Expand Down Expand Up @@ -372,3 +376,111 @@ async def test_healthz(self, client: AsyncClient) -> None:
resp = await client.get("/healthz")
assert resp.status_code == 200
assert resp.json() == {"status": "ok"}


# ---------------------------------------------------------------------------
# PR #24: empty headers in WS error response
# ---------------------------------------------------------------------------

#
# Server guard: orjson.loads(response.headers) if response.headers else {}
# headers="" is falsy → safe today. headers="{}" is valid JSON either way.
# orjson.loads("") raises JSONDecodeError, so "{}" is the correct value for
# any consumer without the guard.


class TestEmptyHeadersHandling:
async def test_empty_string_headers_does_not_crash_server(
self, connection_id: str
) -> None:
# server guard makes "" safe — passes on both old and new code
resp, _ = await _ws_roundtrip(
_make_app(),
connection_id,
make_token(connection_id),
response_headers="",
response_body=b"",
response_status=504,
)
assert resp.status_code == 504

async def test_empty_json_object_headers_works(self, connection_id: str) -> None:
resp, _ = await _ws_roundtrip(
_make_app(),
connection_id,
make_token(connection_id),
response_headers="{}",
response_body=b"",
response_status=504,
)
assert resp.status_code == 504

def test_empty_string_is_not_valid_json(self) -> None:
# Guard is load-bearing: removing it would crash on headers=""
import pytest

with pytest.raises(ValueError):
orjson.loads("")
assert orjson.loads("{}") == {}


# ---------------------------------------------------------------------------
# PR #24: send() must use the queue captured at connect, not dict re-lookup
# ---------------------------------------------------------------------------

#
# If buffers[connection_id] is replaced while a WS is active, the original
# send() (dict lookup each iteration) drains the replacement queue silently.
# The fix captures `queue` as a local variable at connect time.


class TestQueueStability:
async def test_send_uses_captured_queue_not_dict_lookup(
self, connection_id: str
) -> None:
"""Replace buffers[connection_id] while send() is blocked; verify send()
ignores the replacement (fixed) rather than draining it (original bug)."""
app = _make_app()
token = make_token(connection_id)
scope: dict[str, object] = {
"type": "websocket",
"asgi": {"version": "3.0"},
"http_version": "1.1",
"path": "/",
"query_string": f"token={token}".encode(),
"headers": [],
}
inbox: asyncio.Queue[dict[str, object]] = asyncio.Queue()
outbox: asyncio.Queue[dict[str, object]] = asyncio.Queue()

await inbox.put({"type": "websocket.connect"})
app_task = asyncio.create_task(app(scope, inbox.get, outbox.put)) # type: ignore[arg-type]

msg = await asyncio.wait_for(outbox.get(), timeout=5)
assert msg["type"] == "websocket.accept"

buffers: dict[str, asyncio.Queue[BufferGateRequest]] = app.extra["buffers"]
replacement: asyncio.Queue[BufferGateRequest] = asyncio.Queue(maxsize=100)
buffers[connection_id] = replacement

replacement.put_nowait(
BufferGateRequest(
correlation_id=uuid.uuid4(),
url_path="injected",
url_query="[]",
method="GET",
headers="{}",
body="",
)
)

await asyncio.sleep(0.05)
received_from_replacement = not outbox.empty()

await inbox.put({"type": "websocket.disconnect", "code": 1000})
with contextlib.suppress(Exception):
await asyncio.wait_for(app_task, timeout=2)

assert not received_from_replacement, (
"send() read from a replacement queue — it must use the captured queue ref"
)
Loading