From 8dce286bbdc8010a5b93514a37d6a40b9e7611e8 Mon Sep 17 00:00:00 2001 From: JavadMoqaddam Date: Sun, 22 Nov 2026 23:59:03 +0000 Subject: [PATCH 1/9] fix(grpclib): cap retained h2 closed-stream history per channel (fixes PasarGuard/panel#1254) --- PasarGuardNodeBridge/grpclib.py | 49 ++++++++++++- tests/test_closed_streams_cap.py | 116 +++++++++++++++++++++++++++++++ 2 files changed, 163 insertions(+), 2 deletions(-) create mode 100644 tests/test_closed_streams_cap.py diff --git a/PasarGuardNodeBridge/grpclib.py b/PasarGuardNodeBridge/grpclib.py index 4bfbf51..3294213 100644 --- a/PasarGuardNodeBridge/grpclib.py +++ b/PasarGuardNodeBridge/grpclib.py @@ -13,6 +13,8 @@ from grpclib.const import Status from grpclib.exceptions import GRPCError, StreamTerminatedError from grpclib.protocol import H2Protocol +from h2.settings import SettingCodes +from h2.utilities import SizeLimitDict from python_socks.async_.asyncio import Proxy from PasarGuardNodeBridge.abstract_node import PasarGuardNode @@ -26,12 +28,42 @@ RequestT = TypeVar("RequestT", bound=Message) ResponseT = TypeVar("ResponseT", bound=Message) +# Default per-connection retention for closed streams. h2 keeps up to +# MAX_CLOSED_STREAMS (65536) closed streams per connection for late-frame +# handling; a panel<->node bridge never needs that much history, and 69 +# long-lived connections at the default cap retain hundreds of MiB. +DEFAULT_MAX_CLOSED_STREAMS = 4096 + + +class _CappedH2Protocol(H2Protocol): + """H2Protocol whose h2 connection retains at most `max_closed_streams` closed streams.""" + + max_closed_streams: int | None = None + + def connection_made(self, transport: BaseTransport) -> None: + super().connection_made(transport) + if self.max_closed_streams is not None: + h2_conn = self.connection._connection + h2_conn._closed_streams._size_limit = self.max_closed_streams + h2_conn._closed_streams._check_size_limit() + class ProxiedChannel(Channel): - def __init__(self, *args: Any, proxy_url: str, proxy_rdns: bool | None = None, **kwargs: Any) -> None: + def __init__(self, *args: Any, proxy_url: str, proxy_rdns: bool | None = None, max_closed_streams: int | None = DEFAULT_MAX_CLOSED_STREAMS, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self._proxy_url = proxy_url self._proxy_rdns = proxy_rdns + self._max_closed_streams = max_closed_streams + + def _protocol_factory(self) -> H2Protocol: + protocol = super()._protocol_factory() + base = protocol.__class__ if protocol.__class__ is not H2Protocol else H2Protocol + protocol.__class__ = type( + "ProxiedCappedH2Protocol", + (_CappedH2Protocol, base), + {"max_closed_streams": self._max_closed_streams}, + ) + return protocol async def _create_connection(self) -> H2Protocol: proxy = Proxy.from_url(self._proxy_url, rdns=self._proxy_rdns) @@ -51,11 +83,22 @@ async def _create_connection(self) -> H2Protocol: class VerifiedChannel(Channel): - def __init__(self, *args: Any, tls_policy: TLSPolicy, tls_status: TLSStatus | None = None, **kwargs: Any) -> None: + def __init__(self, *args: Any, tls_policy: TLSPolicy, tls_status: TLSStatus | None = None, max_closed_streams: int | None = DEFAULT_MAX_CLOSED_STREAMS, **kwargs: Any) -> None: self._tls_policy = tls_policy self._tls_status = tls_status + self._max_closed_streams = max_closed_streams super().__init__(*args, **kwargs) + def _protocol_factory(self) -> H2Protocol: + protocol = super()._protocol_factory() + base = protocol.__class__ if protocol.__class__ is not H2Protocol else H2Protocol + protocol.__class__ = type( + "VerifiedCappedH2Protocol", + (_CappedH2Protocol, base), + {"max_closed_streams": self._max_closed_streams}, + ) + return protocol + async def _create_connection(self) -> H2Protocol: policy = self._tls_policy status = self._tls_status @@ -90,6 +133,7 @@ def __init__( internal_timeout: int = 15, max_message_size: int | None = None, proxy: str | None = None, + max_closed_streams: int | None = DEFAULT_MAX_CLOSED_STREAMS, *, server_ca: str | None = None, certificate_sha256: str | None = None, @@ -120,6 +164,7 @@ def __init__( self._max_message_size = max_message_size channel_class = VerifiedChannel if self._proxy is None else VerifiedProxiedChannel channel_kwargs = {} + channel_kwargs["max_closed_streams"] = max_closed_streams if self._proxy is not None: if not self._proxy.grpc_supported: raise NodeAPIError(-7, f"{self._proxy.scheme.upper()} proxies are not supported for gRPC transport") diff --git a/tests/test_closed_streams_cap.py b/tests/test_closed_streams_cap.py new file mode 100644 index 0000000..58b3b07 --- /dev/null +++ b/tests/test_closed_streams_cap.py @@ -0,0 +1,116 @@ +"""h2 closed-stream history retention tests (#1254). + +A long-lived gRPC connection whose streams keep closing retains a bounded +per-connection history of closed streams. h2's default cap (MAX_CLOSED_STREAMS += 65536) is far above what a panel<->node bridge ever needs to hold, so the +bridge must lower the per-channel retention without touching stream lifecycle +itself. + +The test drives a real local plaintext gRPC server through the bridge's own +`ProxiedChannel` with a pass-through proxy dialer, then asserts the h2 +connection's `_closed_streams` stays at the configured cap. +""" + +import asyncio +import logging +import unittest +from unittest.mock import patch + +from grpclib.const import Cardinality, Handler +from grpclib.server import Server + +import PasarGuardNodeBridge.grpclib as bridge_grpclib +from PasarGuardNodeBridge.common import service_pb2 as service +from PasarGuardNodeBridge.common import service_grpc +from PasarGuardNodeBridge.grpclib import Node as GrpcNode, ProxiedChannel +from PasarGuardNodeBridge.storage import InMemoryUserSyncStore + + +class _DirectProxy: + """Pass-through stand-in for python-socks Proxy: dials the destination directly.""" + + def __init__(self, *args, **kwargs): + pass + + @classmethod + def from_url(cls, url: str, rdns=None, **kwargs): + return cls() + + async def connect(self, dest_host, dest_port, timeout=None, **kwargs): + import socket + + sock = socket.create_connection((dest_host, dest_port)) + sock.setblocking(False) + return sock + + +class ClosedStreamsCapTests(unittest.IsolatedAsyncioTestCase): + def make_node(self, port, **kwargs): + with patch("ssl.SSLContext.load_verify_locations"): + return GrpcNode( + address="127.0.0.1", + port=port, + api_port=1, + server_ca="test", + api_key="00000000-0000-0000-0000-000000000000", + node_id="closed-streams-cap", + user_sync_store=InMemoryUserSyncStore(), + sync_poll_interval=0.01, + logger=logging.getLogger("closed-streams-test"), + **kwargs, + ) + + async def test_lowered_cap_bounds_closed_stream_history(self): + """With max_closed_streams set, the retained closed-stream history stays at the cap.""" + + class Receiver: + async def sync_users(inner, stream): + await stream.recv_message() + await stream.send_message(service.Empty()) + + def __mapping__(inner): + return { + "/service.NodeService/SyncUsers": Handler( + inner.sync_users, Cardinality.UNARY_UNARY, service.Users, service.Empty + ), + } + + server = Server([Receiver()]) + await server.start("127.0.0.1", 0) + port = server._server.sockets[0].getsockname()[1] + + cap = 8 + node = self.make_node(port, max_closed_streams=cap) + node._close_chan() + with patch.object(bridge_grpclib, "Proxy", _DirectProxy): + node.channel = ProxiedChannel( + "127.0.0.1", port, ssl=False, proxy_url="socks5://127.0.0.1:1", + max_closed_streams=cap, + ) + node._client = service_grpc.NodeServiceStub(node.channel) + try: + for _ in range(cap * 4): + await node._client.SyncUsers( + service.Users(users=[service.User(email="u0@x")]), + metadata=node._metadata, + ) + h2_conn = node.channel._protocol.connection._connection + self.assertLessEqual(len(h2_conn._closed_streams), cap) + finally: + node._close_chan() + server.close() + await server.wait_closed() + + async def test_default_keeps_h2_behavior(self): + """Without the kwarg the cap is the bridge default (4096), not h2's 65536.""" + node = self.make_node(1) + node._close_chan() + node.channel = ProxiedChannel( + "127.0.0.1", 1, ssl=False, proxy_url="socks5://127.0.0.1:1" + ) + self.assertEqual(node.channel._max_closed_streams, bridge_grpclib.DEFAULT_MAX_CLOSED_STREAMS) + node._close_chan() + + +if __name__ == "__main__": + unittest.main() From bea76a907efef52618f0c04731262de55811716a Mon Sep 17 00:00:00 2001 From: JavadMoqaddam Date: Wed, 25 Nov 2026 10:46:18 +0000 Subject: [PATCH 2/9] Fix CodeRabbit findings: asyncio.BaseTransport annotation, double cap wrapping, lost user cap - Annotate connection_made transport as asyncio.BaseTransport (F821 NameError on import under Python <= 3.13, which do not postpone annotation evaluation) - Skip rewrapping when super()._protocol_factory() already returned a _CappedH2Protocol subclass (inconsistent MRO TypeError whenever proxy and verified TLS are combined) - Assign _max_closed_streams after super().__init__() so ProxiedChannel's default no longer silently overwrites the caller-provided cap --- PasarGuardNodeBridge/grpclib.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/PasarGuardNodeBridge/grpclib.py b/PasarGuardNodeBridge/grpclib.py index 3294213..b899726 100644 --- a/PasarGuardNodeBridge/grpclib.py +++ b/PasarGuardNodeBridge/grpclib.py @@ -40,7 +40,7 @@ class _CappedH2Protocol(H2Protocol): max_closed_streams: int | None = None - def connection_made(self, transport: BaseTransport) -> None: + def connection_made(self, transport: asyncio.BaseTransport) -> None: super().connection_made(transport) if self.max_closed_streams is not None: h2_conn = self.connection._connection @@ -57,6 +57,8 @@ def __init__(self, *args: Any, proxy_url: str, proxy_rdns: bool | None = None, m def _protocol_factory(self) -> H2Protocol: protocol = super()._protocol_factory() + if isinstance(protocol, _CappedH2Protocol): + return protocol base = protocol.__class__ if protocol.__class__ is not H2Protocol else H2Protocol protocol.__class__ = type( "ProxiedCappedH2Protocol", @@ -86,11 +88,13 @@ class VerifiedChannel(Channel): def __init__(self, *args: Any, tls_policy: TLSPolicy, tls_status: TLSStatus | None = None, max_closed_streams: int | None = DEFAULT_MAX_CLOSED_STREAMS, **kwargs: Any) -> None: self._tls_policy = tls_policy self._tls_status = tls_status - self._max_closed_streams = max_closed_streams super().__init__(*args, **kwargs) + self._max_closed_streams = max_closed_streams def _protocol_factory(self) -> H2Protocol: protocol = super()._protocol_factory() + if isinstance(protocol, _CappedH2Protocol): + return protocol base = protocol.__class__ if protocol.__class__ is not H2Protocol else H2Protocol protocol.__class__ = type( "VerifiedCappedH2Protocol", From 77ac85cbcf0b5e6b97819253208288213cd96313 Mon Sep 17 00:00:00 2001 From: JavadMoqaddam Date: Wed, 25 Nov 2026 10:56:08 +0000 Subject: [PATCH 3/9] Drop unused h2 imports left from the cap prototype (ruff F401) --- PasarGuardNodeBridge/grpclib.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/PasarGuardNodeBridge/grpclib.py b/PasarGuardNodeBridge/grpclib.py index b899726..9359607 100644 --- a/PasarGuardNodeBridge/grpclib.py +++ b/PasarGuardNodeBridge/grpclib.py @@ -13,8 +13,6 @@ from grpclib.const import Status from grpclib.exceptions import GRPCError, StreamTerminatedError from grpclib.protocol import H2Protocol -from h2.settings import SettingCodes -from h2.utilities import SizeLimitDict from python_socks.async_.asyncio import Proxy from PasarGuardNodeBridge.abstract_node import PasarGuardNode From d0c165ab78d45d0c8dac092be98c8eb0bdaf84c4 Mon Sep 17 00:00:00 2001 From: JavadMoqaddam Date: Wed, 25 Nov 2026 12:23:41 +0000 Subject: [PATCH 4/9] Add safe floor for max_closed_streams (CodeRabbit minor #4) Below the floor, ordinary client cancels evict their own history entries fast enough that a late HEADERS/DATA for an evicted stream surfaces as a connection-level PROTOCOL_ERROR and kills every unrelated RPC on the connection (h2 turns 'unknown stream' into a connection error unless it can see the stream was closed by reset; h2/connection.py:1547-1555 and h2/connection.py:648). Values below MIN_MAX_CLOSED_STREAMS (128) are clamped with a warning at both the Node level and the two channel classes, mirroring the panel's _clamp_timeout pattern (app/utils/reality_scan.py:190-192); None (uncapped) stays untouched. Floor picked from measured h2 history cost (~120 B/entry => ~15 KiB at 128). Regression test added; existing cap=8 test moved to the floor. --- PasarGuardNodeBridge/grpclib.py | 28 +++++++++++++++++++++ tests/test_closed_streams_cap.py | 43 ++++++++++++++++++++++++++++---- 2 files changed, 66 insertions(+), 5 deletions(-) diff --git a/PasarGuardNodeBridge/grpclib.py b/PasarGuardNodeBridge/grpclib.py index 9359607..46f2b06 100644 --- a/PasarGuardNodeBridge/grpclib.py +++ b/PasarGuardNodeBridge/grpclib.py @@ -32,6 +32,16 @@ # long-lived connections at the default cap retain hundreds of MiB. DEFAULT_MAX_CLOSED_STREAMS = 4096 +logger = logging.getLogger(__name__) + +# Floor for explicit caps. Below this, ordinary client cancels (RST_STREAM) +# evict their own history entries fast enough that a late HEADERS/DATA for an +# evicted stream surfaces as a connection-level PROTOCOL_ERROR and kills every +# unrelated RPC multiplexed on the same connection (h2 turns "unknown stream" +# into a connection error unless it can see the stream was closed by reset). +# At ~120 bytes per entry the whole history at this floor is ~15 KiB. +MIN_MAX_CLOSED_STREAMS = 128 + class _CappedH2Protocol(H2Protocol): """H2Protocol whose h2 connection retains at most `max_closed_streams` closed streams.""" @@ -51,6 +61,12 @@ def __init__(self, *args: Any, proxy_url: str, proxy_rdns: bool | None = None, m super().__init__(*args, **kwargs) self._proxy_url = proxy_url self._proxy_rdns = proxy_rdns + if max_closed_streams is not None and max_closed_streams < MIN_MAX_CLOSED_STREAMS: + logger.warning( + "max_closed_streams=%d is below the safe floor; using %d instead", + max_closed_streams, MIN_MAX_CLOSED_STREAMS, + ) + max_closed_streams = MIN_MAX_CLOSED_STREAMS self._max_closed_streams = max_closed_streams def _protocol_factory(self) -> H2Protocol: @@ -87,6 +103,12 @@ def __init__(self, *args: Any, tls_policy: TLSPolicy, tls_status: TLSStatus | No self._tls_policy = tls_policy self._tls_status = tls_status super().__init__(*args, **kwargs) + if max_closed_streams is not None and max_closed_streams < MIN_MAX_CLOSED_STREAMS: + logger.warning( + "max_closed_streams=%d is below the safe floor; using %d instead", + max_closed_streams, MIN_MAX_CLOSED_STREAMS, + ) + max_closed_streams = MIN_MAX_CLOSED_STREAMS self._max_closed_streams = max_closed_streams def _protocol_factory(self) -> H2Protocol: @@ -164,6 +186,12 @@ def __init__( if max_message_size is None: max_message_size = 64 * 1024 * 1024 # 64MB self._max_message_size = max_message_size + if max_closed_streams is not None and max_closed_streams < MIN_MAX_CLOSED_STREAMS: + logger.warning( + "max_closed_streams=%d is below the safe floor; using %d instead", + max_closed_streams, MIN_MAX_CLOSED_STREAMS, + ) + max_closed_streams = MIN_MAX_CLOSED_STREAMS channel_class = VerifiedChannel if self._proxy is None else VerifiedProxiedChannel channel_kwargs = {} channel_kwargs["max_closed_streams"] = max_closed_streams diff --git a/tests/test_closed_streams_cap.py b/tests/test_closed_streams_cap.py index 58b3b07..f1dd5f7 100644 --- a/tests/test_closed_streams_cap.py +++ b/tests/test_closed_streams_cap.py @@ -11,7 +11,6 @@ connection's `_closed_streams` stays at the configured cap. """ -import asyncio import logging import unittest from unittest.mock import patch @@ -20,9 +19,10 @@ from grpclib.server import Server import PasarGuardNodeBridge.grpclib as bridge_grpclib -from PasarGuardNodeBridge.common import service_pb2 as service from PasarGuardNodeBridge.common import service_grpc -from PasarGuardNodeBridge.grpclib import Node as GrpcNode, ProxiedChannel +from PasarGuardNodeBridge.common import service_pb2 as service +from PasarGuardNodeBridge.grpclib import Node as GrpcNode +from PasarGuardNodeBridge.grpclib import ProxiedChannel from PasarGuardNodeBridge.storage import InMemoryUserSyncStore @@ -61,7 +61,7 @@ def make_node(self, port, **kwargs): ) async def test_lowered_cap_bounds_closed_stream_history(self): - """With max_closed_streams set, the retained closed-stream history stays at the cap.""" + """With max_closed_streams set (>= the safe floor), the retained closed-stream history stays at the cap.""" class Receiver: async def sync_users(inner, stream): @@ -79,7 +79,7 @@ def __mapping__(inner): await server.start("127.0.0.1", 0) port = server._server.sockets[0].getsockname()[1] - cap = 8 + cap = bridge_grpclib.MIN_MAX_CLOSED_STREAMS node = self.make_node(port, max_closed_streams=cap) node._close_chan() with patch.object(bridge_grpclib, "Proxy", _DirectProxy): @@ -111,6 +111,39 @@ async def test_default_keeps_h2_behavior(self): self.assertEqual(node.channel._max_closed_streams, bridge_grpclib.DEFAULT_MAX_CLOSED_STREAMS) node._close_chan() + async def test_low_cap_clamped_to_floor(self): + """A cap below the safe floor is silently clamped (with a warning), not honored. + + Below the floor, ordinary client cancels evict their own history entries + fast enough that a late HEADERS/DATA for an evicted stream surfaces as a + connection-level PROTOCOL_ERROR and kills every unrelated RPC on the + connection. None (uncapped) must stay untouched. + """ + node = self.make_node(1) + node._close_chan() + with self.assertLogs("PasarGuardNodeBridge.grpclib", level="WARNING") as captured: + node.channel = ProxiedChannel( + "127.0.0.1", 1, ssl=False, proxy_url="socks5://127.0.0.1:1", + max_closed_streams=1, + ) + self.assertEqual(node.channel._max_closed_streams, bridge_grpclib.MIN_MAX_CLOSED_STREAMS) + self.assertIn(str(bridge_grpclib.MIN_MAX_CLOSED_STREAMS), "\n".join(captured.output)) + node._close_chan() + + node.channel = ProxiedChannel( + "127.0.0.1", 1, ssl=False, proxy_url="socks5://127.0.0.1:1", + max_closed_streams=None, + ) + self.assertIsNone(node.channel._max_closed_streams) + node._close_chan() + + node.channel = ProxiedChannel( + "127.0.0.1", 1, ssl=False, proxy_url="socks5://127.0.0.1:1", + max_closed_streams=bridge_grpclib.MIN_MAX_CLOSED_STREAMS, + ) + self.assertEqual(node.channel._max_closed_streams, bridge_grpclib.MIN_MAX_CLOSED_STREAMS) + node._close_chan() + if __name__ == "__main__": unittest.main() From 3af4af202a17b6b173c1e8d92e2bbf3be17e6721 Mon Sep 17 00:00:00 2001 From: JavadMoqaddam Date: Wed, 25 Nov 2026 12:50:28 +0000 Subject: [PATCH 5/9] Use self.logger for the low-cap warning so logger=None does not crash (CodeRabbit minor) --- PasarGuardNodeBridge/grpclib.py | 2 +- tests/test_closed_streams_cap.py | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/PasarGuardNodeBridge/grpclib.py b/PasarGuardNodeBridge/grpclib.py index 46f2b06..0bf094e 100644 --- a/PasarGuardNodeBridge/grpclib.py +++ b/PasarGuardNodeBridge/grpclib.py @@ -187,7 +187,7 @@ def __init__( max_message_size = 64 * 1024 * 1024 # 64MB self._max_message_size = max_message_size if max_closed_streams is not None and max_closed_streams < MIN_MAX_CLOSED_STREAMS: - logger.warning( + self.logger.warning( "max_closed_streams=%d is below the safe floor; using %d instead", max_closed_streams, MIN_MAX_CLOSED_STREAMS, ) diff --git a/tests/test_closed_streams_cap.py b/tests/test_closed_streams_cap.py index f1dd5f7..e84bd79 100644 --- a/tests/test_closed_streams_cap.py +++ b/tests/test_closed_streams_cap.py @@ -144,6 +144,31 @@ async def test_low_cap_clamped_to_floor(self): self.assertEqual(node.channel._max_closed_streams, bridge_grpclib.MIN_MAX_CLOSED_STREAMS) node._close_chan() + async def test_low_cap_node_without_logger_clamps(self): + """Node(max_closed_streams=1) with logger omitted must clamp, not raise. + + The low-cap warning used the `logger` parameter, which is None when + omitted, so construction raised AttributeError (wrapped as NodeAPIError) + instead of clamping to the safe floor. + """ + with patch("ssl.SSLContext.load_verify_locations"), self.assertLogs(level="WARNING") as captured: + node = GrpcNode( + address="127.0.0.1", + port=1, + api_port=1, + server_ca="test", + api_key="00000000-0000-0000-0000-000000000000", + node_id="cap-floor-no-logger", + user_sync_store=InMemoryUserSyncStore(), + sync_poll_interval=0.01, + max_closed_streams=1, + ) + try: + self.assertEqual(node.channel._max_closed_streams, bridge_grpclib.MIN_MAX_CLOSED_STREAMS) + self.assertIn("below the safe floor", "\n".join(captured.output)) + finally: + node._close_chan() + if __name__ == "__main__": unittest.main() From 0adcf27c5bfb223bea9e5b50ef1b5c4c08f0934f Mon Sep 17 00:00:00 2001 From: JavadMoqaddam Date: Sun, 29 Nov 2026 07:13:50 +0000 Subject: [PATCH 6/9] Cover the cap on the TLS+proxy path and late frames on evicted streams CodeRabbit's Linked Issues check on #1254 asked for the untested parts: - VerifiedProxiedChannel keeps the caller's cap and wraps the protocol once (the double wrap was the inconsistent-MRO crash on every proxied TLS channel) - a real TLS gRPC connection through the proxy path stays capped and keeps serving RPCs after the cap trims history - a late frame on a reset stream stays a stream error while the floor keeps it in h2's history, and becomes a connection error once the cap evicts it --- tests/test_closed_streams_cap.py | 180 ++++++++++++++++++++++++++++++- 1 file changed, 179 insertions(+), 1 deletion(-) diff --git a/tests/test_closed_streams_cap.py b/tests/test_closed_streams_cap.py index e84bd79..cf209e3 100644 --- a/tests/test_closed_streams_cap.py +++ b/tests/test_closed_streams_cap.py @@ -12,18 +12,30 @@ """ import logging +import ssl +import tempfile import unittest +from datetime import UTC, datetime, timedelta +from ipaddress import ip_address +from pathlib import Path from unittest.mock import patch +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.x509.oid import NameOID from grpclib.const import Cardinality, Handler from grpclib.server import Server +from h2.connection import H2Connection +from h2.exceptions import StreamIDTooLowError import PasarGuardNodeBridge.grpclib as bridge_grpclib from PasarGuardNodeBridge.common import service_grpc from PasarGuardNodeBridge.common import service_pb2 as service from PasarGuardNodeBridge.grpclib import Node as GrpcNode -from PasarGuardNodeBridge.grpclib import ProxiedChannel +from PasarGuardNodeBridge.grpclib import ProxiedChannel, VerifiedProxiedChannel from PasarGuardNodeBridge.storage import InMemoryUserSyncStore +from PasarGuardNodeBridge.tls import TLSPolicy, TLSStatus class _DirectProxy: @@ -44,6 +56,71 @@ async def connect(self, dest_host, dest_port, timeout=None, **kwargs): return sock +class _SyncUsersReceiver: + async def sync_users(self, stream): + await stream.recv_message() + await stream.send_message(service.Empty()) + + def __mapping__(self): + return { + "/service.NodeService/SyncUsers": Handler( + self.sync_users, Cardinality.UNARY_UNARY, service.Users, service.Empty + ), + } + + +def tls_server_context(): + """Self-signed h2 server context for 127.0.0.1, plus the PEM the client trusts.""" + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "127.0.0.1")]) + now = datetime.now(UTC) + cert = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(days=1)) + .not_valid_after(now + timedelta(days=1)) + .add_extension(x509.SubjectAlternativeName([x509.IPAddress(ip_address("127.0.0.1"))]), False) + .sign(key, hashes.SHA256()) + ) + directory = Path(tempfile.mkdtemp()) + cert_path, key_path = directory / "cert.pem", directory / "key.pem" + cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM)) + key_path.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption() + ) + ) + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.load_cert_chain(cert_path, key_path) + ctx.set_alpn_protocols(["h2", "http/1.1"]) + return ctx, cert.public_bytes(serialization.Encoding.PEM).decode() + + +class _StubTransport: + """Just enough transport for _CappedH2Protocol.connection_made.""" + + def __init__(self): + self.written = b"" + + def get_extra_info(self, name, default=None): + return default + + def write(self, data): + self.written += bytes(data) + + def close(self): + pass + + +def late_frame(encoder, stream_id): + """A HEADERS frame the client never asked for: the server answers after the client moved on.""" + block = encoder.encode([(":status", "200"), ("grpc-status", "0")]) + return len(block).to_bytes(3, "big") + b"\x01\x05" + stream_id.to_bytes(4, "big") + block + + class ClosedStreamsCapTests(unittest.IsolatedAsyncioTestCase): def make_node(self, port, **kwargs): with patch("ssl.SSLContext.load_verify_locations"): @@ -169,6 +246,107 @@ async def test_low_cap_node_without_logger_clamps(self): finally: node._close_chan() + async def test_verified_proxied_channel_keeps_the_cap(self): + """A proxied TLS channel keeps the caller's cap and wraps the protocol once. + + The protocol factory used to wrap an already capped protocol a second time, + which made the capped class its own base (TypeError: inconsistent MRO) and + failed every connection on the TLS + proxy path. + """ + policy = TLSPolicy.resolve(None, None) + cap = bridge_grpclib.MIN_MAX_CLOSED_STREAMS + channel = VerifiedProxiedChannel( + host="127.0.0.1", + port=1, + ssl=policy.context("h2"), + tls_policy=policy, + tls_status=TLSStatus(), + proxy_url="socks5://127.0.0.1:1", + max_closed_streams=cap, + ) + try: + protocol = channel._protocol_factory() + self.assertIsInstance(protocol, bridge_grpclib._CappedH2Protocol) + self.assertEqual(type(protocol).max_closed_streams, cap) + self.assertIs(type(protocol).__mro__[1], bridge_grpclib._CappedH2Protocol) + self.assertEqual(channel._max_closed_streams, cap) + finally: + channel.close() + + async def test_verified_proxied_channel_caps_real_tls_history(self): + """A real TLS gRPC connection through the proxy path stays capped and usable.""" + ctx, pem = tls_server_context() + policy = TLSPolicy.resolve(pem, None) + cap = bridge_grpclib.MIN_MAX_CLOSED_STREAMS + + server = Server([_SyncUsersReceiver()]) + await server.start("127.0.0.1", 0, ssl=ctx) + port = server._server.sockets[0].getsockname()[1] + + channel = VerifiedProxiedChannel( + host="127.0.0.1", + port=port, + ssl=policy.context("h2"), + tls_policy=policy, + tls_status=TLSStatus(), + proxy_url="socks5://127.0.0.1:1", + max_closed_streams=cap, + ) + try: + with patch.object(bridge_grpclib, "Proxy", _DirectProxy): + stub = service_grpc.NodeServiceStub(channel) + for _ in range(cap * 4): + await stub.SyncUsers(service.Users(users=[service.User(email="u0@x")])) + h2_conn = channel._protocol.connection._connection + self.assertEqual(h2_conn._closed_streams._size_limit, cap) + self.assertLessEqual(len(h2_conn._closed_streams), cap) + # The cap trims history without breaking the connection: unrelated RPCs keep working. + await stub.SyncUsers(service.Users(users=[service.User(email="u1@x")])) + finally: + channel.close() + server.close() + await server.wait_closed() + + async def test_floor_keeps_a_reset_stream_recognisable(self): + """At the floor a late frame on a reset stream is a stream error, not a connection kill. + + h2 answers a frame for a locally reset stream with RST_STREAM only while the + stream is still in the closed-stream history. Once the cap evicts it, the very + same frame becomes a connection-level error that takes every unrelated RPC + with it. The floor therefore protects a reset stream for exactly + MIN_MAX_CLOSED_STREAMS more closures, and no longer. + """ + cap = bridge_grpclib.MIN_MAX_CLOSED_STREAMS + channel = ProxiedChannel(host="127.0.0.1", port=1, proxy_url="socks5://127.0.0.1:1", max_closed_streams=cap) + try: + protocol = channel._protocol_factory() + protocol.connection_made(_StubTransport()) + h2_conn = protocol.connection._connection + encoder = H2Connection().encoder + self.assertEqual(h2_conn._closed_streams._size_limit, cap) + + h2_conn.send_headers(3, [(":method", "POST"), (":path", "/x")], end_stream=False) + h2_conn.reset_stream(3) + stream_id = 5 + for _ in range(cap - 2): + h2_conn.send_headers(stream_id, [(":method", "POST"), (":path", "/x")], end_stream=True) + h2_conn.receive_data(late_frame(encoder, stream_id)) + stream_id += 2 + + self.assertIn(3, h2_conn._closed_streams) + h2_conn.receive_data(late_frame(encoder, 3)) + h2_conn.send_headers(stream_id, [(":method", "POST"), (":path", "/x")], end_stream=True) + h2_conn.receive_data(late_frame(encoder, stream_id)) + + while 3 in h2_conn._closed_streams: + stream_id += 2 + h2_conn.send_headers(stream_id, [(":method", "POST"), (":path", "/x")], end_stream=True) + h2_conn.receive_data(late_frame(encoder, stream_id)) + with self.assertRaises(StreamIDTooLowError): + h2_conn.receive_data(late_frame(encoder, 3)) + finally: + channel.close() + if __name__ == "__main__": unittest.main() From 75db9aecaeef393be181a38a9a118c7436bc32d2 Mon Sep 17 00:00:00 2001 From: JavadMoqaddam Date: Sun, 29 Nov 2026 07:17:28 +0000 Subject: [PATCH 7/9] Apply make format to the cap implementation and its tests --- PasarGuardNodeBridge/grpclib.py | 27 ++++++++++++++++++++++----- tests/test_closed_streams_cap.py | 28 ++++++++++++++++++---------- 2 files changed, 40 insertions(+), 15 deletions(-) diff --git a/PasarGuardNodeBridge/grpclib.py b/PasarGuardNodeBridge/grpclib.py index 0bf094e..c0e861a 100644 --- a/PasarGuardNodeBridge/grpclib.py +++ b/PasarGuardNodeBridge/grpclib.py @@ -57,14 +57,22 @@ def connection_made(self, transport: asyncio.BaseTransport) -> None: class ProxiedChannel(Channel): - def __init__(self, *args: Any, proxy_url: str, proxy_rdns: bool | None = None, max_closed_streams: int | None = DEFAULT_MAX_CLOSED_STREAMS, **kwargs: Any) -> None: + def __init__( + self, + *args: Any, + proxy_url: str, + proxy_rdns: bool | None = None, + max_closed_streams: int | None = DEFAULT_MAX_CLOSED_STREAMS, + **kwargs: Any, + ) -> None: super().__init__(*args, **kwargs) self._proxy_url = proxy_url self._proxy_rdns = proxy_rdns if max_closed_streams is not None and max_closed_streams < MIN_MAX_CLOSED_STREAMS: logger.warning( "max_closed_streams=%d is below the safe floor; using %d instead", - max_closed_streams, MIN_MAX_CLOSED_STREAMS, + max_closed_streams, + MIN_MAX_CLOSED_STREAMS, ) max_closed_streams = MIN_MAX_CLOSED_STREAMS self._max_closed_streams = max_closed_streams @@ -99,14 +107,22 @@ async def _create_connection(self) -> H2Protocol: class VerifiedChannel(Channel): - def __init__(self, *args: Any, tls_policy: TLSPolicy, tls_status: TLSStatus | None = None, max_closed_streams: int | None = DEFAULT_MAX_CLOSED_STREAMS, **kwargs: Any) -> None: + def __init__( + self, + *args: Any, + tls_policy: TLSPolicy, + tls_status: TLSStatus | None = None, + max_closed_streams: int | None = DEFAULT_MAX_CLOSED_STREAMS, + **kwargs: Any, + ) -> None: self._tls_policy = tls_policy self._tls_status = tls_status super().__init__(*args, **kwargs) if max_closed_streams is not None and max_closed_streams < MIN_MAX_CLOSED_STREAMS: logger.warning( "max_closed_streams=%d is below the safe floor; using %d instead", - max_closed_streams, MIN_MAX_CLOSED_STREAMS, + max_closed_streams, + MIN_MAX_CLOSED_STREAMS, ) max_closed_streams = MIN_MAX_CLOSED_STREAMS self._max_closed_streams = max_closed_streams @@ -189,7 +205,8 @@ def __init__( if max_closed_streams is not None and max_closed_streams < MIN_MAX_CLOSED_STREAMS: self.logger.warning( "max_closed_streams=%d is below the safe floor; using %d instead", - max_closed_streams, MIN_MAX_CLOSED_STREAMS, + max_closed_streams, + MIN_MAX_CLOSED_STREAMS, ) max_closed_streams = MIN_MAX_CLOSED_STREAMS channel_class = VerifiedChannel if self._proxy is None else VerifiedProxiedChannel diff --git a/tests/test_closed_streams_cap.py b/tests/test_closed_streams_cap.py index cf209e3..ae84f3d 100644 --- a/tests/test_closed_streams_cap.py +++ b/tests/test_closed_streams_cap.py @@ -89,9 +89,7 @@ def tls_server_context(): cert_path, key_path = directory / "cert.pem", directory / "key.pem" cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM)) key_path.write_bytes( - key.private_bytes( - serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption() - ) + key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()) ) ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_cert_chain(cert_path, key_path) @@ -161,7 +159,10 @@ def __mapping__(inner): node._close_chan() with patch.object(bridge_grpclib, "Proxy", _DirectProxy): node.channel = ProxiedChannel( - "127.0.0.1", port, ssl=False, proxy_url="socks5://127.0.0.1:1", + "127.0.0.1", + port, + ssl=False, + proxy_url="socks5://127.0.0.1:1", max_closed_streams=cap, ) node._client = service_grpc.NodeServiceStub(node.channel) @@ -182,9 +183,7 @@ async def test_default_keeps_h2_behavior(self): """Without the kwarg the cap is the bridge default (4096), not h2's 65536.""" node = self.make_node(1) node._close_chan() - node.channel = ProxiedChannel( - "127.0.0.1", 1, ssl=False, proxy_url="socks5://127.0.0.1:1" - ) + node.channel = ProxiedChannel("127.0.0.1", 1, ssl=False, proxy_url="socks5://127.0.0.1:1") self.assertEqual(node.channel._max_closed_streams, bridge_grpclib.DEFAULT_MAX_CLOSED_STREAMS) node._close_chan() @@ -200,7 +199,10 @@ async def test_low_cap_clamped_to_floor(self): node._close_chan() with self.assertLogs("PasarGuardNodeBridge.grpclib", level="WARNING") as captured: node.channel = ProxiedChannel( - "127.0.0.1", 1, ssl=False, proxy_url="socks5://127.0.0.1:1", + "127.0.0.1", + 1, + ssl=False, + proxy_url="socks5://127.0.0.1:1", max_closed_streams=1, ) self.assertEqual(node.channel._max_closed_streams, bridge_grpclib.MIN_MAX_CLOSED_STREAMS) @@ -208,14 +210,20 @@ async def test_low_cap_clamped_to_floor(self): node._close_chan() node.channel = ProxiedChannel( - "127.0.0.1", 1, ssl=False, proxy_url="socks5://127.0.0.1:1", + "127.0.0.1", + 1, + ssl=False, + proxy_url="socks5://127.0.0.1:1", max_closed_streams=None, ) self.assertIsNone(node.channel._max_closed_streams) node._close_chan() node.channel = ProxiedChannel( - "127.0.0.1", 1, ssl=False, proxy_url="socks5://127.0.0.1:1", + "127.0.0.1", + 1, + ssl=False, + proxy_url="socks5://127.0.0.1:1", max_closed_streams=bridge_grpclib.MIN_MAX_CLOSED_STREAMS, ) self.assertEqual(node.channel._max_closed_streams, bridge_grpclib.MIN_MAX_CLOSED_STREAMS) From 68aff03d18c75bcfbefc9eb5f83f79a4957df27a Mon Sep 17 00:00:00 2001 From: JavadMoqaddam Date: Sun, 29 Nov 2026 08:44:08 +0000 Subject: [PATCH 8/9] Cover peer resets, late DATA and timing-out requests under the cap --- tests/test_closed_streams_cap.py | 108 ++++++++++++++++++++++++++++++- 1 file changed, 107 insertions(+), 1 deletion(-) diff --git a/tests/test_closed_streams_cap.py b/tests/test_closed_streams_cap.py index ae84f3d..8367a97 100644 --- a/tests/test_closed_streams_cap.py +++ b/tests/test_closed_streams_cap.py @@ -11,6 +11,7 @@ connection's `_closed_streams` stays at the configured cap. """ +import asyncio import logging import ssl import tempfile @@ -26,12 +27,13 @@ from cryptography.x509.oid import NameOID from grpclib.const import Cardinality, Handler from grpclib.server import Server -from h2.connection import H2Connection +from h2.connection import ConnectionState, H2Connection from h2.exceptions import StreamIDTooLowError import PasarGuardNodeBridge.grpclib as bridge_grpclib from PasarGuardNodeBridge.common import service_grpc from PasarGuardNodeBridge.common import service_pb2 as service +from PasarGuardNodeBridge.controller import NodeAPIError from PasarGuardNodeBridge.grpclib import Node as GrpcNode from PasarGuardNodeBridge.grpclib import ProxiedChannel, VerifiedProxiedChannel from PasarGuardNodeBridge.storage import InMemoryUserSyncStore @@ -119,6 +121,16 @@ def late_frame(encoder, stream_id): return len(block).to_bytes(3, "big") + b"\x01\x05" + stream_id.to_bytes(4, "big") + block +def late_data_frame(stream_id, payload=b"late"): + """A DATA frame for a stream the peer already closed.""" + return len(payload).to_bytes(3, "big") + b"\x00\x00" + stream_id.to_bytes(4, "big") + payload + + +def peer_reset_frame(stream_id, error_code=8): + """A RST_STREAM the peer sends for a stream it no longer knows.""" + return (4).to_bytes(3, "big") + b"\x03\x00" + stream_id.to_bytes(4, "big") + error_code.to_bytes(4, "big") + + class ClosedStreamsCapTests(unittest.IsolatedAsyncioTestCase): def make_node(self, port, **kwargs): with patch("ssl.SSLContext.load_verify_locations"): @@ -355,6 +367,100 @@ async def test_floor_keeps_a_reset_stream_recognisable(self): finally: channel.close() + async def test_peer_reset_and_late_data_on_evicted_stream_keep_other_rpcs_alive(self): + """Frames for a stream the cap evicted must not cost the connection its other RPCs. + + After the cap drops a stream from `_closed_streams`, h2 no longer knows it: + a peer RST_STREAM and a late DATA are ignored, a late HEADERS is the + connection-level StreamIDTooLowError documented above. Either way the same + connection keeps serving new RPCs. + """ + server = Server([_SyncUsersReceiver()]) + await server.start("127.0.0.1", 0) + port = server._server.sockets[0].getsockname()[1] + + cap = bridge_grpclib.MIN_MAX_CLOSED_STREAMS + node = self.make_node(port, max_closed_streams=cap) + node._close_chan() + with patch.object(bridge_grpclib, "Proxy", _DirectProxy): + node.channel = ProxiedChannel( + "127.0.0.1", port, ssl=False, proxy_url="socks5://127.0.0.1:1", max_closed_streams=cap + ) + node._client = service_grpc.NodeServiceStub(node.channel) + try: + for _ in range(cap * 4): + await node._client.SyncUsers(service.Users(), metadata=node._metadata) + + h2_conn = node.channel._protocol.connection._connection + self.assertEqual(h2_conn._closed_streams._size_limit, cap) + self.assertNotIn(1, h2_conn._closed_streams) + + # The peer's frames for a stream the cap evicted are ignored, not fatal. + self.assertEqual(h2_conn.receive_data(peer_reset_frame(1)), []) + self.assertEqual(h2_conn.receive_data(late_data_frame(1)), []) + self.assertNotEqual(h2_conn.state_machine.state, ConnectionState.CLOSED) + + await node._client.SyncUsers(service.Users(), metadata=node._metadata) + self.assertLessEqual(len(h2_conn._closed_streams), cap) + finally: + node._close_chan() + server.close() + await server.wait_closed() + + async def test_timed_out_request_leaves_capped_history_and_channel_usable(self): + """A request timeout cancels its stream; the cap still bounds history and later RPCs work.""" + release = asyncio.Event() + + class Receiver(_SyncUsersReceiver): + async def get_base_info(self, stream): + await stream.recv_message() + await release.wait() + await stream.send_message(service.BaseInfoResponse()) + + def __mapping__(self): + return { + "/service.NodeService/SyncUsers": Handler( + self.sync_users, Cardinality.UNARY_UNARY, service.Users, service.Empty + ), + "/service.NodeService/GetBaseInfo": Handler( + self.get_base_info, Cardinality.UNARY_UNARY, service.Empty, service.BaseInfoResponse + ), + } + + server = Server([Receiver()]) + await server.start("127.0.0.1", 0) + port = server._server.sockets[0].getsockname()[1] + + cap = bridge_grpclib.MIN_MAX_CLOSED_STREAMS + node = self.make_node(port, max_closed_streams=cap) + node._close_chan() + with patch.object(bridge_grpclib, "Proxy", _DirectProxy): + node.channel = ProxiedChannel( + "127.0.0.1", port, ssl=False, proxy_url="socks5://127.0.0.1:1", max_closed_streams=cap + ) + node._client = service_grpc.NodeServiceStub(node.channel) + try: + with self.assertRaises(NodeAPIError) as raised: + await node._handle_grpc_request(node._client.GetBaseInfo, service.Empty(), timeout=0.2) + self.assertEqual(raised.exception.detail, "Request timed out") + + h2_conn = node.channel._protocol.connection._connection + self.assertEqual(h2_conn._closed_streams._size_limit, cap) + self.assertLessEqual(len(h2_conn._closed_streams), cap) + + for _ in range(cap * 4): + await node._client.SyncUsers(service.Users(), metadata=node._metadata) + self.assertLessEqual(len(h2_conn._closed_streams), cap) + + release.set() + info = await node._handle_grpc_request(node._client.GetBaseInfo, service.Empty(), timeout=5) + self.assertIsInstance(info, service.BaseInfoResponse) + finally: + node._close_chan() + release.set() + server.close() + await server.wait_closed() + if __name__ == "__main__": unittest.main() From 9aaa9370c71e2503353e6a4e6daac91604b39004 Mon Sep 17 00:00:00 2001 From: JavadMoqaddam Date: Sun, 29 Nov 2026 09:00:23 +0000 Subject: [PATCH 9/9] Cover the cap on the connection built after a reconnect --- tests/test_closed_streams_cap.py | 33 ++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/test_closed_streams_cap.py b/tests/test_closed_streams_cap.py index 8367a97..bede9ab 100644 --- a/tests/test_closed_streams_cap.py +++ b/tests/test_closed_streams_cap.py @@ -327,6 +327,39 @@ async def test_verified_proxied_channel_caps_real_tls_history(self): server.close() await server.wait_closed() + async def test_reconnect_keeps_the_cap_on_the_new_connection(self): + """A dropped transport makes the channel dial again; the fresh h2 connection is capped too.""" + server = Server([_SyncUsersReceiver()]) + await server.start("127.0.0.1", 0) + port = server._server.sockets[0].getsockname()[1] + + cap = bridge_grpclib.MIN_MAX_CLOSED_STREAMS + with patch.object(bridge_grpclib, "Proxy", _DirectProxy): + channel = ProxiedChannel( + "127.0.0.1", port, ssl=False, proxy_url="socks5://127.0.0.1:1", max_closed_streams=cap + ) + try: + stub = service_grpc.NodeServiceStub(channel) + await stub.SyncUsers(service.Users()) + first = channel._protocol.connection._connection + self.assertEqual(first._closed_streams._size_limit, cap) + + channel._protocol.connection._transport.close() + for _ in range(50): + if not channel._connected: + break + await asyncio.sleep(0.02) + self.assertFalse(channel._connected) + + await stub.SyncUsers(service.Users()) + second = channel._protocol.connection._connection + self.assertIsNot(second, first) + self.assertEqual(second._closed_streams._size_limit, cap) + finally: + channel.close() + server.close() + await server.wait_closed() + async def test_floor_keeps_a_reset_stream_recognisable(self): """At the floor a late frame on a reset stream is a stream error, not a connection kill.