Skip to content
Open
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
62 changes: 60 additions & 2 deletions PasarGuardNodeBridge/rest.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import ast
import asyncio
import logging
import random
import re
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from types import TracebackType
from typing import Any, NoReturn, Self, TypeVar, overload

import aiohttp
from aiohttp.http_exceptions import BadStatusLine, HttpProcessingError
from google.protobuf.message import DecodeError, Message

from PasarGuardNodeBridge.abstract_node import PasarGuardNode
Expand All @@ -19,6 +22,55 @@

ProtoMessageT = TypeVar("ProtoMessageT", bound=Message)

# aiohttp's C parser quotes the bytes it could not parse as a Python bytes literal
_QUOTED_BYTES = re.compile(r"b'(?:[^'\\\n]|\\.)*'|b\"(?:[^\"\\\n]|\\.)*\"")
# An HTTP/2 or HTTP/3 status line: the whole version token, so HTTP/200 is not read as HTTP/2
_HTTP2_OR_3_STATUS = re.compile(rb"HTTP/([23])(?:\.0)?(?:\s|$)")


def _is_http2_control_frame(data: bytes) -> bool:
"""True if data starts with a SETTINGS or GOAWAY frame header as a server sends first (RFC 9113, 4.1 / 6.5 / 6.8)."""
if len(data) < 9:
return False
length = int.from_bytes(data[:3], "big")
stream_id = int.from_bytes(data[5:9], "big") & 0x7FFFFFFF # the top bit is reserved
if stream_id != 0 or length > 16384: # both frames belong to stream 0; 16384 is the initial max frame size
return False
return (data[3] == 0x4 and length % 6 == 0) or (data[3] == 0x7 and length >= 8)


def _describe_non_http11_answer(error: aiohttp.ClientResponseError) -> str | None:
"""Describe an answer without an HTTP/1.x status line, or return None for any other error."""
parse_error = error.__cause__
bad_status_line = getattr(parse_error, "__cause__", None)
if not isinstance(parse_error, HttpProcessingError) or not isinstance(bad_status_line, BadStatusLine):
return None
# The pure-Python parser keeps the status line in .line, the C parser quotes the bytes in the message
received = (bad_status_line.line or "").encode(errors="replace")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if not received and (match := _QUOTED_BYTES.search(bad_status_line.message or "")):
try:
received = ast.literal_eval(match.group())
except (SyntaxError, ValueError):
received = b""

if received.startswith(b"HTTP/1."):
return None # a malformed HTTP/1.x status line keeps the usual 400 mapping
if version := _HTTP2_OR_3_STATUS.match(received):
got = f"HTTP/{version[1].decode()}"
elif received.rstrip(b"\r\n") == b"PRI * HTTP/2.0" or _is_http2_control_frame(received):
# both parsers keep only the first line of the client preface, so it must match exactly
got = "HTTP/2" # the client preface or a SETTINGS/GOAWAY frame
elif received[:1] in (b"\x15", b"\x16") and received[1:2] == b"\x03":
got = "TLS data"
elif received:
got = repr(received[:32])
else:
got = "an unparsable response"
return (
f"Node did not answer with HTTP/1.1 (got {got}); the REST API needs HTTP/1.1, "
"check the reverse proxy and TLS settings"
)


class Node(PasarGuardNode):
def __init__(
Expand Down Expand Up @@ -108,6 +160,9 @@ def _handle_error(self, error: BaseException) -> NoReturn:
raise NodeAPIError(code=-2, detail=f"Network error: {error}")
elif isinstance(error, BufferedStatusError):
raise NodeAPIError(code=error.response.status_code, detail=f"HTTP error: {error.response.text}")
elif isinstance(error, aiohttp.ClientResponseError) and (detail := _describe_non_http11_answer(error)):
# aiohttp reports an answer it cannot parse as status 400, but the node never sent a status
raise NodeAPIError(code=-2, detail=f"Protocol error: {detail}")
elif isinstance(error, aiohttp.ClientResponseError):
raise NodeAPIError(code=error.status, detail=f"HTTP error: {error.message}")
else:
Expand Down Expand Up @@ -391,8 +446,11 @@ async def _iter_chunks() -> AsyncGenerator[bytes, None]:
return []
except Exception as e:
error_type = type(e).__name__
error_text = str(e)
if isinstance(e, aiohttp.ClientResponseError) and (protocol := _describe_non_http11_answer(e)):
error_text = f"Protocol error: {protocol}"
self.logger.warning(
f"[{self.name}] Chunked REST sync failed for {len(users)} user(s) | Error: {error_type} - {e!s}"
f"[{self.name}] Chunked REST sync failed for {len(users)} user(s) | Error: {error_type} - {error_text}"
)
# The node answers 500 with its backend's error when it refused the batch. It answers
# "backend not initialized" or "backend is not started" (also 500) or 503 when no core
Expand All @@ -403,7 +461,7 @@ async def _iter_chunks() -> AsyncGenerator[bytes, None]:
and e.response.status_code == 500
and detail not in ("backend not initialized", "backend is not started")
)
return FailedUsers(users, rejected=rejected, detail=detail if rejected else str(e))
return FailedUsers(users, rejected=rejected, detail=detail if rejected else error_text)

async def list_routing_rules(self, timeout: int | None = None) -> service.RoutingRulesResponse | None:
timeout = timeout or self._default_timeout
Expand Down
171 changes: 171 additions & 0 deletions tests/test_rest_protocol_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
"""A REST node behind something that does not answer with HTTP/1.1 gets a readable error, not aiohttp's parser text."""

import asyncio
import logging
import unittest
from unittest.mock import patch

from aiohttp import http_parser

from PasarGuardNodeBridge import NodeAPIError
from PasarGuardNodeBridge.aiohttp_compat import LazyClientSession, make_timeout
from PasarGuardNodeBridge.common import service_pb2 as service
from PasarGuardNodeBridge.rest import Node as RestNode
from PasarGuardNodeBridge.storage import InMemoryUserSyncStore

# What a server sends first on an HTTP/2-only port: a SETTINGS frame, here followed by GOAWAY
HTTP2_FRAMES = bytes.fromhex("000006040000000000000300000064") + bytes.fromhex("000008070000000000000000000000000001")
# The start of a TLS record (a handshake, as a TLS-only port would send), received over plain HTTP
TLS_RECORD = bytes.fromhex("160303007a020000760303")
# aiohttp's C parser rejects such bytes at once; the pure-Python one waits for a header block and sees a closed connection
C_PARSER = http_parser.HttpResponseParser.__module__ == "aiohttp._http_parser"


class RestProtocolErrorTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.answer = b""
self.server = await asyncio.start_server(self.handle, "127.0.0.1", 0)
port = self.server.sockets[0].getsockname()[1]
with patch("ssl.SSLContext.load_verify_locations"):
self.node = RestNode(
address="127.0.0.1",
port=port,
api_port=1,
server_ca="test",
api_key="00000000-0000-0000-0000-000000000000",
node_id="protocol",
user_sync_store=InMemoryUserSyncStore(),
logger=logging.getLogger("rest-protocol-test"),
)
await self.node._client.close()
self.node._client = LazyClientSession(
ssl_context=None,
headers={"Content-Type": "application/x-protobuf"},
base_url=f"http://127.0.0.1:{port}/",
timeout=make_timeout(None),
)

async def asyncTearDown(self):
await self.node._client.close()
await self.node._json_client.close()
self.server.close()
await self.server.wait_closed()

async def handle(self, reader, writer):
await reader.readuntil(b"\r\n\r\n")
if self.answer:
writer.write(self.answer)
await writer.drain()
writer.close()
await writer.wait_closed()

async def request_error(self) -> NodeAPIError:
with self.assertRaises(NodeAPIError) as caught:
await self.node.info(timeout=5)
return caught.exception

@unittest.skipUnless(C_PARSER, "needs aiohttp's C HTTP parser")
async def test_http2_answer_is_reported_as_protocol_error(self):
self.answer = HTTP2_FRAMES
error = await self.request_error()
self.assertEqual(error.code, -2)
self.assertIn("did not answer with HTTP/1.1 (got HTTP/2)", error.detail)
self.assertIn("check the reverse proxy and TLS settings", error.detail)
self.assertNotIn("Expected HTTP/", error.detail)

async def test_http2_status_line_is_reported_as_protocol_error(self):
self.answer = b"HTTP/2 200\r\ncontent-length: 0\r\n\r\n"
error = await self.request_error()
self.assertEqual(error.code, -2)
self.assertIn("(got HTTP/2)", error.detail)

async def test_http3_status_line_is_labelled_http3(self):
self.answer = b"HTTP/3 200\r\ncontent-length: 0\r\n\r\n"
error = await self.request_error()
self.assertEqual(error.code, -2)
self.assertIn("(got HTTP/3)", error.detail)

async def test_version_prefix_alone_is_not_http2(self):
self.answer = b"HTTP/200 OK\r\ncontent-length: 0\r\n\r\n"
error = await self.request_error()
self.assertEqual(error.code, -2)
self.assertIn("did not answer with HTTP/1.1 (got b'HTTP/200 OK')", error.detail)

async def test_client_preface_line_with_junk_is_quoted(self):
self.answer = b"PRI * HTTP/2.0 junk\r\n\r\n"
error = await self.request_error()
self.assertEqual(error.code, -2)
self.assertIn("(got b'PRI * HTTP/2.0 junk')", error.detail)

async def test_client_preface_is_http2(self):
self.answer = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
error = await self.request_error()
self.assertEqual(error.code, -2)
self.assertIn("(got HTTP/2)", error.detail)

@unittest.skipUnless(C_PARSER, "needs aiohttp's C HTTP parser")
async def test_tls_answer_is_reported_as_protocol_error(self):
self.answer = TLS_RECORD
error = await self.request_error()
self.assertEqual(error.code, -2)
self.assertIn("(got TLS data)", error.detail)

async def test_other_bytes_are_quoted(self):
self.answer = b"SSH-2.0-OpenSSH_9.6\r\n\r\n"
error = await self.request_error()
self.assertEqual(error.code, -2)
self.assertIn("(got b'SSH-2.0-OpenSSH_9.6')", error.detail)

async def test_empty_close_is_still_reported_as_closed_connection(self):
error = await self.request_error()
self.assertEqual(error.code, 500)
self.assertIn("Server closed connection", error.detail)

async def test_malformed_http11_status_line_keeps_400(self):
for answer in (b"HTTP/1.1 abc OK\r\n\r\n", b"HTTP/1.1 2000 OK\r\n\r\n", b"HTTP/1.0 20 OK\r\n\r\n"):
with self.subTest(answer=answer):
self.answer = answer
error = await self.request_error()
self.assertEqual(error.code, 400)
self.assertTrue(error.detail.startswith("HTTP error: "), error.detail)

@unittest.skipUnless(C_PARSER, "needs aiohttp's C HTTP parser")
async def test_frame_type_byte_alone_is_not_http2(self):
# a SETTINGS (0x04) or GOAWAY (0x07) type byte at offset 3, but a non-zero stream id or a bad length
for answer in (
bytes.fromhex("000006040000000001") + b"abcdef",
bytes.fromhex("000005040000000000") + b"abcde",
bytes.fromhex("000008070000000001") + b"abcdefgh",
bytes.fromhex("000004070000000000") + b"abcd",
):
with self.subTest(answer=answer):
self.answer = answer
error = await self.request_error()
self.assertEqual(error.code, -2)
self.assertIn(f"(got {answer!r})", error.detail)

async def test_http_error_status_is_unchanged(self):
self.answer = b"HTTP/1.1 400 Bad Request\r\ncontent-length: 8\r\nconnection: close\r\n\r\nbad body"
error = await self.request_error()
self.assertEqual(error.code, 400)
self.assertEqual(error.detail, "HTTP error: bad body")

async def test_chunked_sync_reports_protocol_error(self):
self.answer = b"HTTP/2 200\r\ncontent-length: 0\r\n\r\n"
users = [service.User(email=f"user-{index}") for index in range(3)]
failed = await self.node.sync_users_chunked(users, chunk_size=2, timeout=5)
self.assertEqual(list(failed), users)
self.assertFalse(failed.rejected)
self.assertIn("Protocol error: Node did not answer with HTTP/1.1 (got HTTP/2)", failed.detail)

async def test_log_stream_open_reports_protocol_error(self):
self.answer = b"HTTP/2 200\r\ncontent-type: text/plain\r\n\r\n"
with self.assertRaises(NodeAPIError) as caught:
async with self.node.stream_logs():
pass
self.assertEqual(caught.exception.code, -2)
self.assertIn("(got HTTP/2)", caught.exception.detail)


if __name__ == "__main__":
unittest.main()