Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(data-warehouse): tunnel Framer WebSocket through the egress proxy (#80823)

jake sciottoafea534dda78
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/framer/framer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/framer/framer.py
index f69865a2d070..84e53e9127a7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/framer/framer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/framer/framer.py
@@ -11,13 +11,17 @@ sent as the `sdkVersion` query parameter, exactly like the SDK release it mirror
import re
import json
import time
+import socket
+import http.client
from collections.abc import Callable, Iterator
from typing import Any, Optional, Protocol
from urllib.parse import unquote, urlencode, urljoin, urlsplit
from structlog.types import FilteringBoundLogger
from websockets.exceptions import ConnectionClosed, InvalidStatus
+from websockets.headers import build_authorization_basic
from websockets.sync.client import connect as websocket_connect
+from websockets.uri import Proxy, get_proxy, parse_proxy, parse_uri
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.framer import devalue
@@ -65,6 +69,39 @@ class WebSocketLike(Protocol):
def close(self) -> None: ...
+def _tunnel_through_proxy(proxy: Proxy, host: str, port: int) -> socket.socket:
+ """Open a CONNECT tunnel to ``host:port`` through an HTTP(S) proxy and return the socket.
+
+ websockets' own proxy support requires an HTTP/1.1 status line on the CONNECT
+ response (until v17), but goproxy-based egress proxies such as Smokescreen answer a
+ successful CONNECT with ``HTTP/1.0 200 OK``, which websockets rejects as
+ "did not receive a valid HTTP response from proxy". ``http.client`` accepts HTTP/1.0,
+ so we establish the tunnel ourselves and hand the socket to websockets. This helper
+ can be dropped once the pinned websockets version is >= 17.
+ """
+ connection_class = http.client.HTTPSConnection if proxy.scheme == "https" else http.client.HTTPConnection
+ connection = connection_class(proxy.host, proxy.port, timeout=CONNECT_TIMEOUT_SECONDS)
+ headers: dict[str, str] = {}
+ if proxy.username is not None:
+ headers["Proxy-Authorization"] = build_authorization_basic(proxy.username, proxy.password or "")
+ connection.set_tunnel(host, port, headers)
+ try:
+ connection.connect()
+ except OSError as e:
+ connection.close()
+ raise FramerAPIError(
+ f"Could not reach Framer through the network proxy ({e}). Try again, and contact support if it keeps failing.",
+ code="PROXY",
+ retryable=True,
+ ) from e
+ sock = connection.sock
+ # Detach before the connection object goes out of scope, so its close() can't
+ # tear down the tunnel we're handing to websockets.
+ connection.sock = None
+ assert sock is not None # connect() either sets the socket or raises
+ return sock
+
+
def parse_project_id(project: str) -> Optional[str]:
"""Resolve a project URL or raw id to the 20-char project id, mirroring the official SDK.
@@ -120,12 +157,26 @@ class FramerClient:
def connect(self) -> None:
query = urlencode({"projectId": self._project_id, "sdkVersion": self._protocol_version})
+ url = f"{self._url}?{query}"
+ connect_kwargs: dict[str, Any] = {}
+ ws_uri = parse_uri(url)
+ proxy = get_proxy(ws_uri)
+ if proxy is not None:
+ proxy_parsed = parse_proxy(proxy)
+ if proxy_parsed.scheme in ("http", "https"):
+ # Tunnel the CONNECT ourselves because websockets < 17 rejects the
+ # HTTP/1.0 success line Smokescreen sends (see _tunnel_through_proxy).
+ # Passing a socket makes websockets skip its own proxy handling while
+ # still doing TLS against the Framer host. SOCKS proxies fall through
+ # to websockets' built-in support.
+ connect_kwargs["sock"] = _tunnel_through_proxy(proxy_parsed, ws_uri.host, ws_uri.port)
try:
self._ws = self._connect_fn(
- f"{self._url}?{query}",
+ url,
additional_headers={"Authorization": f"Token {self._api_key}"},
open_timeout=CONNECT_TIMEOUT_SECONDS,
max_size=MAX_MESSAGE_BYTES,
+ **connect_kwargs,
)
except InvalidStatus as e:
status = e.response.status_code
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/framer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/framer/source.py
index ea110d87b5b9..ee75f6995e17 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/framer/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/framer/source.py
@@ -54,12 +54,14 @@ class FramerSource(SimpleSource[FramerSourceConfig]):
def get_retryable_errors(self) -> set[str]:
# Transient channel conditions the next Temporal attempt recovers from: a busy
- # headless pool, a concurrent-session collision, or a dropped connection.
+ # headless pool, a concurrent-session collision, a dropped connection, or an
+ # egress-proxy hiccup.
return {
"Framer API error POOL_EXHAUSTED",
"Framer API error TOKEN_SESSION_LIMIT",
"Framer API error TIMEOUT",
"Framer API error CONNECTION_CLOSED",
+ "Framer API error PROXY",
}
def get_canonical_descriptions(self) -> CanonicalDescriptions:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/framer/tests/test_framer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/framer/tests/test_framer.py
index 6f9dce9658c4..1ce9b406356a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/framer/tests/test_framer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/framer/tests/test_framer.py
@@ -1,5 +1,8 @@
+import os
import json
import math
+import socket
+import threading
from collections import deque
from collections.abc import Iterable
from datetime import UTC, datetime
@@ -74,6 +77,51 @@ class FakeFramerServer:
self.closed = True
+class FakeConnectProxy:
+ """In-memory CONNECT proxy with a configurable status line, so tests can speak the
+ `HTTP/1.0 200 OK` that goproxy-based egress proxies (Smokescreen) answer with."""
+
+ def __init__(self, status_line: str) -> None:
+ self.status_line = status_line
+ self.connect_request = ""
+ self.tunneled = b""
+ self._server = socket.socket()
+ self._server.settimeout(10)
+ self._server.bind(("127.0.0.1", 0))
+ self._server.listen(1)
+ self.port = self._server.getsockname()[1]
+ self._thread = threading.Thread(target=self._serve, daemon=True)
+ self._thread.start()
+
+ def _serve(self) -> None:
+ connection, _ = self._server.accept()
+ connection.settimeout(10)
+ try:
+ request = b""
+ while b"\r\n\r\n" not in request:
+ request += connection.recv(4096)
+ self.connect_request = request.decode()
+ connection.sendall(f"{self.status_line}\r\n\r\n".encode())
+ while data := connection.recv(4096):
+ self.tunneled += data
+ except OSError:
+ pass
+ finally:
+ connection.close()
+
+ def join(self) -> None:
+ self._thread.join(timeout=10)
+ self._server.close()
+
+
[email protected](autouse=True)
+def no_ambient_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The client resolves proxies from process env, so an ambient HTTP(S)_PROXY on the
+ # host would reroute every connect in this file through a real proxy.
+ for name in [key for key in os.environ if key.lower().endswith("_proxy")]:
+ monkeypatch.delenv(name)
+
+
def make_client(server: FakeFramerServer) -> FramerClient:
client = FramerClient(PROJECT_ID, "test-key", protocol_version="0.1.29", connect_fn=server)
client.connect()
@@ -256,6 +304,45 @@ class TestFramer:
server.enqueue_raw(json.dumps({"$chunk": 1, "id": "c1", "seq": -1, "data": full[middle:]}))
assert client.call("getCollections") == [{"id": "big"}]
+ @parameterized.expand(
+ [
+ ("HTTP/1.0 200 OK",), # goproxy/Smokescreen success line, rejected by websockets < 17
+ ("HTTP/1.1 200 Connection established",),
+ ]
+ )
+ def test_client_tunnels_through_env_configured_proxy(self, status_line: str) -> None:
+ proxy = FakeConnectProxy(status_line)
+ server = FakeFramerServer()
+ with pytest.MonkeyPatch.context() as patcher:
+ patcher.setenv("HTTPS_PROXY", f"http://pod:[email protected]:{proxy.port}")
+ client = FramerClient(PROJECT_ID, "test-key", protocol_version="0.1.29", connect_fn=server)
+ client.connect()
+ client.close()
+ assert proxy.connect_request.startswith("CONNECT api.framer.com:443 ")
+ assert "Proxy-Authorization: Basic" in proxy.connect_request
+ sock = server.connect_kwargs["sock"]
+ sock.sendall(b"tunneled")
+ sock.close()
+ proxy.join()
+ assert proxy.tunneled == b"tunneled"
+
+ def test_client_wraps_proxy_denial_as_retryable(self) -> None:
+ proxy = FakeConnectProxy("HTTP/1.0 407 Request rejected by proxy")
+ server = FakeFramerServer()
+ with pytest.MonkeyPatch.context() as patcher:
+ patcher.setenv("HTTPS_PROXY", f"http://127.0.0.1:{proxy.port}")
+ client = FramerClient(PROJECT_ID, "test-key", protocol_version="0.1.29", connect_fn=server)
+ with pytest.raises(FramerAPIError) as exc_info:
+ client.connect()
+ proxy.join()
+ assert exc_info.value.code == "PROXY"
+ assert exc_info.value.retryable
+
+ def test_client_connects_directly_without_proxy(self) -> None:
+ server = FakeFramerServer()
+ make_client(server)
+ assert "sock" not in server.connect_kwargs
+
def test_validate_credentials_success(self) -> None:
server = FakeFramerServer(methods={"getProjectInfo2": {"id": PROJECT_ID, "name": "Site"}})
with pytest.MonkeyPatch.context() as patcher: